A Claude Code skill that turns any machine into a 3D simulator you can take apart
JavaScript
teardown: interactive 3D machine simulators for Claude Code
elvarofficiale7e668cd44f4
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..14e2c2e--- /dev/null+++ b/.gitignore@@ -0,0 +1,4 @@+node_modules/+teardown-out/+__pycache__/+*.pycdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..ce935de--- /dev/null+++ b/LICENSE@@ -0,0 +1,22 @@+MIT License++Copyright (c) 2026 elvarofficial+Copyright (c) 2026 whaleyxbt++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..f1e9e0e--- /dev/null+++ b/README.md@@ -0,0 +1,60 @@+# teardown++A Claude Code skill that turns any machine into a 3D simulator you can take apart.++Ask how something works. Claude builds it as one offline HTML page: the machine runs in the middle, every panel around it reads the real numbers, a button opens the part doing the work, and when nobody touches it the page tours itself.++++| Cessna 337 landing gear | Strandbeest SB-10 |+|---|---|+|  |  |++## Install++```+npx skills add elvarofficial/teardown -g -a claude-code+```++Then, once, in the installed folder:++```+npm install && npx playwright install chromium+```++You need Node.js 20 or newer. For the video you also need `ffmpeg`, and for the sound Python 3.++## Use++Ask Claude Code in plain words:++> Build me a simulator of a 4-stroke motorcycle engine I can take apart.++> How does a mechanical watch keep time? Show me as a simulator.++> Make a teardown of a hydraulic excavator arm and record a 20-second video of it.++Or open one of the 3 examples first:++```+node sims/build.mjs v8-live # teardown-out/dist/v8-live.html+node sims/build.mjs cessna-live+node sims/build.mjs strandbeest-live+```++## What is inside++| | |+|---|---|+| `SKILL.md` | What Claude reads: how a machine is built, the rules that make it look right, the review loop. |+| `sims/kit/` | Runtime, stage, shader warm-up. |+| `sims/v8-*`, `sims/cessna-*`, `sims/strandbeest-*` | 3 complete machines. `-shared` is the machine, `-live` the page you drive, `-film` the recorded tour. |+| `sims/build.mjs` | Bundles a machine into one HTML file, three.js and fonts inlined. |+| `sims/capture.mjs` | Renders the film frame by frame to a 60 fps mp4, or to review sheets of stills. |+| `sfx/`, `run_sfx.py` | Procedural sound on the film's timeline, mastered to −14 LUFS. |++## Credits++Built on [whaleyxbt/claude-motion](https://github.com/whaleyxbt/claude-motion) (MIT): the runtime, frame capture, sound engine and review rules come from there. Recorded samples are CC0 from Freesound, prepared by [Barty-Bart/motion-graphics](https://github.com/Barty-Bart/motion-graphics); sources in `sfx/samples/SOURCES.md`.++MIT licence.diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..9505e4a--- /dev/null+++ b/SKILL.md@@ -0,0 +1,144 @@+---+name: teardown+description: Build an interactive 3D simulator of a real machine or mechanism (an engine, a landing gear, a walking linkage, a pump, a gearbox) as one offline HTML page people can take apart, with live panels driven by the same model that moves the parts, a button for every subsystem, cutaways, camera views and an auto tour that hands control to the visitor; then record it frame by frame to a 60 fps video with a synced procedural score. Use when someone asks how a machine works, wants a "visual explainer", a "simulator", a "cutaway", an "exploded view" or an "interactive 3D lesson", or wants a 3D object shown working rather than described.+---++# Teardown++One machine, one page. The visitor sees the thing run, presses a button, and the part doing the work opens up while the gauges around it read the real numbers. Left alone, the page tours itself with a cursor. The same code records a film of the tour, frame by frame, with a score built on the same timeline.++`SKILL_DIR` below is the folder this file lives in. Builds and renders go to `./teardown-out` of the folder you run from.++## First run++```+cd "$SKILL_DIR" && npm install && npx playwright install chromium+```++The pages need nothing else. The video needs `ffmpeg` on PATH and the score needs Python 3 (standard library only). Set `FFMPEG`, `PYTHON` or `CHROMIUM` to point at other binaries.++## The 3 examples++Build one, open the HTML, press buttons. Copy the closest one when you start a new machine.++| | The machine | What drives it | Worth stealing |+|---|---|---|---|+| `v8-*` | A cross-plane V8 with glass liners: the charge burns inside the cylinder you track, valves lift on their cams, 8 pistons move from the exact slider-crank. | Crank angle. Firing order 1-8-4-3-6-5-7-2, a chamber pressure model for the indicator diagram. | Cutaway modes (glass, section, solid), the firing order as a cylinder picker, live charts synced to the crank. |+| `cessna-*` | The Cessna 337 main landing gear folding into the airframe on takeoff and dropping on landing. | Stroke 0..1: a 201 mm rack turns a 32-tooth pinion (module 4 mm) through exactly 180°. | One degree of freedom posing a whole mechanism, flight phases as functions of time, a runway that rolls under the model. |+| `strandbeest-*` | Theo Jansen's Strandbeest, 20 legs on one crankshaft, walking broadside over sand. | Wind. The crank speed is integrated from it; every joint follows by circle intersection from Jansen's 11 link lengths. | An exact linkage solver in 67 lines, instanced tubes, foot traces, a contact chart of all 20 feet. |++Each comes in 3 folders: `<name>-shared/` holds the machine, `<name>-film/` the recorded tour, `<name>-live/` the page you drive.++```+node "$SKILL_DIR/sims/build.mjs" v8-live # → teardown-out/dist/v8-live.html, offline, ~800 KB+node "$SKILL_DIR/sims/build.mjs" # all 6+```++## How a machine is built++One folder per machine, split by job. The examples follow this exactly:++| File | Job |+|---|---|+| `kin.js` / `gear.js` / `jansen.js` | The math. Real dimensions in real units, one input (crank angle, stroke, wind) and every pose and readout as a function of it. No three.js in here. |+| `engine.js` / `gear.js` / `beast.js` | The geometry, built from code: lathed parts, tubes, instanced links. `update(input)` poses it. |+| `stage.js` | Studio, lights, shadows, post (GTAO, bloom). `frame(state, cam)` draws one frame. |+| `console.js` | The overlay: fixed 1600 x 900 CSS layout of panels, charts, toggles, callouts with leaders. `update(state)` redraws it from the frame's state. |+| `film.js` | A `SCRIPT` of operator moves (views, isolate, cutaway, throttle) and `render(t)` as a pure function of time. |+| `live.js` | The same machine in real time: buttons, sliders, orbit, zoom, keys. With no input it plays `film.js`'s script as an auto tour with a cursor; any click, drag, wheel or key hands control over, 25 s of quiet hands it back. |+| `score.py` | The sound on the film's timeline. |++For a machine outside `SKILL_DIR`, make a folder with a `main.js` and import the kit by name: `import {runSim} from 'teardown-kit/runtime.js'`. Build it with `node "$SKILL_DIR/sims/build.mjs" ./my-machine`.++## Rules that decide whether it works++1. **Start from a reference, never from imagination.** A photo, a cutaway drawing from a manual, a clip of the real thing. Build against it and compare frame by frame. Machines invented from a sentence come out generic every time; the same model rebuilds a real one closely when it has something to match.+2. **Real numbers, one source.** Get the real dimensions first (bore, stroke, tooth count, link lengths). Every gauge, chart and label reads from the same function that poses the parts, so nothing on screen can disagree with the motion. Check one by hand: in the Cessna, 32 teeth × 4 mm module is a 128 mm pitch diameter, and half its circumference is the 201 mm stroke.+3. **One input drives everything.** Pose from the crank angle, the stroke or the wind. Nothing is keyframed by hand, so the film, the live page and the score never drift.+4. **The part doing the work opens up.** Isolate it, cut it, x-ray it. A camera that goes inside is worth more than ten orbits.+5. **Light studio, one accent.** Pale backgrounds read in a feed; dark ones lose the first second. The accent marks the thing that is changing. Watch near-white parts on a pale backdrop: give them an ink outline or a darker ground.+6. **Pick the camera for the mechanism.** A planar linkage seen face-on collapses into a lattice; a 3/4 view along the spine keeps every leg readable.+7. **Fix collisions with a number.** When a part pokes through another, scale or move it in the parameter block. Never hide it with the camera.++## Live page rules++- **Test on an integrated GPU.** A page that runs at 60 fps on a desktop card can drop to 15 fps on a laptop's built-in one. The examples carry quality tiers (`TIERS` in `live.js`): no AO, lower pixel ratio, smaller shadow maps, panels redrawn every other frame. Find the expensive shader first: a displacement computed 5 times per vertex costs more than every tier together.+- **Warm the shaders.** `kit/warm.js` compiles every program in parallel before the first frame, so the page never freezes on first draw.+- **Keep the page under 1 MB.** Link crawlers (X, Slack) read the share card from the HTML and give up on a 15 MB page. Big models go out as files next to the page: `build.json` → `{"external": {"heavy.glb": "light.glb"}}`.++## render(t) contract++```js+import {runSim} from '../kit/runtime.js';++const DEFAULTS = {duration: 20, fps: 60, hud: {enabled: false}, director: {enabled: false}};++runSim(DEFAULTS, async ({cfg, canvas, capture}) => {+ // build the scene, precompute anything stateful+ return {render(t) { /* draw frame t from scratch */ return {}; }, resize() {}};+});+```++- `render(t)` is pure: no `Math.random` (use `rng(seed)` from `kit/util.js` at setup), no `Date`, no state carried between frames. Capture calls it at arbitrary times.+- Anything that moves by its own rules (agents, particles) is simulated once at load into typed arrays; `render` only reads them. A quantity integrated over time (the Strandbeest's crank under a changing wind) is integrated in closed form or tabulated at load.+- Every beat goes into `<name>-film/timeline.json` in seconds. The score reads the same file.+- Frame 0 is the thumbnail. It must already show the machine.++## Commands++```+node "$SKILL_DIR/sims/build.mjs" v8-film+node "$SKILL_DIR/sims/capture.mjs" v8-film --size 1600x900 --dpr 1.2 --stills beats --cols 4 --out teardown-out/v8-beats.png+node "$SKILL_DIR/sims/capture.mjs" v8-film --size 1600x900 --dpr 1.2 --still 12.5 --out teardown-out/v8-12.5.png+node "$SKILL_DIR/sims/capture.mjs" v8-film --size 1600x900 --dpr 1.2 --out teardown-out/v8-silent.mp4+python "$SKILL_DIR/run_sfx.py" "$SKILL_DIR/sims/v8-shared/score.py"+ffmpeg -y -i teardown-out/v8-silent.mp4 -i teardown-out/v8-score.wav -map 0:v -map 1:a -c:v copy -c:a aac -b:a 256k -shortest -movflags +faststart teardown-out/v8.mp4+node "$SKILL_DIR/wave.mjs" teardown-out/v8.mp4 --timeline "$SKILL_DIR/sims/v8-film/timeline.json"+```++`--size` is the CSS layout and `--dpr` multiplies it: 1600 x 900 at 1.2 gives 1920 x 1080. Capture prints the GPU it got; a software renderer means the GPU flags in `paths.mjs` did not take.++## Review loop++You cannot watch the video; you can look at frames. Never report a machine as done without reading sheets of the current render.++1. `--stills beats`: one tile per timeline beat, 0.3 s after it, each labelled `t=`.+2. Read every tile against the checklist below.+3. Zoom in: `--stills every:0.2 --from A --to B` for a transition, `--still T` for one full frame.+4. Fix, rebuild, go back to 1. Stop when a full pass finds nothing.+5. Final: `node "$SKILL_DIR/sheet.mjs" --video <final.mp4> --timeline <timeline.json>` and read that too: it shows what the encoder wrote.++Checklist:++- **The mechanism.** Every part that should touch touches; nothing passes through anything; the numbers on the panels match the pose.+- **Composition.** One focal point per frame. Nothing important within 60 px of an edge. Labels never cover the part they name.+- **Type.** Nothing clipped. The key readout reads at phone width.+- **3D.** Bloom eats detail: keep emissive layers under 1.0. Near-white surfaces blow out. Glossy metal under a low light streaks: roughness ≥ 0.45 and envMapIntensity ≈ 0.5 on big surfaces.+- **Timing.** Each state holds long enough to read: 1 s for a short phrase plus 0.25 s per word beyond three.++## three.js traps the examples already hit++- `smoothstep(a, b, x)` with `a > b` returns 0 on Windows (ANGLE/D3D). Write `1.0 - smoothstep(b, a, x)`.+- A `ShadowMaterial` or a decal a fraction of a millimetre above the floor loses the depth test inside a post-processing render target. Give it `polygonOffset`.+- A quad laid into the ground with a mirrored mapping gets culled as a back face. Use `DoubleSide`.+- One NaN pixel blacks out the whole frame through bloom. Clamp every `pow()` base in a shader.+- GTAO on a clipped (cutaway) model needs the same clipping planes on `gtao.normalMaterial`, or the cut half returns as a pale ghost.++## Sound++`sfx/` synthesises every sound in pure Python (48 kHz, reproducible) and reads the film's timeline, so sound cannot drift out of sync. `python "$SKILL_DIR/run_sfx.py" --list` shows the generators. `sample()` adds the recorded CC0 sounds in `sfx/samples/`. `sfx/score_kit.py` has the beds and accents the 3 scores use: a chord bed, a soft thud per power stroke, a motor, air under a drag.++- Every time comes from the timeline, never a typed number.+- Mastering is automatic: −14 LUFS, true peak ≤ −2 dBFS.+- Accent, never narrate: continuous motion stays silent. One key for every tonal sound.++## Taste, with numbers++- Easing: entrances `cubic-bezier(0.16, 1, 0.3, 1)`, exits `cubic-bezier(0.6, 0, 0.9, 0.35)` at half the entrance's length, state to state `cubic-bezier(0.65, 0, 0.35, 1)`. Linear only for continuous motion.+- The machine fills 60-70% of its viewport. Labels never under 34 px on a 1080 canvas.+- One accent, and it means something: the part that is working right now.+- Nothing dead-still: one element always alive.++## Credits++The kit, frame capture, sfx engine and review rules come from [whaleyxbt/claude-motion](https://github.com/whaleyxbt/claude-motion) (MIT). The recorded samples are CC0 from Freesound, trimmed by [Barty-Bart/motion-graphics](https://github.com/Barty-Bart/motion-graphics) (MIT); sources in `sfx/samples/SOURCES.md`.diff --git a/docs/cessna.jpg b/docs/cessna.jpgnew file mode 100644index 0000000..9a6f12aBinary files /dev/null and b/docs/cessna.jpg differdiff --git a/docs/strandbeest.jpg b/docs/strandbeest.jpgnew file mode 100644index 0000000..6836c85Binary files /dev/null and b/docs/strandbeest.jpg differdiff --git a/docs/v8.gif b/docs/v8.gifnew file mode 100644index 0000000..ddfc8dfBinary files /dev/null and b/docs/v8.gif differdiff --git a/package-lock.json b/package-lock.jsonnew file mode 100644index 0000000..61d09d8--- /dev/null+++ b/package-lock.json@@ -0,0 +1,545 @@+{+ "name": "teardown",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "teardown",+ "version": "1.0.0",+ "license": "MIT",+ "dependencies": {+ "@fontsource-variable/inter": "5.3.0",+ "@fontsource/jetbrains-mono": "5.3.0",+ "esbuild": "0.28.1",+ "playwright": "1.58.2",+ "three": "0.186.1"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz",+ "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz",+ "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz",+ "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz",+ "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz",+ "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz",+ "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz",+ "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz",+ "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz",+ "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==",+ "cpu": [+ "arm"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz",+ "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz",+ "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz",+ "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==",+ "cpu": [+ "loong64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz",+ "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==",+ "cpu": [+ "mips64el"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz",+ "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==",+ "cpu": [+ "ppc64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz",+ "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==",+ "cpu": [+ "riscv64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz",+ "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==",+ "cpu": [+ "s390x"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz",+ "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz",+ "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz",+ "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz",+ "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/openharmony-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz",+ "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "openharmony"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz",+ "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz",+ "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==",+ "cpu": [+ "arm64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz",+ "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==",+ "cpu": [+ "ia32"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz",+ "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==",+ "cpu": [+ "x64"+ ],+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/@fontsource-variable/inter": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",+ "integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",+ "license": "OFL-1.1",+ "funding": {+ "url": "https://github.com/sponsors/ayuhito"+ }+ },+ "node_modules/@fontsource/jetbrains-mono": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",+ "integrity": "sha512-fqDfB5I9f1p1TV486aUgB9t8zP84P0O1FtQR5Ol9vjwPy+S+EIGlVYm1cvj2W5shcZMTg2nZFdVMoH5wFu8a1A==",+ "license": "OFL-1.1",+ "funding": {+ "url": "https://github.com/sponsors/ayuhito"+ }+ },+ "node_modules/esbuild": {+ "version": "0.28.1",+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",+ "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==",+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.28.1",+ "@esbuild/android-arm": "0.28.1",+ "@esbuild/android-arm64": "0.28.1",+ "@esbuild/android-x64": "0.28.1",+ "@esbuild/darwin-arm64": "0.28.1",+ "@esbuild/darwin-x64": "0.28.1",+ "@esbuild/freebsd-arm64": "0.28.1",+ "@esbuild/freebsd-x64": "0.28.1",+ "@esbuild/linux-arm": "0.28.1",+ "@esbuild/linux-arm64": "0.28.1",+ "@esbuild/linux-ia32": "0.28.1",+ "@esbuild/linux-loong64": "0.28.1",+ "@esbuild/linux-mips64el": "0.28.1",+ "@esbuild/linux-ppc64": "0.28.1",+ "@esbuild/linux-riscv64": "0.28.1",+ "@esbuild/linux-s390x": "0.28.1",+ "@esbuild/linux-x64": "0.28.1",+ "@esbuild/netbsd-arm64": "0.28.1",+ "@esbuild/netbsd-x64": "0.28.1",+ "@esbuild/openbsd-arm64": "0.28.1",+ "@esbuild/openbsd-x64": "0.28.1",+ "@esbuild/openharmony-arm64": "0.28.1",+ "@esbuild/sunos-x64": "0.28.1",+ "@esbuild/win32-arm64": "0.28.1",+ "@esbuild/win32-ia32": "0.28.1",+ "@esbuild/win32-x64": "0.28.1"+ }+ },+ "node_modules/fsevents": {+ "version": "2.3.2",+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",+ "hasInstallScript": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ }+ },+ "node_modules/playwright": {+ "version": "1.58.2",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",+ "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.58.2"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=18"+ },+ "optionalDependencies": {+ "fsevents": "2.3.2"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.58.2",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",+ "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/three": {+ "version": "0.186.1",+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",+ "license": "MIT"+ }+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..40a6b12--- /dev/null+++ b/package.json@@ -0,0 +1,18 @@+{+ "name": "teardown",+ "version": "1.0.0",+ "private": true,+ "description": "A Claude Code skill that builds interactive 3D simulators of real machines and records them to 60 fps video.",+ "license": "MIT",+ "scripts": {+ "setup": "npm install && npx playwright install chromium",+ "build": "node sims/build.mjs"+ },+ "dependencies": {+ "@fontsource-variable/inter": "5.3.0",+ "@fontsource/jetbrains-mono": "5.3.0",+ "esbuild": "0.28.1",+ "playwright": "1.58.2",+ "three": "0.186.1"+ }+}diff --git a/paths.mjs b/paths.mjsnew file mode 100644index 0000000..265c70e--- /dev/null+++ b/paths.mjs@@ -0,0 +1,30 @@+// Paths and browser flags for the kit. Everything resolves from this folder, so the skill runs wherever it is installed.+// Override any of them with an environment variable.++import {createRequire} from 'node:module';+import path from 'node:path';+import {fileURLToPath} from 'node:url';++const ROOT = path.dirname(fileURLToPath(import.meta.url));++export const FFMPEG = process.env.FFMPEG || 'ffmpeg';+export const FFPROBE = process.env.FFPROBE || 'ffprobe';+export const PYTHON = process.env.PYTHON || (process.platform === 'win32' ? 'python' : 'python3');++// three, esbuild, fonts and playwright: `npm install` in this folder puts them here.+export const DEPS = process.env.TEARDOWN_DEPS || path.join(ROOT, 'node_modules');+// Unset: playwright uses the Chromium that `npx playwright install chromium` downloaded.+export const CHROMIUM = process.env.CHROMIUM || undefined;+// Real GPU WebGL instead of a software rasteriser. On Windows d3d11 plus --force_high_performance_gpu keeps ANGLE off+// an integrated GPU when a discrete one exists. capture.mjs prints the GPU it got on every run.+export const CHROMIUM_ARGS = [+ ...(process.platform === 'win32' ? ['--use-angle=d3d11'] : []),+ '--force_high_performance_gpu', '--ignore-gpu-blocklist', '--enable-gpu-rasterization', '--enable-webgl', '--hide-scrollbars',+];++// Builds and renders land in ./teardown-out of the folder you run from.+export const OUT = path.resolve(process.env.TEARDOWN_OUT || 'teardown-out');+export const DIST = path.join(OUT, 'dist');++export const fromDeps = (id) => createRequire(path.join(DEPS, 'x.js'))(id);+export const playwright = () => fromDeps('playwright');diff --git a/run_sfx.py b/run_sfx.pynew file mode 100644index 0000000..ff8b146--- /dev/null+++ b/run_sfx.py@@ -0,0 +1,10 @@+"""Render a cue sheet to a mastered WAV from any folder: python run_sfx.py <cues.py> | --list"""++import os+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++from sfx.__main__ import main # noqa: E402++main()diff --git a/sfx/__init__.py b/sfx/__init__.pynew file mode 100644index 0000000..d38f6b1--- /dev/null+++ b/sfx/__init__.py@@ -0,0 +1,10 @@+"""Procedural sound design for motion graphics. Pure Python stdlib, 48 kHz stereo.++ python run_sfx.py sfx/cues/effort.py render a cue sheet to WAV+ python run_sfx.py --list list the sound generators+"""++from .mix import Mix+from .synth import SR++__all__ = ["Mix", "SR"]diff --git a/sfx/__main__.py b/sfx/__main__.pynew file mode 100644index 0000000..84ebe11--- /dev/null+++ b/sfx/__main__.py@@ -0,0 +1,64 @@+"""CLI: render a cue sheet, or list the available generators."""++import argparse+import importlib.util+import inspect+import json+import os+import sys++from . import synth+from .mix import Mix+++def list_generators():+ for name, fn in inspect.getmembers(synth, inspect.isfunction):+ if fn.__module__ != synth.__name__ or name.startswith("_"):+ continue+ doc = (fn.__doc__ or "").strip().splitlines()[0] if fn.__doc__ else ""+ print(f"{name}{inspect.signature(fn)}\n {doc}")+++def load_cues(path):+ spec = importlib.util.spec_from_file_location("cues", path)+ cues = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(cues)+ if not hasattr(cues, "score"):+ sys.exit(f"{path} needs a score(mix, tl) function")+ return cues+++def main():+ ap = argparse.ArgumentParser(prog="python run_sfx.py", description="Render a cue sheet to a mastered WAV.")+ ap.add_argument("cues", nargs="?", help="cue sheet: a .py file with score(mix, tl)")+ ap.add_argument("--timeline", help="timeline JSON (default: the cue sheet's TIMELINE, else timeline.json)")+ ap.add_argument("--out", help="output WAV (default: the cue sheet's OUT, else teardown-out/<cue>.wav, or $TEARDOWN_OUT)")+ ap.add_argument("--list", action="store_true", help="list sound generators and exit")+ args = ap.parse_args()++ if args.list:+ list_generators()+ return+ if not args.cues:+ ap.error("pass a cue sheet, or --list")++ cues = load_cues(args.cues)+ # A relative TIMELINE in the cue sheet is read next to the cue sheet, so it runs from any folder.+ timeline = args.timeline or os.path.join(os.path.dirname(os.path.abspath(args.cues)), getattr(cues, "TIMELINE", "timeline.json"))+ stem = os.path.splitext(os.path.basename(args.cues))[0]+ out = args.out or getattr(cues, "OUT", os.path.join(os.environ.get("TEARDOWN_OUT", "teardown-out"), f"{stem}.wav"))+ with open(timeline, encoding="utf8") as f:+ tl = json.load(f)++ mix = Mix(tl["duration"], seed=getattr(cues, "SEED", 11))+ cues.score(mix, tl)+ stats = mix.master(target_lufs=getattr(cues, "TARGET_LUFS", -14.0))+ mix.write(out)+ print(+ f"wrote {out}: {tl['duration']}s, {mix.count} sounds, "+ f"{stats['lufs']:.1f} LUFS, true peak {stats['peak_db']:.1f} dBFS, drive {stats['drive']}"+ )+++if __name__ == "__main__":+ main()diff --git a/sfx/dsp.py b/sfx/dsp.pynew file mode 100644index 0000000..6363160--- /dev/null+++ b/sfx/dsp.py@@ -0,0 +1,453 @@+"""DSP building blocks (oscillators, filters, delays, reverb), pure Python stdlib at 48 kHz.++Used by sound scripts that need more than the one-shot generators in synth.py,+e.g. sims/engine/sound.py.++Signals are plain lists of floats. Speed comes from two tricks:++- A Python per-sample loop costs about 0.3 µs/sample and a list comprehension+ about 0.05 µs. So constant-pitch oscillators are one comprehension (the naive+ ramp) plus a sparse PolyBLEP fix-up at each wrap. Feedback delays and the+ reverb combs/allpasses run one block at a time, where the block is no longer+ than the delay, so every block depends only on earlier blocks and is a single+ comprehension.+- Filters whose state really is sequential (SVF, biquad, ladder) are tight+ loops, run only on short one-shots or on the few full-length buses that need+ them.+"""++import math++from .synth import SR++TAU = 2.0 * math.pi+_tanh = math.tanh+++# ---------------------------------------------------------------- buffers+++def zeros(n):+ return [0.0] * n+++def add(dst, src, at=0, gain=1.0):+ """dst[at:] += gain * src, in place, clipped to dst."""+ if at < 0:+ src = src[-at:]+ at = 0+ end = min(len(dst), at + len(src))+ if end <= at:+ return+ seg = dst[at:end]+ if gain == 1.0:+ dst[at:end] = [a + b for a, b in zip(seg, src)]+ else:+ dst[at:end] = [a + b * gain for a, b in zip(seg, src)]+++def scaled(x, g):+ return [v * g for v in x]+++def mul(x, y):+ return [a * b for a, b in zip(x, y)]+++def summed(a, b):+ return [p + q for p, q in zip(a, b)]+++def rms(x):+ return math.sqrt(sum(v * v for v in x) / len(x)) if x else 0.0+++def peak(x):+ return max(max(x), -min(x)) if x else 0.0+++def pan_gains(pan):+ """Equal-power pan, -1 left .. +1 right."""+ ang = (pan + 1.0) * math.pi / 4.0+ return math.cos(ang), math.sin(ang)+++def fade(x, fin=0, fout=0):+ """Linear fade in/out over fin/fout samples, in place."""+ n = len(x)+ fin, fout = min(fin, n), min(fout, n)+ for i in range(fin):+ x[i] *= i / fin+ for i in range(fout):+ x[n - 1 - i] *= i / fout+ return x+++# ------------------------------------------------------------ oscillators+++def _blep(out, phase, dt, n, h=1.0):+ """Subtract the PolyBLEP residual at every wrap of the ramp phase + i*dt (downward jump 2h)."""+ k = 1+ while True:+ j = math.ceil((k - phase) / dt)+ # float guard: make j the first sample whose wrapped phase is small+ if j < n and (phase + j * dt) % 1.0 > 0.5:+ j += 1+ if j >= 1 and (phase + (j - 1) * dt) % 1.0 < 0.5:+ j -= 1+ if j - 1 >= n:+ break+ if 0 <= j < n:+ u = ((phase + j * dt) % 1.0) / dt+ if u < 1.0:+ out[j] -= h * (u + u - u * u - 1.0)+ if 1 <= j <= n:+ u = (((phase + (j - 1) * dt) % 1.0) - 1.0) / dt+ if u > -1.0:+ out[j - 1] -= h * (u * u + u + u + 1.0)+ k += 1+++def saw(freq, n, phase=0.0):+ """Band-limited sawtooth (PolyBLEP) at constant freq, -1..1."""+ dt = freq / SR+ phase %= 1.0+ out = [2.0 * ((phase + i * dt) % 1.0) - 1.0 for i in range(n)]+ if 0.0 < dt < 0.5:+ _blep(out, phase, dt, n)+ return out+++def pulse(freq, n, width=0.5, phase=0.0):+ """Band-limited pulse as the difference of two PolyBLEP saws; zero mean."""+ a = saw(freq, n, phase)+ b = saw(freq, n, phase + width)+ return [p - q for p, q in zip(a, b)]+++def sine(freq, n, phase=0.0):+ w = TAU * freq / SR+ ph = TAU * phase+ sin = math.sin+ return [sin(ph + w * i) for i in range(n)]+++def noise(rng, n):+ r = rng.random+ return [2.0 * r() - 1.0 for _ in range(n)]+++# ---------------------------------------------------------------- filters+++def _norm(b0, b1, b2, a0, a1, a2):+ return (b0 / a0, b1 / a0, b2 / a0, a1 / a0, a2 / a0)+++def lp(fc, q=0.7071):+ w = TAU * min(fc, 0.45 * SR) / SR+ c, al = math.cos(w), math.sin(w) / (2 * q)+ return _norm((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + al, -2 * c, 1 - al)+++def hp(fc, q=0.7071):+ w = TAU * min(fc, 0.45 * SR) / SR+ c, al = math.cos(w), math.sin(w) / (2 * q)+ return _norm((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + al, -2 * c, 1 - al)+++def bp(fc, q=1.0):+ w = TAU * min(fc, 0.45 * SR) / SR+ c, al = math.cos(w), math.sin(w) / (2 * q)+ return _norm(al, 0.0, -al, 1 + al, -2 * c, 1 - al)+++def peaking(fc, q, db):+ a = 10 ** (db / 40)+ w = TAU * min(fc, 0.45 * SR) / SR+ c, al = math.cos(w), math.sin(w) / (2 * q)+ return _norm(1 + al * a, -2 * c, 1 - al * a, 1 + al / a, -2 * c, 1 - al / a)+++def shelf(fc, db, high=True):+ a = 10 ** (db / 40)+ w = TAU * min(fc, 0.45 * SR) / SR+ c, s = math.cos(w), math.sin(w)+ al = s / 2 * math.sqrt(2)+ sa = 2 * math.sqrt(a) * al+ if high:+ return _norm(+ a * ((a + 1) + (a - 1) * c + sa), -2 * a * ((a - 1) + (a + 1) * c), a * ((a + 1) + (a - 1) * c - sa),+ (a + 1) - (a - 1) * c + sa, 2 * ((a - 1) - (a + 1) * c), (a + 1) - (a - 1) * c - sa,+ )+ return _norm(+ a * ((a + 1) - (a - 1) * c + sa), 2 * a * ((a - 1) - (a + 1) * c), a * ((a + 1) - (a - 1) * c - sa),+ (a + 1) + (a - 1) * c + sa, -2 * ((a - 1) + (a + 1) * c), (a + 1) + (a - 1) * c - sa,+ )+++def biquad(x, c):+ """Static biquad (transposed direct form II); c from lp/hp/bp/peaking/shelf."""+ b0, b1, b2, a1, a2 = c+ z1 = z2 = 0.0+ out = [0.0] * len(x)+ i = 0+ for v in x:+ y = b0 * v + z1+ z1 = b1 * v - a1 * y + z2+ z2 = b2 * v - a2 * y+ out[i] = y+ i += 1+ return out+++def svf(x, fc, q=0.7071, mode="lp", ctrl=32):+ """Zero-delay-feedback state-variable filter (Cytomic/Simper), stable under fast modulation.++ fc: Hz, or a function of the sample index evaluated every `ctrl` samples.+ mode: 'lp', 'bp' or 'hp'.+ """+ n = len(x)+ out = [0.0] * n+ k = 1.0 / q+ ic1 = ic2 = 0.0+ const = not callable(fc)+ if const:+ ctrl = max(n, 1)+ tan = math.tan+ pis = math.pi / SR+ for s in range(0, n, ctrl):+ f = fc if const else fc(s)+ f = 10.0 if f < 10.0 else 20000.0 if f > 20000.0 else f+ g = tan(pis * f)+ a1 = 1.0 / (1.0 + g * (g + k))+ a2 = g * a1+ a3 = g * a2+ e = s + ctrl if s + ctrl < n else n+ if mode == "lp":+ for i in range(s, e):+ v3 = x[i] - ic2+ v1 = a1 * ic1 + a2 * v3+ v2 = ic2 + a2 * ic1 + a3 * v3+ ic1 = v1 + v1 - ic1+ ic2 = v2 + v2 - ic2+ out[i] = v2+ elif mode == "bp":+ for i in range(s, e):+ v3 = x[i] - ic2+ v1 = a1 * ic1 + a2 * v3+ v2 = ic2 + a2 * ic1 + a3 * v3+ ic1 = v1 + v1 - ic1+ ic2 = v2 + v2 - ic2+ out[i] = v1+ else:+ for i in range(s, e):+ xi = x[i]+ v3 = xi - ic2+ v1 = a1 * ic1 + a2 * v3+ v2 = ic2 + a2 * ic1 + a3 * v3+ ic1 = v1 + v1 - ic1+ ic2 = v2 + v2 - ic2+ out[i] = xi - k * v1 - v2+ return out+++def onepole_hp(x, fc):+ """Gentle 6 dB/oct high-pass; used as a DC blocker."""+ a = math.exp(-TAU * fc / SR)+ out = [0.0] * len(x)+ px = py = 0.0+ i = 0+ for v in x:+ py = a * (py + v - px)+ px = v+ out[i] = py+ i += 1+ return out+++def sweep(x, start, end, f0, f1, mode="lp", q=0.9, wet_in=0.0, wet_out=0.0):+ """Filter x[start:end] in place, cutoff gliding exponentially f0 -> f1.++ wet_in / wet_out (fractions of the region) crossfade from / back to the+ dry signal, so the region's edges are seamless.+ """+ start, end = max(0, start), min(len(x), end)+ n = end - start+ if n <= 0:+ return+ seg = x[start:end]+ r = f1 / f0+ y = svf(seg, lambda i: f0 * r ** (i / n), q, mode, 32)+ a = max(1, int(wet_in * n))+ b = max(1, int(wet_out * n))+ out = []+ for i in range(n):+ w = 1.0+ if wet_in and i < a:+ w = i / a+ if wet_out and i > n - b:+ w = min(w, (n - i) / b)+ out.append(seg[i] + (y[i] - seg[i]) * w)+ x[start:end] = out+++# ------------------------------------------------------- delay and reverb++_COMBS = (1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617)+_ALLPASSES = (556, 441, 341, 225)+++def _comb(x, m, fb, damp):+ """Freeverb comb, block-vectorized; the in-loop damping is a 2-tap low-pass."""+ n = len(x)+ a = fb * (1.0 - damp)+ b = fb * damp+ w = [0.0] * (n + m + 1) # w[i + m + 1] = W(i)+ for s in range(0, n, m):+ e = min(s + m, n)+ w[s + m + 1:e + m + 1] = [xi + a * p + b * q for xi, p, q in zip(x[s:e], w[s + 1:e + 1], w[s:e])]+ return w[1:n + 1]+++def _allpass(x, m, g=0.5):+ n = len(x)+ v = [0.0] * (n + m) # v[i + m] = V(i)+ for s in range(0, n, m):+ e = min(s + m, n)+ v[s + m:e + m] = [xi + g * p for xi, p in zip(x[s:e], v[s:e])]+ return [p - xi for xi, p in zip(x, v)]+++def reverb(x, size=0.7, damp=0.45, scale=1.0, spread=23):+ """Freeverb (8 combs + 4 allpasses per side): mono in, (left, right) wet out.++ size 0..1 maps to comb feedback 0.7..0.98; scale stretches every delay+ (0.3 = small room, 1.5 = hall). Output is roughly level-matched to input.+ """+ fb = 0.7 + 0.28 * size+ r = SR / 44100 * scale+ outs = []+ for off in (0, spread):+ acc = None+ for m in _COMBS:+ c = _comb(x, max(8, int((m + off) * r)), fb, damp)+ acc = c if acc is None else [p + q for p, q in zip(acc, c)]+ for m in _ALLPASSES:+ acc = _allpass(acc, max(8, int((m + off) * r)))+ outs.append(acc)+ g = math.sqrt((1 - fb * fb) / 8.0) * 1.4+ return [v * g for v in outs[0]], [v * g for v in outs[1]]+++def pingpong(x, d, fb=0.5, damp=0.35):+ """Ping-pong delay, mono in -> (left, right) wet; first echo left at d samples, then alternating."""+ n = len(x)+ xp = [0.0] * d + x+ a = [0.0] * (n + d + 1) # a[i + d + 1] = A(i)+ b = [0.0] * (n + d + 1)+ c0 = fb * (1.0 - damp)+ c1 = fb * damp+ for s in range(0, n, d):+ e = min(s + d, n)+ av = [xi + c0 * p + c1 * q for xi, p, q in zip(xp[s:e], b[s + 1:e + 1], b[s:e])]+ bv = [c0 * p + c1 * q for p, q in zip(a[s + 1:e + 1], a[s:e])]+ a[s + d + 1:e + d + 1] = av+ b[s + d + 1:e + d + 1] = bv+ return a[d + 1:], b[d + 1:]+++# --------------------------------------------------------------- dynamics+++def softclip(x, drive=1.5):+ norm = 1.0 / _tanh(drive)+ return [_tanh(drive * v) * norm for v in x]+++def compress(left, right, thresh_db=-12.0, ratio=2.0, attack=0.01, release=0.15, knee_db=6.0, block=64):+ """Stereo-linked RMS bus compressor at control rate (one gain per block, interpolated)."""+ n = len(left)+ pw = [a * a + b * b for a, b in zip(left, right)]+ ca = math.exp(-block / (attack * SR))+ cr = math.exp(-block / (release * SR))+ slope = 1.0 / ratio - 1.0+ half = knee_db / 2+ gr = 0.0+ gains = []+ # warm the detector on the first second so the start isn't uncompressed+ for warm in (True, False):+ for s in range(0, n if not warm else min(n, SR), block):+ p = sum(pw[s:s + block]) / (2 * block)+ db = 10 * math.log10(p + 1e-12)+ over = db - thresh_db+ if over <= -half:+ want = 0.0+ elif over < half:+ want = slope * (over + half) ** 2 / (2 * knee_db)+ else:+ want = slope * over+ c = ca if want < gr else cr+ gr = c * gr + (1 - c) * want+ if not warm:+ gains.append(10 ** (gr / 20))+ ramp = [k / block for k in range(block)]+ g = []+ prev = gains[0]+ for cur in gains:+ d = cur - prev+ g.extend([prev + d * r for r in ramp])+ prev = cur+ return [a * b for a, b in zip(left, g)], [a * b for a, b in zip(right, g)]+++def mono_below(left, right, fc=120.0):+ """Collapse the side signal below fc (24 dB/oct), so the low end is mono."""+ mid = [(a + b) * 0.5 for a, b in zip(left, right)]+ side = [(a - b) * 0.5 for a, b in zip(left, right)]+ c = hp(fc)+ side = biquad(biquad(side, c), c)+ return [m + s for m, s in zip(mid, side)], [m - s for m, s in zip(mid, side)]+++# --------------------------------------------------------- glitch effects+++def crush(x, bits=8, hold=2):+ """Bit and sample-rate reduction (intentionally aliasing)."""+ q = float(2 ** (bits - 1))+ return [round(x[i - i % hold] * q) / q for i in range(len(x))]+++def stutter(x, start, slice_n, repeats, decay=0.9, edge=48):+ """Beat-repeat in place: x[start:start+slice_n] repeated `repeats` times."""+ sl = x[start:start + slice_n]+ if len(sl) < slice_n:+ return+ sl = fade(sl[:], edge, edge)+ for r in range(repeats):+ a = start + r * slice_n+ if a + slice_n > len(x):+ break+ x[a:a + slice_n] = [v * decay ** r for v in sl]+++def tapestop(x, start, n, curve=1.6):+ """Tape stop in place over x[start:start+n]: playback slows to zero."""+ seg = x[start:start + n]+ n = len(seg)+ if n < 2:+ return+ out = []+ pos = 0.0+ for i in range(n):+ j = int(pos)+ if j + 1 >= n:+ out.append(0.0)+ else:+ f = pos - j+ out.append(seg[j] + (seg[j + 1] - seg[j]) * f)+ pos += (1 - i / n) ** curve+ fade(out, 0, min(n, 480))+ x[start:start + n] = outdiff --git a/sfx/loudness.py b/sfx/loudness.pynew file mode 100644index 0000000..6dce897--- /dev/null+++ b/sfx/loudness.py@@ -0,0 +1,72 @@+"""Integrated loudness (ITU-R BS.1770-4, EBU R128 gating) for 48 kHz stereo."""++import math++# K-weighting at 48 kHz: high shelf, then high-pass (coefficients from BS.1770).+_SHELF = ((1.53512485958697, -2.69169618940638, 1.19839281085285), (-1.69065929318241, 0.73248077421585))+_HIGHPASS = ((1.0, -2.0, 1.0), (-1.99004745483398, 0.99007225036621))+++def _biquad(x, coeffs):+ (b0, b1, b2), (a1, a2) = coeffs+ y = [0.0] * len(x)+ x1 = x2 = y1 = y2 = 0.0+ for i, xi in enumerate(x):+ yi = b0 * xi + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2+ x2, x1, y2, y1 = x1, xi, y1, yi+ y[i] = yi+ return y+++def _kernels(taps=8):+ out = []+ for frac in (0.25, 0.5, 0.75):+ k = []+ for j in range(-taps + 1, taps + 1):+ d = j - frac+ k.append((j, math.sin(math.pi * d) / (math.pi * d) * 0.5 * (1 + math.cos(math.pi * d / taps))))+ out.append(k)+ return out+++_TP_KERNELS = _kernels()+++def true_peak(x, near=0.7):+ """Linear true peak: 4x windowed-sinc interpolation around samples above near × sample peak."""+ peak = max(map(abs, x)) or 0.0+ lim = near * peak+ tp = peak+ for i in range(8, len(x) - 8):+ if abs(x[i]) < lim and abs(x[i + 1]) < lim:+ continue+ for kernel in _TP_KERNELS:+ v = abs(sum(c * x[i + j] for j, c in kernel))+ if v > tp:+ tp = v+ return tp+++def integrated_lufs(left, right, sr=48000):+ """Integrated loudness in LUFS; -inf for silence."""+ if sr != 48000:+ raise ValueError("K-weighting coefficients here are for 48 kHz")+ kl = _biquad(_biquad(left, _SHELF), _HIGHPASS)+ kr = _biquad(_biquad(right, _SHELF), _HIGHPASS)++ cs = [0.0]+ acc = 0.0+ for a, b in zip(kl, kr):+ acc += a * a + b * b+ cs.append(acc)++ block, hop = int(0.4 * sr), int(0.1 * sr)+ z = [(cs[i + block] - cs[i]) / block for i in range(0, len(kl) - block + 1, hop)]+ lufs = lambda power: -0.691 + 10 * math.log10(power)++ above_abs = [p for p in z if p > 0 and lufs(p) > -70]+ if not above_abs:+ return float("-inf")+ relative = lufs(sum(above_abs) / len(above_abs)) - 10+ gated = [p for p in above_abs if lufs(p) > relative]+ return lufs(sum(gated) / len(gated))diff --git a/sfx/mix.py b/sfx/mix.pynew file mode 100644index 0000000..358294b--- /dev/null+++ b/sfx/mix.py@@ -0,0 +1,111 @@+"""Mixer: place sounds in time, master to a loudness target, write a WAV."""++import math+import os+import random+import struct+import wave++from .loudness import integrated_lufs, true_peak+from .synth import SR, key++DRIVES = (1.2, 1.5, 1.8, 2.0, 2.2, 2.5, 3.0, 4.0)+++class Mix:+ def __init__(self, duration, seed=11):+ random.seed(seed)+ self.duration = duration+ self.n = int(SR * duration)+ self.left = [0.0] * self.n+ self.right = [0.0] * self.n+ self.count = 0+ self._out = None++ def put(self, t, samples, gain=1.0, pan=0.0):+ """Place mono samples at t seconds. pan: -1 left, 0 centre, +1 right (equal power)."""+ ang = (pan + 1) * math.pi / 4+ gl, gr = gain * math.cos(ang), gain * math.sin(ang)+ i0 = int(t * SR)+ for k, s in enumerate(samples):+ i = i0 + k+ if 0 <= i < self.n:+ self.left[i] += s * gl+ self.right[i] += s * gr+ self.count += 1++ def put_stereo(self, t, left, right, gain=1.0):+ """Place a stereo pair (e.g. from synth.pad) at t seconds."""+ i0 = int(t * SR)+ for k, (a, b) in enumerate(zip(left, right)):+ i = i0 + k+ if 0 <= i < self.n:+ self.left[i] += a * gain+ self.right[i] += b * gain+ self.count += 1++ def typing(self, start, end, chars, gain=(0.16, 0.26), jitter=0.006, spread=0.3):+ """One keystroke per character, evenly spaced from start to end, humanized."""+ for k in range(chars):+ tk = start + (end - start) * k / chars+ self.put(tk + random.uniform(-jitter, jitter), key(), random.uniform(*gain), random.uniform(-spread, spread))++ def master(self, target_lufs=-14.0, ceiling_db=-2.0, fade_out=0.25):+ """Soft-clip and set gain so the mix hits target_lufs with true peak <= ceiling_db.++ Drive only rises when the ceiling would otherwise be crossed. The ceiling+ leaves room for AAC overshoot, so the muxed MP4 stays under -1 dBTP. If no+ drive reaches the target within the ceiling, the mix comes out quieter+ rather than crushed.+ """+ peak = max(max(map(abs, self.left)), max(map(abs, self.right))) or 1.0+ fade_n = int(fade_out * SR)+ fade = [1.0 if i < self.n - fade_n else (self.n - i) / fade_n for i in range(self.n)]+ ceiling = 10 ** (ceiling_db / 20)++ best = None+ for drive in DRIVES:+ norm = math.tanh(drive)+ left = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.left, fade)]+ right = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.right, fade)]+ gain = 10 ** ((target_lufs - integrated_lufs(left, right)) / 20)+ if gain > ceiling:+ continue+ tp = max(true_peak(left), true_peak(right))+ fit = min(gain, ceiling / tp)+ if best is None or fit / gain > best[0]:+ best = (fit / gain, drive, left, right, fit, tp)+ if gain * tp <= ceiling:+ break+ if best is None:+ drive = DRIVES[0]+ norm = math.tanh(drive)+ left = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.left, fade)]+ right = [math.tanh(drive * x / peak) / norm * f for x, f in zip(self.right, fade)]+ tp = max(true_peak(left), true_peak(right))+ best = (0, drive, left, right, ceiling / tp, tp)+ _, drive, left, right, gain, tp = best++ self._out = ([x * gain for x in left], [x * gain for x in right])+ lufs = integrated_lufs(*self._out)+ if lufs < target_lufs - 0.5:+ print(+ f"warning: {lufs:.1f} LUFS, short of {target_lufs}: the mix is too sparse to get louder "+ "without clipping. Add sustained sound (a pad, longer tails) or accept it quieter."+ )+ return {"lufs": lufs, "peak_db": 20 * math.log10(gain * tp), "drive": drive}++ def write(self, path):+ """Write 16-bit stereo WAV; masters with defaults first if master() wasn't called."""+ if self._out is None:+ self.master()+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)+ left, right = self._out+ with wave.open(path, "wb") as wf:+ wf.setnchannels(2)+ wf.setsampwidth(2)+ wf.setframerate(SR)+ frames = bytearray()+ for a, b in zip(left, right):+ frames += struct.pack("<hh", int(a * 32767), int(b * 32767))+ wf.writeframes(bytes(frames))diff --git a/sfx/samples/SOURCES.md b/sfx/samples/SOURCES.mdnew file mode 100644index 0000000..1d81701--- /dev/null+++ b/sfx/samples/SOURCES.md@@ -0,0 +1,23 @@+# Recorded samples++Real recordings for what synthesis does badly: keyboards, room tone, a mouth pop, a tape eject.+All 12 are CC0 1.0. Each Freesound page was checked for the CC0 licence on 2026-10-18.+Taken from the `sound-effects` skill of github.com/Barty-Bart/motion-graphics (MIT), which had already trimmed them, normalised them (one-shots to -3 dBFS peak, ambience to -35 LUFS) and encoded them as OGG.++Load one in a cue sheet with `sample("<file>")` from `sfx.synth`.++| File | Use | Author | Source |+|---|---|---|---|+| fs-447909-keyboard-typing.ogg | keyboard, 3.8 s | Breviceps | https://freesound.org/people/Breviceps/sounds/447909/ |+| fs-323432-typing.ogg | keyboard, 4 s | Alivvie | https://freesound.org/people/Alivvie/sounds/323432/ |+| fs-79388-keyboard-typing-wav.ogg | keyboard, 4 s | j1987 | https://freesound.org/people/j1987/sounds/79388/ |+| fs-416777-digital-typing-wav.ogg | digital typing, 1 s | Sky_Motion | https://freesound.org/people/Sky_Motion/sounds/416777/ |+| fs-329533-room-tone-in-an-apartment-livi.ogg | room tone, 17 s | leonelmail | https://freesound.org/people/leonelmail/sounds/329533/ |+| fs-426767-apartment-room-tone-wav.ogg | room tone, 20 s | cMilan | https://freesound.org/people/cMilan/sounds/426767/ |+| fs-329569-roomtone-bedroom-yew.ogg | room tone, 20 s | leonelmail | https://freesound.org/people/leonelmail/sounds/329569/ |+| fs-258269-mouth-pop.ogg | mouth pop | jcallison | https://freesound.org/people/jcallison/sounds/258269/ |+| fs-447910-plop.ogg | plop | Breviceps | https://freesound.org/people/Breviceps/sounds/447910/ |+| fs-824189-pop-in-sfx.ogg | pop-in | Sadiquecat | https://freesound.org/people/Sadiquecat/sounds/824189/ |+| fs-349504-triangle-open-04.ogg | triangle ding, 4 s | cabled_mess | https://freesound.org/people/cabled_mess/sounds/349504/ |+| fs-339521-vhs-rewind-forward-and-eject.ogg | VHS rewind and eject, 4 s | lucaslima | https://freesound.org/people/lucaslima/sounds/339521/ |+diff --git a/sfx/samples/fs-258269-mouth-pop.ogg b/sfx/samples/fs-258269-mouth-pop.oggnew file mode 100644index 0000000..269f578Binary files /dev/null and b/sfx/samples/fs-258269-mouth-pop.ogg differdiff --git a/sfx/samples/fs-323432-typing.ogg b/sfx/samples/fs-323432-typing.oggnew file mode 100644index 0000000..3a13e88Binary files /dev/null and b/sfx/samples/fs-323432-typing.ogg differdiff --git a/sfx/samples/fs-329533-room-tone-in-an-apartment-livi.ogg b/sfx/samples/fs-329533-room-tone-in-an-apartment-livi.oggnew file mode 100644index 0000000..aa2f3a9Binary files /dev/null and b/sfx/samples/fs-329533-room-tone-in-an-apartment-livi.ogg differdiff --git a/sfx/samples/fs-329569-roomtone-bedroom-yew.ogg b/sfx/samples/fs-329569-roomtone-bedroom-yew.oggnew file mode 100644index 0000000..8a95cf2Binary files /dev/null and b/sfx/samples/fs-329569-roomtone-bedroom-yew.ogg differdiff --git a/sfx/samples/fs-339521-vhs-rewind-forward-and-eject.ogg b/sfx/samples/fs-339521-vhs-rewind-forward-and-eject.oggnew file mode 100644index 0000000..0db8f8bBinary files /dev/null and b/sfx/samples/fs-339521-vhs-rewind-forward-and-eject.ogg differdiff --git a/sfx/samples/fs-349504-triangle-open-04.ogg b/sfx/samples/fs-349504-triangle-open-04.oggnew file mode 100644index 0000000..4fd791aBinary files /dev/null and b/sfx/samples/fs-349504-triangle-open-04.ogg differdiff --git a/sfx/samples/fs-416777-digital-typing-wav.ogg b/sfx/samples/fs-416777-digital-typing-wav.oggnew file mode 100644index 0000000..ab86f2eBinary files /dev/null and b/sfx/samples/fs-416777-digital-typing-wav.ogg differdiff --git a/sfx/samples/fs-426767-apartment-room-tone-wav.ogg b/sfx/samples/fs-426767-apartment-room-tone-wav.oggnew file mode 100644index 0000000..c10315fBinary files /dev/null and b/sfx/samples/fs-426767-apartment-room-tone-wav.ogg differdiff --git a/sfx/samples/fs-447909-keyboard-typing.ogg b/sfx/samples/fs-447909-keyboard-typing.oggnew file mode 100644index 0000000..9c3e272Binary files /dev/null and b/sfx/samples/fs-447909-keyboard-typing.ogg differdiff --git a/sfx/samples/fs-447910-plop.ogg b/sfx/samples/fs-447910-plop.oggnew file mode 100644index 0000000..fda1ba2Binary files /dev/null and b/sfx/samples/fs-447910-plop.ogg differdiff --git a/sfx/samples/fs-79388-keyboard-typing-wav.ogg b/sfx/samples/fs-79388-keyboard-typing-wav.oggnew file mode 100644index 0000000..5f52d61Binary files /dev/null and b/sfx/samples/fs-79388-keyboard-typing-wav.ogg differdiff --git a/sfx/samples/fs-824189-pop-in-sfx.ogg b/sfx/samples/fs-824189-pop-in-sfx.oggnew file mode 100644index 0000000..9388203Binary files /dev/null and b/sfx/samples/fs-824189-pop-in-sfx.ogg differdiff --git a/sfx/score_kit.py b/sfx/score_kit.pynew file mode 100644index 0000000..ad22991--- /dev/null+++ b/sfx/score_kit.py@@ -0,0 +1,206 @@+"""Shared pieces for the figure scores: a parameterised lo-fi bed and a handful of accents.++A figure's score.py imports this (it sits next to the sfx engine on sys.path when run through+run_sfx.py) and adds its own accents on the tour's seconds.+"""++import math+import os+import random++from sfx.dsp import add, reverb, svf, zeros+from sfx.synth import SR, bandnoise, bass, blip, epiano, hat, kick, snare+++def env_fade(x, fin, fout):+ n = len(x)+ a = max(1, int(fin * SR))+ b = max(1, int(fout * SR))+ for i in range(min(a, n)):+ x[i] *= i / a+ for i in range(min(b, n)):+ x[n - 1 - i] *= i / b+ return x+++def bed(dur, bpm, chords, motif=(), motif_voice="epiano", bass_pattern=((0, 1.15, 0.9), (2.5, 0.85, 0.6)),+ kicks=(0, 2.75), snares=(1, 3), hats=8, swing=0.12, drums_from=1, keys_lp=4200, crackle_level=0.0, keys_vel=0.9):+ """A looping bed: e-piano chords (one per bar), a bass line, soft drums and an optional motif every other bar.++ chords: [([note Hz, ...], root Hz), ...]. bass_pattern: (beat, length in beats, velocity). Returns stereo keys+ plus mono bass and drum stems, all faded in and out.+ """+ if os.environ.get("FIG_VARIANT"):+ # the second-upload variant: three semitones up, a touch faster, the other motif voice+ up = 2 ** (3 / 12)+ chords = [([f * up for f in notes], root * up) for notes, root in chords]+ motif = [(bt, f * up) for bt, f in motif]+ motif_voice = "blip" if motif_voice == "epiano" else "epiano"+ bpm *= 1.06+ beat = 60 / bpm+ bar = 4 * beat+ n = int(dur * SR)+ keys, low, drums = zeros(n), zeros(n), zeros(n)+ bars = int(dur / bar) + 1+ for b in range(bars):+ t = 0.12 + b * bar+ notes, root = chords[b % len(chords)]+ for i, f in enumerate(notes):+ add(keys, epiano(f, 2.9 * 84 / bpm + 0.4, keys_vel), int((t + 0.012 * i) * SR))+ if i >= 2:+ add(keys, epiano(f, 1.3, keys_vel * 0.5), int((t + 1.5 * beat + 0.01 * i) * SR))+ if b % 2 == 1:+ for bt, f in motif:+ v = epiano(f, 1.1, 0.34, 0.6) if motif_voice == "epiano" else blip(f, 0.32, 0.11)+ add(keys, v, int((t + bt * beat) * SR), 1.0 if motif_voice == "epiano" else 0.5)+ for bt, length, vel in bass_pattern:+ add(low, bass(root, length * beat, vel), int((t + bt * beat) * SR))+ if drums_from <= b < bars - 2:+ for bt in kicks:+ add(drums, kick(1.0 if bt == 0 else 0.75), int((t + bt * beat) * SR))+ for bt in snares:+ add(drums, snare(0.55), int((t + bt * beat) * SR))+ for e in range(hats):+ sw = swing * beat if (hats == 8 and e % 2) else 0.0+ add(drums, hat(0.5 if e % 2 == 0 else 0.32), int((t + e * 4 * beat / hats + sw) * SR))+ keys = svf(keys, keys_lp, 0.6, "lp")+ wl, wr = reverb(keys, size=0.6, damp=0.5, scale=0.9)+ left = [k * 0.8 + w * 0.36 for k, w in zip(keys, wl)]+ right = [k * 0.8 + w * 0.36 for k, w in zip(keys, wr)]+ low = svf(low, 900, 0.7, "lp")+ drums = svf(drums, 7000, 0.6, "lp")+ for buf in (left, right, low, drums):+ env_fade(buf, 1.0, 2.2)+ return left, right, low, drums+++def thud(f=95, decay=0.12, dur=0.4):+ """A soft body hitting something: a plush toy landing, a knock."""+ n = int(dur * SR)+ return [math.sin(2 * math.pi * f * k / SR) * math.exp(-k / (decay * SR)) * min(1, k / 40) for k in range(n)]+++def motor(dur, f0=220, grit_hz=1400, wobble=17):+ """A small electric motor: a buzzy tone plus brush noise, faded at both ends."""+ n = int(dur * SR)+ grit = bandnoise(n, lambda k: grit_hz, q=0.8)+ out = []+ for k in range(n):+ t = k / SR+ m = 1 + 0.15 * math.sin(2 * math.pi * wobble * t)+ s = sum(math.sin(2 * math.pi * f0 * h * t) / h for h in (1, 2, 3, 4))+ out.append(m * (0.35 * s + 0.5 * grit[k]))+ return env_fade(out, 0.06, 0.1)+++def airy(dur, f0, f1, level=1.0):+ """Moving air: band noise sweeping from f0 to f1 with a soft swell."""+ n = int(dur * SR)+ x = bandnoise(n, lambda k: f0 * (f1 / f0) ** (k / n), q=0.7)+ return [x[k] * level * 1.4 * math.sin(math.pi * k / n) for k in range(n)]+++def bang(level=1.0, seed=0):+ """A small explosion: a low punch and a burst of dark noise."""+ rnd = random.Random(seed)+ n = int(0.42 * SR)+ noise = bandnoise(n, lambda k: 700 + 1600 * math.exp(-k / (0.03 * SR)), q=0.5)+ out = []+ ph = 0.0+ for k in range(n):+ t = k / SR+ f = 48 + 90 * math.exp(-t / 0.03)+ ph += 2 * math.pi * f / SR+ s = math.sin(ph) * math.exp(-t / 0.12) * 1.1 + noise[k] * 1.8 * math.exp(-t / 0.05)+ out.append(level * math.tanh(1.5 * s) * (0.92 + 0.08 * rnd.random()))+ return out+++def puff(level=1.0):+ """A breath of gas out of a pipe."""+ n = int(0.3 * SR)+ x = bandnoise(n, lambda k: 900, q=0.6)+ return [level * x[k] * 1.6 * math.sin(math.pi * min(1, k / (0.06 * SR)) / 2) * math.exp(-k / (0.09 * SR)) for k in range(n)]+++def rumble(dur, f_at, level=1.0):+ """An engine's low hum whose pitch follows f_at(t)."""+ n = int(dur * SR)+ out = []+ ph = 0.0+ for k in range(n):+ f = f_at(k / SR)+ ph += 2 * math.pi * f / SR+ out.append(level * (math.sin(ph) + 0.4 * math.sin(2 * ph) + 0.2 * math.sin(3 * ph)))+ return env_fade(out, 0.3, 0.4)+++_SEMI = {"C": -9, "D": -7, "E": -5, "F": -4, "G": -2, "A": 0, "B": 2}+++def hz(name):+ """Note name to frequency: "A4" = 440, "F#3", "Bb2"."""+ base, rest = name[0], name[1:]+ shift = 0+ while rest and rest[0] in "#b":+ shift += 1 if rest[0] == "#" else -1+ rest = rest[1:]+ return 440.0 * 2 ** ((_SEMI[base] + shift + 12 * (int(rest) - 4)) / 12)+++def chords(*specs):+ """chords("Fmaj7:F3 A3 C4 E4/F2", ...) -> bed() chord list; the part after / is the bass root."""+ out = []+ for spec in specs:+ notes, root = spec.split(":", 1)[1].split("/")+ out.append(([hz(n) for n in notes.split()], hz(root.strip())))+ return out+++def beep(freq, dur=0.12, level=1.0):+ """A clean electronic beep: a keypad, a timer, a piezo horn."""+ n = int(dur * SR)+ a = max(1, int(0.004 * SR))+ return [level * math.sin(2 * math.pi * freq * k / SR) * min(1, k / a, (n - k) / a) for k in range(n)]+++def rattle(dur, rate=18.0, f=3200, seed=0, level=1.0):+ """Many small hard things settling: coins in a box, shavings, capsules."""+ rnd = random.Random(seed)+ n = int(dur * SR)+ out = zeros(n)+ t = 0.0+ while t < dur:+ k = int(t * SR)+ tick = [math.sin(2 * math.pi * f * (0.7 + 0.6 * rnd.random()) * j / SR) * math.exp(-j / (0.004 * SR)) for j in range(int(0.03 * SR))]+ add(out, tick, k, level * (0.4 + 0.6 * rnd.random()) * math.sin(math.pi * min(1.0, t / dur)))+ t += rnd.expovariate(rate)+ return out+++def hiss(dur, fc=5200, level=1.0):+ """Steam or air escaping: bright band noise with a soft swell."""+ n = int(dur * SR)+ x = bandnoise(n, lambda k: fc, q=0.5)+ return [x[k] * level * 1.3 * min(1, k / (0.15 * SR), (n - k) / (0.25 * SR)) for k in range(n)]+++def spans(tl, field, pred):+ """Intervals (t0, t1) in seconds where pred(sampled value of field) holds, from a timeline made with --sample."""+ i = tl["fields"].index(field)+ rate, out, start = tl["rate"], [], None+ for k, row in enumerate(tl["samples"]):+ on = bool(pred(row[i]))+ if on and start is None:+ start = k / rate+ elif not on and start is not None:+ out.append((start, k / rate))+ start = None+ if start is not None:+ out.append((start, len(tl["samples"]) / rate))+ return out+++def rising(tl, field, pred):+ """Moments where pred(sampled value) turns true."""+ return [a for a, _ in spans(tl, field, pred)]diff --git a/sfx/synth.py b/sfx/synth.pynew file mode 100644index 0000000..28089ce--- /dev/null+++ b/sfx/synth.py@@ -0,0 +1,294 @@+"""Sound generators.++Every generator returns mono samples (a list of floats, roughly -1..1) at SR.+The first line of each docstring says what it's for; `python run_sfx.py --list`+prints them. To add a sound, write a function here in the same shape.+Use the module-level `random` for noise so renders stay reproducible.+"""++import array+import bisect+import math+import os+import random+import subprocess++SR = 48000+FFMPEG = r"C:\Users\user_\.claude\bin\ffmpeg.exe"+SAMPLES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "samples")+++def sample(name, start=0.0, dur=None):+ """Recorded sound from sfx/samples (or any path): keyboards, room tone. start/dur trim it in seconds."""+ path = name if os.path.isabs(name) else os.path.join(SAMPLES, name)+ cmd = [FFMPEG, "-v", "error", "-ss", str(start), "-i", path]+ if dur is not None:+ cmd += ["-t", str(dur)]+ cmd += ["-ac", "1", "-ar", str(SR), "-f", "s16le", "-"]+ raw = subprocess.run(cmd, check=True, capture_output=True).stdout+ pcm = array.array("h")+ pcm.frombytes(raw[: len(raw) // 2 * 2])+ return [x / 32768 for x in pcm]+++def bandnoise(n, fc_at, q=0.8):+ """Building block: white noise through a band-pass, fc_at(k) is the cutoff in Hz at sample k."""+ low = band = 0.0+ out = []+ for k in range(n):+ f = 2 * math.sin(math.pi * min(fc_at(k), SR / 6) / SR)+ x = random.uniform(-1, 1)+ low += f * band+ high = x - low - q * band+ band += f * high+ out.append(band)+ return out+++def click(freq=1800, dur=0.05):+ """UI click: a control snapping to a step, a toggle, a tick. Higher freq sounds smaller."""+ n = int(dur * SR)+ out = []+ for k in range(n):+ tt = k / SR+ s = math.sin(2 * math.pi * freq * tt) * math.exp(-tt / 0.012)+ s += random.uniform(-1, 1) * math.exp(-tt / 0.0015) * 0.6+ out.append(s)+ return out+++def key():+ """One keystroke; every call is slightly different. For typing use Mix.typing()."""+ n = int(0.018 * SR)+ fc = random.uniform(2400, 4200)+ noise = bandnoise(n, lambda k: fc, q=0.5)+ thock = random.uniform(160, 220)+ return [+ noise[k] * math.exp(-k / (0.0025 * SR)) * 2.2+ + math.sin(2 * math.pi * thock * k / SR) * math.exp(-k / (0.006 * SR)) * 0.5+ for k in range(n)+ ]+++def blip(freq, dur=0.35, tau=0.12):+ """Soft tonal blip: a word or element landing, one note of a sequence. Keep freq in key."""+ n = int(dur * SR)+ out = []+ ph = 0.0+ for k in range(n):+ tt = k / SR+ ph += 2 * math.pi * freq / SR+ a = min(1, tt / 0.003) * math.exp(-tt / tau)+ out.append(a * (math.sin(ph) + 0.25 * math.sin(2 * ph) + 0.08 * math.sin(3 * ph)))+ return out+++def pop(f0, f1, dur=0.16):+ """Pitched pop: a badge, chip or callout popping in. Sweeps f0 to f1; raise f0 across a sequence."""+ n = int(dur * SR)+ out = []+ ph = 0.0+ for k in range(n):+ tt = k / SR+ f = f0 * (f1 / f0) ** min(1, tt / 0.06)+ ph += 2 * math.pi * f / SR+ a = min(1, tt / 0.002) * math.exp(-tt / 0.045)+ out.append(a * math.sin(ph))+ return out+++def chime(freqs, dur=1.8, tau=0.7):+ """Bell chord: success, arrival, a payoff. Pass freqs from the video's key."""+ n = int(dur * SR)+ out = [0.0] * n+ for j, f in enumerate(freqs):+ ph1 = ph2 = 0.0+ g = 1.0 / (1 + j * 0.35)+ for k in range(n):+ tt = k / SR+ ph1 += 2 * math.pi * f / SR+ ph2 += 2 * math.pi * f * 2.76 / SR+ a = min(1, tt / 0.004) * math.exp(-tt / tau)+ out[k] += g * a * (math.sin(ph1) + 0.18 * math.sin(ph2) * math.exp(-tt / 0.15))+ return out+++def whoosh(dur, f0, f1, peak=0.6, q=0.9):+ """Air whoosh: movement, reveals, transitions. f0 to f1 sets direction, peak (0..1) where it's loudest."""+ n = int(dur * SR)+ p = math.log(0.5) / math.log(peak)+ noise = bandnoise(n, lambda k: f0 * (f1 / f0) ** (k / n), q=q)+ return [noise[k] * math.sin(math.pi * (k / n) ** p) ** 2 * 1.6 for k in range(n)]+++def riser(dur, f0=260, f1=5200):+ """Build-up into a payoff. End it exactly on the hit; one big riser per video."""+ n = int(dur * SR)+ noise = bandnoise(n, lambda k: f0 * (f1 / f0) ** (k / n), q=0.6)+ out = []+ ph = 0.0+ for k in range(n):+ x = k / n+ ph += 2 * math.pi * (180 * (4.0 ** x)) / SR+ tail = min(1, (n - k) / (0.02 * SR))+ out.append((noise[k] * 1.3 + 0.35 * math.sin(ph)) * x ** 2.2 * tail)+ return out+++def impact(dur=1.2):+ """Low impact for the hero moment. One per video."""+ n = int(dur * SR)+ out = []+ ph = 0.0+ lp = 0.0+ for k in range(n):+ tt = k / SR+ f = 38 + 60 * math.exp(-tt / 0.07)+ ph += 2 * math.pi * f / SR+ lp += 0.08 * (random.uniform(-1, 1) - lp)+ s = math.sin(ph) * math.exp(-tt / 0.38)+ s += lp * math.exp(-tt / 0.05) * 3.0+ out.append(math.tanh(1.6 * s))+ return out+++def scratch(dur):+ """Pencil on paper: a sketch or line drawing itself on."""+ n = int(dur * SR)+ noise = bandnoise(n, lambda k: 3800 + 1400 * math.sin(k / SR * 23), q=0.35)+ out = []+ for k in range(n):+ tt = k / SR+ stroke = max(0.0, math.sin(tt * 2 * math.pi * 7.5)) ** 3+ env = math.sin(math.pi * k / n)+ out.append(noise[k] * stroke * env * 1.4)+ return out+++def envelope(points):+ """Helper: piecewise-linear gain curve from [(t, value), ...], for pad volume and ducking."""+ pts = sorted(points)+ ts = [p[0] for p in pts]++ def at(t):+ i = bisect.bisect_right(ts, t)+ if i == 0:+ return pts[0][1]+ if i == len(pts):+ return pts[-1][1]+ (t0, v0), (t1, v1) = pts[i - 1], pts[i]+ return v0 + (v1 - v0) * (t - t0) / (t1 - t0)++ return at+++def pad(duration, chords, volume=None, detune=0.6, tremolo=0.23, xfade=0.35):+ """Music bed under everything; returns (left, right) for Mix.put_stereo. chords = [(start_s, [freqs]), ...]."""+ n = int(duration * SR)+ left = [0.0] * n+ right = [0.0] * n+ for ci, (t0, freqs) in enumerate(chords):+ t_next = chords[ci + 1][0] if ci + 1 < len(chords) else None+ i0 = int(t0 * SR)+ i1 = n if t_next is None else min(n, int((t_next + xfade) * SR))+ phl = [0.0] * len(freqs)+ phr = [0.0] * len(freqs)+ for i in range(i0, i1):+ t = i / SR+ w = 1.0 if ci == 0 else min(1.0, (t - t0) / xfade)+ if t_next is not None and t > t_next:+ w *= max(0.0, 1 - (t - t_next) / xfade)+ v = w * (volume(t) if volume else 1.0) * (0.85 + 0.15 * math.sin(2 * math.pi * tremolo * t))+ sl = sr = 0.0+ for j, f in enumerate(freqs):+ phl[j] += 2 * math.pi * (f - detune) / SR+ phr[j] += 2 * math.pi * (f + detune) / SR+ g = 1 / (1 + j * 0.5)+ sl += g * math.sin(phl[j])+ sr += g * math.sin(phr[j])+ left[i] += sl * v+ right[i] += sr * v+ return left, right+++# ---------------------------------------------------------------- a small band, for music beds+# Added 2026-10-18 for the coffee-machine film. Soft, warm, low in the mix: the bed sits under the picture,+# the accents (clicks, hiss) sit on top of it.+++def epiano(freq, dur=2.6, vel=1.0, decay=1.1):+ """Electric-piano note (tine and warm body), for lo-fi chords. Keep freq in key; vel 0..1."""+ n = int(dur * SR)+ out = [0.0] * n+ w1 = 2 * math.pi * freq / SR+ w2 = 2 * w1+ wt = 2 * math.pi * freq * 6.98 / SR+ wtrem = 2 * math.pi * 4.6 / SR+ sin = math.sin+ exp = math.exp+ for k in range(n):+ t = k / SR+ a = (t / 0.006 if t < 0.006 else 1.0) * exp(-t / decay)+ body = sin(w1 * k) + 0.28 * sin(w2 * k) * exp(-t / 0.5)+ tine = 0.16 * sin(wt * k) * exp(-t / 0.09)+ out[k] = vel * a * (body + tine) * (1 + 0.1 * sin(wtrem * k))+ tail = min(n, int(0.08 * SR))+ for i in range(tail):+ out[n - 1 - i] *= i / tail+ return out+++def bass(freq, dur=0.9, vel=1.0):+ """Round bass note: sine plus a little second harmonic, gently saturated. Roots under the chords."""+ n = int(dur * SR)+ out = [0.0] * n+ w = 2 * math.pi * freq / SR+ sin = math.sin+ exp = math.exp+ for k in range(n):+ t = k / SR+ a = (t / 0.012 if t < 0.012 else 1.0) * exp(-t / 0.45)+ out[k] = math.tanh(1.4 * vel * a * (sin(w * k) + 0.22 * sin(2 * w * k)))+ tail = min(n, int(0.05 * SR))+ for i in range(tail):+ out[n - 1 - i] *= i / tail+ return out+++def kick(vel=1.0):+ """Soft kick: a sine dropping from 110 to 46 Hz. Lo-fi, not club."""+ n = int(0.32 * SR)+ out = [0.0] * n+ ph = 0.0+ for k in range(n):+ t = k / SR+ f = 46 + 64 * math.exp(-t / 0.035)+ ph += 2 * math.pi * f / SR+ out[k] = vel * math.sin(ph) * math.exp(-t / 0.11) * min(1.0, t / 0.002)+ return out+++def snare(vel=1.0):+ """Brushed snare: band-passed noise with a short body tone, for beats 2 and 4."""+ n = int(0.22 * SR)+ noise = bandnoise(n, lambda k: 2100, q=0.55)+ return [vel * (noise[k] * 1.6 * math.exp(-k / (0.06 * SR)) + 0.25 * math.sin(2 * math.pi * 190 * k / SR) * math.exp(-k / (0.025 * SR))) for k in range(n)]+++def hat(vel=1.0):+ """Closed hat tick: high band noise, very short. Swing the off-beats."""+ n = int(0.05 * SR)+ noise = bandnoise(n, lambda k: 7600, q=0.4)+ return [vel * noise[k] * 1.8 * math.exp(-k / (0.011 * SR)) for k in range(n)]+++def crackle(dur, density=7.0, hiss=0.012):+ """Vinyl crackle bed: sparse clicks over a faint hiss. density is clicks per second."""+ n = int(dur * SR)+ out = [random.uniform(-1, 1) * hiss for _ in range(n)]+ for _ in range(int(dur * density)):+ at = random.randrange(n)+ g = random.uniform(0.05, 0.35) * random.choice((-1, 1))+ for i in range(min(40, n - at)):+ out[at + i] += g * math.exp(-i / 6.0)+ return outdiff --git a/sheet.mjs b/sheet.mjsnew file mode 100644index 0000000..ef335ca--- /dev/null+++ b/sheet.mjs@@ -0,0 +1,127 @@+#!/usr/bin/env node+// Contact sheets from any rendered video: the review loop's eyes, and the way to+// read a clip before writing timecodes about it.+//+// node sheet.mjs --video f.mp4 --timeline timeline.json every beat, settled (+0.3s)+// node sheet.mjs --video f.mp4 2.3 4.5 6.9 exact timestamps+// node sheet.mjs --video f.mp4 --every 1 one frame per second+// node sheet.mjs --video f.mp4 --from 3 --to 5 --every 0.2 scrub a transition+//+// Options: --offset 0.3 --cols 4 --rows 2 --size 540 --name beats+// Sheets land next to the video in <video>_sheets/. Every tile is labelled t=.+import {execFileSync} from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import {FFMPEG, FFPROBE} from './paths.mjs';++const argv = process.argv.slice(2);+const opt = (name, fallback) => {+ const i = argv.indexOf(`--${name}`);+ if (i === -1) return fallback;+ const v = argv[i + 1];+ argv.splice(i, 2);+ return v;+};++const video = path.resolve(opt('video', ''));+const timelinePath = opt('timeline', null);+const offset = Number(opt('offset', '0.3'));+const every = opt('every', null);+const from = Number(opt('from', '0'));+const to = opt('to', null);+const cols = Number(opt('cols', '4'));+const rows = Number(opt('rows', '2'));+const size = Number(opt('size', '540'));+let name = opt('name', null);++if (!video || !fs.existsSync(video)) {+ console.error('pass --video <file.mp4>');+ process.exit(1);+}++const probe = (args) =>+ execFileSync(FFPROBE, ['-v', 'error', ...args, '-of', 'csv=p=0', video]).toString().trim();+const duration = Number(probe(['-show_entries', 'format=duration']));++const beats = () => {+ if (!timelinePath) {+ console.error('pass timestamps, --every, or --timeline <file.json>');+ process.exit(1);+ }+ const tl = JSON.parse(fs.readFileSync(timelinePath, 'utf8'));+ const out = [];+ const walk = (v, key) => {+ if (key === 'fps' || key === 'duration') return;+ if (typeof v === 'number') out.push(v);+ else if (Array.isArray(v)) v.forEach((x) => walk(x));+ else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));+ };+ walk(tl);+ return out.map((t) => t + offset);+};++let times;+if (argv.length) {+ times = argv.map(Number);+ name ??= 'picked';+} else if (every) {+ const end = to === null ? duration : Number(to);+ times = [];+ for (let t = from; t <= end + 1e-6; t += Number(every)) times.push(Number(t.toFixed(3)));+ name ??= `every${every}`;+} else {+ times = beats();+ name ??= 'beats';+}++// ffmpeg returns no frame for a seek this close to the end of the file, so keep 50 ms off it+const eps = 0.05;+times = [...new Set(times.map((t) => Math.min(Math.max(t, 0), duration - eps).toFixed(2)))]+ .map(Number)+ .sort((a, b) => a - b);++const base = video.replace(/\.[^.]+$/, '') + '_sheets';+const dir = path.join(base, name);+fs.rmSync(dir, {recursive: true, force: true});+fs.mkdirSync(dir, {recursive: true});++const ffmpeg = (args) => execFileSync(FFMPEG, ['-loglevel', 'error', '-y', ...args], {stdio: 'pipe'});++let labels = true;+times.forEach((t, i) => {+ const file = path.join(dir, `${String(i).padStart(3, '0')}.png`);+ const scale = `scale=${size}:-2`;+ // Consolas ships with Windows; the colon in the drive letter is escaped for the filter parser.+ const label = `drawtext=fontfile='C\\:/Windows/Fonts/consola.ttf':text='t=${t.toFixed(2)}':x=10:y=10:fontsize=${Math.round(+ size / 24,+ )}:fontcolor=white:box=1:[email protected]:boxborderw=6`;+ const grab = (vf) => ffmpeg(['-ss', String(t), '-i', video, '-frames:v', '1', '-vf', vf, file]);+ if (labels) {+ try {+ grab(`${scale},${label}`);+ return;+ } catch {+ labels = false;+ console.warn('drawtext unavailable in this ffmpeg build; sheets will have no timestamps.');+ }+ }+ grab(scale);+});++const perSheet = cols * rows;+const sheets = [];+for (let s = 0; s * perSheet < times.length; s++) {+ const out = path.join(base, `${name}-${s + 1}.png`);+ ffmpeg([+ '-framerate', '1',+ '-start_number', String(s * perSheet),+ '-i', path.join(dir, '%03d.png'),+ '-vf', `tile=${cols}x${rows}:padding=6:color=0x333333`,+ '-frames:v', '1',+ out,+ ]);+ sheets.push(out);+}++console.log(`${times.length} frames from ${video} → ${sheets.length} sheet(s):`);+sheets.forEach((s) => console.log(` ${s}`));diff --git a/sims/beats.py b/sims/beats.pynew file mode 100644index 0000000..92888aa--- /dev/null+++ b/sims/beats.py@@ -0,0 +1,212 @@+#!/usr/bin/env python+"""Beat map for a music track, so a sim can cut and hit on the music.++ python sims/beats.py music/track.mp3 [--duration 30] [--start auto|SECONDS] [-o out.json]++Decodes with ffmpeg, then in pure Python:+- tempo from the autocorrelation of the onset envelope (prefers 100-160 BPM),+- the beat grid, aligned to the onsets,+- downbeats (the beat phase with the most low-band attack),+- kicks (low-band onset peaks, with strength 0..1),+- energy per bar, and the drop (the biggest sustained jump in energy).++With --start auto the 30 s window is placed so the drop lands at ~40 % of the+clip, snapped to a bar. All times in the output are relative to the window start.+"""+import argparse+import json+import math+import os+import subprocess+import sys+from array import array++FFMPEG = os.environ.get('FFMPEG', 'ffmpeg')+SR = 11025+HOP = 256+FPS = SR / HOP # envelope frames per second (~43)+++def decode(path, filt=None):+ cmd = [FFMPEG, '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR)]+ if filt:+ cmd += ['-af', filt]+ cmd += ['-f', 's16le', '-']+ raw = subprocess.run(cmd, check=True, capture_output=True).stdout+ a = array('h')+ a.frombytes(raw[: len(raw) // 2 * 2])+ return a+++def frame_energy(samples):+ n = len(samples) // HOP+ out = array('d', bytes(8 * n))+ for i in range(n):+ s = 0+ for x in samples[i * HOP:(i + 1) * HOP]:+ s += x * x+ out[i] = s / HOP+ return out+++def onset(env):+ """Positive change of log energy, lightly smoothed."""+ lg = [math.log(1e-3 + e) for e in env]+ d = [0.0] + [max(0.0, lg[i] - lg[i - 1]) for i in range(1, len(lg))]+ return [0.5 * d[i] + 0.25 * (d[i - 1] if i else 0) + 0.25 * (d[i + 1] if i + 1 < len(d) else 0)+ for i in range(len(d))]+++def tempo(nov):+ """Best period in frames from the autocorrelation, weighted toward ~126 BPM."""+ n = len(nov)+ mean = sum(nov) / n+ x = [v - mean for v in nov]+ best, best_lag = -1e18, None+ scores = {}+ lo = int(FPS * 60 / 190)+ hi = int(FPS * 60 / 70) + 1+ for lag in range(lo, hi):+ s = 0.0+ for i in range(n - lag):+ s += x[i] * x[i + lag]+ bpm = 60 * FPS / lag+ w = math.exp(-0.5 * (math.log2(bpm / 126) / 0.6) ** 2)+ scores[lag] = s+ if s * w > best:+ best, best_lag = s * w, lag+ # parabolic refinement+ l = best_lag+ if l - 1 in scores and l + 1 in scores:+ a, b, c = scores[l - 1], scores[l], scores[l + 1]+ den = a - 2 * b + c+ if den:+ l = l + 0.5 * (a - c) / den+ return l+++def beat_grid(nov, period):+ """Phase of the grid that sits on the most onset energy, then local snapping."""+ n = len(nov)+ best, best_off = -1, 0+ for off in range(int(period) + 1):+ s, k = 0.0, 0+ while True:+ i = int(round(off + k * period))+ if i >= n:+ break+ s += nov[i]+ k += 1+ if s > best:+ best, best_off = s, off+ beats = []+ while best_off - period >= 0: # grid back to the very start+ best_off -= period+ k = 0+ while True:+ c = best_off + k * period+ if c >= n:+ break+ i = int(round(c))+ lo, hi = max(0, i - 2), min(n - 1, i + 2)+ j = max(range(lo, hi + 1), key=lambda q: nov[q])+ # only snap if the peak is clearly there, else keep the grid+ beats.append(j if nov[j] > 1.5 * nov[i] + 1e-9 else i)+ k += 1+ return beats+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument('track')+ ap.add_argument('--duration', type=float, default=30)+ ap.add_argument('--start', default='auto')+ ap.add_argument('-o', '--out')+ args = ap.parse_args()++ full = decode(args.track)+ low = decode(args.track, 'lowpass=f=140,lowpass=f=140')+ total = len(full) / SR+ env = frame_energy(full)+ envl = frame_energy(low)+ nov = onset(env)+ novl = onset(envl)+ comb = [a + 1.5 * b for a, b in zip(nov, novl)]++ period = tempo(comb)+ bpm = 60 * FPS / period+ beats = beat_grid(comb, period)+ # downbeat phase: most low-band attack+ phase = max(range(4), key=lambda p: sum(novl[b] for b in beats[p::4]))+ downs = beats[phase::4]++ # kicks: low-band onset peaks above an adaptive threshold+ srt = sorted(novl)+ thr = srt[int(len(srt) * 0.9)]+ peak = max(novl) or 1+ kicks = []+ for i in range(1, len(novl) - 1):+ if novl[i] > thr and novl[i] >= novl[i - 1] and novl[i] > novl[i + 1]:+ if not kicks or i - kicks[-1][0] > FPS * 0.18:+ kicks.append((i, novl[i] / peak))++ # energy per bar+ bar_e = []+ for b in range(len(downs) - 1):+ seg = env[downs[b]:downs[b + 1]]+ bar_e.append(math.sqrt(sum(seg) / max(1, len(seg))))+ mx = max(bar_e) or 1+ bar_e = [e / mx for e in bar_e]++ # drop: biggest jump vs the previous 4 bars that holds for the next 2+ drop_bar, best = None, 0+ for b in range(4, len(bar_e) - 2):+ before = sum(bar_e[b - 4:b]) / 4+ after = min(bar_e[b:b + 2])+ j = after - before+ if j > best:+ best, drop_bar = j, b+ drop_t = downs[drop_bar] / FPS if drop_bar is not None else None++ D = args.duration+ if args.start == 'auto':+ if drop_t is not None and best > 0.12:+ want = drop_t - 0.4 * D+ else:+ # loudest window+ nb = max(1, int(D / (240 / bpm)))+ want_bar = max(range(max(1, len(bar_e) - nb)), key=lambda b: sum(bar_e[b:b + nb]))+ want = downs[want_bar] / FPS+ want = min(max(0.0, want), max(0.0, total - D))+ start = min((d / FPS for d in downs), key=lambda d: abs(d - want))+ if start + D > total:+ start = max(0.0, total - D)+ else:+ start = float(args.start)+ end = start + D++ rel = lambda f: round(f / FPS - start, 3)+ inwin = lambda f: start - 1e-6 <= f / FPS < end+ bar_starts = [d for d in downs if inwin(d)]+ out = {+ 'track': os.path.abspath(args.track),+ 'start': round(start, 3),+ 'duration': D,+ 'bpm': round(bpm, 2),+ 'beats': [rel(b) for b in beats if inwin(b)],+ 'downbeats': [rel(d) for d in bar_starts],+ 'kicks': [[rel(i), round(s, 3)] for i, s in kicks if inwin(i)],+ 'barEnergy': [round(bar_e[downs.index(d)], 3) for d in bar_starts if downs.index(d) < len(bar_e)],+ 'drop': round(drop_t - start, 3) if drop_t is not None and start <= drop_t < end else None,+ }+ path = args.out or os.path.splitext(args.track)[0] + f'.beats-{int(round(start))}.json'+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)+ with open(path, 'w') as f:+ json.dump(out, f)+ print(f'{os.path.basename(args.track)}: {out["bpm"]} bpm, window {start:.2f}-{end:.2f} s, '+ f'drop {"%.2f" % out["drop"] if out["drop"] is not None else "none"} (clip time), '+ f'{len(out["beats"])} beats, {len(out["kicks"])} kicks -> {path}')+++if __name__ == '__main__':+ sys.exit(main())diff --git a/sims/build.mjs b/sims/build.mjsnew file mode 100644index 0000000..cf9f635--- /dev/null+++ b/sims/build.mjs@@ -0,0 +1,141 @@+#!/usr/bin/env node+// Bundles every sims/<name>/main.js into one self-contained HTML file:+// teardown-out/dist/<name>.html (three.js, fonts, CSS inlined). Opens from file://,+// works offline, can be published as-is.+//+// node sims/build.mjs every example in sims/+// node sims/build.mjs v8-live one example+// node sims/build.mjs ./my-machine your own sim: any folder with a main.js. Import the kit as+// 'teardown-kit/runtime.js', 'teardown-kit/util.js' and so on.+//+// An entry may carry build.json with {"swap": {"heavy.glb": "light.glb"}}: every import of a file named heavy.glb is+// served from light.glb in the same folder (a site page with lighter models than its film). {"external": {...}} does+// the same but leaves the model out of the page: the import becomes the string "url:light.glb", the file is copied+// next to the page and listed in <name>.assets.json (the site build copies those too). The page stays small enough+// for link crawlers (X reads the share card from it). {"files": [...]} copies more files from node_modules next to the+// page the same way (decoders a loader fetches at runtime).+import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {DEPS, DIST, fromDeps} from '../paths.mjs';++const esbuild = fromDeps('esbuild');++const HERE = path.dirname(fileURLToPath(import.meta.url));+fs.mkdirSync(DIST, {recursive: true});++const font = (weight) => {+ const file = path.join(+ DEPS,+ `@fontsource/jetbrains-mono/files/jetbrains-mono-latin-${weight}-normal.woff2`,+ );+ const b64 = fs.readFileSync(file).toString('base64');+ return `@font-face{font-family:'JetBrains Mono';font-weight:${weight};font-style:normal;font-display:block;src:url(data:font/woff2;base64,${b64}) format('woff2');}`;+};+const inter = fs.readFileSync(path.join(DEPS, '@fontsource-variable/inter/files/inter-latin-wght-normal.woff2')).toString('base64');+const FONTS = [400, 600, 700].map(font).join('\n') ++ `\n@font-face{font-family:'Inter';font-weight:100 900;font-style:normal;font-display:block;src:url(data:font/woff2;base64,${inter}) format('woff2');}`;+const KIT_CSS = fs.readFileSync(path.join(HERE, 'kit/style.css'), 'utf8');++const names = process.argv.slice(2).length+ ? process.argv.slice(2)+ : fs+ .readdirSync(HERE)+ .filter((d) => fs.existsSync(path.join(HERE, d, 'main.js')));++// `teardown-kit/x.js` resolves to sims/kit/x.js, so a sim outside this folder can use the kit.+const kitPlugin = {+ name: 'teardown-kit',+ setup(b) {+ b.onResolve({filter: /^teardown-kit\//}, (args) => ({path: path.join(HERE, 'kit', args.path.slice('teardown-kit/'.length))}));+ },+};++for (const arg of names) {+ const dir = fs.existsSync(path.join(HERE, arg, 'main.js')) ? path.join(HERE, arg) : path.resolve(arg);+ if (!fs.existsSync(path.join(dir, 'main.js'))) {+ console.error(`no main.js in ${dir}`);+ process.exit(1);+ }+ const name = path.basename(dir);+ const t0 = Date.now();+ const cfgFile = path.join(dir, 'build.json');+ const bcfg = fs.existsSync(cfgFile) ? JSON.parse(fs.readFileSync(cfgFile, 'utf8')) : {};+ const swap = bcfg.swap || {};+ const external = bcfg.external || {};+ const assets = [];+ const plugins = Object.keys(external).length+ ? [+ {+ name: 'external',+ setup(b) {+ b.onResolve({filter: /\.glb$/}, (args) => {+ const base = path.basename(args.path);+ if (!external[base]) return undefined;+ const src = path.join(args.resolveDir, path.dirname(args.path), external[base]);+ if (!assets.includes(src)) assets.push(src);+ return {path: external[base], namespace: 'ext'};+ });+ b.onLoad({filter: /.*/, namespace: 'ext'}, (args) => ({contents: `export default ${JSON.stringify('url:' + args.path)};`, loader: 'js'}));+ },+ },+ ]+ : Object.keys(swap).length+ ? [+ {+ name: 'swap',+ setup(b) {+ b.onResolve({filter: /\.glb$/}, (args) => {+ const base = path.basename(args.path);+ if (!swap[base]) return undefined;+ return {path: path.join(args.resolveDir, path.dirname(args.path), swap[base])};+ });+ },+ },+ ]+ : [];+ const res = await esbuild.build({+ plugins: [kitPlugin, ...plugins],+ entryPoints: [path.join(dir, 'main.js')],+ bundle: true,+ nodePaths: [DEPS],+ format: 'esm',+ minify: !process.env.SIMS_DEBUG,+ write: false,+ target: 'es2022',+ legalComments: 'none',+ loader: {'.glb': 'base64', '.woff2': 'base64'},+ logLevel: 'warning',+ });+ const js = res.outputFiles[0].text.replace(/<\/script/g, '<\\/script');+ const css = fs.existsSync(path.join(dir, 'style.css')) ? fs.readFileSync(path.join(dir, 'style.css'), 'utf8') : '';+ const html = `<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">+<title>${name}</title>+<style>+${FONTS}+${KIT_CSS}+${css}+</style>+</head>+<body>+<div id="app"></div>+<script type="module">+${js}+</script>+</body>+</html>+`;+ const out = path.join(DIST, `${name}.html`);+ fs.writeFileSync(out, html);+ const listFile = path.join(DIST, `${name}.assets.json`);+ assets.push(...(bcfg.files || []).map((f) => path.join(DEPS, f)));+ if (assets.length) {+ for (const a of assets) fs.copyFileSync(a, path.join(DIST, path.basename(a)));+ fs.writeFileSync(listFile, JSON.stringify(assets.map((a) => path.basename(a))));+ } else if (fs.existsSync(listFile)) fs.rmSync(listFile);+ console.log(`${out} ${(html.length / 1024).toFixed(0)} KB ${Date.now() - t0} ms`);+}diff --git a/sims/capture.mjs b/sims/capture.mjsnew file mode 100644index 0000000..4a6f0eb--- /dev/null+++ b/sims/capture.mjs@@ -0,0 +1,211 @@+#!/usr/bin/env node+// Frame-accurate capture of a sim page to mp4: steps window.SIM.render(t) for+// every frame in headless Chromium, screenshots, pipes to ffmpeg, then muxes+// a music track if given.+//+// node sims/capture.mjs <name> [--config post.json] [--out teardown-out/x.mp4]+// [--size 1080x1350] [--dpr 1.3333] [--fps 60] [--from 0] [--to <duration>]+// (--size is the layout in CSS px; --dpr multiplies the output: 1080x1350+// at the default 4/3 gives a 1440x1800 video. Default 60 fps, crf 16.)+// [--music music/track.mp3 [--music-start auto|SEC] [--no-sync] [--lufs -21]] [--crf 21]+// [--still 12.5] (--still: one PNG, no video)+// [--stills 0,4,9,14 --cols 3] (tiled review sheet, every tile labelled t=)+// [--stills beats [--timeline f.json]] (one tile per timeline beat, +0.3 s so motion settles)+// [--stills every:0.2 --from 3 --to 5] (scrub a transition)+//+// <name> is a sim built into teardown-out/dist, or a path to any .html+// that exposes window.seek(seconds) and freezes its clock on ?render+// (motion-effects, vox-explainer, milestone-reveal, model-showdown). An .html+// needs --to <seconds> unless it sets window.DURATION.+import {spawn} from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {CHROMIUM, CHROMIUM_ARGS, DIST, FFMPEG, OUT, PYTHON, playwright} from '../paths.mjs';++const {chromium} = playwright();++const HERE = path.dirname(fileURLToPath(import.meta.url));+const argv = process.argv.slice(2);+const name = argv[0];+const opt = (k, d) => {+ const i = argv.indexOf(`--${k}`);+ return i === -1 ? d : argv[i + 1];+};+if (!name) {+ console.error('usage: node sims/capture.mjs <name|file.html> [--config f.json] [--out f.mp4] [--music f.wav]');+ process.exit(1);+}+const SEEK = name.endsWith('.html');+const html = SEEK ? path.resolve(name) : path.join(DIST, `${name}.html`);+const label = SEEK ? path.basename(name, '.html') : name;+if (!fs.existsSync(html)) {+ console.error(SEEK ? `missing ${html}` : `missing ${html}; run node sims/build.mjs ${name}`);+ process.exit(1);+}+const [W, H] = opt('size', '1080x1350').split('x').map(Number);+const config = opt('config') ? JSON.parse(fs.readFileSync(opt('config'), 'utf8')) : {};+// --music <file> [--music-start auto|SECONDS]: analyse the track (sims/beats.py),+// cut the window so the drop lands ~40% in, and give the beat map to the director.+const music = opt('music');+let beats = null;+if (music) {+ const dur = Number(opt('to', config.duration ?? 30)) - Number(opt('from', 0));+ const ms = opt('music-start', 'auto');+ const cache = path.join(OUT, 'beats', `${path.basename(music).replace(/\.[^.]+$/, '')}-${ms}-${dur}.json`);+ fs.mkdirSync(path.dirname(cache), {recursive: true});+ const {execFileSync} = await import('node:child_process');+ if (!fs.existsSync(cache) || fs.statSync(cache).mtimeMs < fs.statSync(music).mtimeMs) {+ execFileSync(PYTHON, ['-I', path.join(HERE, 'beats.py'), music, '--duration', String(dur), '--start', ms, '-o', cache], {stdio: 'inherit'});+ }+ beats = JSON.parse(fs.readFileSync(cache, 'utf8'));+ if (!opt('no-sync')) config.beats = beats;+}+const still = opt('still');+const stamp = new Date().toISOString().slice(5, 16).replace(/[-:T]/g, '');+const out = path.resolve(opt('out', path.join(OUT, still ? `${label}-${still}.png` : `${label}-${stamp}.mp4`)));+fs.mkdirSync(path.dirname(out), {recursive: true});++// Browser and GPU flags come from ../paths.mjs.+const exe = CHROMIUM;+const browser = await chromium.launch({+ executablePath: exe,+ args: CHROMIUM_ARGS,+});+const dpr = Number(opt('dpr', 4 / 3));+const page = await browser.newPage({viewport: {width: W, height: H}, deviceScaleFactor: dpr});+page.on('console', (m) => m.type() === 'error' && console.error('[page]', m.text()));+page.on('pageerror', (e) => console.error('[page error]', e.message));+await page.addInitScript((cfg) => {+ window.__CAPTURE = true;+ window.__SIM_CONFIG = cfg;+}, config);+await page.goto(pathToFileURL(html).href + (SEEK ? '?render' : ''));+await page.waitForFunction(+ (seek) => (seek ? typeof window.seek === 'function' : window.SIM && window.SIM.ready),+ SEEK,+ {timeout: 60000},+);+await page.evaluate(() => document.fonts.ready);+const info = await page.evaluate((seek) => {+ const gl = document.createElement('canvas').getContext('webgl2');+ const ext = gl && gl.getExtension('WEBGL_debug_renderer_info');+ return {+ duration: seek ? window.DURATION : window.SIM.duration,+ fps: seek ? window.FPS : window.SIM.fps,+ gpu: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : 'unknown',+ };+}, SEEK);+console.log(`gpu: ${info.gpu}`);+// One entry point for both contracts: a sim's SIM.render(t) or a page's seek(t).+const draw = (t) => page.evaluate(([x, seek]) => (seek ? window.seek(x) : window.SIM.render(x)), [t, SEEK]);+const end = Number(opt('to', info.duration));+if (!Number.isFinite(end)) {+ console.error('no duration: pass --to <seconds> or set window.DURATION in the page');+ process.exit(1);+}++// --stills: a list, `beats` (every number in the timeline, +0.3 s), or `every:<step>`.+const stillTimes = (arg) => {+ if (arg === 'beats') {+ const file = opt('timeline', path.join(HERE, name, 'timeline.json'));+ const tl = JSON.parse(fs.readFileSync(file, 'utf8'));+ const ts = [];+ const walk = (v, key) => {+ if (key === 'fps' || key === 'duration') return;+ if (typeof v === 'number') ts.push(v + 0.3);+ else if (Array.isArray(v)) v.forEach((x) => walk(x));+ else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));+ };+ walk(tl);+ return [0, ...ts];+ }+ if (arg.startsWith('every:')) {+ const step = Number(arg.slice(6));+ const ts = [];+ for (let t = Number(opt('from', 0)); t <= end + 1e-6; t += step) ts.push(t);+ return ts;+ }+ return arg.split(',').map(Number);+};++const stills = opt('stills');+if (stills) {+ const ts = [...new Set(stillTimes(stills).map((t) => Math.min(Math.max(t, 0), end - 1 / 120).toFixed(2)))]+ .map(Number)+ .sort((a, b) => a - b);+ const dir = out.replace(/\.(png|mp4)$/, '') + '-frames';+ fs.mkdirSync(dir, {recursive: true});+ for (const [i, t] of ts.entries()) {+ await draw(t);+ // The t= label goes into the DOM for the screenshot only, so no ffmpeg font setup is needed.+ await page.evaluate((txt) => {+ const el = document.createElement('div');+ el.id = '__t';+ el.textContent = txt;+ el.style.cssText =+ 'position:fixed;right:12px;top:12px;z-index:2147483647;font:600 28px monospace;color:#fff;background:rgba(0,0,0,.65);padding:4px 10px;border-radius:4px';+ document.body.appendChild(el);+ }, `t=${t.toFixed(2)}`);+ await page.screenshot({path: path.join(dir, `${String(i).padStart(3, '0')}.png`)});+ await page.evaluate(() => document.getElementById('__t')?.remove());+ }+ await browser.close();+ const cols = Math.min(ts.length, Number(opt('cols', 3)));+ const sheet = out.endsWith('.png') ? out : out.replace(/\.mp4$/, '') + '-sheet.png';+ const tw = Math.round(W * 0.4);+ const th = Math.round(H * 0.4);+ await new Promise((r) =>+ spawn(FFMPEG, ['-loglevel', 'error', '-y', '-framerate', '1', '-i', path.join(dir, '%03d.png'),+ '-vf', `scale=${tw}:${th},tile=${cols}x${Math.ceil(ts.length / cols)}:padding=4:color=0x333333`, '-frames:v', '1', sheet],+ {stdio: 'inherit'}).on('close', r),+ );+ console.log(`→ ${sheet} (full frames in ${dir})`);+ process.exit(0);+}++if (still !== undefined) {+ await draw(Number(still));+ await page.screenshot({path: out});+ await browser.close();+ console.log(`→ ${out}`);+ process.exit(0);+}++const fps = Number(opt('fps', 60));+const from = Number(opt('from', 0));+const to = end;+const frames = Math.round((to - from) * fps);+const silent = music ? out.replace(/\.mp4$/, '-silent.mp4') : out;++const ff = spawn(+ FFMPEG,+ ['-loglevel', 'error', '-y', '-f', 'image2pipe', '-framerate', String(fps), '-i', '-',+ '-c:v', 'libx264', '-preset', 'slow', '-crf', String(opt('crf', 16)), '-pix_fmt', 'yuv420p', '-movflags', '+faststart', silent],+ {stdio: ['pipe', 'inherit', 'inherit']},+);+const t0 = Date.now();+for (let i = 0; i < frames; i++) {+ await draw(from + i / fps);+ const buf = await page.screenshot({type: 'jpeg', quality: 97});+ if (!ff.stdin.write(buf)) await new Promise((r) => ff.stdin.once('drain', r));+ if (i % fps === 0) process.stdout.write(`\r${i}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);+}+ff.stdin.end();+await new Promise((r) => ff.on('close', r));+await browser.close();+console.log(`\r${frames}/${frames} frames ${((Date.now() - t0) / 1000).toFixed(0)} s`);++if (music) {+ await new Promise((r, j) =>+ spawn(+ FFMPEG,+ ['-loglevel', 'error', '-y', '-i', silent, '-ss', String(beats.start), '-i', music, '-map', '0:v', '-map', '1:a',+ '-c:v', 'copy', '-c:a', 'aac', '-b:a', '256k', '-af', `loudnorm=I=${opt('lufs', -21)}:TP=-3,afade=t=in:d=0.04,afade=t=out:st=${(to - from - 0.6).toFixed(2)}:d=0.6`,+ '-shortest', '-movflags', '+faststart', out],+ {stdio: 'inherit'},+ ).on('close', (c) => (c === 0 ? r() : j(new Error('mux failed')))),+ );+ fs.rmSync(silent);+}+console.log(`→ ${out}`);diff --git a/sims/cessna-film/main.js b/sims/cessna-film/main.jsnew file mode 100644index 0000000..10c87f8--- /dev/null+++ b/sims/cessna-film/main.js@@ -0,0 +1,4 @@+// CESSNA 337 SKYMASTER main landing gear film. Shared code in ../cessna-shared.+import {run} from '../cessna-shared/film.js';++run();diff --git a/sims/cessna-film/timeline.json b/sims/cessna-film/timeline.jsonnew file mode 100644index 0000000..2c07c46--- /dev/null+++ b/sims/cessna-film/timeline.json@@ -0,0 +1 @@+{"duration":26.2}diff --git a/sims/cessna-live/main.js b/sims/cessna-live/main.jsnew file mode 100644index 0000000..5d6e34c--- /dev/null+++ b/sims/cessna-live/main.js@@ -0,0 +1,5 @@+import {runLive} from '../cessna-shared/live.js';++// The Cessna 337 main landing gear as an interactive page for the site: takeoff and landing, the timeline, views,+// display modes, orbit, and an auto tour when left alone.+runLive();diff --git a/sims/cessna-shared/console.js b/sims/cessna-shared/console.jsnew file mode 100644index 0000000..c21884e--- /dev/null+++ b/sims/cessna-shared/console.js@@ -0,0 +1,288 @@+// The Skymaster gear console, laid out at 1600 x 900: the orange 337 badge and the title,+// the mechanism state with its live schematic, the flight panel, the system overview, the sequence switch, the views,+// the display toggles, the gear operation timeline, floor notes and the labels with leaders into the mechanism.+// update(s) redraws every live part from the frame's state.+export const C = {ink: '#2a2521', mute: '#9b8f80', faint: '#d9cdbb', line: '#eadfcd', panel: 'rgba(252,249,244,.95)', or: '#e3562a', green: '#2fa36b', blue: '#3c79a8'};+export const VIEWS = ['hero', 'front', 'plan', 'top', 'gearbox', 'sidetube'];+export const VIEW_LABEL = {hero: 'HERO', front: 'FRONT', plan: 'PLAN', top: 'TOP ¾', gearbox: 'GEARBOX', sidetube: 'SIDE TUBE'};+export const DISPLAY = ['labels', 'section', 'xray', 'exploded', 'fuselage', 'orbit'];+export const DISPLAY_LABEL = {labels: 'LABELS', section: 'SECTION', xray: 'X-RAY PLATE', exploded: 'EXPLODED', fuselage: 'FUSELAGE', orbit: 'ORBIT'};+const CSS = `+#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}+.ui{position:absolute;inset:0;pointer-events:none}+.mo{font-family:'JetBrains Mono',ui-monospace,monospace}+.cp{position:absolute;background:${C.panel};border:1px solid ${C.line};border-radius:6px;box-shadow:0 2px 10px rgba(120,90,50,.08)}+.ph{position:absolute;display:flex;align-items:center;gap:9px;font:700 10.5px 'JetBrains Mono',monospace;letter-spacing:1.8px}+.ph i{display:block;width:3px;height:13px;background:${C.or}}+.pn{position:absolute;font:500 9.5px 'JetBrains Mono',monospace;color:${C.mute};letter-spacing:1px}+.sm{font:500 9px 'JetBrains Mono',monospace;letter-spacing:1.6px;color:${C.mute};text-transform:uppercase;white-space:nowrap}+.bt{position:absolute;height:21px;padding:0 10px;display:flex;align-items:center;justify-content:center;border:1px solid ${C.faint};border-radius:4px;background:#fffdf9;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink};white-space:nowrap}+.call{position:absolute;white-space:nowrap}+.call b{display:flex;align-items:center;gap:6px;font:700 9.4px 'JetBrains Mono',monospace;letter-spacing:1.3px;color:${C.ink}}+.call b i{display:block;width:6px;height:6px;background:${C.or}}+.call span{display:block;font:500 7.8px 'JetBrains Mono',monospace;letter-spacing:1.2px;color:${C.mute};margin-top:2px}+.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}+.ring{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:1.5px solid ${C.or};opacity:0;z-index:49}+`;+const el = (h) => {+ const d = document.createElement('div');+ d.innerHTML = h.trim();+ return d.firstElementChild;+};++export function createConsole(app) {+ const style = document.createElement('style');+ style.textContent = CSS;+ document.head.appendChild(style);+ const ui = el(`<div class="ui"></div>`);+ app.appendChild(ui);+ const add = (h) => {+ const n = el(h);+ ui.appendChild(n);+ return n;+ };+ const panel = (x, y, w, h, title, n) => {+ add(`<div class="cp" style="left:${x}px;top:${y}px;width:${w}px;height:${h}px"></div>`);+ add(`<div class="ph" style="left:${x + 14}px;top:${y + 13}px"><i></i>${title}</div>`);+ add(`<div class="pn" style="right:${1600 - x - w + 14}px;top:${y + 15}px">${n}</div>`);+ };++ // ------------------------------------------------------------ header+ add(`<div style="position:absolute;left:0;top:0;width:160px;height:89px;background:${C.or}"></div>`);+ add(`<svg style="position:absolute;left:26px;top:30px" width="46" height="28"><g fill="#fff"><path d="M6 0h7L7 28H0z"/><path d="M19 0h7l-6 28h-7z"/><path d="M32 0h7l-6 28h-7z"/></g><circle cx="43" cy="25" r="3" fill="#fff"/></svg>`);+ add(`<div class="mo" style="position:absolute;left:85px;top:35px;color:#fff;font-size:16px;font-weight:600;letter-spacing:4px">337</div>`);+ add(`<div class="sm" style="position:absolute;left:182px;top:22px;letter-spacing:2.4px">GENERAL AVIATION</div>`);+ add(`<div style="position:absolute;left:181px;top:37px;font-size:33px;font-weight:700;letter-spacing:-.6px;line-height:1">Cessna 337 Skymaster <span style="color:${C.or};font-weight:400">/</span></div>`);+ add(`<div class="mo" style="position:absolute;left:182px;top:77px;font-size:11.2px;letter-spacing:2.2px;color:#6d6357">MAIN LANDING GEAR / RETRACTION MECHANISM</div>`);+ add(`<div class="sm" style="position:absolute;left:1087px;top:49px;letter-spacing:2.6px;font-size:9.6px">TWIN ENGINE · CENTRELINE THRUST</div>`);+ add(`<div class="mo" style="position:absolute;left:1352px;top:47px;color:${C.or};font-size:12px;letter-spacing:-1px">//////</div>`);+ add(`<div style="position:absolute;left:1418px;top:34px;color:${C.or};font-size:39px;font-weight:700;letter-spacing:-.8px;line-height:1">337</div>`);+ add(`<div style="position:absolute;left:1500px;top:33px;width:1px;height:44px;background:${C.faint}"></div>`);+ add(`<div class="sm" style="position:absolute;left:1516px;top:34px;line-height:14px;letter-spacing:2.2px">PUSH<br>PULL<br>PERFORM</div>`);+ {+ let h = '';+ for (let r = 0; r < 3; r++) for (let c = 0; c < 12; c++) h += `<path d="M${c * 25.5 + 4} ${r * 25.5}v8M${c * 25.5} ${r * 25.5 + 4}h8" stroke="${C.or}" stroke-width="1.1" opacity=".75"/>`;+ add(`<svg style="position:absolute;left:808px;top:80px" width="300" height="64">${h}</svg>`);+ }++ // ------------------------------------------------------------ 01 mechanism state+ panel(28, 126, 282, 254, 'MECHANISM STATE', '01');+ const chip = add(`<div style="position:absolute;left:42px;top:166px;width:13px;height:24px;border-radius:2px"></div>`);+ const stTitle = add(`<div style="position:absolute;left:66px;top:164px;font-size:15px;font-weight:600"></div>`);+ const stSub = add(`<div class="sm" style="position:absolute;left:67px;top:183px"></div>`);+ add(`<div style="position:absolute;left:42px;top:202px;width:254px;height:1px;background:${C.line}"></div>`);+ const sch = add(`<svg style="position:absolute;left:42px;top:214px" width="254" height="156"></svg>`);++ // ------------------------------------------------------------ 02 flight+ panel(28, 394, 282, 232, 'FLIGHT', '02');+ const fl = add(`<svg style="position:absolute;left:42px;top:430px" width="254" height="70"></svg>`);+ const bars = ['HEIGHT', 'GEAR', 'STROKE'].map((n, i) => {+ const y = 508 + i * 23;+ add(`<div class="sm" style="position:absolute;left:42px;top:${y}px">${n}</div>`);+ add(`<div style="position:absolute;left:97px;top:${y + 4}px;width:134px;height:4px;background:#efe6d8;border-radius:2px"></div>`);+ const f = add(`<div style="position:absolute;left:97px;top:${y + 4}px;height:4px;background:${C.or};border-radius:2px"></div>`);+ const v = add(`<div class="mo" style="position:absolute;right:${1600 - 296}px;top:${y - 2}px;font-size:11px;font-weight:600"></div>`);+ return {f, v};+ });+ add(`<div style="position:absolute;left:42px;top:578px;width:254px;height:1px;background:${C.line}"></div>`);+ add(`<div class="sm" style="position:absolute;left:42px;top:596px">WHEEL</div>`);+ const wheelIcon = add(`<svg style="position:absolute;left:274px;top:590px" width="22" height="22"><g data-r><circle cx="11" cy="11" r="9" fill="none" stroke="${C.blue}" stroke-width="1.5"/><path d="M11 11V2M11 11l7.8 4.5M11 11l-7.8 4.5" stroke="${C.blue}" stroke-width="1.4"/><circle cx="11" cy="11" r="2.4" fill="${C.blue}"/></g></svg>`);++ // ------------------------------------------------------------ 03 system overview+ panel(1313, 126, 258, 210, 'SYSTEM OVERVIEW', '03');+ add(`<div class="mo" style="position:absolute;left:1327px;top:163px;font-size:10.5px;font-weight:700;letter-spacing:1.6px">MAIN LANDING GEAR</div>`);+ add(`<div class="mo" style="position:absolute;left:1327px;top:183px;width:232px;font-size:9.4px;line-height:1.75;color:#5f564b">One hydraulic actuator, a single rack and pinion, and a universal joint at each end of the output shaft. The side tubes spin; they never swing.</div>`);+ add(`<div style="position:absolute;left:1327px;top:276px;width:232px;height:1px;background:${C.line}"></div>`);+ [['1', 'ACTUATOR'], ['2', 'LEGS'], ['180°', 'SWEEP']].forEach(([v, n], i) => {+ const x = 1327 + i * 85;+ if (i) add(`<div style="position:absolute;left:${x - 8}px;top:286px;width:1px;height:38px;background:${C.line}"></div>`);+ add(`<div style="position:absolute;left:${x}px;top:288px;font-size:20px;font-weight:700">${v}</div>`);+ add(`<div class="sm" style="position:absolute;left:${x}px;top:313px">${n}</div>`);+ });++ // ------------------------------------------------------------ 04 sequence, 05 views, 06 display+ const btn = {};+ panel(1313, 353, 258, 82, 'SEQUENCE', '04');+ add(`<div style="position:absolute;left:1327px;top:390px;width:230px;height:30px;border-radius:5px;background:#efe6d8"></div>`);+ btn.takeoff = add(`<div class="bt" style="left:1330px;top:393px;width:112px;height:24px;border:none;background:transparent">TAKEOFF</div>`);+ btn.landing = add(`<div class="bt" style="left:1442px;top:393px;width:112px;height:24px;border:none;background:transparent">LANDING</div>`);+ const btnRow = (keys, labels, x0, y, wmax = 230) => {+ let x = x0;+ let yy = y;+ for (const k of keys) {+ const w = Math.round(labels[k].length * 7.1 + 22);+ if (x + w > x0 + wmax) {+ x = x0;+ yy += 31;+ }+ btn[k] = add(`<div class="bt" style="left:${x}px;top:${yy}px;width:${w}px;height:23px">${labels[k]}</div>`);+ x += w + 6;+ }+ };+ panel(1313, 450, 258, 107, 'VIEWS', '05');+ btnRow(VIEWS, VIEW_LABEL, 1327, 487);+ panel(1313, 572, 258, 138, 'DISPLAY', '06');+ btnRow(DISPLAY, DISPLAY_LABEL, 1327, 609);++ // ------------------------------------------------------------ 07 gear operation+ panel(430, 752, 740, 108, 'GEAR OPERATION', '07');+ btn.play = add(`<div class="bt" style="left:445px;top:795px;width:44px;height:44px;border-radius:50%;border:none;background:${C.or};color:#fff;font-size:15px"></div>`);+ const opFrom = add(`<div class="sm" style="position:absolute;left:506px;top:791px"></div>`);+ const opPhase = add(`<div class="mo" style="position:absolute;left:506px;width:500px;top:790px;text-align:center;font-size:9.6px;font-weight:700;letter-spacing:1.6px;color:${C.or}"></div>`);+ const opTo = add(`<div class="sm" style="position:absolute;right:${1600 - 1010}px;top:791px"></div>`);+ const TL = {x: 508, w: 504};+ add(`<div style="position:absolute;left:${TL.x}px;top:820px;width:${TL.w}px;height:3px;background:#efe6d8;border-radius:2px"></div>`);+ const tlFill = add(`<div style="position:absolute;left:${TL.x}px;top:820px;height:3px;background:${C.or};border-radius:2px"></div>`);+ const tlKnob = add(`<div style="position:absolute;top:814px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#fff;border:2px solid ${C.or};box-sizing:border-box"></div>`);+ const tlTime = add(`<div class="mo" style="position:absolute;left:506px;top:834px;font-size:9.6px;color:${C.mute};letter-spacing:1px"></div>`);+ add(`<div class="sm" style="position:absolute;left:1029px;top:805px">SPEED</div>`);+ const SP = {x: 1031, w: 92};+ add(`<div style="position:absolute;left:${SP.x}px;top:823px;width:${SP.w}px;height:3px;background:#efe6d8;border-radius:2px"></div>`);+ const spFill = add(`<div style="position:absolute;left:${SP.x}px;top:823px;height:3px;background:${C.or};border-radius:2px"></div>`);+ const spKnob = add(`<div style="position:absolute;top:817px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#fff;border:2px solid ${C.or};box-sizing:border-box"></div>`);+ const spVal = add(`<div class="mo" style="position:absolute;left:1128px;top:818px;font-size:10px;font-weight:700"></div>`);++ // ------------------------------------------------------------ footer and floor notes+ add(`<div class="sm" style="position:absolute;left:27px;top:882px;letter-spacing:2.2px">MECHANISM STUDY · PROCEDURAL MODEL · SINGLE DEGREE OF FREEDOM</div>`);+ add(`<div class="sm" style="position:absolute;right:28px;top:882px;letter-spacing:2.2px">BUILT FROM THE TRACED PLATE <span style="color:${C.or}">//////</span></div>`);+ const notes = add(`<div style="position:absolute;inset:0"></div>`);+ notes.innerHTML = `<div class="sm" style="position:absolute;left:367px;top:658px;line-height:16px;letter-spacing:2px">RIGHT MAIN GEAR<br>SHOWN (TYPICAL)</div>+ <svg style="position:absolute;left:752px;top:658px" width="48" height="10"><path d="M0 5h40" stroke="${C.mute}" stroke-width="1.2"/><path d="M40 1l7 4-7 4z" fill="${C.mute}"/></svg>+ <div class="sm" style="position:absolute;left:768px;top:677px">FWD</div>+ <div class="sm" style="position:absolute;left:912px;top:682px;line-height:16px;letter-spacing:2px"><span style="color:${C.mute}">//////</span><br>MAIN LANDING GEAR<br>REV B</div>+ <div style="position:absolute;left:1046px;top:690px;font-size:28px;font-weight:700;color:rgba(155,143,128,.25)">337</div>+ <svg style="position:absolute;left:398px;top:162px" width="90" height="80"><path d="M0 80V0h80" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>+ <svg style="position:absolute;left:1088px;top:606px" width="80" height="80"><path d="M80 0v76H0" fill="none" stroke="${C.or}" stroke-width="1" stroke-dasharray="3 3" opacity=".6"/></svg>`;++ // ------------------------------------------------------------ labels, the pointer+ const callSvg = add(`<svg data-callouts style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);+ const callG = add(`<div data-callouts style="position:absolute;inset:0"></div>`);+ const ring = add(`<div class="ring"></div>`);+ const cur = add(`<div class="cur"><svg width="22" height="22" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#111" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);+ const centre = (n) => {+ const r = n.getBoundingClientRect();+ return [r.left + r.width / 2, r.top + r.height / 2];+ };+ const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));+ const pointer = (c) => {+ cur.style.display = c.x < 0 ? 'none' : 'block';+ cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;+ ring.style.left = `${c.ringX}px`;+ ring.style.top = `${c.ringY}px`;+ ring.style.opacity = String(c.ring * 0.85);+ ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;+ };+ const fmt = (s) => `00:${String(Math.floor(s)).padStart(2, '0')}`;++ return {+ spots,+ btn,+ root: ui,+ timeline: (k) => [TL.x + k * TL.w, 821],+ speedKnob: (k) => [SP.x + k * SP.w, 824],+ TL,+ SP,+ update(s) {+ // state chip and the schematic: actuator, rack, pinion, shaft, the two legs from the front+ const [title, sub, kind] = s.state;+ chip.style.background = kind === 'ok' ? C.green : C.or;+ stTitle.textContent = title;+ stSub.textContent = sub;+ {+ const d = s.stroke;+ const rx = 92 - d * 52;+ const th = s.stroke * Math.PI;+ let h = `<text x="2" y="10" font-size="7.4" letter-spacing="1" fill="${C.mute}" font-family="JetBrains Mono">ACTUATOR</text>`;+ h += `<rect x="2" y="18" width="${rx - 8}" height="17" rx="8" fill="#fbf8f2" stroke="${C.ink}" stroke-width="1.2"/>`;+ h += `<line x1="${rx - 8}" x2="${rx + 2}" y1="26.5" y2="26.5" stroke="${C.ink}" stroke-width="1.6"/><rect x="${rx}" y="14" width="7" height="27" fill="${C.or}"/>`;+ h += `<line x1="0" x2="250" y1="36.5" y2="36.5" stroke="${C.ink}" stroke-width="1"/>`;+ h += `<rect x="${rx - 70}" y="40" width="96" height="7" fill="#fbf8f2" stroke="${C.ink}" stroke-width="1"/>`;+ for (let i = 0; i < 16; i++) h += `<line x1="${rx - 68 + i * 6}" x2="${rx - 68 + i * 6}" y1="47" y2="51" stroke="${C.ink}" stroke-width=".9"/>`;+ h += `<text x="24" y="72" font-size="7.4" letter-spacing="1" fill="${C.mute}" font-family="JetBrains Mono">RACK</text><text x="134" y="76" font-size="7.4" letter-spacing="1" fill="${C.mute}" font-family="JetBrains Mono">PINION</text>`;+ h += `<g transform="translate(108 70) rotate(${((th * 180) / Math.PI).toFixed(1)})"><circle r="17" fill="none" stroke="${C.ink}" stroke-width="1.1"/>${Array.from({length: 16}, (_, i) => `<line x1="0" y1="-17" x2="0" y2="-20.5" stroke="${C.ink}" stroke-width="1" transform="rotate(${i * 22.5})"/>`).join('')}<path d="M-12 -12L12 12M12 -12L-12 12" stroke="${C.ink}" stroke-width="1"/></g>`;+ h += `<text x="96" y="104" font-size="7.4" letter-spacing="1" fill="${C.mute}" font-family="JetBrains Mono">SHAFT</text><text x="220" y="100" font-size="7.4" letter-spacing="1" fill="${C.mute}" font-family="JetBrains Mono">LEG</text>`;+ h += `<line x1="108" x2="108" y1="88" y2="150" stroke="${C.mute}" stroke-width=".8" stroke-dasharray="3 3"/>`;+ // the legs from the front: a stub out, then the leg down, folding up as the tube turns+ const leg = (sx) => {+ const x0 = 108 + sx * 46;+ const y0 = 122;+ const xa = x0 + sx * 44;+ const a = th;+ const lx = xa + sx * 6 * Math.cos(a);+ const ly = y0 + 34 * Math.cos(a);+ const lx2 = xa - sx * 30 * Math.sin(a) * 0.9;+ const X = lx * (1 - Math.sin(a)) + lx2 * Math.sin(a);+ return `<path d="M${x0} ${y0}H${xa}L${X.toFixed(1)} ${ly.toFixed(1)}" fill="none" stroke="${C.or}" stroke-width="2.6" stroke-linejoin="round"/><circle cx="${X.toFixed(1)}" cy="${ly.toFixed(1)}" r="5.5" fill="${C.or}"/><circle cx="${x0}" cy="${y0}" r="4" fill="${C.or}"/>`;+ };+ h += `<line x1="62" x2="154" y1="122" y2="122" stroke="${C.ink}" stroke-width="1.4"/>` + leg(1) + leg(-1);+ sch.innerHTML = h;+ }+ // flight: the climb or the descent, the marker where the aircraft is+ {+ const W = 254;+ const X = (u) => 20 + u * (W - 30);+ const Y = (h) => 58 - (h / 1.7) * 46;+ let p = '';+ for (let i = 0; i <= 40; i++) {+ const u = i / 40;+ const h = s.seq === 'takeoff' ? 1.7 * Math.pow(Math.max(0, (u - 0.38) / 0.62), 1.6) : 1.7 * Math.pow(Math.max(0, 1 - u / 0.74), 1.6);+ p += `${i ? 'L' : 'M'}${X(u).toFixed(1)} ${Y(h).toFixed(1)}`;+ }+ const u = s.prog;+ const mh = s.height;+ const dir = s.seq === 'takeoff' ? 1 : -1;+ const ang = (Math.atan2(-(s.climb ?? 0) * 18, 1) * 180) / Math.PI;+ fl.innerHTML = `<line x1="0" x2="${W}" y1="58" y2="58" stroke="${C.ink}" stroke-width="1"/><path d="${p}" fill="none" stroke="${C.or}" stroke-width="1.1" stroke-dasharray="3 3"/><g transform="translate(${X(u).toFixed(1)} ${Y(mh).toFixed(1)}) scale(${dir} 1) rotate(${ang.toFixed(1)})"><path d="M-10 -6L8 0L-10 6L-6 0z" fill="${C.or}"/></g>`;+ const vals = [[s.height / 1.7, `${s.height.toFixed(2)} m`], [s.stroke, `${Math.round(s.stroke * 180)}°`], [s.stroke, `${Math.round(s.stroke * 201)} mm`]];+ bars.forEach((b, i) => {+ b.f.style.width = `${(Math.min(1, vals[i][0]) * 134).toFixed(1)}px`;+ b.v.textContent = vals[i][1];+ });+ wheelIcon.querySelector('[data-r]').setAttribute('transform', `rotate(${((s.roll * 180) / Math.PI) % 360} 11 11)`);+ }+ // sequence, views, display+ const onBtn = (k, on) => {+ btn[k].style.background = on ? C.or : '#fffdf9';+ btn[k].style.color = on ? '#fff' : C.ink;+ btn[k].style.borderColor = on ? C.or : C.faint;+ };+ for (const k of ['takeoff', 'landing']) {+ const on = s.seq === k;+ btn[k].style.background = on ? C.or : 'transparent';+ btn[k].style.color = on ? '#fff' : '#8d8274';+ btn[k].style.borderRadius = '4px';+ }+ for (const k of VIEWS) onBtn(k, s.view === k);+ for (const k of DISPLAY) onBtn(k, !!s.display[k]);+ // the operation timeline+ btn.play.innerHTML = s.paused ? '▶' : '❚❚';+ opFrom.textContent = s.from;+ opTo.textContent = s.to;+ opPhase.textContent = s.phase;+ const kx = TL.x + s.prog * TL.w;+ tlFill.style.width = `${(s.prog * TL.w).toFixed(1)}px`;+ tlKnob.style.left = `${kx.toFixed(1)}px`;+ tlTime.textContent = `${fmt(s.tau)} / ${fmt(s.dur)}`;+ const sk = SP.x + s.speedK * SP.w;+ spFill.style.width = `${(s.speedK * SP.w).toFixed(1)}px`;+ spKnob.style.left = `${sk.toFixed(1)}px`;+ spVal.textContent = `${s.speed.toFixed(1)}×`;+ // labels: an orange square, the name, the note, a thin leader to the part+ let lh = '';+ let ch = '';+ for (const c of s.callouts) {+ if (c.o < 0.02 || !c.at) continue;+ const [ax, ay] = c.at;+ const [lx, ly] = c.label;+ const right = lx > ax;+ const ex = right ? lx - 6 : lx + c.w + 6;+ lh += `<polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${ex.toFixed(1)},${(ly + 6).toFixed(1)}" fill="none" stroke="${C.or}" stroke-width=".9" opacity="${c.o.toFixed(2)}"/><circle cx="${ax.toFixed(1)}" cy="${ay.toFixed(1)}" r="2.4" fill="${C.or}" opacity="${c.o.toFixed(2)}"/>`;+ ch += `<div class="call" style="left:${lx.toFixed(1)}px;top:${(ly - 1).toFixed(1)}px;opacity:${c.o.toFixed(2)}"><b><i></i>${c.name}</b><span>${c.sub}</span></div>`;+ }+ callSvg.innerHTML = lh;+ callG.innerHTML = ch;+ pointer(s.cursor);+ },+ pointer,+ };+}diff --git a/sims/cessna-shared/film.js b/sims/cessna-shared/film.jsnew file mode 100644index 0000000..51df520--- /dev/null+++ b/sims/cessna-shared/film.js@@ -0,0 +1,254 @@+// CESSNA 337 SKYMASTER, the main landing gear film: the gear (gear.js) over the runway (stage.js) under the+// reference-style console (console.js). The operator flies two takeoffs and two landings (flight.js) and walks the+// views and display modes: the airframe ghost, the gearbox close-up with the labels on, the side tube spinning, the+// front, the x-ray plate, the plan from above, the exploded set, and an orbit for the last landing. A pure function of t.+import {runSim} from '../kit/runtime.js';+import {createConsole, DISPLAY} from './console.js';+import {phaseAt, SEQ, stateAt} from './flight.js';+import {AXIS, E0, G, J, LEG0} from './gear.js';+import {createCessnaStage} from './stage.js';+import * as THREE from 'three';++export const SCRIPT = [+ {t: 0, seq: 'takeoff', view: 'hero'},+ {t: 2.4, display: 'fuselage'},+ {t: 5.4, seq: 'landing'},+ {t: 5.9, view: 'gearbox'},+ {t: 6.5, display: 'labels'},+ {t: 8.7, view: 'sidetube'},+ {t: 10.9, view: 'front'},+ {t: 11.5, display: 'xray'},+ {t: 12.7, display: 'labels'},+ {t: 13.0, seq: 'takeoff'},+ {t: 13.4, view: 'plan'},+ {t: 16.2, display: 'exploded'},+ {t: 17.8, display: 'exploded'},+ {t: 18.3, view: 'hero'},+ {t: 18.7, display: 'orbit'},+ {t: 19.1, seq: 'landing'},+];+export const DURATION = 26.2;+export const DEFAULTS = {duration: DURATION, fps: 60, theme: 'light', hud: {enabled: false, title: 'cessna', subtitle: ''}, director: {enabled: false}, watermark: ''};+const D2R = Math.PI / 180;+const smoother = (x) => {+ const u = Math.min(1, Math.max(0, x));+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));++// ------------------------------------------------------------ the sequence, the display toggles at film time t+export const seqAt = (t) => {+ const e = SCRIPT.filter((x) => x.seq && x.t <= t).pop();+ return {seq: e.seq, tau: Math.min(SEQ[e.seq].dur, t - e.t)};+};+export const displayAt = (t) => {+ const out = Object.fromEntries(DISPLAY.map((k) => [k, 0]));+ for (const e of SCRIPT) if (e.display && e.t <= t) out[e.display] = out[e.display] ? 0 : 1;+ return out;+};+const lastFlip = (key, t) => SCRIPT.filter((e) => e.display === key && e.t <= t).pop()?.t ?? -9;+// an eased 0..1 for a display toggle+export const easedDisplay = (key, t, dur = 0.7) => {+ const on = displayAt(t)[key];+ const k = ss(lastFlip(key, t), lastFlip(key, t) + dur, t);+ return on ? k : 1 - k;+};+export const mechAt = (seq, tau) => {+ const S = SEQ[seq];+ return {stroke: S.stroke(tau), height: S.height(tau), speed: S.speed(tau)};+};+// the runway distance and the wheel spin, integrated over the film+const DT = 1 / 240;+const DIST = [0];+const ROLL = [0];+{+ let w = 0;+ for (let i = 1; i * DT <= DURATION + 1; i++) {+ const t = (i - 0.5) * DT;+ const {seq, tau} = seqAt(t);+ const m = mechAt(seq, tau);+ DIST.push(DIST[i - 1] + m.speed * DT);+ // the wheels roll with the runway, coast down once airborne+ w = m.height < 0.005 ? m.speed / G.wheelR : w * Math.exp(-DT / 1.2);+ ROLL.push(ROLL[i - 1] + w * DT);+ }+}+const look = (A, t) => {+ const u = Math.max(0, Math.min(A.length - 2, t / DT));+ const i = Math.floor(u);+ return A[i] + (A[i + 1] - A[i]) * (u - i);+};+export const distAt = (t) => look(DIST, t);+export const rollAt = (t) => look(ROLL, t);++// ------------------------------------------------------------ views (target relative to the gear), u = seconds on+export const VIEW_FN = {+ hero: (u) => ({tx: 0.1, ty: -0.36, tz: 0, az: 222 + 2.5 * u, el: 21, d: 4.8, sx: 0, sy: -44}),+ front: (u) => ({tx: 0, ty: -0.36, tz: 0, az: 4 + 2 * u, el: 7, d: 4.7, sx: 0, sy: -44}),+ plan: (u) => ({tx: 0, ty: -0.1, tz: -0.1, az: 180 + 1.5 * u, el: 86, d: 4.8, sx: 0, sy: -30}),+ top: (u) => ({tx: 0, ty: -0.25, tz: 0, az: 200 + 2 * u, el: 48, d: 5.0, sx: 0, sy: -36}),+ gearbox: (u) => ({tx: 0.06, ty: -0.14, tz: 0.0, az: 238 + 3 * u, el: 8, d: 2.0, sx: 0, sy: -36}),+ sidetube: (u) => ({tx: 0.38, ty: -0.36, tz: -0.04, az: 148 + 3 * u, el: 14, d: 2.8, sx: 0, sy: -36}),+};+const VIEWS = SCRIPT.filter((e) => e.view).map((e) => [e.t, e.view]);+const blend = (a, b, k) => {+ const o = {};+ for (const key in b) o[key] = key === 'az' ? a.az + ((((b.az - a.az + 540) % 360) - 180) * k) : a[key] + (b[key] - a[key]) * k;+ const swing = Math.min(1, Math.abs(((b.az - a.az + 540) % 360) - 180) / 90);+ o.d += Math.max(0, Math.max(a.d, b.d) + 0.6 * swing - o.d) * Math.sin(Math.PI * k);+ return o;+};+export const camAt = (t, orbit = 0) => {+ let i = 0;+ while (i < VIEWS.length - 1 && VIEWS[i + 1][0] <= t) i++;+ const cur = VIEW_FN[VIEWS[i][1]](t - VIEWS[i][0]);+ let o = cur;+ if (i > 0) {+ const k = ss(VIEWS[i][0], VIEWS[i][0] + 1.6, t);+ if (k < 1) o = blend(VIEW_FN[VIEWS[i - 1][1]](t - VIEWS[i - 1][0]), cur, k);+ }+ // the orbit: a steady turn from when it came on+ if (orbit > 0) o = {...o, az: o.az + 14 * Math.max(0, t - lastFlip('orbit', t)) * orbit};+ return o;+};+export const viewAt = (t) => VIEWS.filter(([a]) => a <= t).pop();++// ------------------------------------------------------------ the operator's pointer+const REST = [[860, 470], [760, 420], [940, 520], [820, 380]];+export function makeCursor(ui) {+ const EV = SCRIPT.filter((e) => e.t > 0).flatMap((e) => {+ const out = [];+ if (e.seq) out.push({t: e.t, spot: ui.spots[e.seq]});+ if (e.view) out.push({t: e.t + (e.seq ? 0.35 : 0), spot: ui.spots[e.view]});+ if (e.display) out.push({t: e.t, spot: ui.spots[e.display]});+ return out;+ });+ const WP = [[0, 900, 600]];+ EV.forEach((e, i) => {+ WP.push([e.t - 0.16, ...e.spot], [e.t + 0.22, ...e.spot]);+ WP.push([e.t + 1.4, ...REST[i % REST.length]]);+ });+ WP.sort((a, b) => a[0] - b[0]);+ return (t) => {+ let i = 0;+ while (i < WP.length - 2 && t > WP[i + 1][0]) i++;+ const [t0, x0, y0] = WP[i];+ const [t1, x1, y1] = WP[i + 1];+ const k = ss(t0, t1, t);+ const len = Math.hypot(x1 - x0, y1 - y0);+ const bow = Math.sin(Math.PI * k) * Math.min(24, len * 0.07);+ let press = false;+ let ring = 0;+ let rx = 0;+ let ry = 0;+ for (const e of EV) {+ if (t >= e.t - 0.07 && t < e.t + 0.09) press = true;+ if (t >= e.t && t < e.t + 0.55) {+ ring = 1 - (t - e.t) / 0.55;+ [rx, ry] = e.spot;+ }+ }+ return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};+ };+}++// ------------------------------------------------------------ the labels: parts of the right gear, in the gear's frame+const V3 = THREE.Vector3;+const PARTS = [+ {name: 'HYDRAULIC ACTUATOR', sub: 'EXTENDS / RETRACTS THE GEAR', at: () => new V3(0, 0.06, -0.42)},+ {name: 'MAIN PLATE', sub: 'AIRFRAME ATTACHMENT', at: () => new V3(0.36, 0.0, 0.08)},+ {name: 'ROD-END CONNECTOR', sub: 'RUNS IN THE PLATE SLOT', at: (m) => new V3(0, 0.06, 0.32 - m.stroke * G.stroke)},+ {name: 'GEAR RACK', sub: 'ONE RACK, FORE AND AFT', at: (m) => new V3(0, -0.055, 0.12 - m.stroke * G.stroke)},+ {name: 'PINION', sub: '32 TEETH, 4 MM MODULE', at: () => new V3(0, G.shaftY - G.pinionR * 0.6, 0)},+ {name: 'ROTARY OUTPUT SHAFT', sub: 'DRIVES BOTH SIDES', at: () => new V3(-0.16, G.shaftY, 0)},+ {name: 'CLEVIS JOINT', sub: 'TRANSFERS ROTATION ONLY', at: () => J.clone()},+ {name: 'SIDE TUBE', sub: 'SPINS ABOUT ITS AXIS', at: () => J.clone().addScaledVector(AXIS, 0.17)},+ {name: 'SPRING LEG', sub: 'STEEL, FLEXES ON TOUCHDOWN', at: (m) => E0.clone().addScaledVector(LEG0, 0.22).sub(J).applyAxisAngle(AXIS, m.stroke * Math.PI).add(J)},+];+export function makeLabels(st) {+ return (m, o) => {+ if (o < 0.02) return [];+ const y0 = st.gear.root.position.y;+ const pts = PARTS.map((p) => {+ const q = p.at(m);+ const ex = m.explode ?? 0;+ return {p, at: st.project(q.x, q.y + y0, q.z), ex};+ }).filter((x) => x.at && x.at[0] > 320 && x.at[0] < 1300 && x.at[1] > 130 && x.at[1] < 745);+ // two columns, stacked by height so no two labels touch+ const L = pts.filter((x) => x.at[0] < 800).sort((a, b) => a.at[1] - b.at[1]);+ const R = pts.filter((x) => x.at[0] >= 800).sort((a, b) => a.at[1] - b.at[1]);+ const out = [];+ const stack = (col, x, w) => {+ let y = 150;+ for (const c of col) {+ y = Math.max(y, Math.min(700, c.at[1] - 10));+ out.push({name: c.p.name, sub: c.p.sub, at: c.at, label: [x, y], w, o});+ y += 34;+ }+ };+ stack(L, 340, 170);+ stack(R, 1110, 170);+ return out;+ };+}++export function makeConsoleFrame(ui, st) {+ const labels = makeLabels(st);+ return (t, s) => {+ const S = SEQ[s.seq];+ const m = s.mech;+ const climb = (S.height(Math.min(S.dur, s.tau + 0.05)) - S.height(s.tau)) / 0.05;+ ui.update({+ state: stateAt(m.stroke, m.height),+ stroke: m.stroke,+ seq: s.seq,+ prog: s.tau / S.dur,+ height: m.height,+ climb,+ roll: s.roll,+ view: s.view,+ display: s.display,+ paused: s.paused ?? false,+ from: S.from,+ to: S.to,+ phase: phaseAt(s.seq, s.tau),+ tau: s.tau,+ dur: S.dur,+ speed: s.speed ?? 1,+ speedK: s.speedK ?? 0.5,+ callouts: labels({...m, explode: s.explode}, s.labels),+ cursor: s.cursor,+ });+ };+}++export function makeFilm() {+ return async ({canvas, capture}) => {+ const st = createCessnaStage({canvas});+ const resize = () => st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));+ resize();+ const ui = createConsole(document.getElementById('app'));+ const cursorAt = makeCursor(ui);+ const frame = makeConsoleFrame(ui, st);+ window.CS = st;+ return {+ resize,+ render(t) {+ const {seq, tau} = seqAt(t);+ const m = mechAt(seq, tau);+ const disp = displayAt(t);+ const explode = easedDisplay('exploded', t, 0.8);+ const cam = camAt(t, disp.orbit);+ st.frame(+ {stroke: m.stroke, roll: rollAt(t), height: m.height, dist: distAt(t), fuselage: easedDisplay('fuselage', t) * 0.9, xray: easedDisplay('xray', t), explode, section: !!disp.section},+ {...cam, az: cam.az * D2R, el: cam.el * D2R},+ );+ const [vt0, view] = viewAt(t);+ frame(t, {seq, tau, mech: m, roll: rollAt(t), view, display: disp, explode, labels: easedDisplay('labels', t, 0.5) * ss(vt0 + 1.1, vt0 + 1.7, t), cursor: cursorAt(t)});+ return {};+ },+ };+ };+}++export const run = () => runSim(DEFAULTS, makeFilm());diff --git a/sims/cessna-shared/flight.js b/sims/cessna-shared/flight.jsnew file mode 100644index 0000000..d5b8a11--- /dev/null+++ b/sims/cessna-shared/flight.js@@ -0,0 +1,53 @@+// The two sequences the gear lives through, as functions of tau (seconds into the sequence): the takeoff (roll, lift+// off, the gear comes up) and the landing (the gear comes down, the flare, touchdown, rollout). Each gives the+// stroke (0 down, 1 up), the height above the runway, the ground speed and the phase line the console shows.+const smoother = (x) => {+ const u = Math.min(1, Math.max(0, x));+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));+export const H_MAX = 1.7;+export const V_MAX = 14;++export const SEQ = {+ takeoff: {+ dur: 5,+ from: 'RUNWAY',+ to: 'GEAR UP',+ stroke: (t) => ss(2.3, 4.5, t),+ height: (t) => H_MAX * Math.pow(ss(1.9, 5.0, t), 1.25),+ speed: (t) => V_MAX * ss(0, 2.0, t),+ phases: [+ [0, 'RUNWAY'],+ [0.6, 'TAKEOFF ROLL'],+ [1.9, 'LIFT OFF'],+ [2.3, 'ACTUATOR STROKES AFT'],+ [3.0, 'RACK TURNS THE PINION'],+ [3.6, 'SIDE TUBES SPIN THE LEGS UP'],+ [4.5, 'GEAR UP & LOCKED'],+ ],+ },+ landing: {+ dur: 7,+ from: 'GEAR UP',+ to: 'RUNWAY',+ stroke: (t) => 1 - ss(0.6, 3.0, t),+ height: (t) => H_MAX * (1 - ss(0, 5.2, t)),+ speed: (t) => V_MAX * (1 - ss(5.2, 7.0, t)),+ phases: [+ [0, 'GEAR DOWN SELECTED'],+ [0.6, 'ACTUATOR STROKES FORWARD'],+ [1.3, 'SIDE TUBES SPIN THE LEGS DOWN'],+ [3.0, 'GEAR DOWN & LOCKED'],+ [5.0, 'TOUCHDOWN'],+ [5.5, 'ROLLOUT'],+ ],+ },+};+export const phaseAt = (seq, t) => SEQ[seq].phases.filter(([a]) => a <= t).pop()[1];+/** the mechanism state chip: [title, sub, colour key] */+export const stateAt = (stroke, height) => {+ if (stroke < 0.002) return height < 0.01 ? ['Gear down & locked', 'ON THE RUNWAY', 'ok'] : ['Gear down & locked', `AIRBORNE · ${height.toFixed(2)} M`, 'ok'];+ if (stroke > 0.998) return ['Gear up & locked', `AIRBORNE · ${height.toFixed(2)} M`, 'ok'];+ return ['In transit', height < 0.01 ? 'ON THE RUNWAY' : `AIRBORNE · ${height.toFixed(2)} M`, 'move'];+};diff --git a/sims/cessna-shared/gear.js b/sims/cessna-shared/gear.jsnew file mode 100644index 0000000..9f5d3d2--- /dev/null+++ b/sims/cessna-shared/gear.js@@ -0,0 +1,364 @@+// The Cessna 337 main landing gear, built from code in metres: the white main plate with its channel rails, the+// hydraulic actuator on top, the rod-end connector and the brass gear rack, the pinion on a transverse rotary output+// shaft, a clevis (universal) joint at each end, the side tubes that spin about their own axis, the orange spring+// legs and the wheels. One degree of freedom: stroke 0..1 moves the rack 201 mm, turns the pinion 180°, and the side+// tubes carry the legs through the same 180° about their own axes. The right gear is built once; the left one is its+// mirror (scale.x = -1).+import * as THREE from 'three';+import {RoundedBoxGeometry} from 'three/addons/geometries/RoundedBoxGeometry.js';++const V3 = THREE.Vector3;+export const G = {+ pinionR: 0.064, // 32 teeth, 4 mm module+ stroke: 0.201, // rack travel for a full 180°+ wheelR: 0.205,+ wheelW: 0.135,+ shaftY: -0.1365,+ jointX: 0.22,+ tubeLen: 0.3,+ legLen: 0.5,+};+const norm = (v) => v.clone().normalize();+// the side tube's axis (outboard, down, aft) and the spring leg's direction when down and locked: half a turn about+// that axis carries the wheel from a wide stance on the runway to a pocket beside the plate, level with it, aft+export const AXIS = norm(new V3(1, -0.6, -1));+export const LEG0 = norm(new V3(1, -1, 0.8));+export const J = new V3(G.jointX, G.shaftY, 0);+export const E0 = J.clone().addScaledVector(AXIS, G.tubeLen);+export const TIP0 = E0.clone().addScaledVector(LEG0, G.legLen);+/** where the wheel centre is (right gear, assembly frame) at gear angle th (radians) */+export const tipAt = (th) => TIP0.clone().sub(J).applyAxisAngle(AXIS, th).add(J);+/** the assembly's height above the ground when down and locked: the tyre touches the runway */+export const GROUND = -(TIP0.y - G.wheelR);++// ------------------------------------------------------------ geometry+function gearGeo(teeth, rp, width, holeR = 0) {+ const ra = rp + 0.004;+ const rr = rp - 0.005;+ const sh = new THREE.Shape();+ for (let i = 0; i < teeth; i++) {+ const a0 = (i / teeth) * Math.PI * 2;+ const da = (Math.PI * 2) / teeth;+ const pts = [[rr, a0], [rr, a0 + da * 0.18], [ra, a0 + da * 0.34], [ra, a0 + da * 0.6], [rr, a0 + da * 0.76]];+ pts.forEach(([r, a], k) => (i === 0 && k === 0 ? sh.moveTo(r * Math.cos(a), r * Math.sin(a)) : sh.lineTo(r * Math.cos(a), r * Math.sin(a))));+ }+ sh.closePath();+ if (holeR) {+ const h = new THREE.Path();+ h.absarc(0, 0, holeR, 0, Math.PI * 2, true);+ sh.holes.push(h);+ }+ const g = new THREE.ExtrudeGeometry(sh, {depth: width, bevelEnabled: true, bevelThickness: 0.002, bevelSize: 0.0015, bevelSegments: 1, curveSegments: 4});+ g.translate(0, 0, -width / 2);+ return g;+}+function rackGeo(len, w, h, pitch) {+ // a bar along z with teeth on its underside+ const sh = new THREE.Shape();+ sh.moveTo(-len / 2, h / 2);+ sh.lineTo(len / 2, h / 2);+ sh.lineTo(len / 2, -h / 2);+ const n = Math.floor(len / pitch);+ for (let i = n - 1; i >= 0; i--) {+ const z0 = -len / 2 + i * pitch;+ sh.lineTo(z0 + pitch * 0.78, -h / 2);+ sh.lineTo(z0 + pitch * 0.62, -h / 2 - 0.008);+ sh.lineTo(z0 + pitch * 0.38, -h / 2 - 0.008);+ sh.lineTo(z0 + pitch * 0.22, -h / 2);+ }+ sh.lineTo(-len / 2, -h / 2);+ sh.closePath();+ const g = new THREE.ExtrudeGeometry(sh, {depth: w, bevelEnabled: true, bevelThickness: 0.002, bevelSize: 0.002, bevelSegments: 1});+ g.translate(0, 0, -w / 2);+ // shape x -> world z, shape y -> world y, depth -> world x+ g.rotateY(-Math.PI / 2);+ return g;+}+// the plate's plan form (x lateral, z fore-aft), extruded down by its thickness+function plateGeo() {+ const sh = new THREE.Shape();+ const P = [+ [-0.12, 0.62], [0.12, 0.62], [0.14, 0.32], [0.42, 0.22], [0.46, 0.12], [0.44, -0.06], [0.16, -0.16],+ [0.14, -0.78], [-0.14, -0.78], [-0.16, -0.16], [-0.44, -0.06], [-0.46, 0.12], [-0.42, 0.22], [-0.14, 0.32],+ ];+ P.forEach(([x, z], i) => (i ? sh.lineTo(x, z) : sh.moveTo(x, z)));+ sh.closePath();+ const g = new THREE.ExtrudeGeometry(sh, {depth: 0.026, bevelEnabled: true, bevelThickness: 0.004, bevelSize: 0.006, bevelSegments: 2});+ g.rotateX(Math.PI / 2);+ return g;+}+// a channel rail along z with lightening holes, its profile an upright plate+function railGeo(len, h) {+ const sh = new THREE.Shape();+ sh.moveTo(-len / 2, 0);+ sh.lineTo(len / 2, 0);+ sh.lineTo(len / 2, h * 0.7);+ sh.lineTo(len / 2 - 0.04, h);+ sh.lineTo(-len / 2 + 0.04, h);+ sh.lineTo(-len / 2, h * 0.7);+ sh.closePath();+ for (let i = 0; i < 6; i++) {+ const hole = new THREE.Path();+ hole.absarc(-len / 2 + 0.14 + i * ((len - 0.28) / 5), h * 0.48, h * 0.22, 0, Math.PI * 2, true);+ sh.holes.push(hole);+ }+ const g = new THREE.ExtrudeGeometry(sh, {depth: 0.012, bevelEnabled: true, bevelThickness: 0.002, bevelSize: 0.002, bevelSegments: 1, curveSegments: 18});+ g.translate(0, 0, -0.006);+ g.rotateY(-Math.PI / 2);+ return g;+}+// the spring leg: a flat orange bar swept from the tube end to the axle, outboard first and then down+function legGeo() {+ const tip = TIP0.clone().sub(E0);+ const out = new V3(1, 0, 0);+ const pts = [new V3(0, 0, 0), out.clone().multiplyScalar(0.12).add(new V3(0, -0.02, 0.02)), tip.clone().multiplyScalar(0.55).add(out.clone().multiplyScalar(0.1)), tip.clone().add(new V3(-0.02, 0.0, 0))];+ const curve = new THREE.CatmullRomCurve3(pts);+ const sh = new THREE.Shape();+ sh.moveTo(-0.048, -0.014);+ sh.lineTo(0.048, -0.014);+ sh.lineTo(0.048, 0.014);+ sh.lineTo(-0.048, 0.014);+ sh.closePath();+ return new THREE.ExtrudeGeometry(sh, {steps: 60, extrudePath: curve, bevelEnabled: false});+}+// a tyre: a rounded lathe profile; the sidewall lettering is a ring with a canvas texture+function tyreGeo() {+ const R = G.wheelR;+ const W = G.wheelW;+ const pts = [];+ const r0 = R * 0.55;+ for (let i = 0; i <= 24; i++) {+ const a = -Math.PI / 2 + (i / 24) * Math.PI;+ pts.push(new THREE.Vector2(R - (W / 2) * 0.55 + (W / 2) * 0.55 * Math.cos(a), (W / 2) * Math.sin(a)));+ }+ pts.unshift(new THREE.Vector2(r0, -W / 2 * 0.9));+ pts.push(new THREE.Vector2(r0, W / 2 * 0.9));+ const g = new THREE.LatheGeometry(pts, 64);+ g.rotateZ(Math.PI / 2);+ return g;+}+function letterTex() {+ const c = document.createElement('canvas');+ c.width = c.height = 1024;+ const g = c.getContext('2d');+ g.clearRect(0, 0, 1024, 1024);+ g.fillStyle = '#f4f1ea';+ g.font = '700 74px Inter, Arial, sans-serif';+ g.textAlign = 'center';+ g.textBaseline = 'middle';+ const word = 'AEROGRIP';+ for (const [a0, w] of [[-Math.PI / 2, word], [Math.PI / 2, '6.00-6 6PLY']]) {+ const span = 0.11;+ [...w].forEach((ch, i) => {+ const a = a0 + (i - (w.length - 1) / 2) * span;+ g.save();+ g.translate(512 + Math.cos(a) * 395, 512 + Math.sin(a) * 395);+ g.rotate(a + Math.PI / 2);+ g.fillText(ch, 0, 0);+ g.restore();+ });+ }+ const t = new THREE.CanvasTexture(c);+ t.colorSpace = THREE.SRGBColorSpace;+ t.anisotropy = 8;+ return t;+}++export function buildGear() {+ const M = {+ white: new THREE.MeshPhysicalMaterial({color: '#f1efea', roughness: 0.35, metalness: 0, clearcoat: 0.35, clearcoatRoughness: 0.35}),+ orange: new THREE.MeshPhysicalMaterial({color: '#e8572a', roughness: 0.32, metalness: 0.05, clearcoat: 0.5, clearcoatRoughness: 0.25}),+ black: new THREE.MeshPhysicalMaterial({color: '#17181b', roughness: 0.35, metalness: 0.2, clearcoat: 0.5}),+ rubber: new THREE.MeshStandardMaterial({color: '#1b1c1e', roughness: 0.82, metalness: 0}),+ steel: new THREE.MeshStandardMaterial({color: '#c9ccd1', roughness: 0.22, metalness: 1}),+ brass: new THREE.MeshStandardMaterial({color: '#b28a3e', roughness: 0.3, metalness: 0.9}),+ hub: new THREE.MeshStandardMaterial({color: '#b8bcc2', roughness: 0.3, metalness: 0.8}),+ plate: null,+ body: null,+ letters: new THREE.MeshStandardMaterial({map: letterTex(), transparent: true, roughness: 0.6, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2}),+ };+ // the plate (and its rails and blocks) and the actuator body get their own white so x-ray and section reach only them+ M.plate = M.white.clone();+ M.body = M.white.clone();+ const all = [];+ const add = (parent, geo, mat) => {+ const m = new THREE.Mesh(geo, mat);+ m.castShadow = true;+ m.receiveShadow = true;+ parent.add(m);+ all.push(m);+ return m;+ };+ const root = new THREE.Group();++ // ------------------------------------------------------------ plate and rails+ const plate = new THREE.Group();+ root.add(plate);+ add(plate, plateGeo(), M.plate);+ const rail = railGeo(1.1, 0.07);+ for (const x of [-0.08, 0.08]) add(plate, rail, M.plate).position.set(x, 0.004, -0.12);+ // pillow blocks under the plate carrying the output shaft+ for (const x of [-0.11, 0.11]) {+ const b = add(plate, new RoundedBoxGeometry(0.05, 0.12, 0.07, 3, 0.012), M.plate);+ b.position.set(x, -0.026 - 0.06 + 0.006, 0);+ }++ // ------------------------------------------------------------ actuator, rod end, rack+ const act = new THREE.Group();+ root.add(act);+ const AY = 0.06;+ const body = add(act, new THREE.CylinderGeometry(0.042, 0.042, 0.46, 32), M.body);+ body.rotation.x = Math.PI / 2;+ body.position.set(0, AY, -0.39);+ for (const z of [-0.6, -0.17]) {+ const band = add(act, new THREE.CylinderGeometry(0.046, 0.046, 0.03, 32), M.black);+ band.rotation.x = Math.PI / 2;+ band.position.set(0, AY, z);+ }+ const clevis = add(act, new RoundedBoxGeometry(0.06, 0.07, 0.07, 3, 0.012), M.brass);+ clevis.position.set(0, AY - 0.005, -0.66);+ const pin = add(act, new THREE.CylinderGeometry(0.012, 0.012, 0.1, 12), M.black);+ pin.rotation.z = Math.PI / 2;+ pin.position.set(0, AY - 0.005, -0.66);+ const nipple = add(act, new THREE.CylinderGeometry(0.012, 0.012, 0.03, 12), M.orange);+ nipple.position.set(0, AY + 0.05, -0.55);+ const rod = add(act, new THREE.CylinderGeometry(0.016, 0.016, 1, 20), M.steel);+ rod.rotation.x = Math.PI / 2;+ const rodEnd = new THREE.Group();+ root.add(rodEnd);+ add(rodEnd, new RoundedBoxGeometry(0.07, 0.06, 0.08, 3, 0.012), M.orange).position.y = AY;+ const web = add(rodEnd, new RoundedBoxGeometry(0.03, 0.1, 0.05, 2, 0.008), M.orange);+ web.position.y = AY - 0.06;+ for (const s of [-1, 1]) {+ const b = add(rodEnd, new THREE.CylinderGeometry(0.008, 0.008, 0.01, 10), M.black);+ b.rotation.z = Math.PI / 2;+ b.position.set(s * 0.036, AY, 0.015);+ }+ const RACK_LEN = 0.34;+ const rack = add(root, rackGeo(RACK_LEN, 0.04, 0.034, 2 * Math.PI * G.pinionR / 32), M.brass);+ const RACK_Y = G.shaftY + G.pinionR + 0.017 + 0.004;++ // ------------------------------------------------------------ pinion and output shaft+ const shaft = new THREE.Group();+ shaft.position.set(0, G.shaftY, 0);+ root.add(shaft);+ const sh = add(shaft, new THREE.CylinderGeometry(0.024, 0.024, 2 * (G.jointX - 0.03), 24), M.black);+ sh.rotation.z = Math.PI / 2;+ const pinion = add(shaft, gearGeo(32, G.pinionR, 0.036, 0.02), M.brass);+ pinion.rotation.y = Math.PI / 2;+ for (const x of [-0.11, 0.11]) {+ const brg = add(shaft, new THREE.CylinderGeometry(0.03, 0.03, 0.05, 24), M.steel);+ brg.rotation.z = Math.PI / 2;+ brg.position.x = x;+ }++ // ------------------------------------------------------------ one side: clevis joint, side tube, leg, wheel+ const sides = [1, -1].map((sx) => {+ const side = new THREE.Group();+ side.scale.x = sx;+ root.add(side);+ // the shaft-side yoke turns with the shaft about x+ const yokeA = new THREE.Group();+ yokeA.position.copy(J);+ side.add(yokeA);+ add(yokeA, new RoundedBoxGeometry(0.05, 0.075, 0.075, 3, 0.014), M.orange).position.x = -0.03;+ for (const s of [-1, 1]) {+ const bolt = add(yokeA, new THREE.CylinderGeometry(0.009, 0.009, 0.012, 10), M.black);+ bolt.rotation.x = Math.PI / 2;+ bolt.position.set(-0.03, s * 0.02, 0.04);+ }+ // the tube group turns about the side tube's own axis; the tube, its yoke, the leg and the wheel ride on it+ const spin = new THREE.Group();+ spin.position.copy(J);+ side.add(spin);+ const yokeB = add(spin, new RoundedBoxGeometry(0.075, 0.06, 0.06, 3, 0.012), M.orange);+ yokeB.position.copy(AXIS).multiplyScalar(0.035);+ yokeB.quaternion.setFromUnitVectors(new V3(1, 0, 0), AXIS);+ const tube = add(spin, new THREE.CylinderGeometry(0.024, 0.024, G.tubeLen - 0.03, 20), M.steel);+ tube.position.copy(AXIS).multiplyScalar((G.tubeLen + 0.03) / 2);+ tube.quaternion.setFromUnitVectors(new V3(0, 1, 0), AXIS);+ // a stripe on the tube so its spin reads+ const stripe = add(spin, new THREE.BoxGeometry(0.006, G.tubeLen * 0.6, 0.044), M.black);+ stripe.position.copy(tube.position);+ stripe.quaternion.copy(tube.quaternion);+ const root2 = add(spin, new RoundedBoxGeometry(0.08, 0.07, 0.07, 3, 0.014), M.orange);+ root2.position.copy(E0).sub(J);+ const leg = add(spin, legGeo(), M.orange);+ leg.position.copy(E0).sub(J);+ // the wheel: axle along x when down, spinning on its axle+ const wheelMount = new THREE.Group();+ wheelMount.position.copy(TIP0).sub(J);+ spin.add(wheelMount);+ const fork = add(wheelMount, new RoundedBoxGeometry(0.05, 0.09, 0.06, 3, 0.012), M.black);+ fork.position.x = -0.07;+ const wheel = new THREE.Group();+ wheelMount.add(wheel);+ add(wheel, tyreGeo(), M.rubber);+ const hub = add(wheel, new THREE.CylinderGeometry(G.wheelR * 0.5, G.wheelR * 0.5, G.wheelW * 0.8, 40), M.hub);+ hub.rotation.z = Math.PI / 2;+ const cap = add(wheel, new THREE.CylinderGeometry(0.035, 0.035, G.wheelW * 0.95, 24), M.black);+ cap.rotation.z = Math.PI / 2;+ for (const s of [-1, 1]) {+ const ring = add(wheel, new THREE.RingGeometry(G.wheelR * 0.62, G.wheelR * 0.98, 64), M.letters);+ ring.rotation.y = (s * Math.PI) / 2;+ ring.position.x = s * (G.wheelW / 2 - 0.002);+ ring.castShadow = false;+ }+ return {side, yokeA, spin, wheel};+ });++ // display modes: x-ray (the plate and the actuator body go to glass), section (both cut at the centreline), exploded+ const CLIP = new THREE.Plane(new V3(-1, 0, 0), 0);+ let xrayNow = -1;+ let sectionNow = false;+ const setXray = (k) => {+ if (Math.abs(k - xrayNow) < 1e-3) return;+ xrayNow = k;+ for (const m of [M.plate, M.body]) {+ m.transparent = k > 0.001;+ m.opacity = 1 - 0.78 * k;+ m.depthWrite = k < 0.5;+ m.needsUpdate = true;+ }+ };+ const setSection = (on) => {+ if (on === sectionNow) return;+ sectionNow = on;+ for (const m of [M.plate, M.body]) {+ m.clippingPlanes = on ? [CLIP] : null;+ m.side = on ? THREE.DoubleSide : THREE.FrontSide;+ m.needsUpdate = true;+ }+ };+ const out = {theta: 0, d: 0, CLIP};+ /** stroke 0..1 (0 down and locked, 1 up), roll (wheel spin, radians), xray 0..1, section, explode 0..1 */+ const update = ({stroke = 0, roll = 0, xray = 0, section = false, explode = 0} = {}) => {+ setXray(xray);+ setSection(section);+ const e = explode;+ plate.position.y = 0.16 * e;+ act.position.y = 0.36 * e;+ const th = stroke * Math.PI;+ const d = stroke * G.stroke;+ out.theta = th;+ out.d = d;+ // the actuator strokes aft: the rod end, the rack with it+ const zRe = 0.32 - d;+ rodEnd.position.set(0, 0.36 * e, zRe);+ const rodFrom = -0.16;+ rod.scale.y = zRe - rodFrom;+ rod.position.set(0, AY, (zRe + rodFrom) / 2);+ rack.position.set(0, RACK_Y + 0.06 * e, zRe - 0.02 - RACK_LEN / 2);+ shaft.position.y = G.shaftY - 0.12 * e;+ // the rack turns the pinion and the shaft (rack aft = shaft turning about +x)+ shaft.rotation.x = th;+ for (const s of sides) {+ s.side.position.set(0.16 * e * s.side.scale.x, -0.12 * e, 0);+ s.yokeA.rotation.x = th;+ s.spin.quaternion.setFromAxisAngle(AXIS, th);+ s.wheel.rotation.x = roll;+ }+ };+ update();+ return {root, update, M, all, plate, act, rack, shaft, sides, out};+}diff --git a/sims/cessna-shared/live.js b/sims/cessna-shared/live.jsnew file mode 100644index 0000000..06ac5fb--- /dev/null+++ b/sims/cessna-shared/live.js@@ -0,0 +1,351 @@+// The Skymaster gear as a page you drive: the film's gear, runway and console run in real time. TAKEOFF and LANDING+// start a sequence, the play button pauses it, the timeline scrubs it, SPEED sets its pace; the six views, the six+// display modes, an orbit you drag and a zoom on the wheel. Left alone it plays the film's script as an auto tour with+// the operator's cursor, looped; a click, drag, wheel or key hands control to the visitor, 25 s of quiet hands it back.+import {warmComposer} from '../kit/warm.js';+import {createConsole, DISPLAY, VIEWS} from './console.js';+import {camAt, displayAt, DURATION, makeConsoleFrame, makeCursor, mechAt, SCRIPT, seqAt, viewAt, VIEW_FN} from './film.js';+import {SEQ} from './flight.js';+import {G} from './gear.js';+import {createCessnaStage} from './stage.js';++const W = 1600;+const H = 900;+const IDLE = 25;+const D2R = Math.PI / 180;+const clamp = (x, a, b) => Math.min(b, Math.max(a, x));+const smoother = (x) => {+ const u = clamp(x, 0, 1);+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));+const wrap = (d) => ((((d + 180) % 360) + 360) % 360) - 180;+const SPEED = [0.1, 2];+const speedK = (v) => (v - SPEED[0]) / (SPEED[1] - SPEED[0]);++const CSS = (top) => `+html,body{background:#f2e6d2;overflow:hidden}+#app{position:absolute!important;inset:auto!important;left:0;top:0;width:${W}px;height:${H}px;transform-origin:0 0}+#gl{touch-action:none;cursor:grab}+#gl.drag{cursor:grabbing}+.bt{pointer-events:auto;cursor:pointer}+.bt:hover{filter:brightness(.96)}+.hit{position:absolute;pointer-events:auto;cursor:ew-resize}+.tourchip{position:absolute;left:800px;top:154px;transform:translateX(-50%);display:flex;align-items:center;gap:7px;height:22px;padding:0 11px;border:1px solid #eadfcd;border-radius:4px;background:rgba(252,249,244,.95);color:#2a2521;font:700 9px 'JetBrains Mono',monospace;letter-spacing:1.3px;white-space:nowrap;cursor:pointer;pointer-events:auto}+.tourchip i{display:block;width:6px;height:6px;border-radius:50%;background:#e3562a}+.tourchip.on i{animation:blink 1.2s steps(2) infinite}+@keyframes blink{50%{opacity:.15}}+.turn{position:fixed;left:0;right:0;bottom:18px;text-align:center;font:600 12px/1.4 'JetBrains Mono',monospace;letter-spacing:1px;color:#9b8f80;text-transform:uppercase;display:none}+@media (orientation:portrait) and (max-width:820px){.turn{display:block}}+`;++export function runLive() {+ const top = Number(document.body.dataset.top || 0);+ const style = document.createElement('style');+ style.textContent = CSS(top);+ document.head.appendChild(style);+ const app = document.getElementById('app');+ const canvas = document.createElement('canvas');+ canvas.id = 'gl';+ app.appendChild(canvas);+ const st = createCessnaStage({canvas});+ const ui = createConsole(app);+ const tourCursor = makeCursor(ui);+ const frameConsole = makeConsoleFrame(ui, st);++ // ------------------------------------------------------------ quality tiers+ const TIERS = [+ {samples: 8, ao: true, shadow: 4096, pr: 2},+ {samples: 4, ao: false, shadow: 2048, pr: 1.5},+ {samples: 2, ao: false, shadow: 1024, pr: 1},+ ];+ const light = matchMedia('(pointer: coarse)').matches || Math.min(innerWidth, innerHeight) < 700;+ let tier = light ? 2 : 0;+ let scale = 1;+ const fit = () => {+ const h = innerHeight - top;+ scale = Math.min(innerWidth / W, h / H);+ app.style.transform = `translate(${(innerWidth - W * scale) / 2}px, ${top + (h - H * scale) / 2}px) scale(${scale})`;+ st.resize(W, H, clamp((devicePixelRatio || 1) * scale, 0.75, TIERS[tier].pr));+ };+ const applyTier = () => {+ const {pr, ...q} = TIERS[tier];+ st.setQuality(q);+ fit();+ };+ applyTier();+ addEventListener('resize', fit);+ const toStage = (cx, cy) => {+ const r = app.getBoundingClientRect();+ return [(cx - r.left) / scale, (cy - r.top) / scale];+ };+ const tourChip = document.createElement('div');+ tourChip.className = 'tourchip';+ ui.root.appendChild(tourChip);+ const note = document.createElement('div');+ note.className = 'turn';+ note.textContent = 'Turn your phone sideways for the full console';+ document.body.appendChild(note);++ // ------------------------------------------------------------ state+ let T = 0;+ let seq = 'takeoff';+ let tau = 0;+ let speed = 1;+ let paused = false;+ let view = 'hero';+ let viewAt0 = 0;+ const disp = Object.fromEntries(DISPLAY.map((k) => [k, {on: 0, t: -9}]));+ const off = {az: 0, el: 0, k: 1};+ const cam = {...VIEW_FN.hero(0)};+ let dist = 0;+ let roll = 0;+ let wheelW = 0;+ let ring = {t: -9, x: 0, y: 0};+ const eased = (k, dur = 0.7) => {+ const d = disp[k];+ const x = ss(d.t, d.t + dur, T);+ return d.on ? x : 1 - x;+ };+ const pulse = (k) => (ring = {t: T, x: ui.spots[k][0], y: ui.spots[k][1]});++ // ------------------------------------------------------------ the tour+ const AP = {on: true, t0: 0, loop: 0, last: -1};+ let lastInput = 0;+ const startTour = () => {+ AP.on = true;+ AP.t0 = T;+ AP.loop = 0;+ AP.last = -1;+ paused = false;+ speed = 1;+ Object.assign(off, {az: 0, el: 0, k: 1});+ };+ const takeOver = () => {+ lastInput = T;+ if (!AP.on) return;+ AP.on = false;+ const cyc = (T - AP.t0) % DURATION;+ const [t0, v] = viewAt(cyc);+ view = v;+ viewAt0 = T - (cyc - t0);+ };+ tourChip.addEventListener('pointerdown', (e) => {+ e.stopPropagation();+ lastInput = T;+ if (AP.on) takeOver();+ else startTour();+ });+ addEventListener('pointerdown', (e) => {+ if (e.target !== tourChip) takeOver();+ });+ // the tour's display toggles land in the same state the visitor drives, so a takeover keeps them+ const syncDisplay = (cyc) => {+ const want = displayAt(cyc);+ for (const k of DISPLAY) {+ if (disp[k].on !== want[k]) {+ disp[k].on = want[k];+ disp[k].t = T;+ }+ }+ };++ // ------------------------------------------------------------ controls+ const startSeq = (s) => {+ seq = s;+ tau = 0;+ paused = false;+ };+ for (const s of ['takeoff', 'landing'])+ ui.btn[s].addEventListener('click', () => {+ takeOver();+ pulse(s);+ startSeq(s);+ });+ for (const v of VIEWS)+ ui.btn[v].addEventListener('click', () => {+ takeOver();+ pulse(v);+ view = v;+ viewAt0 = T;+ Object.assign(off, {az: 0, el: 0, k: 1});+ });+ for (const k of DISPLAY)+ ui.btn[k].addEventListener('click', () => {+ takeOver();+ pulse(k);+ disp[k].on = disp[k].on ? 0 : 1;+ disp[k].t = T;+ });+ ui.btn.play.addEventListener('click', () => {+ takeOver();+ pulse('play');+ if (tau >= SEQ[seq].dur - 1e-3) tau = 0;+ paused = !paused;+ });+ const slider = (x0, w, y, apply) => {+ const d = document.createElement('div');+ d.className = 'hit';+ Object.assign(d.style, {left: `${x0 - 8}px`, top: `${y - 11}px`, width: `${w + 16}px`, height: '22px'});+ const move = (e) => {+ const [x] = toStage(e.clientX, e.clientY);+ apply(clamp((x - x0) / w, 0, 1));+ lastInput = T;+ };+ d.addEventListener('pointerdown', (e) => {+ takeOver();+ d.setPointerCapture(e.pointerId);+ const up = () => {+ removeEventListener('pointermove', move);+ removeEventListener('pointerup', up);+ };+ addEventListener('pointermove', move);+ addEventListener('pointerup', up);+ move(e);+ });+ ui.root.appendChild(d);+ };+ slider(ui.TL.x, ui.TL.w, 821, (k) => {+ tau = k * SEQ[seq].dur;+ paused = true;+ });+ slider(ui.SP.x, ui.SP.w, 824, (k) => (speed = SPEED[0] + k * (SPEED[1] - SPEED[0])));+ addEventListener('keydown', (e) => {+ if (e.altKey || e.ctrlKey || e.metaKey) return;+ const key = e.key.toLowerCase();+ const v = {1: 'hero', 2: 'front', 3: 'plan', 4: 'top', 5: 'gearbox', 6: 'sidetube'}[key];+ if (v) ui.btn[v].click();+ else if (key === ' ') ui.btn.play.click();+ else if (key === 't') ui.btn.takeoff.click();+ else if (key === 'l') ui.btn.landing.click();+ else if (key === 'f') ui.btn.fuselage.click();+ else if (key === 'x') ui.btn.xray.click();+ else if (key === 'e') ui.btn.exploded.click();+ else return;+ e.preventDefault();+ });+ let drag = null;+ canvas.addEventListener('pointerdown', (e) => {+ drag = {x: e.clientX, y: e.clientY};+ canvas.setPointerCapture(e.pointerId);+ canvas.classList.add('drag');+ });+ canvas.addEventListener('pointermove', (e) => {+ if (!drag) return;+ off.az += ((e.clientX - drag.x) / scale) * 0.3;+ off.el = clamp(off.el + ((e.clientY - drag.y) / scale) * 0.2, -25, 60);+ drag = {x: e.clientX, y: e.clientY};+ lastInput = T;+ });+ const endDrag = () => {+ drag = null;+ canvas.classList.remove('drag');+ };+ canvas.addEventListener('pointerup', endDrag);+ canvas.addEventListener('pointercancel', endDrag);+ canvas.addEventListener(+ 'wheel',+ (e) => {+ e.preventDefault();+ takeOver();+ off.k = clamp(off.k * Math.exp(e.deltaY * 0.0012), 0.4, 2.4);+ },+ {passive: false},+ );++ // ------------------------------------------------------------ the frame+ startTour();+ let last = performance.now();+ const perf = {n: 0, sum: 0, slow: 0, age: 0};+ const frame = (now) => {+ const dt = Math.min(0.1, Math.max(0, (now - last) / 1000));+ last = now;+ T += dt;+ if (tier < TIERS.length - 1) {+ perf.age += dt;+ if (perf.age > 0.6) {+ perf.sum += dt;+ perf.n++;+ if (perf.sum >= 0.5 && perf.n >= 6) {+ perf.slow = perf.sum / perf.n > 0.022 ? perf.slow + 1 : 0;+ perf.sum = 0;+ perf.n = 0;+ if (perf.slow >= (perf.age < 6 ? 1 : 2)) {+ tier++;+ applyTier();+ Object.assign(perf, {age: 0, slow: 0});+ }+ }+ }+ }++ let tgt;+ let cursor;+ let since;+ if (AP.on) {+ const c = T - AP.t0;+ const loop = Math.floor(c / DURATION);+ const cyc = c - loop * DURATION;+ if (loop > AP.loop) AP.loop = loop;+ const s = seqAt(cyc);+ seq = s.seq;+ tau = s.tau;+ syncDisplay(cyc);+ tgt = camAt(cyc, displayAt(cyc).orbit);+ const [t0, v] = viewAt(cyc);+ view = v;+ since = cyc - t0;+ cursor = tourCursor(cyc);+ if (AP.loop > 0 && cyc < 0.8) {+ const end = tourCursor(DURATION - 0.01);+ const k = ss(0, 0.8, cyc);+ cursor = {...cursor, x: end.x + (cursor.x - end.x) * k, y: end.y + (cursor.y - end.y) * k};+ }+ } else {+ if (T - lastInput > IDLE) startTour();+ if (!paused) tau = Math.min(SEQ[seq].dur, tau + dt * speed);+ since = T - viewAt0;+ tgt = VIEW_FN[view](since);+ tgt.az += off.az + (disp.orbit.on ? 14 * (T - disp.orbit.t) : 0);+ tgt.el = clamp(tgt.el + off.el, -20, 88);+ tgt.d *= off.k;+ const rk = Math.max(0, 1 - (T - ring.t) / 0.55);+ cursor = {x: -99, y: -99, press: false, ring: rk, ringX: ring.x, ringY: ring.y};+ }+ const m = mechAt(seq, tau);+ // the runway and the wheels: rolled by the ground speed, the wheels coasting once airborne+ const live = AP.on || !paused;+ dist += live ? m.speed * dt * (AP.on ? 1 : speed) : 0;+ wheelW = m.height < 0.005 ? m.speed / G.wheelR : wheelW * Math.exp(-dt / 1.2);+ roll += live ? wheelW * dt * (AP.on ? 1 : speed) : 0;++ const k = 1 - Math.exp(-dt / (AP.on ? 0.18 : 0.45));+ cam.az += wrap(tgt.az - cam.az) * k;+ for (const key of ['tx', 'ty', 'tz', 'el', 'd', 'sx', 'sy']) cam[key] += (tgt[key] - cam[key]) * k;+ const explode = eased('exploded', 0.8);+ st.frame(+ {stroke: m.stroke, roll, height: m.height, dist, fuselage: eased('fuselage') * 0.9, xray: eased('xray'), explode, section: !!disp.section.on},+ {...cam, az: cam.az * D2R, el: cam.el * D2R},+ );+ const display = Object.fromEntries(DISPLAY.map((x) => [x, disp[x].on]));+ frameConsole(T, {seq, tau, mech: m, roll, view, display, explode, labels: eased('labels', 0.5) * ss(1.1, 1.7, since), cursor, paused: AP.on ? false : paused, speed: AP.on ? 1 : speed, speedK: speedK(AP.on ? 1 : speed)});+ if (tourChip.classList.contains('on') !== AP.on || !tourChip.firstChild) {+ tourChip.classList.toggle('on', AP.on);+ tourChip.innerHTML = AP.on ? '<i></i>AUTO TOUR · CLICK TO TAKE OVER' : '▶ RESUME TOUR';+ }+ // the site page swaps its poster for the canvas on this+ if (!window.SIM_SHOWN) {+ window.SIM_SHOWN = true;+ dispatchEvent(new Event('simframe'));+ }+ requestAnimationFrame(frame);+ };+ // every shader compiles at once off the main thread before the first frame (kit/warm.js)+ warmComposer(st.renderer, st.composer, st.scene, st.camera).then(() => requestAnimationFrame(frame));+ window.LIVE = {st, cam, startTour, takeOver, get tier() {+ return tier;+ }, get T() {+ return T;+ }};+ void SCRIPT;+}diff --git a/sims/cessna-shared/score.py b/sims/cessna-shared/score.pynew file mode 100644index 0000000..b1adeed--- /dev/null+++ b/sims/cessna-shared/score.py@@ -0,0 +1,41 @@+"""Score for the Cessna 337 main landing gear film: a light bed (Dmaj9 chords, 96 bpm) at one level the whole way, a+hydraulic whine under every gear transit, a soft air at each lift-off, a tyre thud at each touchdown and a quiet+click on every button the operator presses.++ python run_sfx.py sims/cessna-shared/score.py++Times from cessna-shared/film.js (SCRIPT) and flight.js (the sequences' own timings).+"""++import os++from sfx.score_kit import airy, bed, chords, hz, motor, thud+from sfx.synth import click++TIMELINE = "../cessna-film/timeline.json"+OUT = os.path.join(os.environ.get("TEARDOWN_OUT", "teardown-out"), "cessna-score.wav")+TARGET_LUFS = -14.0+SEED = 17++CHORDS = chords("Dmaj9:D2 A2 C#3 E3 F#3/D1", "Bm9:B1 F#2 A2 C#3 D3/B0", "Gmaj7:G2 D3 F#3 B3/G1", "A6sus:A2 D3 E3 F#3 B3/A1")+MOTIF = [(0.5, hz("F#5")), (1.5, hz("A5")), (2.5, hz("E5"))]+CLICKS = (2.4, 5.4, 5.9, 6.5, 8.7, 10.9, 11.5, 12.7, 13.0, 13.4, 16.2, 17.8, 18.3, 18.7, 19.1)+TAKEOFFS = (0.0, 13.0)+LANDINGS = (5.4, 19.1)+++def score(mix, tl):+ dur = tl["duration"]+ left, right, low, drums = bed(dur, 96, CHORDS, MOTIF, motif_voice="epiano", kicks=(0, 2.5), snares=(), hats=8, swing=0.0, keys_vel=0.7, keys_lp=3600)+ mix.put_stereo(0, left, right, 0.12)+ mix.put(0, low, 0.12)+ mix.put(0, drums, 0.045)+ for t0 in TAKEOFFS:+ mix.put(t0 + 1.8, airy(1.6, 500, 1600, 0.6), 0.03)+ mix.put(t0 + 2.3, motor(2.2, 190, 1300, 14), 0.02)+ for t0 in LANDINGS:+ mix.put(t0 + 0.6, motor(2.4, 175, 1200, 14), 0.02)+ if t0 + 5.2 < dur - 0.3:+ mix.put(t0 + 5.2, thud(80, 0.05, 0.4), 0.09)+ for t in CLICKS:+ mix.put(t, click(2400, 0.025), 0.055)diff --git a/sims/cessna-shared/stage.js b/sims/cessna-shared/stage.jsnew file mode 100644index 0000000..bf6c4e1--- /dev/null+++ b/sims/cessna-shared/stage.js@@ -0,0 +1,248 @@+// The landing gear's stage: a warm peach studio over a runway (centreline dashes, edge bars, threshold letters drawn+// in a shader and a canvas), soft shadows, GTAO kept off the ground. frame(state, cam) poses the gear, slides the+// runway under it by the distance rolled and draws one frame.+import * as THREE from 'three';+import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';+import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';+import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';+import {Pass} from 'three/addons/postprocessing/Pass.js';+import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';+import {buildGear, GROUND} from './gear.js';++const V3 = THREE.Vector3;+export const COL = {bg: '#f2e6d2', ground: '#efe0c6', mark: '#d6bf9a', shadow: '#7a5a3a'};++const GROUND_VERT = /* glsl */ `varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`;+const GROUND_FRAG = /* glsl */ `uniform vec3 uG; uniform vec3 uM; uniform vec3 uBg; uniform float uRoll; uniform vec3 uC; varying vec3 vW;+ float box(vec2 p, vec2 b){ vec2 d = abs(p) - b; return max(d.x, d.y); }+ void main(){+ // runway frame: x across, z along; the runway slides under the gear by uRoll+ float z = vW.z + uRoll;+ float x = vW.x - 1.4;+ float m = 0.0;+ // centreline dashes, 0.4 wide, 3 m on 2 m off+ float cz = mod(z, 5.0);+ m = max(m, step(abs(x), 0.2) * step(cz, 3.0));+ // edge bars, short blocks every 2.4 m+ float ez = mod(z, 2.4);+ m = max(m, step(abs(abs(x) - 6.0), 0.35) * step(ez, 1.2));+ // touchdown zone stripes+ float tz = mod(z + 1.0, 18.0);+ m = max(m, step(abs(abs(x) - 2.6), 0.9) * step(abs(mod(x + 0.4, 0.8) - 0.4), 0.22) * step(tz, 4.0));+ // a speckle so the ground reads as a surface+ float n = fract(sin(dot(floor(vW.xz * 40.0), vec2(12.9898, 78.233))) * 43758.5453);+ vec3 col = mix(uG, uM, m * 0.85) * (0.985 + 0.03 * n);+ float d = length(vW.xz - uC.xz);+ gl_FragColor = vec4(mix(col, uBg, smoothstep(5.0, 16.0, d)), 1.0);+ }`;++// the airframe as a ghost: a fresnel shell, bright at the silhouette, nearly clear face on+const GHOST_VERT = /* glsl */ `varying vec3 vN; varying vec3 vV; void main(){ vec4 mv = modelViewMatrix * vec4(position, 1.0); vN = normalize(normalMatrix * normal); vV = normalize(-mv.xyz); gl_Position = projectionMatrix * mv; }`;+const GHOST_FRAG = /* glsl */ `uniform vec3 uCol; uniform float uA; varying vec3 vN; varying vec3 vV;+ void main(){ float f = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.4); gl_FragColor = vec4(uCol, uA * (0.05 + 0.6 * f)); }`;+// the Skymaster's shape around the gear plate (the plate top is the belly, y = 0; the nose toward +z): a pod with the+// tractor engine forward and the pusher aft, a high wing, twin booms and the tail between them+function buildGhost(mat) {+ const g = new THREE.Group();+ const lathe = (prof, seg = 48) => new THREE.LatheGeometry(prof.map(([r, z]) => new THREE.Vector2(r, z)), seg);+ const add = (geo, f) => {+ const m = new THREE.Mesh(geo, mat);+ m.renderOrder = 6;+ f(m);+ g.add(m);+ return m;+ };+ // the pod along z (lathe about y, then turned onto z), a little flattened+ const pod = lathe([[0.001, -2.6], [0.18, -2.5], [0.42, -2.0], [0.56, -1.1], [0.6, 0.0], [0.58, 1.0], [0.48, 1.8], [0.3, 2.35], [0.12, 2.6], [0.001, 2.65]]);+ add(pod, (m) => {+ m.rotation.x = Math.PI / 2;+ m.scale.set(1, 1, 0.92);+ m.position.set(0, 0.56, 0.2);+ });+ // the high wing+ add(new THREE.BoxGeometry(9.2, 0.08, 0.95), (m) => m.position.set(0, 1.18, 0.15));+ // twin booms and the tail+ for (const x of [-1.25, 1.25]) {+ add(new THREE.CylinderGeometry(0.1, 0.07, 3.6, 20), (m) => {+ m.rotation.x = Math.PI / 2;+ m.position.set(x, 1.05, -1.95);+ });+ add(new THREE.BoxGeometry(0.06, 0.75, 0.55), (m) => m.position.set(x, 1.38, -3.6));+ }+ add(new THREE.BoxGeometry(2.6, 0.05, 0.42), (m) => m.position.set(0, 1.62, -3.65));+ // the two propellers' discs+ add(new THREE.CylinderGeometry(0.85, 0.85, 0.01, 48), (m) => {+ m.rotation.x = Math.PI / 2;+ m.position.set(0, 0.62, 2.9);+ });+ add(new THREE.CylinderGeometry(0.85, 0.85, 0.01, 48), (m) => {+ m.rotation.x = Math.PI / 2;+ m.position.set(0, 0.62, -2.5);+ });+ return g;+}++export function createCessnaStage({canvas}) {+ const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});+ renderer.toneMapping = THREE.NeutralToneMapping;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.VSMShadowMap;+ renderer.localClippingEnabled = true;+ const scene = new THREE.Scene();+ scene.background = new THREE.Color(COL.bg);+ scene.fog = new THREE.Fog(COL.bg, 8, 22);+ const camera = new THREE.PerspectiveCamera(28, 16 / 9, 0.02, 80);+ const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 8}));+ composer.addPass(new RenderPass(scene, camera));+ const gtao = new GTAOPass(scene, camera, 4, 4);+ gtao.output = GTAOPass.OUTPUT.Default;+ gtao.blendIntensity = 0.8;+ gtao.updateGtaoMaterial({radius: 0.06, distanceExponent: 1.4, thickness: 0.6, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});+ gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, rings: 2, samples: 16});+ class Toggle extends Pass {+ constructor(fn) {+ super();+ this.needsSwap = false;+ this.fn = fn;+ }+ render() {+ this.fn();+ }+ }+ const groundVis = (v) => () => {+ ground.visible = v;+ shade.visible = v;+ for (const o of ghosts) o.visible = v && o.userData.on;+ };+ const ghosts = [];+ composer.addPass(new Toggle(groundVis(false)));+ composer.addPass(gtao);+ composer.addPass(new Toggle(groundVis(true)));+ composer.addPass(new OutputPass());++ {+ const env = new THREE.Scene();+ env.background = new THREE.Color('#e9dcc6');+ const box = (w, h, pos, k) => {+ const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(1, 0.98, 0.95).multiplyScalar(k), side: THREE.DoubleSide}));+ m.position.copy(pos);+ m.lookAt(0, 0, 0);+ env.add(m);+ };+ box(12, 12, new V3(0, 14, 2), 2.4);+ box(3, 14, new V3(-12, 4, 6), 3.0);+ box(3, 14, new V3(12, 4, -4), 2.0);+ box(18, 2, new V3(0, 2, 14), 1.5);+ const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: '#d8c6a8', side: THREE.DoubleSide}));+ g.rotation.x = -Math.PI / 2;+ g.position.y = -2;+ env.add(g);+ const pm = new THREE.PMREMGenerator(renderer);+ scene.environment = pm.fromScene(env, 0.02).texture;+ scene.environmentIntensity = 0.95;+ pm.dispose();+ }+ const SUN_DIR = new V3(-0.35, 0.82, 0.45).normalize();+ const sun = new THREE.DirectionalLight('#fff6ea', 2.3);+ sun.castShadow = true;+ const EXT = 1.6;+ Object.assign(sun.shadow.camera, {left: -EXT, right: EXT, top: EXT, bottom: -EXT, near: 0.5, far: 20});+ sun.shadow.mapSize.set(4096, 4096);+ sun.shadow.radius = 10;+ sun.shadow.blurSamples = 20;+ sun.shadow.bias = -0.0003;+ sun.shadow.normalBias = 0.002;+ scene.add(sun, sun.target);+ scene.add(new THREE.HemisphereLight('#fffaf2', '#d9c6a6', 0.65));++ const groundMat = new THREE.ShaderMaterial({+ vertexShader: GROUND_VERT,+ fragmentShader: GROUND_FRAG,+ uniforms: {uG: {value: new THREE.Color(COL.ground)}, uM: {value: new THREE.Color(COL.mark)}, uBg: {value: new THREE.Color(COL.bg)}, uRoll: {value: 0}, uC: {value: new V3()}},+ toneMapped: false,+ });+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), groundMat);+ ground.rotation.x = -Math.PI / 2;+ scene.add(ground);+ const shade = new THREE.Mesh(+ new THREE.PlaneGeometry(200, 200),+ new THREE.ShadowMaterial({color: COL.shadow, opacity: 0.3, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -8}),+ );+ shade.rotation.x = -Math.PI / 2;+ shade.receiveShadow = true;+ scene.add(shade);++ const gear = buildGear();+ scene.add(gear.root);+ const ghostMat = new THREE.ShaderMaterial({vertexShader: GHOST_VERT, fragmentShader: GHOST_FRAG, uniforms: {uCol: {value: new THREE.Color('#ffffff')}, uA: {value: 0}}, transparent: true, depthWrite: false, side: THREE.DoubleSide});+ const ghost = buildGhost(ghostMat);+ ghost.userData.on = false;+ ghost.visible = false;+ gear.root.add(ghost);+ ghosts.push(ghost);++ const size = {w: 1600, h: 900};+ const resize = (w, h, pr) => {+ size.w = w;+ size.h = h;+ renderer.setPixelRatio(pr);+ renderer.setSize(w, h, false);+ composer.setPixelRatio(pr);+ composer.setSize(w, h);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ };+ const tmp = new V3();+ const right = new V3().crossVectors(new V3(0, 1, 0), SUN_DIR).normalize();+ const upL = new V3().crossVectors(SUN_DIR, right);+ let texel = (2 * EXT) / sun.shadow.mapSize.x;++ // st: {stroke, roll (wheel spin), height (m above the down-locked ride), dist (m rolled)}+ // cam: {tx, ty, tz, az, el, d (radians, metres), sx, sy}; the target is relative to the gear+ const frame = (st, cam) => {+ gear.update(st);+ ghostMat.uniforms.uA.value = st.fuselage ?? 0;+ ghost.userData.on = (st.fuselage ?? 0) > 0.01;+ ghost.visible = ghost.userData.on;+ const y = GROUND + (st.height ?? 0);+ gear.root.position.set(0, y, 0);+ groundMat.uniforms.uRoll.value = st.dist ?? 0;+ const tx = cam.tx;+ const ty = cam.ty + y;+ const tz = cam.tz;+ camera.position.set(tx + cam.d * Math.cos(cam.el) * Math.sin(cam.az), ty + cam.d * Math.sin(cam.el), tz + cam.d * Math.cos(cam.el) * Math.cos(cam.az));+ camera.lookAt(tx, ty, tz);+ camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);+ camera.updateMatrixWorld();+ groundMat.uniforms.uC.value.set(tx, 0, tz);+ tmp.set(0, y * 0.5, 0);+ const rr = Math.round(tmp.dot(right) / texel) * texel;+ const uu = Math.round(tmp.dot(upL) / texel) * texel;+ sun.target.position.copy(right).multiplyScalar(rr).addScaledVector(upL, uu).addScaledVector(SUN_DIR, tmp.dot(SUN_DIR));+ sun.position.copy(sun.target.position).addScaledVector(SUN_DIR, 8);+ sun.target.updateMatrixWorld();+ composer.render();+ };+ const pv = new V3();+ const project = (x, y, z) => {+ pv.set(x, y, z).project(camera);+ if (pv.z > 1) return null;+ return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];+ };+ const setQuality = ({samples, ao, shadow}) => {+ if (samples !== undefined)+ for (const t of [composer.renderTarget1, composer.renderTarget2]) {+ t.samples = samples;+ t.dispose();+ }+ if (ao !== undefined) gtao.enabled = ao;+ if (shadow !== undefined) {+ sun.shadow.mapSize.set(shadow, shadow);+ sun.shadow.map?.dispose();+ sun.shadow.map = null;+ texel = (2 * EXT) / shadow;+ }+ };+ return {renderer, scene, camera, gear, composer, gtao, sun, resize, frame, project, size, ghosts, setQuality};+}diff --git a/sims/kit/director.js b/sims/kit/director.jsnew file mode 100644index 0000000..aacf2d9--- /dev/null+++ b/sims/kit/director.js@@ -0,0 +1,300 @@+import {clamp01, easeOutExpo, fmt, hash, smooth} from './util.js';++/**+ * The director edits a sim to the music: hard cuts between wide and tight+ * shots on bar lines, punch-ins on kicks, a shake and flash on the drop,+ * glitches on stage changes, and big readable story captions on the beat.+ *+ * Beats come from cfg.beats (sims/beats.py output, injected by capture.mjs).+ * Without music it runs on a synthetic grid (cfg.director.bpm) so live pages+ * still feel edited.+ *+ * Shots crop the 3D render (crisp re-render of a sub-rectangle) when the sim+ * uses kit/stage3d; otherwise they scale the target element with CSS.+ * Sims can return `foci: [{x, y}]` (screen px) in their render info: tight+ * shots frame those points.+ *+ * Story: cfg.story = [{at | bar | drop, text, sub, kind: 'hero'|'num', hold,+ * from, to, prefix, suffix, tag}]. `drop` is in bars relative to the drop,+ * `bar` counts bars from the clip start, `hold` is in beats. *word* gets the+ * accent box.+ */+export const DIRECTOR = {+ enabled: true,+ bpm: 128,+ drop: null,+ hero: null,+ // cut every N beats before / after the drop+ cutBeats: [4, 2],+ shots: [+ {z: 1},+ {z: 1.75, f: 0},+ {z: 1.3, f: 1},+ {z: 2.2, f: 2},+ {z: 1.12, f: 0},+ {z: 1.6, f: 1},+ ],+ punch: [0.03, 0.07],+ shake: 1,+ flash: 1,+ glitch: 1,+ target: '#gl',+};++const before = (arr, t) => {+ let lo = 0;+ let hi = arr.length;+ while (lo < hi) {+ const m = (lo + hi) >> 1;+ if (arr[m] <= t) lo = m + 1;+ else hi = m;+ }+ return lo - 1;+};++export function createDirector(app, cfg) {+ const d = {...DIRECTOR, ...(cfg.director || {})};+ const D = cfg.duration;+ const music = cfg.beats && cfg.beats.beats && cfg.beats.beats.length > 4;+ const spb = music ? 60 / cfg.beats.bpm : 60 / d.bpm;+ const beats = music ? cfg.beats.beats : Array.from({length: Math.ceil(D / spb) + 8}, (_, i) => i * spb);+ // pad the grid past both ends so lookups never fall off+ while (beats[0] > 0) beats.unshift(beats[0] - spb);+ while (beats[beats.length - 1] < D + 4 * spb) beats.push(beats[beats.length - 1] + spb);+ let downs = music && cfg.beats.downbeats.length ? cfg.beats.downbeats.slice() : beats.filter((_, i) => i % 4 === 0);+ while (downs[0] > 0) downs.unshift(downs[0] - 4 * spb);+ while (downs[downs.length - 1] < D + 8 * spb) downs.push(downs[downs.length - 1] + 4 * spb);+ const kicks = music ? cfg.beats.kicks : beats.map((b) => [b, 0.8]);+ const kickT = kicks.map((k) => k[0]);+ const energy = music ? cfg.beats.barEnergy : null;+ const drop = (music && cfg.beats.drop) ?? d.drop ?? Math.round((0.4 * D) / (4 * spb)) * 4 * spb;+ const dropBar = before(downs, drop + 0.01);++ const barTime = (b) => downs[Math.max(0, Math.min(downs.length - 1, b))];++ // ---- time warp: the sim's hero moment lands on the drop+ const warp = (t) => {+ if (d.hero == null || !d.enabled) return t;+ const h = d.hero;+ if (t <= drop) return (t / drop) * h;+ return h + ((t - drop) / (D - drop)) * (D - h);+ };++ const beat = (t) => {+ const sh = shotAt(t);+ const bi = before(beats, t);+ const b0 = beats[Math.max(0, bi)];+ const b1 = beats[bi + 1] ?? b0 + spb;+ const ri = before(downs, t);+ const r0 = downs[Math.max(0, ri)];+ const r1 = downs[ri + 1] ?? r0 + 4 * spb;+ const ki = before(kickT, t);+ const kick = ki >= 0 ? kicks[ki][1] * Math.exp(-(t - kicks[ki][0]) / 0.11) : 0;+ const down = Math.exp(-(t - r0) / 0.18);+ return {+ music,+ bpm: 60 / spb,+ beat: bi,+ beatPhase: clamp01((t - b0) / (b1 - b0)),+ bar: ri,+ barPhase: clamp01((t - r0) / (r1 - r0)),+ kick,+ down,+ energy: energy ? energy[Math.max(0, Math.min(energy.length - 1, ri))] ?? 1 : 1,+ drop,+ sinceDrop: t - drop,+ isDrop: t >= drop,+ // current shot: sims may change camera angle per shot index+ shot: sh.k,+ shotZ: sh.shot.z || 1,+ };+ };++ // ---- story timing+ const story = (cfg.story || []).map((s, i) => {+ const start = s.at ?? (s.bar != null ? barTime(s.bar) : s.drop != null ? barTime(dropBar + s.drop) : 0);+ const b0 = before(beats, start + 0.02);+ const hold = s.hold ?? 8;+ const end = s.end ?? beats[Math.min(beats.length - 1, b0 + hold)] ?? start + hold * spb;+ return {...s, i, start, end, b0};+ });++ // ---- DOM layers+ app.insertAdjacentHTML(+ 'beforeend',+ `<canvas class="dir-glitch"></canvas><div class="dir-flash"></div><div class="dir-story"></div>`,+ );+ const gcv = app.querySelector('.dir-glitch');+ const gctx = gcv.getContext('2d');+ const flash = app.querySelector('.dir-flash');+ const storyEl = app.querySelector('.dir-story');++ let foci = [];+ let crop = {z: 1, x0: 0, y0: 0};+ let built = -1;+ let parts = null;++ const stageCuts = (cfg.stages || []).map((s) => s.at).filter((a) => a > 0.2);++ const dropBeat = before(beats, drop + 0.01);+ function shotAt(t) {+ const bi = before(beats, t);+ const isDrop = t >= drop;+ const every = isDrop ? d.cutBeats[1] : d.cutBeats[0];+ // the first beats of the drop always open wide+ if (isDrop && bi - dropBeat < every) return {shot: d.shots[0], k: 0};+ const rel = isDrop ? bi - dropBeat : bi - before(beats, 0.01);+ const k = Math.floor(rel / every) + (isDrop ? 1000 : 0);+ return {shot: d.shots[((k % d.shots.length) + d.shots.length) % d.shots.length], k};+ }++ const target = () => document.querySelector(d.target);++ return {+ warp,+ beat,+ /** Before the sim renders: set this frame's crop. */+ pre(t) {+ if (!d.enabled) return;+ const {shot} = shotAt(t);+ const b = beat(t);+ const punch = 1 + (b.isDrop ? d.punch[1] : d.punch[0]) * b.kick;+ const drift = 1 + 0.035 * b.barPhase;+ let z = (shot.z || 1) * punch * (shot.z > 1 ? drift : 1);+ const vw = innerWidth;+ const vh = innerHeight;+ let f = {x: vw / 2, y: vh / 2};+ if (shot.z > 1 && foci.length) f = foci[(shot.f ?? 0) % foci.length];+ else if (window.__STAGE) {+ const vp = window.__STAGE.hudViewport();+ f = {x: vw / 2, y: (vp.top + vh - vp.bottom) / 2};+ }+ // drop shake (decays over ~0.6 s)+ const sk = d.shake * (b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.25) : 0);+ const sx = sk * (hash(t * 91.7) - 0.5) * 26;+ const sy = sk * (hash(t * 53.3 + 7) - 0.5) * 26;+ const st = window.__STAGE;+ if (st) {+ crop = st.setCrop(z, f.x + sx, f.y + sy);+ } else {+ const el = target();+ if (el) {+ el.style.transformOrigin = `${f.x}px ${f.y}px`;+ el.style.transform = `translate(${sx}px, ${sy}px) scale(${z})`;+ }+ crop = {z: 1, x0: 0, y0: 0};+ }+ },+ /** After the sim renders: remember its foci, draw overlays and the story. */+ post(t, info = {}) {+ if (!d.enabled) return;+ if (info.foci && info.foci.length) {+ // convert from this frame's cropped screen back to base screen coords+ foci = info.foci.map((p) => ({x: crop.x0 + p.x / crop.z, y: crop.y0 + p.y / crop.z}));+ }+ const b = beat(t);+ const vw = innerWidth;+ const vh = innerHeight;++ // flash: accent bloom on downbeats after the drop, white hit on the drop+ const dropHit = b.sinceDrop >= 0 ? Math.exp(-b.sinceDrop / 0.22) : 0;+ const onBar = b.isDrop ? 0.16 * b.down * b.energy : 0;+ flash.style.opacity = String(d.flash * Math.min(0.85, dropHit * 0.7 + onBar));++ // glitch: 3 frames around each stage change and the drop+ const gl = [...stageCuts, b.drop].some((c) => t >= c - 0.03 && t < c + 0.1);+ if (gcv.width !== vw || gcv.height !== vh) {+ gcv.width = vw;+ gcv.height = vh;+ }+ gctx.clearRect(0, 0, vw, vh);+ const src = document.getElementById('gl');+ if (gl && d.glitch && src && src.width) {+ const n = 7;+ for (let i = 0; i < n; i++) {+ const y = Math.floor(hash(t * 13 + i) * vh);+ const h = 6 + Math.floor(hash(t * 7 + i * 3) * 60);+ const dx = (hash(t * 31 + i * 5) - 0.5) * 120;+ const sx = src.width / vw;+ gctx.globalAlpha = 0.9;+ gctx.drawImage(src, 0, y * sx, src.width, h * sx, dx, y, vw, h);+ }+ gctx.globalAlpha = 0.25;+ gctx.fillStyle = cfg.accent;+ gctx.fillRect(0, Math.floor(hash(t * 3.3) * vh), vw, 3 + hash(t) * 10);+ gctx.globalAlpha = 1;+ }++ // ---- story+ const cur = story.find((s) => t >= s.start && t < s.end);+ if (!cur) {+ storyEl.style.opacity = '0';+ return;+ }+ if (built !== cur.i) {+ built = cur.i;+ const words = (cur.text || '').split(/\s+/).filter(Boolean);+ storyEl.innerHTML = `<div class="cap ${cur.kind || 'hero'}">+ ${cur.tag ? `<div class="cap-tag">${cur.tag}</div>` : ''}+ <div class="cap-main">${+ cur.kind === 'num'+ ? `<span class="w"><span class="n"></span></span>`+ : (() => {+ // *several words* → each word gets the accent box+ let on = false;+ return words+ .map((w) => {+ const open = w.startsWith('*');+ const close = w.endsWith('*') && (w.length > 1 || on);+ if (open) on = true;+ const hl = on;+ if (close) on = false;+ return `<span class="w${hl ? ' hl' : ''}">${w.replace(/^\*|\*$/g, '')}</span>`;+ })+ .join(' ');+ })()+ }</div>+ ${cur.sub ? `<div class="cap-sub"></div>` : ''}+ </div>`;+ parts = {+ words: [...storyEl.querySelectorAll('.w')],+ num: storyEl.querySelector('.n'),+ sub: storyEl.querySelector('.cap-sub'),+ main: storyEl.querySelector('.cap-main'),+ };+ }+ const vp = window.__HUDVP ? window.__HUDVP() : {top: 0, bottom: 0};+ storyEl.style.top = `${vp.top}px`;+ storyEl.style.bottom = `${vp.bottom}px`;+ storyEl.style.opacity = '1';+ const ex = clamp01((t - (cur.end - 0.18)) / 0.18);+ // words slam in on successive beats (half-beats if the text is long)+ const step = parts.words.length > 4 ? 0.5 : 1;+ let lastIn = cur.start;+ parts.words.forEach((w, i) => {+ const bi = cur.b0 + i * step;+ const wt = Math.floor(bi) === bi ? beats[bi] : (beats[Math.floor(bi)] + beats[Math.ceil(bi)]) / 2;+ const k = cur.start <= 0.001 ? 1 : clamp01((t - wt) / 0.12);+ lastIn = Math.max(lastIn, wt);+ const s = 1 + 0.35 * (1 - easeOutExpo(k)) + 0.03 * b.kick;+ w.style.opacity = String(k > 0 ? 1 : 0);+ w.style.transform = `scale(${s}) translateY(${ex * -0.25}em)`;+ w.style.filter = k < 1 ? `blur(${(1 - k) * 8}px)` : 'none';+ });+ if (cur.kind === 'num' && parts.num) {+ const roll = cur.roll ?? 6;+ const k = easeOutExpo(clamp01((t - cur.start) / (roll * spb)));+ const v = cur.from + (cur.to - cur.from) * k;+ parts.num.textContent = `${cur.prefix ?? ''}${fmt(v, cur.decimals ?? 0)}${cur.suffix ?? ''}`;+ lastIn = cur.start + roll * spb * 0.6;+ }+ if (parts.sub) {+ const n = Math.floor(Math.max(0, t - lastIn - 0.15) / 0.022);+ parts.sub.textContent = cur.sub.slice(0, n);+ }+ parts.main.style.opacity = String(1 - ex);+ if (parts.sub) parts.sub.style.opacity = String(1 - ex);+ storyEl.firstElementChild.style.transform = `translateX(${ex * (hash(t * 41) - 0.5) * 40}px)`;+ },+ };+}diff --git a/sims/kit/hud.js b/sims/kit/hud.jsnew file mode 100644index 0000000..289f0f5--- /dev/null+++ b/sims/kit/hud.js@@ -0,0 +1,194 @@+import {clamp01, pad} from './util.js';++/**+ * Instrument-style HUD: header with stage/command/clock, annotations over the+ * viewport, a terminal log and a side panel (minimap + stats) at the bottom.+ * Everything is derived from `t` and the config's stages, so it's deterministic.+ *+ * cfg.stages: [{at, name, cmd, logs: [string]}]. A log line starting with "!"+ * is highlighted in the accent. {key} tokens are replaced from `facts`.+ */+export function createHud(root, cfg) {+ const h = cfg.hud;+ root.insertAdjacentHTML(+ 'beforeend',+ `<div class="hud">+ <div class="ann"></div>+ <div class="wm"></div>+ <div class="hdr">+ <div class="row row1">+ <div class="title"><i class="bar"></i><span class="t"></span></div>+ <div class="sub"></div>+ <div class="right"></div>+ </div>+ <div class="row row2">+ <div class="stage accent"></div>+ <div class="cmd"></div>+ <div class="time accent"></div>+ </div>+ <div class="prog"><i></i></div>+ </div>+ <div class="bot">+ <div class="term">+ <div class="thead">+ <span class="host accent"></span><span class="path"></span>+ <span class="status accent"><i></i><span></span></span>+ </div>+ <div class="prompt"></div>+ <div class="logs"></div>+ <div class="tfoot"></div>+ </div>+ <div class="side">+ <div class="shead accent"></div>+ <canvas class="mini"></canvas>+ <div class="stats"></div>+ <div class="sfoot"></div>+ </div>+ <div class="baseline"><i></i></div>+ </div>+ </div>`,+ );+ const $ = (s) => root.querySelector(s);+ const el = {+ hud: $('.hud'),+ ann: $('.ann'),+ stage: $('.row2 .stage'),+ cmd: $('.row2 .cmd'),+ time: $('.row2 .time'),+ prog: $('.prog i'),+ prompt: $('.prompt'),+ logs: $('.logs'),+ tfoot: $('.tfoot'),+ status: $('.thead .status span'),+ stats: $('.stats'),+ sfoot: $('.sfoot'),+ base: $('.baseline i'),+ mini: $('.mini'),+ };+ $('.title .t').textContent = h.title;+ $('.sub').textContent = h.subtitle;+ $('.right').textContent = h.right;+ $('.wm').textContent = cfg.watermark;+ $('.thead .host').textContent = h.host;+ $('.thead .path').textContent = h.path;+ $('.shead').textContent = h.sideTitle;++ const stages = cfg.stages;+ const D = cfg.duration;+ const TYPE_CMD = 0.028;+ const TYPE_LOG = 0.011;++ // Log line schedule: each stage types its command, then its lines spread+ // over the stage.+ const lines = [];+ stages.forEach((s, i) => {+ const end = i + 1 < stages.length ? stages[i + 1].at : D;+ const t0 = s.at + 0.25 + s.cmd.length * TYPE_CMD + 0.2;+ const n = s.logs.length;+ const gap = Math.min(0.8, Math.max(0.22, (end - t0 - 0.4) / Math.max(1, n)));+ s.logs.forEach((text, j) => lines.push({at: t0 + j * gap, text, stage: i}));+ });++ const stageAt = (t) => {+ let i = 0;+ while (i + 1 < stages.length && stages[i + 1].at <= t) i++;+ return i;+ };+ const fill = (text, facts) => text.replace(/\{(\w+)\}/g, (m, k) => (k in facts ? facts[k] : m));+ const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<');++ let lastStats = '';+ let lastLogs = '';+ const annPool = [];++ return {+ minimap: el.mini,+ stageAt,+ setVisible(v) {+ el.hud.classList.toggle('hidden', !v);+ },+ /** Viewport between header and bottom panel, in CSS px. */+ viewport() {+ const fs = parseFloat(getComputedStyle(document.documentElement).fontSize);+ return {top: 13.4 * fs, bottom: 30.5 * fs};+ },+ render(t, frame, info = {}) {+ const facts = {...cfg.facts, ...(info.facts || {})};+ const si = stageAt(t);+ const s = stages[si];+ const dt = t - s.at;+ const typed = Math.floor(Math.max(0, dt - 0.15) / TYPE_CMD);+ const cmd = fill(s.cmd, facts);+ const typing = typed < cmd.length;+ const caretOn = typing || Math.floor(t * 2.4) % 2 === 0;++ el.stage.textContent = `${pad(si + 1, 2)} / ${s.name}`;+ el.cmd.textContent = cmd.slice(0, typed);+ el.time.textContent = `${t.toFixed(2).padStart(5, '0')} / ${D}`;+ el.prog.style.width = `${(clamp01(t / D) * 100).toFixed(2)}%`;+ el.base.style.width = `${(clamp01(dt / ((stages[si + 1]?.at ?? D) - s.at)) * 100).toFixed(2)}%`;+ el.prompt.innerHTML = `<span class="accent">></span> ${esc(cmd.slice(0, typed))}${+ caretOn ? '<i class="caret"></i>' : ''+ }`;++ const shown = lines.filter((l) => l.at <= t);+ const rows = shown.slice(-h.logRows);+ const offset = shown.length - rows.length;+ const html = rows+ .map((l, j) => {+ const full = fill(l.text, facts);+ const hl = full.startsWith('!');+ const text = hl ? full.slice(1) : full;+ const n = Math.floor((t - l.at) / TYPE_LOG);+ const isLast = j === rows.length - 1 && n < text.length;+ return `<div><span class="ln">${pad(offset + j, 3)}</span><span class="${hl ? 'hl' : ''}">${esc(+ text.slice(0, n),+ )}</span>${isLast ? '<i class="caret"></i>' : ''}</div>`;+ })+ .join('');+ if (html !== lastLogs) {+ el.logs.innerHTML = html;+ lastLogs = html;+ }++ el.tfoot.textContent = `frame ${pad(frame, 4)} delta ${pad((dt * 7.3) % 100, 2)} / ${s.name.toLowerCase()}`;+ el.status.textContent = info.status ?? (t >= D - 0.05 ? 'DONE' : 'RUNNING');+ el.sfoot.textContent = `view ${pad(si + 1, 2)} / ${pad(h.views, 2)} seed ${cfg.seed} · t+${dt.toFixed(2)}s`;++ const stats = (info.stats || []).map((x) => `<div>${esc(x.label)}<b>${esc(String(x.value))}</b></div>`).join('');+ if (stats !== lastStats) {+ el.stats.innerHTML = stats;+ lastStats = stats;+ }++ const anns = info.annotations || [];+ while (annPool.length < anns.length) {+ const d = document.createElement('div');+ el.ann.appendChild(d);+ annPool.push(d);+ }+ annPool.forEach((d, i) => {+ const a = anns[i];+ if (!a) {+ d.style.display = 'none';+ return;+ }+ d.style.display = '';+ d.className = a.cls || '';+ d.style.left = `${a.x}px`;+ d.style.top = `${a.y}px`;+ d.style.opacity = a.opacity ?? 1;+ if (a.html !== undefined) d.innerHTML = a.html;+ else d.textContent = a.text;+ // keep labels inside the viewport (between header and bottom panel)+ const vp = this.viewport();+ const w = d.offsetWidth;+ const hh = d.offsetHeight;+ const x = Math.min(Math.max(a.x, 8), innerWidth - w - 40);+ const y = Math.min(Math.max(a.y, vp.top + hh / 2 + 8), innerHeight - vp.bottom - hh / 2 - 8);+ d.style.left = `${x}px`;+ d.style.top = `${y}px`;+ });+ },+ };+}diff --git a/sims/kit/runtime.js b/sims/kit/runtime.jsnew file mode 100644index 0000000..db073e1--- /dev/null+++ b/sims/kit/runtime.js@@ -0,0 +1,168 @@+import {createDirector, DIRECTOR} from './director.js';+import {createHud} from './hud.js';+import {merge} from './util.js';++/** Config every sim starts from; a sim's defaults and the post config merge over it. */+export const BASE = {+ duration: 30,+ fps: 30,+ seed: 746337560,+ theme: 'dark',+ accent: '#f2b632',+ watermark: '',+ hud: {+ title: 'AGENT MESH',+ subtitle: '/ SIMULATION',+ right: 'VISUAL SIMULATION',+ host: 'agent@local',+ path: '~/session-01',+ sideTitle: 'LOCAL VIEW',+ logRows: 5,+ views: 10,+ },+ stages: [{at: 0, name: 'RUN', cmd: 'run', logs: []}],+ facts: {},+ director: DIRECTOR,+ story: [],+ beats: null,+};++const fromBase64 = (s) => decodeURIComponent(escape(atob(s.replace(/-/g, '+').replace(/_/g, '/'))));++/**+ * Config sources, later wins: BASE, the sim's defaults, window.__SIM_CONFIG+ * (injected by the capture script), ?config=<base64 json>, and a few plain+ * query params (?title= ?accent= ?seed= ?theme= ?duration=).+ */+export function loadConfig(defaults) {+ let cfg = merge(BASE, defaults);+ if (window.__SIM_CONFIG) cfg = merge(cfg, window.__SIM_CONFIG);+ const q = new URLSearchParams(location.search);+ if (q.get('config')) {+ try {+ cfg = merge(cfg, JSON.parse(fromBase64(q.get('config'))));+ } catch (e) {+ console.warn('bad ?config', e);+ }+ }+ if (q.get('title')) cfg = merge(cfg, {hud: {title: q.get('title')}});+ if (q.get('accent')) cfg.accent = '#' + q.get('accent').replace('#', '');+ if (q.get('seed')) cfg.seed = Number(q.get('seed'));+ if (q.get('theme')) cfg.theme = q.get('theme');+ if (q.get('duration')) cfg.duration = Number(q.get('duration'));+ if (q.has('nodirector')) cfg.director = {...cfg.director, enabled: false};+ return cfg;+}++/**+ * Boots a sim. `setup({cfg, canvas, hud, capture})` returns (or resolves to)+ * `{render(t) -> hudInfo, resize()}`. render must be a pure function of t.+ *+ * Live mode loops in real time. Keys: space pause, h hide HUD, f fullscreen,+ * r restart, ←/→ seek 2 s, 1–9 jump to a stage.+ * Capture mode (?capture or window.__CAPTURE) exposes window.SIM.render(t).+ */+export async function runSim(defaults, setup) {+ const cfg = loadConfig(defaults);+ const q = new URLSearchParams(location.search);+ const capture = !!window.__CAPTURE || q.has('capture');+ const root = document.documentElement;+ root.dataset.theme = cfg.theme;+ root.style.setProperty('--accent', cfg.accent);+ document.title = `${cfg.hud.title} ${cfg.hud.subtitle}`.trim();++ const scale = () => {+ root.style.fontSize = `${10 * Math.min(innerWidth / 1080, innerHeight / 1350)}px`;+ };+ scale();++ const app = document.getElementById('app');+ const canvas = document.createElement('canvas');+ canvas.id = 'gl';+ app.appendChild(canvas);+ // cfg.hud.enabled === false: no instrument chrome (UI demos, infographics).+ const hud =+ cfg.hud.enabled === false+ ? {minimap: null, stageAt: () => 0, setVisible() {}, viewport: () => ({top: 0, bottom: 0}), render() {}}+ : createHud(app, cfg);++ await Promise.all([+ document.fonts.load('400 20px "JetBrains Mono"'),+ document.fonts.load('600 20px "JetBrains Mono"'),+ document.fonts.load('800 20px "Inter"'),+ ]).catch(() => {});++ window.__HUDVP = () => hud.viewport();+ const sim = await setup({cfg, canvas, hud, capture});+ if (!capture && sim.warm) await sim.warm();+ const dir = createDirector(app, cfg);+ // The sim and HUD run on warped time (hero lands on the drop); the+ // director's cuts, punches and story run on real (music) time.+ const draw = (t) => {+ const tw = dir.warp(t);+ dir.pre(t);+ const info = sim.render(tw, dir.beat(t)) || {};+ hud.render(tw, Math.round(t * cfg.fps), info);+ dir.post(t, info);+ };++ let cur = 0;+ let paused = false;+ const resize = () => {+ scale();+ sim.resize?.();+ if (paused || capture) draw(cur);+ };+ addEventListener('resize', resize);+ resize();++ window.SIM = {+ cfg,+ duration: cfg.duration,+ fps: cfg.fps,+ ready: true,+ render: (t) => {+ cur = t;+ draw(t);+ },+ };+ if (capture) {+ draw(0);+ return;+ }++ let start = performance.now();+ const seek = (t) => {+ cur = ((t % cfg.duration) + cfg.duration) % cfg.duration;+ start = performance.now() - cur * 1000;+ };+ let hudOn = true;+ addEventListener('keydown', (e) => {+ if (e.key === ' ') {+ paused = !paused;+ if (!paused) seek(cur);+ } else if (e.key === 'h') {+ hudOn = !hudOn;+ hud.setVisible(hudOn);+ } else if (e.key === 'f') {+ if (document.fullscreenElement) document.exitFullscreen();+ else document.documentElement.requestFullscreen();+ } else if (e.key === 'r') seek(0);+ else if (e.key === 'ArrowRight') seek(cur + 2);+ else if (e.key === 'ArrowLeft') seek(cur - 2);+ else if (/^[1-9]$/.test(e.key) && cfg.stages[+e.key - 1]) seek(Math.max(0, cfg.stages[+e.key - 1].at));+ else return;+ e.preventDefault();+ });+ const loop = (now) => {+ if (!paused) cur = Math.max(0, (now - start) / 1000) % cfg.duration;+ draw(cur);+ // the site page swaps its poster for the canvas on this+ if (!window.SIM_SHOWN) {+ window.SIM_SHOWN = true;+ dispatchEvent(new Event('simframe'));+ }+ requestAnimationFrame(loop);+ };+ requestAnimationFrame(loop);+}diff --git a/sims/kit/stage3d.js b/sims/kit/stage3d.jsnew file mode 100644index 0000000..09950f2--- /dev/null+++ b/sims/kit/stage3d.js@@ -0,0 +1,114 @@+import * as THREE from 'three';+import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';+import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';+import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';+import {UnrealBloomPass} from 'three/addons/postprocessing/UnrealBloomPass.js';++/**+ * Renderer + scene + camera + bloom. The camera's projection centre is shifted+ * to the middle of the HUD viewport (between header and bottom panel), so the+ * subject is centred in the visible area, not behind the terminal.+ */+export function createStage(canvas, hud, opts = {}) {+ const {+ bg = '#09090a',+ fov = 38,+ bloom = {strength: 0.85, radius: 0.55, threshold: 0.62},+ capture = false,+ exposure = 1,+ } = opts;+ const renderer = new THREE.WebGLRenderer({+ canvas,+ antialias: false,+ preserveDrawingBuffer: true,+ powerPreference: 'high-performance',+ });+ renderer.setClearColor(new THREE.Color(bg), 1);+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = exposure;+ renderer.outputColorSpace = THREE.SRGBColorSpace;++ const scene = new THREE.Scene();+ scene.background = new THREE.Color(bg);+ const camera = new THREE.PerspectiveCamera(fov, 1, 0.5, 6000);++ const target = new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 4});+ const composer = new EffectComposer(renderer, target);+ composer.addPass(new RenderPass(scene, camera));+ const bloomPass = new UnrealBloomPass(new THREE.Vector2(4, 4), bloom.strength, bloom.radius, bloom.threshold);+ composer.addPass(bloomPass);+ composer.addPass(new OutputPass());++ const size = {w: 1, h: 1, centre: 0.5};+ // Director crop: render a sub-rectangle of the base view (crisp punch-ins).+ const crop = {z: 1, fx: 0, fy: 0, x0: 0, y0: 0};+ const applyView = () => {+ const {w, h, centre} = size;+ const offY = h / 2 - centre;+ if (crop.z <= 1.0001) {+ crop.x0 = 0;+ crop.y0 = 0;+ camera.setViewOffset(w, h, 0, offY, w, h);+ } else {+ const cw = w / crop.z;+ const ch = h / crop.z;+ crop.x0 = Math.min(Math.max(crop.fx - cw / 2, 0), w - cw);+ crop.y0 = Math.min(Math.max(crop.fy - ch / 2, 0), h - ch);+ camera.setViewOffset(w, h, crop.x0, offY + crop.y0, cw, ch);+ }+ camera.updateProjectionMatrix();+ };+ // opts.pr fixes the pixel ratio (a capture that wants the 3D at the output resolution, a page that adapts it)+ let prFixed = opts.pr;+ const resize = () => {+ const w = canvas.clientWidth || innerWidth;+ const h = canvas.clientHeight || innerHeight;+ const pr = prFixed ?? (capture ? 1 : Math.min(devicePixelRatio || 1, 2));+ size.w = w;+ size.h = h;+ renderer.setPixelRatio(pr);+ renderer.setSize(w, h, false);+ composer.setPixelRatio(pr);+ composer.setSize(w, h);+ const vp = hud.viewport();+ size.centre = (vp.top + (h - vp.bottom)) / 2;+ camera.aspect = w / h;+ applyView();+ };+ /** Zoom z around base-screen point (fx, fy); returns {z, x0, y0} for mapping back. */+ const setCrop = (z, fx, fy) => {+ crop.z = Math.max(1, z);+ crop.fx = fx;+ crop.fy = fy;+ applyView();+ return {z: crop.z, x0: crop.x0, y0: crop.y0};+ };++ const v = new THREE.Vector3();+ /** World point → CSS px on screen, plus whether it's in front of the camera. */+ const project = (p) => {+ v.set(p[0] ?? p.x, p[1] ?? p.y, p[2] ?? p.z).project(camera);+ return {x: (v.x * 0.5 + 0.5) * size.w, y: (-v.y * 0.5 + 0.5) * size.h, visible: v.z < 1};+ };++ const st = {+ THREE,+ renderer,+ scene,+ camera,+ composer,+ bloomPass,+ size,+ resize,+ setPixelRatio: (v) => {+ prFixed = v;+ resize();+ },+ project,+ render: () => composer.render(),+ setCrop,+ hudViewport: () => hud.viewport(),+ };+ window.__STAGE = st;+ return st;+}diff --git a/sims/kit/style.css b/sims/kit/style.cssnew file mode 100644index 0000000..7bf7ca8--- /dev/null+++ b/sims/kit/style.css@@ -0,0 +1,137 @@+/* HUD chrome shared by every sim. 1rem = 10px at the 1080x1350 reference+ size; runtime sets html font-size from the viewport so it scales. */++:root {+ --bg: #09090a;+ --fg: #ece6d6;+ --dim: rgba(236, 230, 214, 0.64);+ --mute: rgba(236, 230, 214, 0.38);+ --faint: rgba(236, 230, 214, 0.16);+ --line: rgba(236, 230, 214, 0.14);+ --panel: rgba(9, 9, 10, 0.9);+ --accent: #f2b632;+ --top: 13.4rem;+ --bot: 30.5rem;+}+:root[data-theme='light'] {+ --bg: #f3f2ee;+ --fg: #151515;+ --dim: rgba(21, 21, 21, 0.66);+ --mute: rgba(21, 21, 21, 0.42);+ --faint: rgba(21, 21, 21, 0.16);+ --line: rgba(21, 21, 21, 0.16);+ --panel: rgba(243, 242, 238, 0.93);+}++* { box-sizing: border-box; }+html, body { margin: 0; height: 100%; background: var(--bg); overflow: hidden; }+#app {+ position: fixed; inset: 0; color: var(--fg);+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-variant-ligatures: none; -webkit-font-smoothing: antialiased;+}+#gl { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }+.hud { position: absolute; inset: 0; pointer-events: none; }+.hud.hidden { display: none; }+.accent { color: var(--accent); }++/* header */+.hdr {+ position: absolute; left: 0; right: 0; top: 0; height: var(--top);+ padding: 2.4rem 2.8rem 0;+ background: linear-gradient(var(--bg) 0%, var(--bg) 78%, transparent 100%);+}+.row { display: flex; align-items: baseline; white-space: nowrap; }+.row1 { gap: 5.6rem; }+.title { display: flex; align-items: center; gap: 1.3rem; font-size: 3.6rem; font-weight: 600; letter-spacing: 0.04em; }+.title .bar { display: inline-block; width: 0.75rem; height: 3.6rem; background: var(--accent); }+.sub { font-size: 1.75rem; color: var(--dim); letter-spacing: 0.08em; }+.right { margin-left: auto; font-size: 1.6rem; color: var(--dim); letter-spacing: 0.1em; }+.row2 { margin-top: 2rem; font-size: 1.95rem; }+.row2 .stage { width: 21rem; letter-spacing: 0.05em; }+.row2 .cmd { color: var(--fg); }+.row2 .time { margin-left: auto; letter-spacing: 0.05em; }+.prog { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 1.2rem; height: 0.35rem; }+.prog i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }++/* viewport overlays */+.ann { position: absolute; inset: 0; overflow: hidden; }+.ann div {+ position: absolute; transform: translate(1.4rem, -50%); white-space: nowrap;+ font-size: 1.7rem; letter-spacing: 0.04em; color: var(--fg);+ text-shadow: 0 0 0.6rem var(--bg), 0 0 1.2rem var(--bg);+}+.ann div.a { color: var(--accent); }+.ann div.box {+ padding: 0.8rem 1.1rem; border: 1px solid var(--line); background: var(--panel);+ text-shadow: none; line-height: 1.45; font-size: 1.55rem;+}+.ann div.box b { color: var(--accent); font-weight: 600; }+.wm {+ position: absolute; right: 3rem; bottom: calc(var(--bot) + 1.6rem);+ font-size: 2.3rem; letter-spacing: 0.06em; color: var(--fg); opacity: 0.3;+}++/* bottom panel */+.bot {+ position: absolute; left: 0; right: 0; bottom: 0; height: var(--bot);+ display: flex; border-top: 1px solid var(--line); background: var(--panel);+ padding: 2rem 2.8rem 1.6rem;+}+.term { flex: 1; min-width: 0; display: flex; flex-direction: column; padding-right: 2.6rem; }+.thead { display: flex; align-items: baseline; gap: 2.4rem; font-size: 1.75rem; white-space: nowrap; }+.thead .host { font-size: 2.1rem; }+.thead .path { color: var(--dim); }+.thead .status { margin-left: auto; font-size: 1.5rem; letter-spacing: 0.1em; display: flex; align-items: center; gap: 0.9rem; }+.thead .status i { width: 1rem; height: 1rem; border-radius: 50%; background: var(--accent); display: inline-block; }+.prompt { margin-top: 1.9rem; font-size: 2.2rem; white-space: nowrap; overflow: hidden; }+.logs { margin-top: 1.1rem; font-size: 1.85rem; line-height: 1.52; flex: 1; overflow: hidden; }+.logs div { white-space: nowrap; overflow: hidden; text-overflow: clip; }+.logs .ln { color: var(--mute); display: inline-block; width: 6.4rem; }+.logs .hl { color: var(--accent); }+.caret { display: inline-block; width: 0.95em; height: 1.05em; vertical-align: -0.15em; background: var(--accent); margin-left: 0.15em; }+.tfoot { font-size: 1.35rem; color: var(--mute); white-space: nowrap; letter-spacing: 0.04em; }+.side {+ width: 31%; border-left: 1px solid var(--line); padding-left: 2.2rem;+ display: flex; flex-direction: column;+}+.shead { font-size: 1.45rem; letter-spacing: 0.12em; }+.mini { width: 100%; flex: 1; min-height: 0; display: block; margin: 0.8rem 0; }+.stats { display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem 1.4rem; font-size: 1.35rem; color: var(--mute); }+.stats b { display: block; font-size: 2rem; color: var(--fg); font-weight: 600; letter-spacing: 0.02em; }+.sfoot { margin-top: 0.8rem; font-size: 1.3rem; color: var(--mute); letter-spacing: 0.05em; }+.baseline { position: absolute; left: 2.8rem; right: 2.8rem; bottom: 0.9rem; height: 0.25rem; background: var(--line); }+.baseline i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }++/* director layers */+.dir-glitch { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }+.dir-flash {+ position: absolute; inset: 0; pointer-events: none; opacity: 0; mix-blend-mode: screen;+ background: radial-gradient(ellipse 75% 55% at 50% 45%, var(--accent) 0%, transparent 70%), rgba(255,255,255,0.18);+}+.dir-story {+ position: absolute; left: 0; right: 0; top: 0; bottom: 0; pointer-events: none;+ display: flex; align-items: flex-end; justify-content: center; padding: 0 4.5rem 6rem; opacity: 0;+}+.cap { text-align: center; max-width: 96rem; position: relative; }+.cap::before {+ content: ''; position: absolute; inset: -6rem -10rem; z-index: -1;+ background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(0,0,0,0.62) 0%, rgba(0,0,0,0) 100%);+}+:root[data-theme='light'] .cap::before { background: radial-gradient(ellipse 50% 50% at 50% 55%, rgba(243,242,238,0.8) 0%, rgba(243,242,238,0) 100%); }+.cap-main {+ font-family: 'Inter', 'Inter Variable', system-ui, sans-serif; font-weight: 800;+ font-size: 11.5rem; line-height: 0.98; letter-spacing: -0.035em; color: var(--fg);+ text-shadow: 0 0.4rem 2.4rem rgba(0,0,0,0.55);+}+.cap.num .cap-main { font-size: 15rem; font-variant-numeric: tabular-nums; letter-spacing: -0.045em; }+.cap-main .w { display: inline-block; transform-origin: 50% 70%; }+.cap-main .w.hl { background: var(--accent); color: #0a0a0a; padding: 0 0.14em; text-shadow: none; border-radius: 0.06em; }+.cap-sub {+ margin-top: 2rem; font-size: 2.7rem; letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--fg); opacity: 0.85; min-height: 1.3em;+}+.cap-tag {+ display: inline-block; margin-bottom: 1.8rem; padding: 0.5rem 1.2rem; font-size: 2.2rem; letter-spacing: 0.12em;+ border: 1px solid var(--accent); color: var(--accent); background: rgba(0,0,0,0.5);+}diff --git a/sims/kit/util.js b/sims/kit/util.jsnew file mode 100644index 0000000..1dbf9d0--- /dev/null+++ b/sims/kit/util.js@@ -0,0 +1,79 @@+// Small pure helpers shared by every sim. Everything animated must be a pure+// function of `t` (seconds) so live playback and frame capture match.++export const clamp01 = (x) => Math.min(1, Math.max(0, x));+export const lerp = (a, b, k) => a + (b - a) * k;+export const smooth = (x) => {+ const k = clamp01(x);+ return k * k * (3 - 2 * k);+};+export const easeOutCubic = (x) => 1 - Math.pow(1 - clamp01(x), 3);+export const easeInOutCubic = (x) => {+ const k = clamp01(x);+ return k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;+};+export const easeOutExpo = (x) => (x >= 1 ? 1 : 1 - Math.pow(2, -10 * clamp01(x)));+export const easeOutBack = (x, s = 1.7) => {+ const k = clamp01(x) - 1;+ return 1 + (s + 1) * k * k * k + s * k * k;+};+/** 0..1 progress of t between t0 and t1, eased. */+export const prog = (t, t0, t1, ease = easeInOutCubic) => ease((t - t0) / (t1 - t0));++/** Seeded PRNG (mulberry32). Same seed → same sequence. */+export const rng = (seed) => {+ let s = seed >>> 0;+ return () => {+ s = (s + 0x6d2b79f5) >>> 0;+ let x = s;+ x = Math.imul(x ^ (x >>> 15), x | 1);+ x ^= x + Math.imul(x ^ (x >>> 7), x | 61);+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;+ };+};++/** Stateless hash noise in [0,1). */+export const hash = (n) => {+ const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;+ return x - Math.floor(x);+};++/** Random unit vector from a PRNG. */+export const randDir = (r) => {+ const u = r() * 2 - 1;+ const a = r() * Math.PI * 2;+ const s = Math.sqrt(1 - u * u);+ return [s * Math.cos(a), u, s * Math.sin(a)];+};++/**+ * Keyframed value: keys = [[t, value], ...] with numbers or arrays of numbers.+ * Eased between keys, held outside.+ */+export const keyed = (keys, t, ease = easeInOutCubic) => {+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 0; i < keys.length - 1; i++) {+ const [t0, v0] = keys[i];+ const [t1, v1] = keys[i + 1];+ if (t <= t1) {+ const k = ease((t - t0) / (t1 - t0));+ return Array.isArray(v0) ? v0.map((v, j) => lerp(v, v1[j], k)) : lerp(v0, v1, k);+ }+ }+ return keys[keys.length - 1][1];+};++export const fmt = (n, d = 0) =>+ Number(n).toLocaleString('en-US', {minimumFractionDigits: d, maximumFractionDigits: d});+export const pad = (n, w) => String(Math.max(0, Math.floor(n))).padStart(w, '0');++/** Deep merge plain objects; arrays and scalars from `b` replace `a`. */+export const merge = (a, b) => {+ if (!b || typeof b !== 'object' || Array.isArray(b)) return b === undefined ? a : b;+ const out = {...a};+ for (const k of Object.keys(b)) {+ out[k] =+ a && typeof a[k] === 'object' && !Array.isArray(a[k]) && a[k] !== null ? merge(a[k], b[k]) : b[k];+ }+ return out;+};diff --git a/sims/kit/warm.js b/sims/kit/warm.jsnew file mode 100644index 0000000..6c54d75--- /dev/null+++ b/sims/kit/warm.js@@ -0,0 +1,66 @@+// Shader warm-up before a live page's first frame. three.js links a program the first time something draws with it,+// and the frame waits on every one in turn: 1-2 s on a phone or an integrated GPU, and a frozen page meanwhile. Here+// all of them start at once and the page awaits them without blocking (renderer.compileAsync, KHR_parallel_shader_compile):+// the scene's materials and the ones held by post passes (GTAO, bloom, ink, output), which compileAsync never meets+// on its own because they only reach the renderer inside composer.render().+//+// A warmed program only helps when its cache key matches the one the frame asks for, so everything here mirrors the+// frame: each set compiles against the target it draws into (tone mapping, colour space), pass quads have no normals+// like three's fullscreen triangle, override materials (GTAO's normals) see the scene's lights and shadows, and the+// two settings three only fixes on its first render (PCFSoftShadowMap, OutputPass defines) are fixed first.+import * as THREE from 'three';++// three's FullScreenQuad geometry: position and uv, no normal+const TRI = new THREE.BufferGeometry();+TRI.setAttribute('position', new THREE.Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3));+TRI.setAttribute('uv', new THREE.Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2));+// a stand-in for the scene's meshes under an override material+const MESH = new THREE.PlaneGeometry(1, 1);++// every material a pass holds directly or in an array (GTAOPass, UnrealBloomPass, ShaderPass, OutputPass)+const materialsOf = (pass) => Object.values(pass).flatMap((v) => (v?.isMaterial ? [v] : Array.isArray(v) ? v.filter((m) => m?.isMaterial) : []));+// drawn over the scene's own meshes instead of on a quad+const isOverride = (m) => m.isMeshNormalMaterial || m.isMeshDepthMaterial || m.isMeshDistanceMaterial;++/**+ * jobs: [{scene, target}] or [{materials, target, lights, override}]; target null is the canvas, lights a scene whose+ * lights apply, override true for materials drawn as scene.overrideMaterial whatever their type.+ */+export function warmUp(renderer, camera, jobs) {+ // three swaps the removed PCFSoftShadowMap for PCFShadowMap inside its first shadow render, after any warm-up+ if (renderer.shadowMap.type === THREE.PCFSoftShadowMap) renderer.shadowMap.type = THREE.PCFShadowMap;+ const prev = renderer.getRenderTarget();+ const waits = jobs.map(({scene, materials = [], target = null, lights = null, override = false}) => {+ let root = scene;+ if (!root) {+ root = new THREE.Scene();+ for (const m of materials) root.add(new THREE.Mesh(override || isOverride(m) ? MESH : TRI, m));+ }+ renderer.setRenderTarget(target);+ return renderer.compileAsync(root, camera, lights);+ });+ renderer.setRenderTarget(prev);+ return Promise.all(waits);+}++/** The scene and every enabled pass of an EffectComposer; the last pass draws to the canvas when the composer does. */+export function warmComposer(renderer, composer, scene, camera, jobs = []) {+ const target = composer.renderTarget1;+ const passes = composer.passes.filter((p) => p.enabled);+ const last = composer.renderToScreen ? passes[passes.length - 1] : null;+ // OutputPass picks its defines from the renderer on its first render: run that part now, with the draw left out+ for (const p of passes.filter((x) => x.isOutputPass)) {+ const quad = p._fsQuad;+ p._fsQuad = {render() {}};+ p.render(renderer, composer.renderTarget2, composer.renderTarget1);+ p._fsQuad = quad;+ }+ const mats = passes.filter((p) => p !== last).flatMap(materialsOf);+ return warmUp(renderer, camera, [+ {scene, target},+ {materials: mats.filter((m) => !isOverride(m)), target},+ {materials: mats.filter(isOverride), target, lights: scene},+ {materials: last ? materialsOf(last) : [], target: null},+ ...jobs,+ ]);+}diff --git a/sims/strandbeest-film/main.js b/sims/strandbeest-film/main.jsnew file mode 100644index 0000000..2f5c920--- /dev/null+++ b/sims/strandbeest-film/main.js@@ -0,0 +1,4 @@+// Strandbeest SB-10 console film. Shared code in ../strandbeest-shared.+import {run} from '../strandbeest-shared/film.js';++run();diff --git a/sims/strandbeest-film/timeline.json b/sims/strandbeest-film/timeline.jsonnew file mode 100644index 0000000..a7efe83--- /dev/null+++ b/sims/strandbeest-film/timeline.json@@ -0,0 +1 @@+{"duration":30.7}diff --git a/sims/strandbeest-live/main.js b/sims/strandbeest-live/main.jsnew file mode 100644index 0000000..048b869--- /dev/null+++ b/sims/strandbeest-live/main.js@@ -0,0 +1,5 @@+import {runLive} from '../strandbeest-shared/live.js';++// SB-10 as an interactive page for the site: views, isolate a leg, trace the feet, the wind slider, orbit, an auto+// tour when left alone.+runLive();diff --git a/sims/strandbeest-shared/beast.js b/sims/strandbeest-shared/beast.jsnew file mode 100644index 0000000..61b705c--- /dev/null+++ b/sims/strandbeest-shared/beast.js@@ -0,0 +1,419 @@+// The beest itself, built from nothing but tubes, red joint caps, crank throws, rubber feet and sails. One crankshaft+// runs the long axis (z); each station on it carries a crank throw and two mirrored Jansen legs (front and back),+// so the beast walks broadside along -x like the real ones on the beach. update(theta, t) poses every link from the+// solved linkage: instanced meshes, matrices recomposed per frame, nothing animated by hand.+import * as THREE from 'three';+import {FOOT_MIN, JOINTS, LINKS, PATH, solveLeg, solveMirror} from './jansen.js';++const V3 = THREE.Vector3;+export const S = 0.012; // metres per Jansen unit+export const PAD = 2.2; // foot pad half-height, units+export const CFG = {stations: 10, spacing: 26, half: 4.2};+// phase of each station's crank throw: a wave that runs down the spine+export const phaseOf = (s) => -s * ((Math.PI * 2) / CFG.stations);+// link layers inside a leg plane, toward (+1) or away from (-1) the station centre+const LAYER = {j: 1, k: 1, b: -1, c: -1, d: -1, e: 0, f: 0, g: -1, h: 0, i: 1};++// ------------------------------------------------------------ body motion without foot slip+// The body moves at minus the mean stance velocity of the feet on the ground, integrated over one crank turn.+const NT = 1440;+const legsAt = (th) => {+ const out = [];+ for (let s = 0; s < CFG.stations; s++) {+ const ps = th + phaseOf(s);+ out.push(solveLeg(ps).F, solveMirror(ps).F);+ }+ return out;+};+const MOTION = (() => {+ const X = new Float32Array(NT + 1);+ const Y = new Float32Array(NT + 1);+ const dth = (Math.PI * 2) / NT;+ let x = 0;+ let vPrev = 20;+ for (let n = 0; n <= NT; n++) {+ const th = n * dth;+ const a = legsAt(th - dth * 0.5);+ const b = legsAt(th + dth * 0.5);+ let ws = 0;+ let vs = 0;+ let low = Infinity;+ for (let q = 0; q < a.length; q++) {+ const lift = (a[q][1] + b[q][1]) / 2 - FOOT_MIN;+ low = Math.min(low, lift);+ const w = Math.max(0, 1 - lift / 1.2);+ ws += w;+ vs += (w * (b[q][0] - a[q][0])) / dth;+ }+ const v = ws > 0 ? vs / ws : vPrev;+ vPrev = v;+ X[n] = x;+ Y[n] = low;+ x -= v * dth;+ }+ return {X, Y, stride: X[NT]};+})();+/** Body offset along x (units) and the lowest foot's lift for crank angle theta (any number of turns). */+export function bodyAt(theta) {+ const turns = Math.floor(theta / (Math.PI * 2));+ const u = (theta / (Math.PI * 2) - turns) * NT;+ const n = Math.floor(u);+ const k = u - n;+ return {x: turns * MOTION.stride + MOTION.X[n] + (MOTION.X[n + 1] - MOTION.X[n]) * k, low: MOTION.Y[n] + (MOTION.Y[n + 1] - MOTION.Y[n]) * k};+}+export const STRIDE = MOTION.stride;+/** One leg's joints for station s, side 0 (front, foot toward -x) or 1 (the mirror), at crank angle theta. */+export const legAt = (s, side, theta) => (side ? solveMirror : solveLeg)(theta + phaseOf(s));+/** The leg plane's z, in units, for station s and side. */+export const legZ = (s, side) => -((CFG.stations - 1) * CFG.spacing) / 2 + s * CFG.spacing + (side ? CFG.half : -CFG.half);+/** Where a foot sits on its own path (0..1, the path's crank parameter) at crank angle theta. */+export const footParam = (s, side, theta) => {+ const ps = theta + phaseOf(s);+ const a = side ? Math.PI - ps : ps;+ return (((a / (Math.PI * 2)) % 1) + 1) % 1;+};++// the foot path as a lit trace: visible over the arc the foot swept in the last uLen of a turn+const TRACE_VERT = /* glsl */ `attribute float aS; varying float vS; void main(){ vS = aS; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;+const TRACE_FRAG = /* glsl */ `uniform vec3 uCol; uniform float uHead; uniform float uLen; uniform float uSign; uniform float uAlpha; varying float vS;+ void main(){+ float d = fract(uSign * (uHead - vS));+ float on = 1.0 - smoothstep(uLen - 0.004, uLen + 0.004, d);+ // the freshest part of the arc burns brighter+ float hot = 0.75 + 0.25 * (1.0 - d / max(uLen, 1e-3));+ if (on * uAlpha < 0.01) discard;+ gl_FragColor = vec4(uCol * hot, on * uAlpha);+ }`;++// ------------------------------------------------------------ the build+export function buildBeast(P) {+ const group = new THREE.Group();+ const N = CFG.stations;+ const z0 = -((N - 1) * CFG.spacing) / 2;+ const zs = (s) => z0 + s * CFG.spacing;++ const mats = {+ tube: new THREE.MeshPhysicalMaterial({color: P.tube, roughness: 0.34, metalness: 0, clearcoat: 0.35, clearcoatRoughness: 0.4}),+ joint: new THREE.MeshPhysicalMaterial({color: P.joint, roughness: 0.32, metalness: 0, clearcoat: 0.5, clearcoatRoughness: 0.3}),+ steel: new THREE.MeshStandardMaterial({color: P.steel, roughness: 0.32, metalness: 0.75}),+ foot: new THREE.MeshStandardMaterial({color: P.foot, roughness: 0.85, metalness: 0}),+ sail: new THREE.MeshStandardMaterial({color: P.sail, roughness: 0.7, metalness: 0, transparent: true, opacity: 0.86, side: THREE.DoubleSide, depthWrite: false}),+ };+ // the isolated leg keeps its own solid copies while everything else turns to glass+ mats.heroTube = mats.tube.clone();+ mats.heroJoint = mats.joint.clone();+ mats.heroFoot = mats.foot.clone();+ for (const k of ['tube', 'joint', 'steel', 'foot']) mats[k].transparent = true;+ const tubeCol = new THREE.Color(P.tube);+ const heroCol = new THREE.Color(P.hero || '#2a2622');+ const tubeGeo = new THREE.CylinderGeometry(1, 1, 1, 16, 1, true);+ const capGeo = new THREE.CylinderGeometry(1, 1, 1, 24, 1);+ // a joint cap: a short cylinder with a bevel, axis along z+ capGeo.rotateX(Math.PI / 2);+ const footGeo = new THREE.SphereGeometry(1, 24, 14);++ // counts+ const legs = N * 2;+ const nTubes = legs * LINKS.length + N * 6 + (N - 1) * 3 + N * 3; // legs, frame triangles, longerons, mast + boom + stay+ const nCaps = legs * (JOINTS.length + 1) + N * 3 + N * 2; // leg joints + the crank pin per leg, bearings, mast caps+ const nSteel = N * 3 + 1; // crank pins, two webs per station, the axle+ const tubes = new THREE.InstancedMesh(tubeGeo, mats.tube, nTubes);+ const caps = new THREE.InstancedMesh(capGeo, mats.joint, nCaps);+ const steel = new THREE.InstancedMesh(tubeGeo, mats.steel, nSteel);+ const feet = new THREE.InstancedMesh(footGeo, mats.foot, legs);+ const heroTubes = new THREE.InstancedMesh(tubeGeo, mats.heroTube, LINKS.length + 1);+ const heroCaps = new THREE.InstancedMesh(capGeo, mats.heroJoint, JOINTS.length + 2);+ const heroFeet = new THREE.InstancedMesh(footGeo, mats.heroFoot, 1);+ const main = [tubes, caps, steel, feet];+ const hero = [heroTubes, heroCaps, heroFeet];+ for (const m of [...main, ...hero]) {+ m.castShadow = true;+ m.receiveShadow = true;+ m.frustumCulled = false;+ m.instanceMatrix.setUsage(THREE.DynamicDrawUsage);+ group.add(m);+ }++ // foot traces, one closed loop per leg in its own plane, the crank parameter carried per vertex+ const traces = [];+ {+ const NP = PATH.length;+ const cum = new Float32Array(NP + 1);+ for (let n = 1; n <= NP; n++) {+ const a = PATH[n - 1];+ const b = PATH[n % NP];+ cum[n] = cum[n - 1] + Math.hypot(b[0] - a[0], b[1] - a[1]);+ }+ const SEG = 240;+ const RAD = 8;+ for (let st = 0; st < N; st++)+ for (let side = 0; side < 2; side++) {+ const zl = legZ(st, side);+ const pts = [];+ const par = [];+ for (let i = 0; i < SEG; i++) {+ // even steps along the loop, each tagged with the crank parameter it was reached at+ const target = (i / SEG) * cum[NP];+ let lo = 0;+ let hi = NP;+ while (hi - lo > 1) {+ const m = (lo + hi) >> 1;+ if (cum[m] <= target) lo = m;+ else hi = m;+ }+ const a = PATH[lo % NP];+ const b = PATH[(lo + 1) % NP];+ const k = (target - cum[lo]) / Math.max(1e-6, cum[lo + 1] - cum[lo]);+ const u = a[0] + (b[0] - a[0]) * k;+ const v = a[1] + (b[1] - a[1]) * k;+ pts.push(new V3((side ? -u : u) * S, (v - PAD * 0.25) * S, zl * S));+ par.push((lo + k) / NP);+ }+ const geo = new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts, true), SEG, 0.55 * S, RAD, true);+ const aS = new Float32Array(geo.attributes.position.count);+ for (let i = 0; i <= SEG; i++) for (let r = 0; r <= RAD; r++) aS[i * (RAD + 1) + r] = par[i % SEG];+ geo.setAttribute('aS', new THREE.BufferAttribute(aS, 1));+ const mat = new THREE.ShaderMaterial({+ vertexShader: TRACE_VERT,+ fragmentShader: TRACE_FRAG,+ uniforms: {uCol: {value: new THREE.Color(P.trace || '#e0662b')}, uHead: {value: 0}, uLen: {value: 1}, uSign: {value: side ? -1 : 1}, uAlpha: {value: 0}},+ transparent: true,+ depthWrite: false,+ });+ const mesh = new THREE.Mesh(geo, mat);+ mesh.renderOrder = 3;+ mesh.frustumCulled = false;+ mesh.visible = false;+ mesh.userData = {st, side};+ group.add(mesh);+ traces.push(mesh);+ }+ }++ // sails: one cambered sheet per station, re-shaped every frame (wind fill + flutter)+ const SU = 14;+ const SV = 18;+ const sailTex = (() => {+ const c = document.createElement('canvas');+ c.width = c.height = 512;+ const g = c.getContext('2d');+ g.fillStyle = '#ffffff';+ g.fillRect(0, 0, 512, 512);+ g.strokeStyle = 'rgba(120,112,100,0.5)';+ g.lineWidth = 2;+ for (let k = 1; k < 6; k++) {+ g.beginPath();+ g.moveTo(0, (k * 512) / 6);+ g.lineTo(512, (k * 512) / 6);+ g.stroke();+ }+ g.strokeStyle = 'rgba(120,112,100,0.26)';+ for (let k = 1; k < 4; k++) {+ g.beginPath();+ g.moveTo((k * 512) / 4, 0);+ g.lineTo((k * 512) / 4, 512);+ g.stroke();+ }+ const t = new THREE.CanvasTexture(c);+ t.colorSpace = THREE.SRGBColorSpace;+ t.anisotropy = 8;+ return t;+ })();+ mats.sail.map = sailTex;+ const SAIL = {mast: 30, base: 30, height: 64, chord: 52, yaw: -0.5};+ const cy = Math.cos(SAIL.yaw);+ const sy = Math.sin(SAIL.yaw);+ // a point of the sail plane (u along the chord, zz off the plane) turned about the mast to meet the wind+ const yawU = (u, zz) => SAIL.mast + (u - SAIL.mast) * cy - zz * sy;+ const yawZ = (u, zz) => (u - SAIL.mast) * sy + zz * cy;+ const sails = [...Array(N)].map((_, s) => {+ const geo = new THREE.PlaneGeometry(1, 1, SU, SV);+ const mesh = new THREE.Mesh(geo, mats.sail);+ mesh.position.z = zs(s) * S;+ mesh.renderOrder = 2;+ mesh.frustumCulled = false;+ group.add(mesh);+ return mesh;+ });+ // the sail outline in (u, v) for chord fraction r (0 at the mast) and height fraction q+ const sailPt = (r, q) => {+ const chord = SAIL.chord * (1 - Math.pow(q, 1.35)) * (0.92 + 0.08 * Math.sin(q * Math.PI));+ return [SAIL.mast - r * chord, SAIL.base + q * SAIL.height - r * r * 10 * (1 - q)];+ };++ // ------------------------------------------------------------ per-frame pose+ const M4 = new THREE.Matrix4();+ const q = new THREE.Quaternion();+ const qZ = new THREE.Quaternion(); // caps are built along z already+ const Y = new V3(0, 1, 0);+ const dir = new V3();+ const mid = new V3();+ const sc = new V3();+ const pa = new V3();+ const pb = new V3();+ let it = 0;+ let ic = 0;+ let is = 0;+ let ht = 0;+ let hc = 0;+ const tube = (mesh, i, A, B, r) => {+ dir.subVectors(B, A);+ const L = dir.length();+ mid.addVectors(A, B).multiplyScalar(0.5);+ q.setFromUnitVectors(Y, dir.multiplyScalar(1 / L));+ sc.set(r * S, L, r * S);+ M4.compose(mid, q, sc);+ mesh.setMatrixAt(i, M4);+ };+ let toHero = false;+ const T = (u0, v0, z0_, u1, v1, z1, r = 1.15) => {+ pa.set(u0 * S, v0 * S, z0_ * S);+ pb.set(u1 * S, v1 * S, z1 * S);+ if (toHero) tube(heroTubes, ht++, pa, pb, r);+ else tube(tubes, it++, pa, pb, r);+ };+ const ST = (u0, v0, z0_, u1, v1, z1, r) => {+ pa.set(u0 * S, v0 * S, z0_ * S);+ pb.set(u1 * S, v1 * S, z1 * S);+ tube(steel, is++, pa, pb, r);+ };+ const CAP = (u, v, z, r = 2.1, len = 5.2) => {+ mid.set(u * S, v * S, z * S);+ sc.set(r * S, r * S, len * S);+ M4.compose(mid, qZ, sc);+ if (toHero) heroCaps.setMatrixAt(hc++, M4);+ else caps.setMatrixAt(ic++, M4);+ };+ const TOP = 20; // frame apex above the axle++ // ops: iso (0..1) isolates the hero leg {st, side}; trace (0..1) shows every foot loop, heroTrace (0..1) how much+ // of the hero's loop its foot has drawn so far+ const out = {heroJ: null, heroZ: 0};+ const update = (theta, t = 0, wind = 1, ops = {}) => {+ const iso = ops.iso ?? 0;+ const H = ops.hero ?? {st: 0, side: 0};+ it = 0;+ ic = 0;+ is = 0;+ ht = 0;+ hc = 0;+ // glass: the ghosted frame fades, the hero leg darkens to ink+ const ghost = 1 - 0.84 * iso;+ mats.tube.opacity = ghost;+ mats.joint.opacity = ghost;+ mats.foot.opacity = ghost;+ mats.steel.opacity = 1 - 0.6 * iso;+ mats.heroTube.color.copy(tubeCol).lerp(heroCol, iso);+ for (const m of hero) m.visible = iso > 0.001;+ const hw = CFG.half;+ // the crankshaft+ ST(0, 0, zs(0) - 14, 0, 0, zs(N - 1) + 14, 1.5);+ const feetM = [];+ for (let s = 0; s < N; s++) {+ const z = zs(s);+ const ps = theta + phaseOf(s);+ const legsS = [+ {J: solveLeg(ps), z: z - hw, w: 1},+ {J: solveMirror(ps), z: z + hw, w: -1},+ ];+ // crank throw: two webs and the pin both legs ride on+ const A = legsS[0].J.A;+ ST(0, 0, z - hw - 3.2, A[0], A[1], z - hw - 3.2, 1.6);+ ST(0, 0, z + hw + 3.2, A[0], A[1], z + hw + 3.2, 1.6);+ ST(A[0], A[1], z - hw - 3.2, A[0], A[1], z + hw + 3.2, 1.25);+ legsS.forEach(({J, z: zl, w}, side) => {+ toHero = iso > 0.001 && s === H.st && side === H.side;+ for (const [p, r, key] of LINKS) {+ const dz = LAYER[key] * w * 1.25;+ T(J[p][0], J[p][1], zl + dz, J[r][0], J[r][1], zl + dz);+ }+ for (const key of JOINTS) CAP(J[key][0], J[key][1], zl, key === 'P' ? 2.5 : 2.05, key === 'P' ? 6.2 : 5.0);+ CAP(J.A[0], J.A[1], zl, 1.9, 4.4);+ if (toHero) {+ // the crank m drawn as part of the leg, and the axle bearing it turns on+ T(0, 0, zl + w * 2.6, J.A[0], J.A[1], zl + w * 2.6, 1.3);+ CAP(0, 0, zl, 2.9, 4.6);+ }+ if (s === H.st && side === H.side) {+ out.heroJ = J;+ out.heroZ = zl;+ }+ feetM.push([J.F, zl, J.E, toHero]);+ toHero = false;+ // frame: axle bearing to the fixed pivot, pivot to the apex+ T(0, 0, zl, J.P[0], J.P[1], zl, 1.3);+ T(J.P[0], J.P[1], zl, 0, TOP, z, 1.3);+ });+ CAP(0, 0, z - hw, 2.9, 4.6);+ CAP(0, 0, z + hw, 2.9, 4.6);+ CAP(0, TOP, z, 2.4, 6);+ // mast, boom and a stay to the frame+ const top = sailPt(0, 1);+ const foot = sailPt(1, 0);+ T(SAIL.mast, TOP, z, top[0], top[1] + 4, z, 1.05);+ T(SAIL.mast, SAIL.base, z, yawU(foot[0], 0), foot[1], z + yawZ(foot[0], 0), 0.9);+ T(0, TOP, z, SAIL.mast, SAIL.base - 2, z, 1.0);+ CAP(SAIL.mast, SAIL.base, z, 1.8, 3.6);+ CAP(top[0], top[1] + 4, z, 1.6, 3.2);+ }+ // longerons: pivot rails front and back, the apex spine+ for (let s = 0; s < N - 1; s++) {+ const a = zs(s);+ const b = zs(s + 1);+ T(-38, -7.8, a - hw, -38, -7.8, b - hw, 1.2);+ T(38, -7.8, a + hw, 38, -7.8, b + hw, 1.2);+ T(0, TOP, a, 0, TOP, b, 1.3);+ }+ // feet: rubber pads under each lower link, flattened and tipped with the shin+ let fk = 0;+ for (let k = 0; k < feetM.length; k++) {+ const [F, zl, E, isHero] = feetM[k];+ dir.set(F[0] - E[0], F[1] - E[1], 0).normalize();+ q.setFromUnitVectors(Y, dir.multiplyScalar(-1));+ mid.set(F[0] * S, (F[1] - PAD * 0.25) * S, zl * S);+ sc.set(3.4 * S, PAD * S, 4.2 * S);+ M4.compose(mid, q, sc);+ if (isHero) heroFeet.setMatrixAt(0, M4);+ else feet.setMatrixAt(fk++, M4);+ }+ tubes.count = it;+ caps.count = ic;+ steel.count = is;+ feet.count = fk;+ heroTubes.count = ht;+ heroCaps.count = hc;+ for (const m of [...main, ...hero]) m.instanceMatrix.needsUpdate = true;++ // foot traces: the hero's loop draws itself, the rest fade in together+ const trace = ops.trace ?? 0;+ const heroTrace = ops.heroTrace ?? 0;+ for (const m of traces) {+ const {st, side} = m.userData;+ const isH = st === H.st && side === H.side;+ const u = m.material.uniforms;+ u.uHead.value = footParam(st, side, theta);+ u.uLen.value = isH && heroTrace > 0 ? Math.min(1, heroTrace) : 1;+ u.uAlpha.value = (isH ? Math.max(heroTrace > 0 ? 1 : 0, trace) : trace * (1 - 0.9 * iso)) * (ops.traceFade ?? 1);+ m.visible = u.uAlpha.value > 0.01 && u.uLen.value > 0.002;+ }++ // sails: filled by the wind, a flutter running aft along the leech+ for (let s = 0; s < N; s++) {+ const pos = sails[s].geometry.attributes.position;+ let n = 0;+ for (let iv = 0; iv <= SV; iv++) {+ const qv = 1 - iv / SV;+ for (let iu = 0; iu <= SU; iu++) {+ const r = iu / SU;+ const [u, v] = sailPt(r, qv);+ const fill = wind * 7.5 * Math.sin(Math.PI * Math.min(1, r * 1.15)) * (0.55 + 0.45 * qv);+ const flut = 0.9 * r * r * Math.sin(t * 9.0 - r * 7.0 + qv * 3.0 + s * 1.7) * (0.4 + 0.6 * wind);+ pos.setXYZ(n++, yawU(u, fill + flut) * S, v * S, yawZ(u, fill + flut) * S);+ }+ }+ pos.needsUpdate = true;+ sails[s].geometry.computeVertexNormals();+ }+ };+ return {group, update, mats, sails, traces, main, hero, out, length: ((N - 1) * CFG.spacing + 28) * S, zs};+}diff --git a/sims/strandbeest-shared/console.js b/sims/strandbeest-shared/console.jsnew file mode 100644index 0000000..219c7cc--- /dev/null+++ b/sims/strandbeest-shared/console.js@@ -0,0 +1,375 @@+// The SB-10 console: an engineering sheet laid over the full-bleed dune (warm paper+// panels, sepia ink) with a burnt-orange accent that matches the foot traces. Fixed 1600 x 900 CSS layout;+// update(state) redraws every live part from the frame's state (the linkage panel is the hero leg's real pose, the+// contact chart the real stance of all 20 feet, the crank dial the real throws), so a captured frame depends only on t.+import {HOLY, PATH} from './jansen.js';++export const C = {ink: '#2f2a22', mute: '#8a7f6c', faint: '#b9ae99', line: 'rgba(110,98,78,.55)', paper: 'rgba(243,238,227,.88)', accent: '#d0592a', red: '#c9342a', dark: '#3a342b'};+export const VIEW_KEYS = ['cine', 'leg', 'front', 'side', 'top'];+export const TOGGLES = ['iso', 'trace'];+// the order the hero leg's labels appear in, and what each one is+export const LABELS = [+ ['a', 'PIVOT OFFSET · X'],+ ['l', 'PIVOT OFFSET · Y'],+ ['m', 'CRANK'],+ ['j', 'UPPER DRIVE BAR'],+ ['k', 'LOWER DRIVE BAR'],+ ['b', 'UPPER ROCKER'],+ ['c', 'LOWER ROCKER'],+ ['d', 'UPPER TRIANGLE'],+ ['e', 'UPPER TRIANGLE'],+ ['f', 'CONNECTING BAR'],+ ['g', 'LOWER TRIANGLE'],+ ['h', 'SHIN'],+ ['i', 'SHIN BRACE'],+];+const TABLE = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];+const CSS = `+#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}+.ui{position:absolute;inset:0;pointer-events:none}+.pn{position:absolute;background:${C.paper};border:1px solid ${C.line};backdrop-filter:blur(3px)}+.hd{font-size:9px;font-weight:700;letter-spacing:1.7px;text-transform:uppercase;white-space:nowrap}+.hd i{font-style:normal;color:${C.accent};margin-right:7px;letter-spacing:0}+.lb{font-size:8px;font-weight:600;letter-spacing:1.3px;color:${C.mute};text-transform:uppercase;white-space:nowrap}+.vl{font-size:10.5px;font-weight:600;letter-spacing:.4px;white-space:nowrap}+.mono{font-family:'JetBrains Mono',ui-monospace,monospace}+.vb{position:absolute;height:19px;padding:0 9px;display:flex;align-items:center;font-size:8.5px;font-weight:700;letter-spacing:1.4px;border:1px solid ${C.line};background:rgba(243,238,227,.9);color:${C.dark}}+.call{position:absolute;white-space:nowrap;background:rgba(243,238,227,.86);border:1px solid ${C.line};padding:4px 7px 4px}+.call b{display:block;font-size:8.5px;font-weight:700;letter-spacing:1.4px}+.call span{display:block;font-size:7.5px;letter-spacing:1.1px;color:${C.mute};margin-top:2px}+.tag{position:absolute;display:flex;align-items:center;gap:5px;white-space:nowrap;transform:translate(-50%,-50%)}+.tag b{width:17px;height:17px;border-radius:50%;display:grid;place-items:center;font:700 10px 'JetBrains Mono',monospace;color:#f6f1e6;background:${C.dark};box-shadow:0 0 0 1.5px rgba(246,241,230,.9)}+.tag span{font:600 8.5px 'JetBrains Mono',monospace;color:${C.dark};background:rgba(243,238,227,.86);padding:1px 4px;border:1px solid ${C.line}}+.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 2px 3px rgba(0,0,0,.3))}+.ring{position:absolute;width:40px;height:40px;margin:-20px 0 0 -20px;border-radius:50%;border:1.6px solid ${C.accent};opacity:0;z-index:49}+`;+const el = (h) => {+ const d = document.createElement('div');+ d.innerHTML = h.trim();+ return d.firstElementChild;+};+const SPECS = [+ ['CLASS', 'WIND-POWERED WALKER'],+ ['LEGS', '20 · 10 CRANK THROWS × 2'],+ ['LINKAGE', 'JANSEN · 11 BARS PER LEG'],+ ['LENGTH', '3.1 m'],+ ['HEIGHT', '2.3 m TO SAIL TIP'],+ ['FRAME', 'PVC CONDUIT Ø 28 mm'],+ ['DRIVE', '10 SAILS → 1 CRANKSHAFT'],+];+export const WIND_MAX = 16;++export function createConsole(app) {+ const style = document.createElement('style');+ style.textContent = CSS;+ document.head.appendChild(style);+ const ui = el(`<div class="ui"></div>`);+ app.appendChild(ui);+ const add = (h) => {+ const n = el(h);+ ui.appendChild(n);+ return n;+ };++ // ------------------------------------------------------------ top bar: the sheet's header, views and toggles+ add(`<div style="position:absolute;left:12px;right:12px;top:8px;height:24px;border-bottom:1px solid ${C.line}"></div>`);+ add(`<div class="lb" style="left:18px;top:14px;position:absolute;color:${C.dark}">◇ BEACH KINEMATICS LAB · WIND DIVISION</div>`);+ add(`<div class="lb mono" style="position:absolute;left:0;right:0;top:14px;text-align:center;color:${C.dark};letter-spacing:2px">◆ SB-10-001 ◆</div>`);+ const btn = {};+ {+ let x = 1588;+ const right = (key, txt, w) => {+ x -= w;+ btn[key] = add(`<div class="vb" style="left:${x}px;top:10px;width:${w}px;justify-content:center">${txt}</div>`);+ x -= 4;+ };+ right('pause', '❚❚ PAUSE', 84);+ x -= 10;+ right('trace', 'TRACE FEET', 90);+ right('iso', 'ISOLATE LEG', 98);+ x -= 10;+ for (const k of [...VIEW_KEYS].reverse()) right(k, k.toUpperCase(), k.length * 7 + 22);+ add(`<div class="lb" style="position:absolute;left:${x - 34}px;top:15px">VIEW</div>`);+ }+ add(`<div class="lb" style="position:absolute;right:16px;top:36px;letter-spacing:1px;font-size:7.5px">DRAG TO ORBIT · 1–5 VIEWS · I ISOLATE · T TRACE · SPACE PAUSE</div>`);++ // ------------------------------------------------------------ title block, specs and live readings, top left+ add(`<div style="position:absolute;left:34px;top:50px;font-size:31px;font-weight:500;letter-spacing:.6px;line-height:1">STRANDBEEST <span style="color:${C.accent}">SB-10</span></div>`);+ add(`<div class="lb" style="position:absolute;left:35px;top:88px;color:${C.dark};font-size:8.5px;letter-spacing:1.6px">WIND-POWERED WALKING MACHINE · JANSEN LINKAGE</div>`);+ add(`<div style="position:absolute;left:35px;top:110px;display:grid;grid-template-columns:96px auto;row-gap:6px">${SPECS.map(([k, v]) => `<span class="lb">${k}:</span><span class="vl">${v}</span>`).join('')}+ <span style="grid-column:1/3;height:1px;background:${C.line};margin:3px 0"></span>+ <span class="lb">WIND:</span><span class="vl mono" data-k="wind"></span>+ <span class="lb">CRANK:</span><span class="vl mono" data-k="rpm"></span>+ <span class="lb">GROUND SPEED:</span><span class="vl mono" data-k="speed"></span>+ <span class="lb">FEET ON SAND:</span><span class="vl mono" data-k="feet"></span></div>`);++ // ------------------------------------------------------------ the holy numbers, left+ const HN = {x: 34, y: 368, w: 262, h: 352};+ add(`<div class="pn" style="left:${HN.x}px;top:${HN.y}px;width:${HN.w}px;height:${HN.h}px"></div>`);+ add(`<div class="hd" style="position:absolute;left:${HN.x + 12}px;top:${HN.y + 11}px"><i>›››</i>THE ELEVEN HOLY NUMBERS</div>`);+ add(`<div class="lb" style="position:absolute;left:${HN.x + 12}px;top:${HN.y + 26}px;font-size:7px">LINK LENGTHS · JANSEN 1990 · UNITS ≈ CM</div>`);+ const rows = {};+ TABLE.forEach((k, i) => {+ const y = HN.y + 46 + i * 21 + (i >= 11 ? 10 : 0);+ rows[k] = add(`<div style="position:absolute;left:${HN.x + 12}px;top:${y}px;width:${HN.w - 24}px;height:19px;display:flex;align-items:center;gap:9px">+ <span class="mono" data-r="dot" style="width:17px;height:17px;border-radius:50%;display:grid;place-items:center;font-size:9.5px;font-weight:700;border:1px solid ${C.line}">${k}</span>+ <span class="mono" data-r="val" style="font-size:11px;font-weight:600;width:38px;text-align:right">${HOLY[k].toFixed(1)}</span>+ <span style="flex:1;height:5px;background:rgba(110,98,78,.14);position:relative"><span data-r="bar" style="position:absolute;left:0;top:0;bottom:0;width:${((HOLY[k] / 66) * 100).toFixed(1)}%;background:${C.faint}"></span></span></div>`);+ });+ add(`<div style="position:absolute;left:${HN.x + 12}px;top:${HN.y + 46 + 11 * 21 + 1}px;width:${HN.w - 24}px;height:0;border-top:1px dashed ${C.line}"></div>`);+ add(`<div class="lb" style="position:absolute;left:${HN.x + 12}px;top:${HN.y + HN.h - 18}px;font-size:7px">l, m · THE CRANK AND ITS AXLE OFFSET</div>`);++ // ------------------------------------------------------------ leg linkage, top right+ const LP = {x: 1300, y: 52, w: 272, h: 398};+ add(`<div class="pn" style="left:${LP.x}px;top:${LP.y}px;width:${LP.w}px;height:${LP.h}px"></div>`);+ add(`<div class="hd" style="position:absolute;left:${LP.x + 12}px;top:${LP.y + 11}px"><i>›››</i>LEG LINKAGE · LEG 01F</div>`);+ const link = add(`<svg style="position:absolute;left:${LP.x + 12}px;top:${LP.y + 30}px" width="248" height="290"></svg>`);+ add(`<div style="position:absolute;left:${LP.x + 12}px;top:${LP.y + 326}px;width:${LP.w - 24}px;display:grid;grid-template-columns:1fr 1fr;row-gap:5px">+ <span class="lb">STANCE</span><span class="vl mono" style="text-align:right">155° OF 360°</span>+ <span class="lb">STRIDE</span><span class="vl mono" style="text-align:right">672 mm</span>+ <span class="lb">FOOT LIFT</span><span class="vl mono" style="text-align:right">268 mm</span>+ <span class="lb">CRANK ANGLE</span><span class="vl mono" style="text-align:right" data-k="crank"></span></div>`);++ // ------------------------------------------------------------ wind and drive, right+ const WP = {x: 1300, y: 462, w: 272, h: 258};+ add(`<div class="pn" style="left:${WP.x}px;top:${WP.y}px;width:${WP.w}px;height:${WP.h}px"></div>`);+ add(`<div class="hd" style="position:absolute;left:${WP.x + 12}px;top:${WP.y + 11}px"><i>›››</i>WIND · DRIVE TRAIN</div>`);+ const SL = {x: WP.x + 16, y: WP.y + 54, w: WP.w - 32};+ add(`<div class="lb" style="position:absolute;left:${SL.x}px;top:${SL.y - 18}px">WIND SPEED</div>`);+ const windVal = add(`<div class="vl mono" style="position:absolute;right:${1600 - (SL.x + SL.w)}px;top:${SL.y - 20}px;color:${C.accent}"></div>`);+ add(`<div style="position:absolute;left:${SL.x}px;top:${SL.y}px;width:${SL.w}px;height:3px;background:rgba(110,98,78,.22)"></div>`);+ const fill = add(`<div style="position:absolute;left:${SL.x}px;top:${SL.y}px;height:3px;background:${C.accent}"></div>`);+ const knob = add(`<div style="position:absolute;top:${SL.y - 6.5}px;width:15px;height:15px;margin-left:-7.5px;border-radius:50%;background:#f6f1e6;border:1.6px solid ${C.dark}"></div>`);+ add(`<svg style="position:absolute;left:${SL.x}px;top:${SL.y + 8}px" width="${SL.w}" height="14">${[0, 4, 8, 12, 16].map((v) => `<line x1="${(v / WIND_MAX) * SL.w}" x2="${(v / WIND_MAX) * SL.w}" y1="0" y2="4" stroke="${C.dark}" stroke-width=".8"/><text x="${Math.min(SL.w - 8, Math.max(4, (v / WIND_MAX) * SL.w))}" y="12" font-size="6.5" text-anchor="middle" fill="${C.mute}">${v}${v === 16 ? ' m/s' : ''}</text>`).join('')}</svg>`);+ const windHist = add(`<svg style="position:absolute;left:${SL.x}px;top:${SL.y + 34}px" width="${SL.w}" height="58"></svg>`);+ add(`<div style="position:absolute;left:${SL.x}px;top:${SL.y + 102}px;width:${SL.w}px;display:grid;grid-template-columns:1fr auto;row-gap:5px">+ <span class="lb">SAIL LOAD</span><span class="vl mono" data-k="load"></span>+ <span class="lb">CRANKSHAFT</span><span class="vl mono" data-k="rpm2"></span>+ <span class="lb">STEPS / MIN</span><span class="vl mono" data-k="steps"></span>+ <span class="lb">DISTANCE WALKED</span><span class="vl mono" data-k="dist"></span></div>`);++ // ------------------------------------------------------------ bottom strip: contact chart, crankshaft, ride+ const BY = 734;+ const BH = 154;+ add(`<div class="pn" style="left:34px;top:${BY}px;width:960px;height:${BH}px"></div>`);+ add(`<div class="hd" style="position:absolute;left:46px;top:${BY + 11}px"><i>›››</i>FOOT CONTACT · 20 LEGS · LAST 3 S</div>`);+ add(`<div class="lb" style="position:absolute;left:760px;top:${BY + 12}px"><span style="display:inline-block;width:14px;height:6px;background:${C.dark};vertical-align:middle;margin-right:6px"></span>ON SAND <span style="display:inline-block;width:14px;height:6px;background:${C.accent};vertical-align:middle;margin:0 6px 0 14px"></span>LEG 01F</div>`);+ const gait = add(`<svg style="position:absolute;left:46px;top:${BY + 30}px" width="936" height="116"></svg>`);++ add(`<div class="pn" style="left:1002px;top:${BY}px;width:276px;height:${BH}px"></div>`);+ add(`<div class="hd" style="position:absolute;left:1014px;top:${BY + 11}px"><i>›››</i>CRANKSHAFT · 10 THROWS</div>`);+ const crank = add(`<svg style="position:absolute;left:1012px;top:${BY + 26}px" width="124" height="124"></svg>`);+ add(`<div style="position:absolute;left:1142px;top:${BY + 34}px;width:126px;display:flex;flex-direction:column;gap:6px">+ <div><div class="lb">PHASE STEP</div><div class="vl mono">36.0°</div></div>+ <div><div class="lb">THROW RADIUS</div><div class="vl mono">m = 15.0</div></div>+ <div><div class="lb">THROW 01 AT</div><div class="vl mono" data-k="throw"></div></div>+ <div><div class="lb">WAVE</div><div class="vl mono">HEAD → TAIL</div></div></div>`);++ add(`<div class="pn" style="left:1286px;top:${BY}px;width:286px;height:${BH}px"></div>`);+ add(`<div class="hd" style="position:absolute;left:1298px;top:${BY + 11}px"><i>›››</i>RIDE HEIGHT · FOOT LIFT</div>`);+ const ride = add(`<svg style="position:absolute;left:1296px;top:${BY + 28}px" width="268" height="96"></svg>`);+ add(`<div style="position:absolute;left:1298px;top:${BY + 128}px;width:262px;display:flex;justify-content:space-between">+ <span class="lb"><b style="color:${C.accent}">—</b> FOOT 01F <b class="mono" style="color:${C.ink}" data-k="lift"></b></span>+ <span class="lb"><b style="color:${C.ink}">—</b> BODY <b class="mono" style="color:${C.ink}" data-k="body"></b></span></div>`);++ // ------------------------------------------------------------ overlays: callouts, leg labels, the pointer+ const callG = add(`<div data-callouts style="position:absolute;inset:0"></div>`);+ const callSvg = add(`<svg data-callouts style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);+ const tags = add(`<div data-callouts style="position:absolute;inset:0"></div>`);+ const ring = add(`<div class="ring"></div>`);+ const cur = add(`<div class="cur"><svg width="24" height="24" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#1d1a16" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);++ const K = {};+ for (const n of ui.querySelectorAll('[data-k]')) K[n.dataset.k] = n;+ const centre = (n) => {+ const r = n.getBoundingClientRect();+ return [r.left + r.width / 2, r.top + r.height / 2];+ };+ const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));+ const knobAt = (w) => [SL.x + (w / WIND_MAX) * SL.w, SL.y + 1.5];+ // the screen areas the panels cover, so a callout never lands under one+ const PANELS = [[1300, 52, 1572, 720], [34, 368, 296, 720], [34, BY, 1572, 888], [30, 44, 330, 340], [1000, 6, 1592, 44]];+ const covered = (x, y) => PANELS.some(([a, b, c, d]) => x > a - 8 && x < c + 8 && y > b - 8 && y < d + 8);++ const pointer = (c) => {+ cur.style.display = c.x < 0 ? 'none' : 'block';+ cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;+ ring.style.left = `${c.ringX}px`;+ ring.style.top = `${c.ringY}px`;+ ring.style.opacity = String(c.ring * 0.85);+ ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;+ };++ // the linkage panel's frame: Jansen units to panel px, walking to the right like the 3D view of leg 01F+ const LS = 2.4;+ const LX = (u) => 54 - u * LS;+ const LY = (v) => 58 - v * LS;+ const pathD = PATH.filter((_, i) => i % 6 === 0)+ .map(([u, v], i) => `${i ? 'L' : 'M'}${LX(u).toFixed(1)} ${LY(v).toFixed(1)}`)+ .join(' ');+ const LINKS2 = [['A', 'B', 'j'], ['A', 'C', 'k'], ['P', 'B', 'b'], ['P', 'C', 'c'], ['P', 'D', 'd'], ['B', 'D', 'e'], ['D', 'E', 'f'], ['C', 'E', 'g'], ['E', 'F', 'h'], ['C', 'F', 'i'], ['O', 'A', 'm']];++ return {+ spots,+ btn,+ root: ui,+ covered,+ knobAt,+ update(s) {+ // live readings+ K.wind.textContent = `${s.wind.toFixed(1)} m/s`;+ K.rpm.textContent = `${s.rpm.toFixed(1)} rpm`;+ K.speed.textContent = `${s.speed.toFixed(2)} m/s`;+ K.feet.textContent = `${s.feetDown} / 20`;+ K.crank.textContent = `${((((s.crankDeg % 360) + 360) % 360)).toFixed(0).padStart(3, '0')}°`;+ K.load.textContent = `${(s.wind * s.wind * 0.61 * 0.9 * 10 * 0.001).toFixed(2)} kN`;+ K.rpm2.textContent = `${s.rpm.toFixed(1)} rpm`;+ K.steps.textContent = `${(s.rpm * 20).toFixed(0)}`;+ K.dist.textContent = `${s.dist.toFixed(1)} m`;+ K.throw.textContent = `${((((s.crankDeg % 360) + 360) % 360)).toFixed(0).padStart(3, '0')}°`;+ K.lift.textContent = `${s.liftMM.toFixed(0)} mm`;+ K.body.textContent = `±${s.bodyMM.toFixed(1)} mm`;++ // the holy numbers: revealed rows inked, the newest one lit+ for (const k of TABLE) {+ const r = rows[k];+ const st = s.rows[k] || 0; // 0 idle, 1 shown, 2 lit+ const dot = r.querySelector('[data-r=dot]');+ const bar = r.querySelector('[data-r=bar]');+ dot.style.background = st === 2 ? C.accent : st === 1 ? C.dark : 'transparent';+ dot.style.color = st ? '#f6f1e6' : C.dark;+ dot.style.borderColor = st ? 'transparent' : C.line;+ bar.style.background = st === 2 ? C.accent : st === 1 ? C.dark : C.faint;+ r.querySelector('[data-r=val]').style.color = st === 2 ? C.accent : C.ink;+ }++ // the linkage panel: the hero leg's live pose, its foot's path, the stance arc, letters on the bars+ {+ const J = s.leg;+ const P2 = (k) => `${LX(J[k][0]).toFixed(1)} ${LY(J[k][1]).toFixed(1)}`;+ let h = `<line x1="0" x2="248" y1="${LY(-91.83 - 2.75)}" y2="${LY(-91.83 - 2.75)}" stroke="${C.dark}" stroke-width=".8"/>`;+ for (let i = 0; i < 31; i++) h += `<line x1="${i * 8}" y1="${LY(-94.6) + 2}" x2="${i * 8 + 5}" y2="${LY(-94.6) + 7}" stroke="${C.faint}" stroke-width=".6"/>`;+ h += `<path d="${pathD} Z" fill="none" stroke="${C.accent}" stroke-width="1.3" stroke-dasharray="3 2" opacity=".85"/>`;+ // dimension lines for a and l+ h += `<g stroke="${C.mute}" stroke-width=".6" fill="none"><path d="M${LX(0)} ${LY(14)} V${LY(4)} M${LX(-38)} ${LY(14)} V${LY(-4)}"/><path d="M${LX(0)} ${LY(11)} H${LX(-38)}" stroke-dasharray="2 2"/><path d="M${LX(-46)} ${LY(0)} H${LX(-40)} M${LX(-46)} ${LY(-7.8)} H${LX(-40)} M${LX(-44)} ${LY(0)} V${LY(-7.8)}"/></g>`;+ h += `<text x="${LX(-19)}" y="${LY(13)}" font-size="8" text-anchor="middle" fill="${C.mute}" font-family="JetBrains Mono">a</text><text x="${LX(-49)}" y="${LY(-4.5)}" font-size="8" text-anchor="middle" fill="${C.mute}" font-family="JetBrains Mono">l</text>`;+ h += `<circle cx="${LX(0)}" cy="${LY(0)}" r="${15 * LS}" fill="none" stroke="${C.faint}" stroke-width=".7" stroke-dasharray="2 2"/>`;+ for (const [a, b, k] of LINKS2) {+ const lit = s.rows[k] === 2;+ h += `<line x1="${LX(J[a][0]).toFixed(1)}" y1="${LY(J[a][1]).toFixed(1)}" x2="${LX(J[b][0]).toFixed(1)}" y2="${LY(J[b][1]).toFixed(1)}" stroke="${lit ? C.accent : k === 'm' ? C.dark : C.ink}" stroke-width="${lit ? 3 : k === 'm' ? 2.6 : 2}" stroke-linecap="round"/>`;+ }+ for (const k of ['O', 'P', 'A', 'B', 'C', 'D', 'E']) h += `<circle cx="${LX(J[k][0]).toFixed(1)}" cy="${LY(J[k][1]).toFixed(1)}" r="${k === 'O' || k === 'P' ? 3.6 : 2.8}" fill="${k === 'O' || k === 'P' ? C.dark : '#f3eee3'}" stroke="${C.red}" stroke-width="1.4"/>`;+ h += `<path d="M${LX(-8)} ${LY(-3)} l-6 6 h12z" fill="none" stroke="${C.dark}" stroke-width=".8"/><path d="M${LX(-38) - 6} ${LY(-7.8) + 9} h12" stroke="${C.dark}" stroke-width=".8"/>`;+ h += `<ellipse cx="${LX(J.F[0]).toFixed(1)}" cy="${(LY(J.F[1]) + 2).toFixed(1)}" rx="6" ry="3" fill="${C.dark}"/>`;+ h += `<circle cx="${LX(J.F[0]).toFixed(1)}" cy="${LY(J.F[1]).toFixed(1)}" r="4.5" fill="none" stroke="${C.accent}" stroke-width="1.6"/>`;+ for (const [a, b, k] of LINKS2) {+ const mx = (LX(J[a][0]) + LX(J[b][0])) / 2;+ const my = (LY(J[a][1]) + LY(J[b][1])) / 2;+ const lit = s.rows[k] === 2;+ h += `<circle cx="${mx.toFixed(1)}" cy="${my.toFixed(1)}" r="5.6" fill="${lit ? C.accent : '#f3eee3'}" stroke="${lit ? C.accent : C.line}" stroke-width=".8"/><text x="${mx.toFixed(1)}" y="${(my + 2.6).toFixed(1)}" font-size="7.5" font-weight="700" text-anchor="middle" fill="${lit ? '#f6f1e6' : C.dark}" font-family="JetBrains Mono">${k}</text>`;+ }+ h += `<text x="244" y="${LY(-91.83) - 6}" font-size="6.5" text-anchor="end" fill="${C.mute}">WALK →</text>`;+ link.innerHTML = h;+ }++ // wind: the slider, the last 12 s of wind+ {+ const [kx] = knobAt(s.wind);+ knob.style.left = `${kx.toFixed(1)}px`;+ knob.style.transform = `scale(${s.drag ? 1.18 : 1})`;+ knob.style.borderColor = s.drag ? C.accent : C.dark;+ fill.style.width = `${(kx - SL.x).toFixed(1)}px`;+ windVal.textContent = `${s.wind.toFixed(1)} m/s`;+ const W = SL.w;+ let p = '';+ s.windHist.forEach((w, i) => (p += `${i ? 'L' : 'M'}${((i / (s.windHist.length - 1)) * W).toFixed(1)} ${(54 - (w / WIND_MAX) * 50).toFixed(1)}`));+ windHist.innerHTML = `<rect x="0" y="0" width="${W}" height="56" fill="rgba(110,98,78,.06)"/>${[4, 8, 12].map((v) => `<line x1="0" x2="${W}" y1="${54 - (v / WIND_MAX) * 50}" y2="${54 - (v / WIND_MAX) * 50}" stroke="${C.faint}" stroke-width=".5" stroke-dasharray="2 3"/>`).join('')}<path d="${p} L${W} 56 L0 56 Z" fill="rgba(208,89,42,.12)"/><path d="${p}" fill="none" stroke="${C.accent}" stroke-width="1.4"/><text x="2" y="9" font-size="6.5" fill="${C.mute}">LAST 12 S</text>`;+ }++ // contact chart: a row per leg, ink where the foot is on the sand; the wave runs down the rows+ {+ const W = 936;+ const x0 = 46;+ const rowH = 5.2;+ let h = '';+ s.gait.forEach((row, r) => {+ const y = 4 + r * rowH + (r >= 10 ? 4 : 0);+ const hero = r === 0;+ h += `<text x="0" y="${y + 4.4}" font-size="5.6" fill="${C.mute}" font-family="JetBrains Mono">${String((r % 10) + 1).padStart(2, '0')}${r < 10 ? 'F' : 'B'}</text>`;+ for (const [a, b] of row) h += `<rect x="${(x0 + a * (W - x0)).toFixed(1)}" y="${y}" width="${Math.max(0.8, (b - a) * (W - x0)).toFixed(1)}" height="${rowH - 1.4}" fill="${hero ? C.accent : C.dark}" opacity="${hero ? 1 : 0.78}"/>`;+ });+ h += `<line x1="${W}" x2="${W}" y1="0" y2="112" stroke="${C.accent}" stroke-width="1"/><text x="${W - 3}" y="114" font-size="6" text-anchor="end" fill="${C.mute}">NOW</text>`;+ gait.innerHTML = h;+ }++ // crankshaft dial: the ten throws at their real angles, throw 01 lit+ {+ const cx = 62;+ const cy = 62;+ let h = `<circle cx="${cx}" cy="${cy}" r="54" fill="none" stroke="${C.line}" stroke-width=".8"/><circle cx="${cx}" cy="${cy}" r="8" fill="${C.dark}"/>`;+ for (let i = 0; i < 72; i++) {+ const a = (i / 72) * Math.PI * 2;+ const r1 = i % 6 ? 51 : 47;+ h += `<line x1="${cx + Math.cos(a) * 54}" y1="${cy + Math.sin(a) * 54}" x2="${cx + Math.cos(a) * r1}" y2="${cy + Math.sin(a) * r1}" stroke="${C.mute}" stroke-width=".5"/>`;+ }+ s.throws.forEach((a, i) => {+ const x = cx + Math.cos(-a) * 38;+ const y = cy + Math.sin(-a) * 38;+ const lit = i === 0;+ h += `<line x1="${cx}" y1="${cy}" x2="${x.toFixed(1)}" y2="${y.toFixed(1)}" stroke="${lit ? C.accent : C.dark}" stroke-width="${lit ? 2.2 : 1.1}" opacity="${lit ? 1 : 0.55}"/><circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="${lit ? 6.5 : 5.5}" fill="${lit ? C.accent : '#f3eee3'}" stroke="${lit ? C.accent : C.dark}" stroke-width=".8"/><text x="${x.toFixed(1)}" y="${(y + 2.3).toFixed(1)}" font-size="6.2" font-weight="700" text-anchor="middle" fill="${lit ? '#f6f1e6' : C.dark}" font-family="JetBrains Mono">${i + 1}</text>`;+ });+ crank.innerHTML = h;+ }++ // ride: the foot's lift against the body's height over the last 4 s, on the same scale+ {+ const W = 268;+ const Y = (mm) => 82 - (mm / 300) * 74;+ let pf = '';+ let pb = '';+ s.liftHist.forEach((v, i) => (pf += `${i ? 'L' : 'M'}${((i / (s.liftHist.length - 1)) * W).toFixed(1)} ${Y(v).toFixed(1)}`));+ s.bodyHist.forEach((v, i) => (pb += `${i ? 'L' : 'M'}${((i / (s.bodyHist.length - 1)) * W).toFixed(1)} ${(Y(150) - v * 0.6).toFixed(1)}`));+ ride.innerHTML = `${[0, 100, 200, 300].map((v) => `<line x1="18" x2="${W}" y1="${Y(v)}" y2="${Y(v)}" stroke="${C.faint}" stroke-width=".5" stroke-dasharray="2 3"/><text x="0" y="${Y(v) + 2}" font-size="6" fill="${C.mute}" font-family="JetBrains Mono">${v}</text>`).join('')}<path d="${pf}" fill="none" stroke="${C.accent}" stroke-width="1.5" transform="translate(18 0) scale(${(W - 18) / W} 1)"/><path d="${pb}" fill="none" stroke="${C.ink}" stroke-width="1.5" transform="translate(18 0) scale(${(W - 18) / W} 1)"/><text x="${W}" y="${Y(150) - 5}" font-size="6" text-anchor="end" fill="${C.mute}">BODY LEVEL</text>`;+ }++ // views and toggles+ for (const k of VIEW_KEYS) {+ const v = s.viewOn[k] || 0;+ btn[k].style.background = v > 0.5 ? C.dark : 'rgba(243,238,227,.9)';+ btn[k].style.color = v > 0.5 ? '#f3eee3' : C.dark;+ }+ for (const k of TOGGLES) {+ const on = s[k] > 0.5;+ btn[k].style.background = on ? C.accent : 'rgba(243,238,227,.9)';+ btn[k].style.color = on ? '#f6f1e6' : C.dark;+ btn[k].style.borderColor = on ? C.accent : C.line;+ }++ // callouts over the beast, and the hero leg's letters+ let ch = '';+ let lh = '';+ for (const c of s.callouts) {+ if (c.o < 0.02) continue;+ const [ax, ay] = c.at;+ const lx = ax + c.dx;+ const ly = ay + c.dy;+ lh += `<g opacity="${c.o.toFixed(2)}"><polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${lx.toFixed(1)},${ly.toFixed(1)} ${(lx + (c.dx < 0 ? -26 : 26)).toFixed(1)},${ly.toFixed(1)}" fill="none" stroke="${C.dark}" stroke-width=".8"/><circle cx="${ax.toFixed(1)}" cy="${ay.toFixed(1)}" r="2.2" fill="${C.accent}"/></g>`;+ ch += `<div class="call" style="left:${(lx + (c.dx < 0 ? -30 : 30)).toFixed(1)}px;top:${(ly - 8).toFixed(1)}px;opacity:${c.o.toFixed(2)};transform:translateX(${c.dx < 0 ? '-100%' : '0'});text-align:${c.dx < 0 ? 'right' : 'left'}"><b>${c.name}</b><span>${c.sub}</span></div>`;+ }+ for (const d of s.dims) {+ if (d.o < 0.02) continue;+ lh += `<line x1="${d.a[0].toFixed(1)}" y1="${d.a[1].toFixed(1)}" x2="${d.b[0].toFixed(1)}" y2="${d.b[1].toFixed(1)}" stroke="${C.dark}" stroke-width="1" stroke-dasharray="4 3" opacity="${d.o.toFixed(2)}"/>`;+ }+ callSvg.innerHTML = lh;+ callG.innerHTML = ch;+ let th = '';+ for (const g of s.tags) {+ if (g.o < 0.02) continue;+ th += `<div class="tag" style="left:${g.at[0].toFixed(1)}px;top:${g.at[1].toFixed(1)}px;opacity:${g.o.toFixed(2)}"><b style="${g.lit ? `background:${C.accent}` : ''};transform:scale(${(0.7 + 0.3 * Math.min(1, g.o * 1.5)).toFixed(2)})">${g.k}</b>${g.lit ? `<span>${HOLY[g.k].toFixed(1)}</span>` : ''}</div>`;+ }+ tags.innerHTML = th;+ pointer(s.cursor);+ },+ pointer,+ };+}diff --git a/sims/strandbeest-shared/film.js b/sims/strandbeest-shared/film.jsnew file mode 100644index 0000000..91e72c5--- /dev/null+++ b/sims/strandbeest-shared/film.js@@ -0,0 +1,352 @@+// STRANDBEEST SB-10, the console film: the beast on the dune (stage.js) under the SB-10 engineering sheet+// (console.js). An operator isolates one leg and letters its eleven bars, traces its foot, lights all twenty loops,+// opens the wind from 6 to 12.5 m/s and follows the walk from the front, along the spine and from above over the+// footprints. Wind drives the crank, the crank drives everything: theta(t) is the integral of the wind's crank speed.+// A pure function of t.+import {runSim} from '../kit/runtime.js';+import {CFG, legAt, legZ, phaseOf, S, STRIDE} from './beast.js';+import {createConsole, LABELS, VIEW_KEYS} from './console.js';+import {footLift} from './jansen.js';+import {createBeestStage} from './stage.js';++// the foot traces are off in this cut (no trace events); the console keeps the TRACE FEET button for the live page+export const SCRIPT = [+ {t: 0, view: 'cine'},+ {t: 3.4, iso: 1, view: 'leg'},+ {t: 9.6, iso: 0, view: 'front'},+ {t: 13.0, wind: [6, 12.5, 1.6]},+ {t: 16.8, view: 'side'},+ {t: 21.0, view: 'top'},+ {t: 25.8, view: 'cine'},+];+export const DURATION = 30.7;+export const DEFAULTS = {duration: DURATION, fps: 60, theme: 'light', hud: {enabled: false, title: 'beestsim', subtitle: ''}, director: {enabled: false}, watermark: ''};+export const HERO = {st: 0, side: 0};+const D2R = Math.PI / 180;+const smoother = (x) => {+ const u = Math.min(1, Math.max(0, x));+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));++// ------------------------------------------------------------ wind, crank and the distance the wind has run+const WIND_EV = SCRIPT.find((e) => e.wind);+export const windAt = (t) => {+ const [w0, w1, dur] = WIND_EV.wind;+ const base = w0 + (w1 - w0) * ss(WIND_EV.t, WIND_EV.t + dur, t);+ return base + 0.35 * Math.sin(t * 0.9) + 0.2 * Math.sin(t * 2.3 + 1);+};+// the crank's turn rate for a wind: 0.42 rev/s at 6 m/s, rising slower than the wind+export const rpsAt = (w) => 0.42 * Math.pow(Math.max(0.5, w) / 6, 0.75);+const T0 = -16;+const DT = 1 / 240;+const NTAB = Math.ceil((DURATION + 2 - T0) / DT);+const TH = new Float64Array(NTAB + 1);+const FLOW = new Float64Array(NTAB + 1);+{+ // integrate from t = 0 both ways so theta(0) = 0 and the body starts at the origin+ const i0 = Math.round(-T0 / DT);+ for (let i = i0 + 1; i <= NTAB; i++) {+ const t = T0 + (i - 0.5) * DT;+ TH[i] = TH[i - 1] + rpsAt(windAt(t)) * Math.PI * 2 * DT;+ FLOW[i] = FLOW[i - 1] + windAt(t) * DT;+ }+ for (let i = i0 - 1; i >= 0; i--) {+ const t = T0 + (i + 0.5) * DT;+ TH[i] = TH[i + 1] - rpsAt(windAt(t)) * Math.PI * 2 * DT;+ FLOW[i] = FLOW[i + 1] - windAt(t) * DT;+ }+}+const lookup = (A, t) => {+ const u = Math.min(NTAB - 1e-6, Math.max(0, (t - T0) / DT));+ const i = Math.floor(u);+ return A[i] + (A[i + 1] - A[i]) * (u - i);+};+export const thetaAt = (t) => lookup(TH, t);+export const flowAt = (t) => lookup(FLOW, t);++// ------------------------------------------------------------ operator state+const evAt = (key, t, init = 0) => {+ let v = init;+ for (const e of SCRIPT) if (e[key] !== undefined) v += (e[key] - v) * ss(e.t, e.t + 0.7, t);+ return v;+};+export const isoAt = (t) => evAt('iso', t);+const TRACE_ON = SCRIPT.find((e) => e.trace === 1)?.t ?? Infinity;+const TRACE_OFF = SCRIPT.find((e) => e.trace === 0)?.t ?? Infinity;+// when the hero's foot has drawn one full loop+const LOOP_DONE = (() => {+ if (!Number.isFinite(TRACE_ON)) return Infinity;+ const th0 = thetaAt(TRACE_ON);+ let t = TRACE_ON;+ while (thetaAt(t) - th0 < Math.PI * 2) t += 0.01;+ return t;+})();+export const traceState = (t) => ({+ heroTrace: t < TRACE_ON ? 0 : Math.min(1, (thetaAt(t) - thetaAt(TRACE_ON)) / (Math.PI * 2)),+ trace: ss(LOOP_DONE, LOOP_DONE + 0.9, t),+ traceFade: 1 - ss(TRACE_OFF, TRACE_OFF + 0.7, t),+ on: t >= TRACE_ON && t < TRACE_OFF + 0.2 ? 1 : 0,+});+export const ISO_T = SCRIPT.find((e) => e.iso === 1).t;+// the hero's letters come up one by one, starting 0.9 s after the leg is isolated+export const labelTimes = (start) => LABELS.map((_, i) => start + 0.9 + i * 0.3);++// ------------------------------------------------------------ views+const heroZ = legZ(HERO.st, HERO.side) * S;+// each view as a function of u, the seconds since it was switched on, and the body's x+export const VIEW_FN = {+ cine: (u, bx) => ({tx: bx + 0.05, ty: 1.1, tz: 0.1, az: 319.6 + 1.4 * u, el: 11, d: 9.2, sx: 14, sy: -58}),+ leg: (u, bx) => ({tx: bx - 0.34, ty: 0.74, tz: heroZ, az: 94 + 0.9 * u, el: 4, d: 5.6, sx: 0, sy: -40}),+ front: (u, bx) => ({tx: bx - 0.1, ty: 1.08, tz: 0, az: 196 + 1.1 * u, el: 7, d: 9.6, sx: -6, sy: -50}),+ side: (u, bx) => ({tx: bx + 0.1, ty: 0.95, tz: -0.2, az: 262 - 1.2 * u, el: 11, d: 9.6, sx: -6, sy: -58}),+ top: (u, bx) => ({tx: bx + 1.1, ty: 0.3, tz: 0, az: 192 + 1.6 * u, el: 60, d: 13.5, sx: 0, sy: -40}),+};+const VIEWS_LIST = SCRIPT.filter((e) => e.view).map((e) => [e.t, e.view]);+export const scriptView = (t) => VIEWS_LIST.filter(([t0]) => t0 <= t).pop();+const lerpDeg = (a, b, k) => a + ((((b - a + 540) % 360) - 180) * k);+export const viewAt = (t, bx, list = VIEWS_LIST) => {+ let i = 0;+ while (i < list.length - 1 && list[i + 1][0] <= t) i++;+ const cur = VIEW_FN[list[i][1]](t - list[i][0], bx);+ if (i === 0) return cur;+ const prev = VIEW_FN[list[i - 1][1]](t - list[i - 1][0], bx);+ const k = ss(list[i][0], list[i][0] + 1.9, t);+ const o = {};+ for (const key in cur) o[key] = key === 'az' ? lerpDeg(prev.az, cur.az, k) : prev[key] + (cur[key] - prev[key]) * k;+ // a move through a wide swing backs off and climbs so the camera never passes through the beast+ const swing = Math.min(1, Math.abs(((cur.az - prev.az + 540) % 360) - 180) / 90);+ o.el += 8 * Math.sin(Math.PI * k) * swing;+ o.d += Math.max(0, Math.max(prev.d, cur.d) + 2.5 * swing - o.d) * Math.sin(Math.PI * k);+ return o;+};+export const toCam = (c) => ({...c, az: c.az * D2R, el: c.el * D2R});++// ------------------------------------------------------------ footprints from the walk itself+export function footprints(bodyPos, t1 = DURATION) {+ const out = [];+ let r = 17;+ const rnd = () => (r = (r * 16807) % 2147483647) / 2147483647;+ for (let st = 0; st < CFG.stations; st++)+ for (let side = 0; side < 2; side++) {+ let on = false;+ let t0 = 0;+ for (let t = T0; t <= t1; t += 1 / 120) {+ const ps = thetaAt(t) + phaseOf(st);+ const lift = footLift(side ? Math.PI - ps : ps);+ if (!on && lift < 0.5) {+ on = true;+ t0 = t;+ } else if (on && lift >= 0.5) {+ on = false;+ const tm = (t0 + t) / 2;+ const th = thetaAt(tm);+ const J = legAt(st, side, th);+ out.push([bodyPos(th).x + J.F[0] * S, legZ(st, side) * S, t0, (rnd() - 0.5) * 0.25]);+ }+ }+ }+ return out;+}++// ------------------------------------------------------------ the operator's pointer+const REST = [[820, 430], [700, 480], [900, 380], [760, 520], [640, 420]];+export function makeCursor(ui) {+ const EV = SCRIPT.filter((e) => e.t > 0).map((e) => {+ const key = e.iso !== undefined ? 'iso' : e.trace !== undefined ? 'trace' : e.wind ? 'wind' : e.view;+ return {t: e.t, key, spot: key === 'wind' ? ui.knobAt(e.wind[0]) : ui.spots[key], drag: key === 'wind' ? e.wind[2] : 0};+ });+ const WP = [[0, 840, 560]];+ EV.forEach((e, i) => {+ WP.push([e.t - 0.16, ...e.spot]);+ if (e.drag) {+ for (let k = 0; k <= 12; k++) {+ const tt = e.t + (k / 12) * e.drag;+ WP.push([tt + 0.02, ...ui.knobAt(windAt(tt) - 0.35 * Math.sin(tt * 0.9) - 0.2 * Math.sin(tt * 2.3 + 1))]);+ }+ WP.push([e.t + e.drag + 0.3, ...ui.knobAt(SCRIPT.find((x) => x.wind).wind[1])]);+ } else WP.push([e.t + 0.24, ...e.spot]);+ WP.push([e.t + e.drag + 1.7, ...REST[i % REST.length]]);+ });+ WP.sort((a, b) => a[0] - b[0]);+ return (t) => {+ let i = 0;+ while (i < WP.length - 2 && t > WP[i + 1][0]) i++;+ const [t0, x0, y0] = WP[i];+ const [t1, x1, y1] = WP[i + 1];+ const lin = WP[i + 1][0] - WP[i][0] < 0.2;+ const k = lin ? Math.min(1, Math.max(0, (t - t0) / (t1 - t0))) : ss(t0, t1, t);+ const len = Math.hypot(x1 - x0, y1 - y0);+ const bow = lin ? 0 : Math.sin(Math.PI * k) * Math.min(26, len * 0.07);+ let press = false;+ let drag = false;+ let ring = 0;+ let rx = 0;+ let ry = 0;+ for (const e of EV) {+ if (t >= e.t - 0.07 && t < e.t + Math.max(0.09, e.drag + 0.1)) press = true;+ if (e.drag && t >= e.t && t < e.t + e.drag + 0.1) drag = true;+ if (t >= e.t && t < e.t + 0.55) {+ ring = 1 - (t - e.t) / 0.55;+ [rx, ry] = e.spot;+ }+ }+ return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, drag, ring, ringX: rx, ringY: ry};+ };+}++// ------------------------------------------------------------ console data for a frame+const CALLS = [+ {name: 'SAIL ARRAY', sub: '10 SAILS · 0.9 m² EACH', pt: (B) => [6, 66, B.zs(6)]},+ {name: 'CRANKSHAFT', sub: '10 THROWS · 36° APART', pt: (B) => [0, 0, B.zs(8)]},+ {name: 'JANSEN LEG', sub: '11 BARS · 1 CRANK · NO MOTOR', pt: (B, th) => {+ const J = legAt(3, 0, th);+ return [(J.C[0] + J.E[0]) / 2, (J.C[1] + J.E[1]) / 2, legZ(3, 0)];+ }},+ {name: 'RUBBER FOOT', sub: 'ON THE SAND FOR 155° OF CRANK', pt: (B, th) => [legAt(1, 0, th).F[0], legAt(1, 0, th).F[1], legZ(1, 0)]},+];+const CALL_VIEWS = {cine: 1, front: 1, side: 0, leg: 0, top: 0};+const FILM_SRC = {thetaAt: (t) => thetaAt(t), windAt: (t) => windAt(t)};++// src gives the crank angle and the wind at any recent time (the film's integral, or the live page's history);+// ops.labelStart is when the leg was last isolated, ops.trace whether the TRACE FEET button is lit+export function makeConsoleFrame(ui, st, src = FILM_SRC) {+ const {thetaAt, windAt} = src;+ const legLift = (s, side, th) => {+ const ps = th + phaseOf(s);+ return footLift(side ? Math.PI - ps : ps);+ };+ return (t, ops) => {+ const th = thetaAt(t);+ const wind = windAt(t);+ const rps = rpsAt(wind);+ const {view, since, iso, cursor} = ops;+ const LABEL_T = labelTimes(ops.labelStart ?? ISO_T);+ // the contact chart: 150 columns over the last 3 s, a run per stance+ const gait = [];+ for (let r = 0; r < 20; r++) {+ const s = r % 10;+ const side = r < 10 ? 0 : 1;+ const runs = [];+ let a = -1;+ for (let c = 0; c <= 150; c++) {+ const on = legLift(s, side, thetaAt(t - 3 + (c / 150) * 3)) < 0.6;+ if (on && a < 0) a = c / 150;+ if ((!on || c === 150) && a >= 0) {+ runs.push([a, c / 150]);+ a = -1;+ }+ }+ gait.push(runs);+ }+ let feetDown = 0;+ for (let r = 0; r < 20; r++) if (legLift(r % 10, r < 10 ? 0 : 1, th) < 0.6) feetDown++;+ const liftHist = [];+ const bodyHist = [];+ let bodyMax = 0;+ for (let i = 0; i <= 120; i++) {+ const tt = t - 4 + (i / 120) * 4;+ const tth = thetaAt(tt);+ liftHist.push(legLift(0, 0, tth) * 12);+ const low = st.bodyPos(tth).y;+ bodyHist.push((low - st.bodyPos(0).y) * 1000);+ bodyMax = Math.max(bodyMax, Math.abs((low - st.bodyPos(0).y) * 1000));+ }+ const windHist = Array.from({length: 97}, (_, i) => windAt(t - 12 + i * 0.125));+ // the holy numbers and the hero's letters+ const rows = {};+ const tags = [];+ const dims = [];+ const J = st.beast.out.heroJ;+ const z = st.beast.out.heroZ;+ const W = (u, v) => st.project(...st.beastWorld(u, v, z));+ LABELS.forEach(([k], i) => {+ const tl = LABEL_T[i];+ if (t >= tl) rows[k] = t - tl < 0.7 ? 2 : 1;+ const o = ss(tl, tl + 0.25, t) * iso * (view === 'leg' ? 1 : 0.0);+ if (o < 0.02 || !J) return;+ let at;+ if (k === 'a') at = W(-19, 0);+ else if (k === 'l') at = W(-38, -3.9);+ else if (k === 'm') at = W(J.A[0] / 2, J.A[1] / 2);+ else {+ const pair = {j: ['A', 'B'], k: ['A', 'C'], b: ['P', 'B'], c: ['P', 'C'], d: ['P', 'D'], e: ['B', 'D'], f: ['D', 'E'], g: ['C', 'E'], h: ['E', 'F'], i: ['C', 'F']}[k];+ at = W((J[pair[0]][0] + J[pair[1]][0]) / 2, (J[pair[0]][1] + J[pair[1]][1]) / 2);+ }+ if (at) tags.push({k, at, o, lit: rows[k] === 2});+ if (k === 'a') {+ const A = W(0, 0);+ const B = W(-38, 0);+ if (A && B) dims.push({a: A, b: B, o});+ }+ if (k === 'l') {+ const A = W(-38, 0);+ const B = W(-38, -7.8);+ if (A && B) dims.push({a: A, b: B, o});+ }+ });+ // callouts on the beast in the wide views+ const vw = (CALL_VIEWS[view] ?? 0) * ss(1.2, 1.9, since) * (1 - iso);+ const callouts = CALLS.map((c) => {+ if (vw < 0.02) return {o: 0};+ const at = st.project(...st.beastWorld(...c.pt(st.beast, th)));+ if (!at || at[0] < 40 || at[0] > 1560 || at[1] < 60 || at[1] > 720 || ui.covered(at[0], at[1])) return {o: 0};+ const dx = at[0] < 790 ? -70 : 70;+ if (ui.covered(at[0] + dx + (dx < 0 ? -170 : 170), at[1] - 64)) return {o: 0};+ return {...c, at, dx, dy: -64, o: vw};+ });+ ui.update({+ wind,+ rpm: rps * 60,+ speed: rps * Math.abs(STRIDE) * S,+ feetDown,+ dist: ops.dist ?? Math.abs(st.bodyPos(th).x - st.bodyPos(0).x),+ crankDeg: (th * 180) / Math.PI,+ leg: legAt(0, 0, th),+ rows,+ gait,+ throws: Array.from({length: 10}, (_, s) => th + phaseOf(s)),+ liftHist,+ bodyHist,+ liftMM: legLift(0, 0, th) * 12,+ bodyMM: Math.max(0.1, bodyMax),+ windHist,+ drag: cursor.drag,+ viewOn: Object.fromEntries(VIEW_KEYS.map((k) => [k, k === view ? 1 : 0])),+ iso,+ trace: ops.trace ?? traceState(t).on,+ tags,+ dims,+ callouts,+ cursor,+ });+ };+}++export function makeFilm() {+ return async ({cfg, canvas, capture}) => {+ const st = createBeestStage({canvas, palette: cfg.palette ?? 'dune', ink: cfg.ink ?? 0.7});+ const resize = () => st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));+ resize();+ st.setPrints(footprints(st.bodyPos));+ const ui = createConsole(document.getElementById('app'));+ const cursorAt = makeCursor(ui);+ const frame = makeConsoleFrame(ui, st);+ window.BEEST = st;+ return {+ resize,+ render(t) {+ const th = thetaAt(t);+ const b = st.bodyPos(th);+ const iso = isoAt(t);+ const ts = traceState(t);+ st.frame(th, t, toCam(viewAt(t, b.x)), {wind: windAt(t), flow: flowAt(t) * 0.35, iso, hero: HERO, ...ts});+ const [t0, view] = scriptView(t);+ frame(t, {view, since: t - t0, iso, cursor: cursorAt(t)});+ return {};+ },+ };+ };+}++export const run = () => runSim(DEFAULTS, makeFilm());diff --git a/sims/strandbeest-shared/jansen.js b/sims/strandbeest-shared/jansen.jsnew file mode 100644index 0000000..3e51041--- /dev/null+++ b/sims/strandbeest-shared/jansen.js@@ -0,0 +1,67 @@+// Theo Jansen's linkage, solved exactly. Eleven "holy numbers" (the link lengths Jansen evolved in 1990) plus the+// crank: turn the crank and every joint follows by circle intersection, no IK, no springs. The foot traces the+// classic path: a flat bottom for ~155° of crank, then a 22-unit lift back. Units are Jansen's own (≈ cm).+export const HOLY = {a: 38, b: 41.5, c: 39.3, d: 40.1, e: 55.8, f: 39.4, g: 36.7, h: 65.7, i: 49, j: 50, k: 61.9, l: 7.8, m: 15};+const {a, b, c, d, e, f, g, h, i, j, k, l, m} = HOLY;+export const PIVOT = [-a, -l];++// the two points at distance r0 from p0 and r1 from p1; pick chooses one+const cc = (p0, r0, p1, r1, pick) => {+ const dx = p1[0] - p0[0];+ const dy = p1[1] - p0[1];+ const D = Math.hypot(dx, dy);+ const A = (r0 * r0 - r1 * r1 + D * D) / (2 * D);+ const H = Math.sqrt(Math.max(0, r0 * r0 - A * A));+ const mx = p0[0] + (A * dx) / D;+ const my = p0[1] + (A * dy) / D;+ return pick([mx + (H * dy) / D, my - (H * dx) / D], [mx - (H * dy) / D, my + (H * dx) / D]);+};+const hiY = (s, t) => (s[1] > t[1] ? s : t);+const loY = (s, t) => (s[1] < t[1] ? s : t);+const loX = (s, t) => (s[0] < t[0] ? s : t);++/** Every joint of one leg for crank angle th (radians), crank axle at the origin, foot toward -x. */+export function solveLeg(th) {+ const A = [m * Math.cos(th), m * Math.sin(th)];+ const B = cc(A, j, PIVOT, b, hiY);+ const C = cc(A, k, PIVOT, c, loY);+ const D = cc(B, e, PIVOT, d, loX);+ const E = cc(D, f, C, g, loX);+ const F = cc(E, h, C, i, loY);+ return {O: [0, 0], P: PIVOT, A, B, C, D, E, F};+}+/** The mirrored leg on the same crank pin: foot toward +x, pushing the same way. */+export function solveMirror(th) {+ const s = solveLeg(Math.PI - th);+ const out = {};+ for (const key in s) out[key] = [-s[key][0], s[key][1]];+ return out;+}+// the links of one leg as joint pairs, with the holy number each one carries+export const LINKS = [+ ['A', 'B', 'j'],+ ['A', 'C', 'k'],+ ['P', 'B', 'b'],+ ['P', 'C', 'c'],+ ['P', 'D', 'd'],+ ['B', 'D', 'e'],+ ['D', 'E', 'f'],+ ['C', 'E', 'g'],+ ['E', 'F', 'h'],+ ['C', 'F', 'i'],+];+export const JOINTS = ['B', 'C', 'D', 'E', 'P'];++// the foot path sampled once: its floor, its stride, and the stance velocity used to move the body without slip+const N = 720;+export const PATH = Array.from({length: N}, (_, n) => solveLeg((n / N) * Math.PI * 2).F);+export const FOOT_MIN = Math.min(...PATH.map((p) => p[1]));+export const FOOT_MAX = Math.max(...PATH.map((p) => p[1]));+/** How far above its lowest point the foot is at crank angle th (0 = planted). */+export const footLift = (th) => {+ const u = ((((th / (Math.PI * 2)) % 1) + 1) % 1) * N;+ const n = Math.floor(u);+ const p0 = PATH[n % N][1];+ const p1 = PATH[(n + 1) % N][1];+ return p0 + (p1 - p0) * (u - n) - FOOT_MIN;+};diff --git a/sims/strandbeest-shared/live.js b/sims/strandbeest-shared/live.jsnew file mode 100644index 0000000..aee1af1--- /dev/null+++ b/sims/strandbeest-shared/live.js@@ -0,0 +1,420 @@+// SB-10 as a page you drive: the film's console (console.js) over the stage (stage.js), run in real time. The view+// buttons and keys 1-5, ISOLATE LEG (I), TRACE FEET (T), PAUSE (space), the wind slider, an orbit you drag and a zoom+// on the wheel. Left alone it plays the film's script as an auto tour with the operator's cursor, looped; a click,+// drag, wheel or key hands control to the visitor, and 25 s of quiet hands it back. Wind drives the crank here too:+// theta is integrated frame by frame, and the console reads its last seconds from a short history.+import {warmComposer} from '../kit/warm.js';+import {legAt, legZ, phaseOf, S} from './beast.js';+import {createConsole, VIEW_KEYS, WIND_MAX} from './console.js';+import {DURATION, HERO, isoAt, makeConsoleFrame, makeCursor, rpsAt, scriptView, VIEW_FN, windAt} from './film.js';+import {footLift} from './jansen.js';+import {createBeestStage} from './stage.js';++const W = 1600;+const H = 900;+const IDLE = 25;+const D2R = Math.PI / 180;+const clamp = (x, a, b) => Math.min(b, Math.max(a, x));+const smoother = (x) => {+ const u = clamp(x, 0, 1);+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));+const wrapDeg = (d) => ((((d + 180) % 360) + 360) % 360) - 180;++const CSS = (top) => `+html,body{background:#e9e2d6;overflow:hidden}+#app{position:absolute!important;inset:auto!important;left:0;top:0;width:${W}px;height:${H}px;transform-origin:0 0}+#gl{touch-action:none;cursor:grab}+#gl.drag{cursor:grabbing}+.vb{pointer-events:auto;cursor:pointer}+.vb:hover{filter:brightness(.94)}+.windhit{position:absolute;pointer-events:auto;cursor:ew-resize}+.tourchip{position:absolute;left:800px;top:48px;transform:translateX(-50%);display:flex;align-items:center;gap:7px;height:21px;padding:0 11px;border:1px solid rgba(110,98,78,.55);background:rgba(243,238,227,.92);color:#3a342b;font:700 8.5px Inter,sans-serif;letter-spacing:1.4px;white-space:nowrap;cursor:pointer;pointer-events:auto}+.tourchip i{display:block;width:6px;height:6px;border-radius:50%;background:#d0592a}+.tourchip.on i{animation:blink 1.2s steps(2) infinite}+@keyframes blink{50%{opacity:.15}}+.turn{position:fixed;left:0;right:0;bottom:18px;text-align:center;font:600 12px/1.4 'JetBrains Mono',monospace;letter-spacing:1px;color:#8a7f6c;text-transform:uppercase;display:none}+@media (orientation:portrait) and (max-width:820px){.turn{display:block}}+`;++export function runLive() {+ const top = Number(document.body.dataset.top || 0);+ const style = document.createElement('style');+ style.textContent = CSS(top);+ document.head.appendChild(style);+ const app = document.getElementById('app');+ const canvas = document.createElement('canvas');+ canvas.id = 'gl';+ app.appendChild(canvas);++ const st = createBeestStage({canvas, palette: 'dune', ink: 0.7});+ st.usePrintRing(640);+ const ui = createConsole(app);+ const tourCursorAt = makeCursor(ui);++ // ------------------------------------------------------------ quality tiers+ // the film's look, then lighter shadows and MSAA, then the outline without AO, PCF shadows and no MSAA; integrated+ // GPUs settle within a couple of seconds, phones start on the last step+ const TIERS = [+ {samples: 8, shadow: 4096, blur: 20, radius: 7, ao: 16, pcf: false, grains: 9000, pr: 2},+ {samples: 4, shadow: 2048, blur: 10, radius: 5, ao: 8, pcf: false, grains: 6000, pr: 1.5},+ {samples: 0, shadow: 1024, blur: 6, radius: 2, ao: 0, pcf: true, grains: 3000, pr: 1.1},+ ];+ const light = matchMedia('(pointer: coarse)').matches || Math.min(innerWidth, innerHeight) < 700;+ let tier = light ? 2 : 0;+ let fitReady = false;+ const applyTier = () => {+ const {pr, ...q} = TIERS[tier];+ st.setQuality(q);+ if (fitReady) fit();+ };+ applyTier();++ // ------------------------------------------------------------ fit the 1600 x 900 console into the window+ let scale = 1;+ const fit = () => {+ const h = innerHeight - top;+ scale = Math.min(innerWidth / W, h / H);+ app.style.transform = `translate(${(innerWidth - W * scale) / 2}px, ${top + (h - H * scale) / 2}px) scale(${scale})`;+ st.resize(W, H, clamp((devicePixelRatio || 1) * scale, 0.75, TIERS[tier].pr));+ };+ addEventListener('resize', fit);+ fit();+ fitReady = true;+ const toStage = (cx, cy) => {+ const r = app.getBoundingClientRect();+ return [(cx - r.left) / scale, (cy - r.top) / scale];+ };++ const tourChip = document.createElement('div');+ tourChip.className = 'tourchip';+ ui.root.appendChild(tourChip);+ const turnNote = document.createElement('div');+ turnNote.className = 'turn';+ turnNote.textContent = 'Turn your phone sideways for the full console';+ document.body.appendChild(turnNote);+ // the wind slider's hit area over its track+ const [kx0, ky] = ui.knobAt(0);+ const [kx1] = ui.knobAt(WIND_MAX);+ const windHit = document.createElement('div');+ windHit.className = 'windhit';+ Object.assign(windHit.style, {left: `${kx0 - 12}px`, top: `${ky - 13}px`, width: `${kx1 - kx0 + 24}px`, height: '26px'});+ ui.root.appendChild(windHit);++ // ------------------------------------------------------------ state+ let T = 0; // wall clock+ let simT = 0; // stops while paused+ let theta = 0;+ let flow = 0;+ let dist = 0;+ let paused = false;+ let wind = 6;+ let windTarget = 6;+ let iso = 0;+ let isoTarget = 0;+ let isoOnAt = Infinity;+ const tr = {on: false, theta0: 0, done: null, fade: 0};+ let view = 'cine';+ let viewAt0 = 0;+ const off = {az: 0, el: 0, k: 1};+ const cam = {...VIEW_FN.cine(0, 0)};+ let ring = {t: -9, x: 0, y: 0};+ // the last 14 s of the crank and the wind, for the console's histories+ const hist = [];+ const histAt = (t, key) => {+ if (!hist.length) return key === 'th' ? theta : wind;+ if (t <= hist[0].t) return key === 'th' ? hist[0].th - rpsAt(hist[0].w) * Math.PI * 2 * (hist[0].t - t) : hist[0].w;+ const last = hist[hist.length - 1];+ if (t >= last.t) return last[key];+ let lo = 0;+ let hi = hist.length - 1;+ while (hi - lo > 1) {+ const m = (lo + hi) >> 1;+ if (hist[m].t <= t) lo = m;+ else hi = m;+ }+ const a = hist[lo];+ const b = hist[hi];+ return a[key] + (b[key] - a[key]) * ((t - a.t) / (b.t - a.t || 1));+ };+ const frameConsole = makeConsoleFrame(ui, st, {thetaAt: (t) => histAt(t, 'th'), windAt: (t) => histAt(t, 'w')});+ const pulse = (key) => {+ const r = ui.btn[key].getBoundingClientRect();+ const [x, y] = toStage(r.left + r.width / 2, r.top + r.height / 2);+ ring = {t: T, x, y};+ };++ const setView = (v) => {+ if (v === view) return;+ view = v;+ viewAt0 = T;+ };+ const setIso = (on) => {+ isoTarget = on ? 1 : 0;+ if (on) {+ isoOnAt = simT;+ setView('leg');+ } else if (view === 'leg') setView('front');+ };+ const setTrace = (on) => {+ if (on === tr.on) return;+ tr.on = on;+ if (on) Object.assign(tr, {theta0: theta, done: null});+ };+ const setPaused = (p) => {+ paused = p;+ ui.btn.pause.textContent = p ? '▶ RESUME' : '❚❚ PAUSE';+ };++ // ------------------------------------------------------------ the tour: the film's script, looped+ const AP = {on: true, t0: 0, loop: 0, prevIso: 0};+ let lastInput = 0;+ const startTour = () => {+ AP.on = true;+ AP.t0 = T;+ AP.loop = 0;+ AP.prevIso = 0;+ if (paused) setPaused(false);+ setTrace(false);+ Object.assign(off, {az: 0, el: 0, k: 1});+ };+ const takeOver = () => {+ lastInput = T;+ if (!AP.on) return;+ AP.on = false;+ windTarget = wind;+ isoTarget = iso > 0.5 ? 1 : 0;+ };+ tourChip.addEventListener('pointerdown', (e) => {+ e.stopPropagation();+ lastInput = T;+ if (AP.on) takeOver();+ else startTour();+ });+ addEventListener('pointerdown', takeOver);+ for (const k of VIEW_KEYS)+ ui.btn[k].addEventListener('click', () => {+ takeOver();+ pulse(k);+ if (k !== 'leg' && isoTarget) isoTarget = 0;+ if (k === 'leg') setIso(true);+ else setView(k);+ Object.assign(off, {az: 0, el: 0, k: 1});+ });+ ui.btn.iso.addEventListener('click', () => {+ takeOver();+ pulse('iso');+ setIso(!isoTarget);+ });+ ui.btn.trace.addEventListener('click', () => {+ takeOver();+ pulse('trace');+ setTrace(!tr.on);+ });+ ui.btn.pause.addEventListener('click', () => {+ takeOver();+ pulse('pause');+ setPaused(!paused);+ });+ {+ const onMove = (e) => {+ const [x] = toStage(e.clientX, e.clientY);+ windTarget = clamp(((x - kx0) / (kx1 - kx0)) * WIND_MAX, 0, WIND_MAX);+ lastInput = T;+ };+ windHit.addEventListener('pointerdown', (e) => {+ takeOver();+ windHit.setPointerCapture(e.pointerId);+ const up = () => {+ removeEventListener('pointermove', onMove);+ removeEventListener('pointerup', up);+ };+ addEventListener('pointermove', onMove);+ addEventListener('pointerup', up);+ onMove(e);+ });+ }+ addEventListener('keydown', (e) => {+ if (e.altKey || e.ctrlKey || e.metaKey) return;+ const key = e.key.toLowerCase();+ const v = {1: 'cine', 2: 'leg', 3: 'front', 4: 'side', 5: 'top'}[key];+ if (v) ui.btn[v].click();+ else if (key === 'i') ui.btn.iso.click();+ else if (key === 't') ui.btn.trace.click();+ else if (key === ' ') ui.btn.pause.click();+ else if (key === 'arrowright' || key === 'arrowleft') {+ takeOver();+ windTarget = clamp(windTarget + (key === 'arrowright' ? 1 : -1), 0, WIND_MAX);+ } else return;+ e.preventDefault();+ });+ let drag = null;+ canvas.addEventListener('pointerdown', (e) => {+ drag = {x: e.clientX, y: e.clientY};+ canvas.setPointerCapture(e.pointerId);+ canvas.classList.add('drag');+ });+ canvas.addEventListener('pointermove', (e) => {+ if (!drag) return;+ const dx = (e.clientX - drag.x) / scale;+ const dy = (e.clientY - drag.y) / scale;+ drag = {x: e.clientX, y: e.clientY};+ off.az -= dx * 0.3;+ off.el = clamp(off.el + dy * 0.2, -10, 70);+ lastInput = T;+ });+ const endDrag = () => {+ drag = null;+ canvas.classList.remove('drag');+ };+ canvas.addEventListener('pointerup', endDrag);+ canvas.addEventListener('pointercancel', endDrag);+ canvas.addEventListener(+ 'wheel',+ (e) => {+ e.preventDefault();+ takeOver();+ off.k = clamp(off.k * Math.exp(e.deltaY * 0.0012), 0.45, 2.2);+ },+ {passive: false},+ );++ // ------------------------------------------------------------ footprints as the feet land+ const wasDown = new Array(20).fill(true);+ const layPrints = (bx) => {+ for (let r = 0; r < 20; r++) {+ const s = r % 10;+ const side = r < 10 ? 0 : 1;+ const ps = theta + phaseOf(s);+ const down = footLift(side ? Math.PI - ps : ps) < 0.5;+ if (down && !wasDown[r]) st.addPrint(bx + legAt(s, side, theta).F[0] * S, legZ(s, side) * S, simT, (((r * 7919) % 100) / 100 - 0.5) * 0.25);+ wasDown[r] = down;+ }+ };++ // ------------------------------------------------------------ the frame+ startTour();+ let last = performance.now();+ const perf = {n: 0, sum: 0, slow: 0, age: 0};+ let odd = false;+ const frame = (now) => {+ const dt = Math.min(0.1, Math.max(0, (now - last) / 1000));+ last = now;+ T += dt;+ // quality steps down after a 0.5 s window slower than 45 fps (two in a row once the page has settled)+ if (tier < TIERS.length - 1) {+ perf.age += dt;+ if (perf.age > 0.4) {+ perf.sum += dt;+ perf.n++;+ if (perf.sum >= 0.5 && perf.n >= 6) {+ perf.slow = perf.sum / perf.n > 0.022 ? perf.slow + 1 : 0;+ perf.sum = 0;+ perf.n = 0;+ if (perf.slow >= (perf.age < 6 ? 1 : 2)) {+ tier++;+ applyTier();+ Object.assign(perf, {age: 0, slow: 0});+ }+ }+ }+ }++ // the operator: the tour's script, or the visitor's last choices+ let cyc = 0;+ let since = T - viewAt0;+ let cursor;+ if (AP.on) {+ const c = T - AP.t0;+ const loop = Math.floor(c / DURATION);+ if (loop > AP.loop) {+ AP.loop = loop;+ AP.prevIso = 0;+ }+ cyc = c - loop * DURATION;+ const [t0, v] = scriptView(cyc);+ view = v;+ since = cyc - t0;+ // keep the view's clock running so a takeover continues the move instead of jumping+ viewAt0 = T - since;+ windTarget = windAt(cyc);+ const isoNow = isoAt(cyc);+ if (isoNow > 0.01 && AP.prevIso <= 0.01) isoOnAt = simT;+ AP.prevIso = isoNow;+ isoTarget = isoNow;+ cursor = tourCursorAt(cyc);+ // from the second loop on, the pointer glides from where the last one left it+ if (AP.loop > 0 && cyc < 0.8) {+ const end = tourCursorAt(DURATION - 0.01);+ const k = ss(0, 0.8, cyc);+ cursor = {...cursor, x: end.x + (cursor.x - end.x) * k, y: end.y + (cursor.y - end.y) * k};+ }+ } else {+ if (T - lastInput > IDLE) startTour();+ const rk = Math.max(0, 1 - (T - ring.t) / 0.55);+ cursor = {x: -99, y: -99, press: false, drag: false, ring: rk, ringX: ring.x, ringY: ring.y};+ }+ wind += (windTarget - wind) * (1 - Math.exp(-dt / 0.35));+ iso += (isoTarget - iso) * (1 - Math.exp(-dt / 0.2));++ // the crank: wind sets its rate, a dead calm lets it coast to a stop+ if (!paused) {+ simT += dt;+ const rps = rpsAt(wind) * ss(0.3, 1.5, wind);+ const th0 = theta;+ theta += rps * Math.PI * 2 * dt;+ flow += wind * dt * 0.35;+ dist += Math.abs(st.bodyPos(theta).x - st.bodyPos(th0).x);+ }+ if (!paused || !hist.length) hist.push({t: simT, th: theta, w: wind});+ while (hist.length > 2 && hist[0].t < simT - 14) hist.shift();+ const b = st.bodyPos(theta);+ if (!paused) layPrints(b.x);++ // the foot traces: the hero's loop draws itself from the click, the rest fade in when it closes+ let heroTrace = 0;+ let trace = 0;+ tr.fade += ((tr.on ? 1 : 0) - tr.fade) * (1 - Math.exp(-dt / 0.25));+ if (tr.on || tr.fade > 0.01) {+ heroTrace = Math.min(1, (theta - tr.theta0) / (Math.PI * 2));+ if (heroTrace >= 1 && tr.done === null) tr.done = simT;+ trace = tr.done === null ? 0 : ss(tr.done, tr.done + 0.9, simT);+ }++ // the camera eases toward the view's own move plus the visitor's orbit; a wide swing backs off on the way+ const tgt = VIEW_FN[view](since, b.x);+ tgt.az += off.az;+ tgt.el = clamp(tgt.el + off.el, 2, 82);+ tgt.d *= off.k;+ const k = 1 - Math.exp(-dt / 0.55);+ const dAz = wrapDeg(tgt.az - cam.az);+ cam.az += dAz * k;+ for (const key of ['tx', 'ty', 'tz', 'el', 'd', 'sx', 'sy']) cam[key] += (tgt[key] - cam[key]) * k;+ const swing = Math.min(1, Math.abs(dAz) / 90);+ st.frame(theta, simT, {...cam, el: (cam.el + 8 * swing) * D2R, az: cam.az * D2R, d: cam.d + 2.5 * swing}, {wind, flow, iso, hero: HERO, trace, heroTrace, traceFade: tr.on ? 1 : tr.fade});++ // the console: every frame on a fast GPU, every other frame (the pointer every frame) on a slow one+ odd = !odd;+ if (tier > 0 && odd) ui.pointer(cursor);+ else frameConsole(simT, {view, since, iso, cursor, labelStart: isoOnAt, trace: tr.on ? 1 : 0, dist});++ if (tourChip.classList.contains('on') !== AP.on || !tourChip.firstChild) {+ tourChip.classList.toggle('on', AP.on);+ tourChip.innerHTML = AP.on ? '<i></i>AUTO TOUR · CLICK TO TAKE OVER' : '▶ RESUME TOUR';+ }+ // the site page swaps its poster for the canvas on this+ if (!window.SIM_SHOWN) {+ window.SIM_SHOWN = true;+ dispatchEvent(new Event('simframe'));+ }+ requestAnimationFrame(frame);+ };+ // every shader compiles at once off the main thread before the first frame (kit/warm.js)+ warmComposer(st.renderer, st.composer, st.scene, st.camera).then(() => requestAnimationFrame(frame));+ window.LIVE = {st, cam, startTour, takeOver, get tier() {+ return tier;+ }, get T() {+ return T;+ }};+}diff --git a/sims/strandbeest-shared/score.py b/sims/strandbeest-shared/score.pynew file mode 100644index 0000000..c437346--- /dev/null+++ b/sims/strandbeest-shared/score.py@@ -0,0 +1,85 @@+"""Score for the STRANDBEEST SB-10 console film: a warm bed (Fmaj9 chords, 88 bpm) at one level the whole way, wind+under it that rises when the operator opens the slider, a soft sand thud on every touchdown of leg 01F, a quiet click+on every button press and a typewriter tick for each of the thirteen letters on the isolated leg.++ python run_sfx.py sims/strandbeest-shared/score.py++Times from strandbeest-shared/film.js (SCRIPT, the label cadence, the wind and crank model, which is mirrored here).+"""++import math+import os++from sfx.score_kit import airy, bed, chords, hz, thud+from sfx.synth import click++TIMELINE = "../strandbeest-film/timeline.json"+OUT = os.path.join(os.environ.get("TEARDOWN_OUT", "teardown-out"), "strandbeest-score.wav")+TARGET_LUFS = -14.0+SEED = 11++CHORDS = chords("Fmaj9:F2 C3 E3 G3 A3/F1", "Dm9:D2 A2 C3 E3 F3/D1", "Bbmaj7:Bb1 F2 A2 D3/Bb0", "C6sus:C2 F2 G2 A2 D3/C1")+MOTIF = [(0.5, hz("C5")), (1.5, hz("A4")), (2.5, hz("G4"))]++CLICKS = (3.4, 9.6, 13.0, 16.8, 21.0, 25.8)+LABELS = [3.4 + 0.9 + i * 0.3 for i in range(13)]+WIND_EV = (13.0, 6.0, 12.5, 1.6)+++def smoother(x):+ u = min(1.0, max(0.0, x))+ return u * u * u * (u * (u * 6 - 15) + 10)+++def wind_at(t):+ t0, w0, w1, dur = WIND_EV+ return w0 + (w1 - w0) * smoother((t - t0) / dur) + 0.35 * math.sin(t * 0.9) + 0.2 * math.sin(t * 2.3 + 1)+++def rps_at(w):+ return 0.42 * (max(0.5, w) / 6) ** 0.75+++def theta_table(dur, dt=1 / 240):+ th, out, t = 0.0, [], 0.0+ while t <= dur:+ out.append((t, th))+ th += rps_at(wind_at(t + dt / 2)) * 2 * math.pi * dt+ t += dt+ return out+++def touchdowns(dur):+ """Leg 01F lands where its crank angle crosses the start of the flat stretch (290° on Jansen's path)."""+ land = math.radians(290)+ out = []+ prev = None+ for t, th in theta_table(dur):+ k = math.floor((th - land) / (2 * math.pi))+ if prev is not None and k != prev:+ out.append(t)+ prev = k+ return out+++def score(mix, tl):+ dur = tl["duration"]+ left, right, low, drums = bed(dur, 88, CHORDS, MOTIF, motif_voice="epiano", kicks=(0, 2.5), snares=(), hats=8, swing=0.0, keys_vel=0.7, keys_lp=3400)+ mix.put_stereo(0, left, right, 0.12)+ mix.put(0, low, 0.13)+ mix.put(0, drums, 0.045)++ # wind: a low steady breath, a gust swelling up the slider drag, a stronger bed after it+ mix.put(0, airy(WIND_EV[0] + 0.4, 380, 520, 0.5), 0.012)+ mix.put(WIND_EV[0], airy(WIND_EV[3] + 0.8, 500, 1900, 0.6), 0.04)+ mix.put(WIND_EV[0] + WIND_EV[3], airy(dur - WIND_EV[0] - WIND_EV[3], 650, 820, 0.5), 0.02)++ for t in touchdowns(dur):+ if t < dur - 0.4:+ mix.put(t, thud(105, 0.035, 0.25), 0.05)+ for t in CLICKS:+ mix.put(t, click(2400, 0.025), 0.055)+ for t in LABELS:+ mix.put(t, click(3400, 0.012), 0.03)+ for t in (9.7, 16.9, 21.1, 25.9):+ mix.put(t, airy(1.1, 700, 1600, 0.6), 0.02)diff --git a/sims/strandbeest-shared/stage.js b/sims/strandbeest-shared/stage.jsnew file mode 100644index 0000000..ec7edff--- /dev/null+++ b/sims/strandbeest-shared/stage.js@@ -0,0 +1,463 @@+// The beest's stage: a warm studio over pale sand. PBR with VSM shadows and GTAO (the sand kept out of the AO pass),+// an unlit sand floor whose ripples fade into the backdrop, shadows laid over it. frame(theta, t, cam) poses the+// beast from the crank angle and draws one frame; the view size is whatever the caller's canvas box is.+import * as THREE from 'three';+import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';+import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';+import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';+import {Pass} from 'three/addons/postprocessing/Pass.js';+import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';+import {ShaderPass} from 'three/addons/postprocessing/ShaderPass.js';+import {bodyAt, buildBeast, PAD, S} from './beast.js';+import {FOOT_MIN} from './jansen.js';++const V3 = THREE.Vector3;+export const PALETTES = {+ sand: {+ bg: '#eee7dc',+ sand: '#ebe2d3',+ tube: '#f4f1eb',+ joint: '#d1322a',+ steel: '#646870',+ foot: '#8c8780',+ sail: '#fbf9f5',+ shadow: ['#5b4936', 0.34],+ env: {bg: '#e4ddd2', ground: '#d6ccbb', k: 0.8},+ hemi: ['#fbf7f1', '#dacdb8', 0.62],+ },+ // tan dune under a pale sky: the white frame stands off a darker ground+ dune: {+ bg: '#e9e2d6',+ sand: '#d2bc98',+ tube: '#f7f4ef',+ joint: '#d1322a',+ steel: '#4e525a',+ foot: '#6f6a64',+ sail: '#fbf9f5',+ shadow: ['#4a3220', 0.42],+ env: {bg: '#dde2e4', ground: '#c9b391', k: 0.85},+ hemi: ['#f4f7fa', '#c7ae86', 0.6],+ hero: '#2a2622',+ trace: '#e2672a',+ print: '#6a4f30',+ grain: '#86683f',+ },+ // a cool slate studio: the most contrast the light console can take+ slate: {+ bg: '#cfd5da',+ sand: '#bcc1c3',+ tube: '#f8f7f4',+ joint: '#d8352b',+ steel: '#3f444b',+ foot: '#5d6166',+ sail: '#fbfbf9',+ shadow: ['#1d2731', 0.4],+ env: {bg: '#cfd5da', ground: '#aeb4b8', k: 0.85},+ hemi: ['#f2f5f8', '#a9afb3', 0.62],+ },+};+const INK_FRAG = /* glsl */ `+ uniform sampler2D tDiffuse; uniform sampler2D tDepth; uniform sampler2D tNormal;+ uniform float uNear; uniform float uFar; uniform vec2 uPx; uniform vec3 uInk; uniform float uStrength;+ varying vec2 vUv;+ float lz(vec2 uv){ float d = texture2D(tDepth, uv).x; return uNear * uFar / (uFar - d * (uFar - uNear)); }+ vec3 nn(vec2 uv){ return normalize(texture2D(tNormal, uv).xyz * 2.0 - 1.0); }+ void main(){+ vec4 c = texture2D(tDiffuse, vUv);+ float z0 = lz(vUv);+ float zl = lz(vUv - vec2(uPx.x, 0.0)), zr = lz(vUv + vec2(uPx.x, 0.0));+ float zd = lz(vUv - vec2(0.0, uPx.y)), zu = lz(vUv + vec2(0.0, uPx.y));+ float lap = (abs(zl + zr - 2.0 * z0) + abs(zu + zd - 2.0 * z0)) / max(z0, 1e-3);+ float eD = smoothstep(0.004, 0.016, lap);+ vec3 n0 = nn(vUv);+ float eN = max(max(1.0 - dot(n0, nn(vUv - vec2(uPx.x, 0.0))), 1.0 - dot(n0, nn(vUv + vec2(uPx.x, 0.0)))),+ max(1.0 - dot(n0, nn(vUv - vec2(0.0, uPx.y))), 1.0 - dot(n0, nn(vUv + vec2(0.0, uPx.y)))));+ float e = max(eD, smoothstep(0.3, 0.6, eN));+ c.rgb = mix(c.rgb, uInk, e * uStrength);+ gl_FragColor = c;+ }`;++const SAND_VERT = /* glsl */ `varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`;+const SAND_FRAG = /* glsl */ `uniform vec3 uSand; uniform vec3 uBg; uniform vec3 uC; varying vec3 vW;+ float h(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }+ float n(vec2 p){ vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f);+ return mix(mix(h(i), h(i + vec2(1, 0)), f.x), mix(h(i + vec2(0, 1)), h(i + vec2(1, 1)), f.x), f.y); }+ void main(){+ vec2 p = vW.xz;+ // wind ripples: long crests bent by a slow noise, light on the windward face+ float bend = n(p * 0.35) * 2.6 + n(p * 1.1) * 0.6;+ float ph = (p.y * 2.9 + p.x * 0.55 + bend) * 6.2831;+ float rip = sin(ph) * 0.5 + 0.5;+ rip = pow(rip, 3.0) - 0.25 * sin(ph + 1.2);+ float grain = n(p * 70.0) * 0.6 + n(p * 190.0) * 0.4;+ float pat = n(p * 0.22);+ vec3 col = uSand * (0.985 + 0.055 * rip - 0.05 * grain + 0.04 * (pat - 0.5));+ // fine fade near the camera's look point keeps the texture under the beast, the horizon melts into the backdrop+ float d = length(p - uC.xz);+ float fade = smoothstep(5.0, 17.0, d);+ gl_FragColor = vec4(mix(col, uBg, fade), 1.0);+ }`;++// footprints: pressed ovals that appear at touchdown and fade over ~20 s; one instance per planted step+const PRINT_VERT = /* glsl */ `attribute vec4 aP; uniform float uT; varying vec2 vUv; varying float vA;+ void main(){+ vec2 c = position.xy;+ float ca = cos(aP.w), sa = sin(aP.w);+ vec2 q = vec2(c.x * 0.085, c.y * 0.105);+ vec2 r = vec2(q.x * ca - q.y * sa, q.x * sa + q.y * ca);+ vUv = c;+ float age = uT - aP.z;+ vA = step(0.0, age) * smoothstep(0.0, 0.15, age) * (1.0 - smoothstep(14.0, 24.0, age));+ gl_Position = projectionMatrix * viewMatrix * vec4(aP.x + r.x, 0.0012, aP.y + r.y, 1.0);+ }`;+const PRINT_FRAG = /* glsl */ `uniform vec3 uCol; varying vec2 vUv; varying float vA;+ void main(){+ float d = length(vUv * 2.0);+ // a pressed hollow with a raised, lit rim pushed out around it+ float hollow = 1.0 - smoothstep(0.6, 1.0, d);+ float rim = smoothstep(0.75, 0.95, d) * (1.0 - smoothstep(1.0, 1.25, d));+ float a = (hollow * 0.5 + rim * 0.16) * vA;+ if (a < 0.003) discard;+ gl_FragColor = vec4(mix(uCol, vec3(1.0), rim * 0.7), a);+ }`;+// blown sand: grains streaming low over the dune with the wind, wrapped in a box around the camera's look point+const GRAIN_VERT = /* glsl */ `attribute vec3 aSeed; uniform float uT; uniform float uFlow; uniform vec3 uC; uniform vec2 uDir; uniform float uPr; uniform float uAmt;+ varying float vA;+ void main(){+ vec3 box = vec3(12.0, 1.0, 9.0);+ vec2 p = aSeed.xz * box.xz + uDir * uFlow * (0.65 + 0.7 * aSeed.y);+ vec2 rel = mod(p - uC.xz + box.xz * 0.5, box.xz);+ vec2 edge = min(rel, box.xz - rel);+ vec3 w = vec3(rel.x + uC.x - box.x * 0.5, 0.012 + aSeed.y * aSeed.y * aSeed.y * 0.55 + 0.03 * sin(uT * 2.3 + aSeed.x * 40.0), rel.y + uC.z - box.z * 0.5);+ vec4 mv = viewMatrix * vec4(w, 1.0);+ gl_Position = projectionMatrix * mv;+ gl_PointSize = uPr * (2.2 + 3.2 * aSeed.z) * clamp(7.0 / -mv.z, 0.5, 2.5);+ vA = uAmt * (0.25 + 0.6 * aSeed.z) * smoothstep(0.0, 1.5, min(edge.x, edge.y));+ }`;+const GRAIN_FRAG = /* glsl */ `uniform vec3 uCol; varying float vA;+ void main(){ vec2 c = gl_PointCoord - 0.5; float a = (1.0 - smoothstep(0.15, 0.5, length(c))) * vA; if (a < 0.01) discard; gl_FragColor = vec4(uCol, a); }`;++export function createBeestStage({canvas, palette = 'sand', ink = 0}) {+ const P = PALETTES[palette] || PALETTES.sand;+ const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});+ renderer.toneMapping = THREE.NeutralToneMapping;+ renderer.toneMappingExposure = 1.0;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.VSMShadowMap;+ const scene = new THREE.Scene();+ scene.background = new THREE.Color(P.bg);+ if (P.sky) {+ // a screen-space sky: the top colour down to the horizon, the horizon colour below it+ const c = document.createElement('canvas');+ c.width = 4;+ c.height = 512;+ const g = c.getContext('2d');+ const gr = g.createLinearGradient(0, 0, 0, 512);+ gr.addColorStop(0, P.sky[0]);+ gr.addColorStop(0.55, P.sky[1]);+ gr.addColorStop(1, P.sky[1]);+ g.fillStyle = gr;+ g.fillRect(0, 0, 4, 512);+ const tex = new THREE.CanvasTexture(c);+ tex.colorSpace = THREE.SRGBColorSpace;+ scene.background = tex;+ }+ scene.fog = new THREE.Fog(P.bg, 9, 24);+ const camera = new THREE.PerspectiveCamera(22, 16 / 9, 0.05, 200);+ const rt = new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: 8});+ const composer = new EffectComposer(renderer, rt);+ composer.addPass(new RenderPass(scene, camera));+ const gtao = new GTAOPass(scene, camera, 4, 4);+ gtao.output = GTAOPass.OUTPUT.Default;+ gtao.blendIntensity = 0.85;+ gtao.updateGtaoMaterial({radius: 0.12, distanceExponent: 1.4, thickness: 1.0, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});+ gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, rings: 2, samples: 16});+ class Toggle extends Pass {+ constructor(fn) {+ super();+ this.needsSwap = false;+ this.fn = fn;+ }+ render() {+ this.fn();+ }+ }+ // what the AO pass (and the ink drawn from it) must not see: the ground, the sheets, the overlays, and the ghosted+ // frame while a leg is isolated+ let isoNow = 0;+ const groundAO = (v) => () => {+ floor.visible = v;+ shade.visible = v;+ prints.visible = v;+ grains.visible = v;+ for (const s of beast.sails) s.visible = v;+ for (const m of beast.traces) m.visible = v && m.userData.on;+ if (isoNow > 0.5) for (const m of beast.main) m.visible = v;+ };+ composer.addPass(new Toggle(groundAO(false)));+ // ink only (a weak GPU): GTAO renders just its normal and depth buffer for the outline, skips the AO and the+ // denoise, and leaves the picture where it is+ let aoOn = true;+ const gtaoRender = gtao.render.bind(gtao);+ gtao.render = (renderer, writeBuffer, readBuffer, ...rest) => {+ if (aoOn) return gtaoRender(renderer, writeBuffer, readBuffer, ...rest);+ gtao._overrideVisibility();+ gtao._renderOverride(renderer, gtao.normalMaterial, gtao.normalRenderTarget, 0x7777ff, 1.0);+ gtao._restoreVisibility();+ };+ composer.addPass(gtao);+ composer.addPass(new Toggle(groundAO(true)));+ // ink: depth creases and normal breaks from the AO pass's g-buffer, which holds the beast alone+ const inkPass = new ShaderPass(+ new THREE.ShaderMaterial({+ uniforms: {+ tDiffuse: {value: null},+ tDepth: {value: gtao.depthTexture},+ tNormal: {value: gtao.normalTexture},+ uNear: {value: camera.near},+ uFar: {value: camera.far},+ uPx: {value: new THREE.Vector2(1 / 1920, 1 / 1080)},+ uInk: {value: new THREE.Color().setRGB(0.07, 0.06, 0.055, THREE.LinearSRGBColorSpace)},+ uStrength: {value: ink},+ },+ vertexShader: /* glsl */ `varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,+ fragmentShader: INK_FRAG,+ }),+ );+ inkPass.enabled = ink > 0;+ composer.addPass(inkPass);+ composer.addPass(new OutputPass());++ // studio environment: warm soft boxes over a sand-coloured ground, prefiltered+ {+ const env = new THREE.Scene();+ env.background = new THREE.Color(P.env.bg);+ const box = (w, h, pos, k, tint = [1, 0.985, 0.95]) => {+ const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(...tint).multiplyScalar(k), side: THREE.DoubleSide}));+ m.position.copy(pos);+ m.lookAt(0, 0, 0);+ env.add(m);+ };+ box(16, 7, new V3(-12, 11, 9), 3.0);+ box(10, 10, new V3(11, 14, -7), 2.2);+ box(20, 3, new V3(2, 5, 17), 1.7);+ const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: P.env.ground, side: THREE.DoubleSide}));+ g.rotation.x = -Math.PI / 2;+ g.position.y = -1.5;+ env.add(g);+ const pm = new THREE.PMREMGenerator(renderer);+ scene.environment = pm.fromScene(env, 0.03).texture;+ scene.environmentIntensity = P.env.k;+ pm.dispose();+ }+ const SUN_DIR = new V3(-0.55, 0.66, 0.52).normalize();+ const sun = new THREE.DirectionalLight('#fff7ec', 2.4);+ sun.castShadow = true;+ const EXT = 3.0;+ Object.assign(sun.shadow.camera, {left: -EXT, right: EXT, top: EXT, bottom: -EXT, near: 0.5, far: 24});+ sun.shadow.mapSize.set(4096, 4096);+ sun.shadow.radius = 7;+ sun.shadow.blurSamples = 20;+ sun.shadow.bias = -0.0003;+ sun.shadow.normalBias = 0.003;+ scene.add(sun, sun.target);+ scene.add(new THREE.HemisphereLight(...P.hemi));++ // sand+ const sandMat = new THREE.ShaderMaterial({+ vertexShader: SAND_VERT,+ fragmentShader: SAND_FRAG,+ uniforms: {uSand: {value: new THREE.Color(P.sand)}, uBg: {value: new THREE.Color(P.bg)}, uC: {value: new V3()}},+ toneMapped: false,+ });+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(400, 400), sandMat);+ floor.rotation.x = -Math.PI / 2;+ scene.add(floor);+ const shade = new THREE.Mesh(new THREE.PlaneGeometry(400, 400), new THREE.ShadowMaterial({color: P.shadow[0], opacity: P.shadow[1], fog: false, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -8}));+ shade.rotation.x = -Math.PI / 2;+ shade.position.y = 0.0004;+ shade.receiveShadow = true;+ scene.add(shade);++ const beast = buildBeast(P);+ scene.add(beast.group);++ // footprints, set by the caller as [x, z, born, angle] per step+ const printGeo = new THREE.InstancedBufferGeometry();+ {+ const base = new THREE.PlaneGeometry(1, 1);+ printGeo.index = base.index;+ printGeo.setAttribute('position', base.attributes.position);+ printGeo.setAttribute('aP', new THREE.InstancedBufferAttribute(new Float32Array(4), 4));+ printGeo.instanceCount = 0;+ }+ const printMat = new THREE.ShaderMaterial({+ vertexShader: PRINT_VERT,+ fragmentShader: PRINT_FRAG,+ uniforms: {uT: {value: 0}, uCol: {value: new THREE.Color(P.print || '#7a5c3a')}},+ transparent: true,+ depthWrite: false,+ // the quad is laid on the ground by a mirrored mapping, so its winding flips+ side: THREE.DoubleSide,+ polygonOffset: true,+ polygonOffsetFactor: -4,+ polygonOffsetUnits: -8,+ });+ const prints = new THREE.Mesh(printGeo, printMat);+ prints.frustumCulled = false;+ prints.renderOrder = 1;+ scene.add(prints);+ const setPrints = (list) => {+ const a = new Float32Array(Math.max(4, list.length * 4));+ list.forEach((p, i) => a.set(p, i * 4));+ printGeo.setAttribute('aP', new THREE.InstancedBufferAttribute(a, 4));+ printGeo.instanceCount = list.length;+ };+ // the live page lays prints as the feet land: a ring of cap slots, unborn slots far in the future+ let ring = null;+ const usePrintRing = (cap) => {+ const a = new Float32Array(cap * 4);+ for (let i = 0; i < cap; i++) a[i * 4 + 2] = 1e9;+ const attr = new THREE.InstancedBufferAttribute(a, 4);+ attr.setUsage(THREE.DynamicDrawUsage);+ printGeo.setAttribute('aP', attr);+ printGeo.instanceCount = cap;+ ring = {attr, cap, i: 0};+ };+ const addPrint = (x, z, born, angle) => {+ ring.attr.array.set([x, z, born, angle], ring.i * 4);+ ring.i = (ring.i + 1) % ring.cap;+ ring.attr.needsUpdate = true;+ };++ // blown sand+ const NG = 9000;+ const grainGeo = new THREE.BufferGeometry();+ {+ const seed = new Float32Array(NG * 3);+ let r = 91;+ const rnd = () => (r = (r * 16807) % 2147483647) / 2147483647;+ for (let i = 0; i < NG * 3; i++) seed[i] = rnd();+ grainGeo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 3));+ grainGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(NG * 3), 3));+ }+ const grainMat = new THREE.ShaderMaterial({+ vertexShader: GRAIN_VERT,+ fragmentShader: GRAIN_FRAG,+ uniforms: {uT: {value: 0}, uFlow: {value: 0}, uC: {value: new V3()}, uDir: {value: new THREE.Vector2(-0.86, 0.5)}, uPr: {value: 1}, uAmt: {value: 0}, uCol: {value: new THREE.Color(P.grain || '#8f7350')}},+ transparent: true,+ depthWrite: false,+ });+ const grains = new THREE.Points(grainGeo, grainMat);+ grains.frustumCulled = false;+ grains.renderOrder = 4;+ scene.add(grains);++ const size = {w: 1600, h: 900};+ const resize = (w, h, pr) => {+ size.w = w;+ size.h = h;+ grainMat.uniforms.uPr.value = pr;+ renderer.setPixelRatio(pr);+ renderer.setSize(w, h, false);+ composer.setPixelRatio(pr);+ composer.setSize(w, h);+ inkPass.material.uniforms.uPx.value.set(1 / (w * pr), 1 / (h * pr));+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ };++ const tmp = new V3();+ const right = new V3().crossVectors(new V3(0, 1, 0), SUN_DIR).normalize();+ const upL = new V3().crossVectors(SUN_DIR, right);+ let texel = (2 * EXT) / sun.shadow.mapSize.x;++ /** The body's world position for crank angle theta: x along the walk, y of the axle. */+ const bodyPos = (theta) => {+ const b = bodyAt(theta);+ return {x: b.x * S, y: -(FOOT_MIN + b.low - PAD * 1.25) * S};+ };++ // ops: wind (m/s), flow (metres of wind run so far), iso, hero, trace, heroTrace; cam.sx / cam.sy shift the picture+ // on screen (CSS px) so the subject sits in the space the console leaves free+ const frame = (theta, t, cam, ops = {}) => {+ const b = bodyPos(theta);+ beast.group.position.set(b.x, b.y, 0);+ const wind = ops.wind ?? 6;+ isoNow = ops.iso ?? 0;+ beast.update(theta, t, 0.45 + 0.6 * Math.min(1.2, wind / 10), ops);+ for (const m of beast.traces) m.userData.on = m.visible;+ printMat.uniforms.uT.value = t;+ grainMat.uniforms.uT.value = t;+ grainMat.uniforms.uFlow.value = ops.flow ?? 0;+ grainMat.uniforms.uAmt.value = 0.25 + 0.75 * Math.min(1, Math.max(0, (wind - 5) / 7));++ const {tx, ty, tz, az, el, d} = cam;+ camera.position.set(tx + d * Math.cos(el) * Math.cos(az), ty + d * Math.sin(el), tz - d * Math.cos(el) * Math.sin(az));+ camera.lookAt(tx, ty, tz);+ camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);+ camera.updateMatrixWorld();+ grainMat.uniforms.uC.value.set(tx, 0, tz);+ sandMat.uniforms.uC.value.set(tx, 0, tz);+ // the sand and its shadow catcher follow the camera in whole metres; the ripples are drawn in world space+ floor.position.x = shade.position.x = Math.round(tx);+ floor.position.z = shade.position.z = Math.round(tz);+ // the shadow box follows the beast, snapped to texels so it never shimmers+ tmp.set(b.x, 0.6, 0);+ const rr = Math.round(tmp.dot(right) / texel) * texel;+ const uu = Math.round(tmp.dot(upL) / texel) * texel;+ sun.target.position.copy(right).multiplyScalar(rr).addScaledVector(upL, uu).addScaledVector(SUN_DIR, tmp.dot(SUN_DIR));+ sun.position.copy(sun.target.position).addScaledVector(SUN_DIR, 10);+ sun.target.updateMatrixWorld();+ composer.render();+ return b;+ };+ // a world point to CSS px on the canvas, null behind the camera+ const pv = new V3();+ const project = (x, y, z) => {+ pv.set(x, y, z).project(camera);+ if (pv.z > 1) return null;+ return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];+ };+ // a point of the beast given in Jansen units of its own frame (u, v, z) to world+ const beastWorld = (u, v, z) => [beast.group.position.x + u * S, beast.group.position.y + v * S, z * S];+ // the live page's quality knobs: MSAA samples, the shadow map and its blur, the AO samples, how many grains blow+ const setQuality = ({samples, shadow, blur, radius, ao, pcf, grains: ng}) => {+ if (samples !== undefined) {+ for (const t of [composer.renderTarget1, composer.renderTarget2]) {+ t.samples = samples;+ t.dispose();+ }+ }+ if (shadow !== undefined) {+ sun.shadow.mapSize.set(shadow, shadow);+ sun.shadow.map?.dispose();+ sun.shadow.map = null;+ texel = (2 * EXT) / shadow;+ }+ if (blur !== undefined) sun.shadow.blurSamples = blur;+ if (radius !== undefined) sun.shadow.radius = radius;+ if (ao !== undefined) {+ aoOn = ao > 0;+ gtao.needsSwap = aoOn;+ if (aoOn) {+ gtao.updateGtaoMaterial({samples: ao});+ gtao.updatePdMaterial({samples: Math.max(4, ao)});+ }+ }+ if (pcf !== undefined) {+ const type = pcf ? THREE.PCFSoftShadowMap : THREE.VSMShadowMap;+ if (renderer.shadowMap.type !== type) {+ renderer.shadowMap.type = type;+ sun.shadow.map?.dispose();+ sun.shadow.map = null;+ scene.traverse((o) => {+ if (o.material) for (const m of [].concat(o.material)) m.needsUpdate = true;+ });+ }+ }+ if (ng !== undefined) grainGeo.setDrawRange(0, ng);+ };+ return {renderer, scene, camera, beast, composer, gtao, inkPass, sun, resize, frame, bodyPos, size, project, beastWorld, setPrints, usePrintRing, addPrint, setQuality};+}diff --git a/sims/v8-film/main.js b/sims/v8-film/main.jsnew file mode 100644index 0000000..279b7a5--- /dev/null+++ b/sims/v8-film/main.js@@ -0,0 +1,4 @@+// V8 · Four-Stroke explorer film. Shared code in ../v8-shared.+import {run} from '../v8-shared/film.js';++run();diff --git a/sims/v8-film/timeline.json b/sims/v8-film/timeline.jsonnew file mode 100644index 0000000..6d761a9--- /dev/null+++ b/sims/v8-film/timeline.json@@ -0,0 +1 @@+{"duration":26}diff --git a/sims/v8-live/main.js b/sims/v8-live/main.jsnew file mode 100644index 0000000..b71e509--- /dev/null+++ b/sims/v8-live/main.js@@ -0,0 +1,5 @@+import {runLive} from '../v8-shared/live.js';++// V8 · Four-Stroke as an interactive page for the site: views, cutaway, overlays, firing order, speed, orbit, and an+// auto tour when left alone.+runLive();diff --git a/sims/v8-shared/console.js b/sims/v8-shared/console.jsnew file mode 100644index 0000000..2426178--- /dev/null+++ b/sims/v8-shared/console.js@@ -0,0 +1,339 @@+// The four-stroke explorer's overlay: title and the rev counter top left, the slider-crank and cross-plane panels,+// the transport bottom left, the charge legend top centre, the cylinder state, valve timing and indicator diagram on+// the right, camera / cutaway / overlay toggles bottom right, the firing order bottom centre, and callouts with thin+// leaders into the engine. Fixed 1600 x 900 CSS layout; update(s) redraws every live part from the frame's state.+import {E, ORDER, PIN_PHASE, pressure, STROKES, volume, liftEx, liftIn, pistonFrac} from './kin.js';++export const C = {ink: '#16181b', mute: '#8b8f95', faint: '#c9ccd0', line: '#e1e3e6', panel: 'rgba(248,248,249,.94)', red: '#d6182b', blue: '#3d8fe0', grey: '#5d6670', orange: '#f05a23', exh: '#8b8f95'};+export const CAMS = ['hero', 'front', 'side', 'valley', 'cyl'];+export const CUTS = ['glass', 'section', 'solid'];+export const OVERLAYS = ['callouts', 'charge', 'arrows', 'isolate', 'refract', 'charts'];+const CSS = `+#app{font-family:Inter,system-ui,sans-serif;color:${C.ink};-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}+.ui{position:absolute;inset:0;pointer-events:none}+.pn{position:absolute;background:${C.panel};border:1px solid ${C.line};box-shadow:0 1px 2px rgba(20,22,26,.04)}+.cp{font-size:9.6px;font-weight:600;letter-spacing:1.5px;text-transform:uppercase;white-space:nowrap}+.mu{color:${C.mute}}+.tb{position:absolute;height:19px;padding:0 7px;display:flex;align-items:center;justify-content:center;font-size:8.8px;font-weight:600;letter-spacing:.9px;text-transform:uppercase;border:1px solid ${C.line};background:#fff;color:${C.ink};white-space:nowrap}+.call{position:absolute;white-space:nowrap}+.call b{display:block;font-size:11.5px;font-weight:600;letter-spacing:.1px}+.call span{display:block;font-size:8.6px;font-weight:500;letter-spacing:1.4px;color:${C.mute};text-transform:uppercase;margin-top:2px}+.cur{position:absolute;left:0;top:0;z-index:50;filter:drop-shadow(0 1px 2px rgba(0,0,0,.3))}+.ring{position:absolute;width:34px;height:34px;margin:-17px 0 0 -17px;border-radius:50%;border:1.5px solid ${C.red};opacity:0;z-index:49}+`;+const el = (h) => {+ const d = document.createElement('div');+ d.innerHTML = h.trim();+ return d.firstElementChild;+};+export const RPM_MAX = 8000;++export function createConsole(app) {+ const style = document.createElement('style');+ style.textContent = CSS;+ document.head.appendChild(style);+ const ui = el(`<div class="ui"></div>`);+ app.appendChild(ui);+ const add = (h) => {+ const n = el(h);+ ui.appendChild(n);+ return n;+ };++ // ------------------------------------------------------------ title and rev counter+ add(`<div style="position:absolute;left:35px;top:33px;width:43px;height:3px;background:${C.red}"></div>`);+ add(`<div style="position:absolute;left:35px;top:47px;font-size:24px;font-weight:700;letter-spacing:-.2px">V8 <span style="color:${C.red}">·</span> Four-Stroke</div>`);+ add(`<div class="cp" style="position:absolute;left:35px;top:81px;font-weight:500;letter-spacing:1.7px;font-size:9.4px">90° CROSS-PLANE • FIRING ORDER 1-8-4-3-6-5-7-2 • 5.8 L</div>`);+ const rpmBig = add(`<div style="position:absolute;left:33px;top:103px;font-size:56px;font-weight:800;letter-spacing:-3.2px;color:${C.red};line-height:1"></div>`);+ add(`<div style="position:absolute;left:255px;top:141px;font-size:11px;font-weight:500">8000</div>`);+ add(`<div style="position:absolute;left:35px;top:166px;width:247px;height:6px;border:1px solid ${C.faint};border-top:none"></div>`);+ add(`<div style="position:absolute;left:35px;top:174px;width:247px;height:9px;background:#e6e7e9"></div>`);+ const rpmFill = add(`<div style="position:absolute;left:35px;top:174px;height:9px;background:${C.red}"></div>`);+ add(`<div class="cp mu" style="position:absolute;left:35px;top:188px;font-size:9px;font-weight:500">0</div>`);+ add(`<div class="cp" style="position:absolute;left:212px;top:188px;font-size:9px;font-weight:500;color:${C.ink}">REV / MIN</div>`);+ add(`<div style="position:absolute;left:35px;top:206px;width:247px;height:1px;background:${C.faint}"></div>`);+ add(`<div style="position:absolute;left:35px;top:213px;font-size:12.5px;font-weight:500">Crankshaft</div>`);++ // ------------------------------------------------------------ slider-crank+ add(`<div class="pn" style="left:35px;top:274px;width:247px;height:208px"></div>`);+ add(`<div class="cp" style="position:absolute;left:46px;top:286px;font-weight:700">SLIDER-CRANK</div>`);+ const scAng = add(`<div class="cp mu" style="position:absolute;right:${1600 - 271}px;top:286px;font-weight:500"></div>`);+ const sc = add(`<svg style="position:absolute;left:46px;top:303px" width="226" height="130"></svg>`);+ add(`<div style="position:absolute;left:46px;top:440px;width:226px;height:1px;background:${C.line}"></div>`);+ add(`<div style="position:absolute;left:46px;top:447px;font-size:9.5px;color:${C.mute};font-family:'JetBrains Mono',monospace">s = r·cos φ + √(L² − r² sin²φ)</div>`);+ add(`<div style="position:absolute;left:46px;top:461px;font-size:9.5px;color:${C.mute}">r <b style="color:${C.ink}">4.4</b> cm · L <b style="color:${C.ink}">14.5</b> cm</div>`);++ // ------------------------------------------------------------ cross-plane crank+ add(`<div class="pn" style="left:35px;top:490px;width:247px;height:192px"></div>`);+ add(`<div class="cp" style="position:absolute;left:46px;top:502px;font-weight:700">CROSS-PLANE CRANK</div>`);+ add(`<div class="cp mu" style="position:absolute;right:${1600 - 271}px;top:502px;font-weight:500">FRONT VIEW</div>`);+ add(`<div class="cp mu" style="position:absolute;left:46px;top:516px;font-size:8.6px;font-weight:500">R BANK</div>`);+ add(`<div class="cp mu" style="position:absolute;right:${1600 - 271}px;top:516px;font-size:8.6px;font-weight:500">L BANK</div>`);+ const cp = add(`<svg style="position:absolute;left:46px;top:526px" width="226" height="130"></svg>`);+ add(`<div style="position:absolute;left:46px;top:654px;width:226px;height:1px;background:${C.line}"></div>`);+ add(`<div style="position:absolute;left:46px;top:661px;font-size:9.5px;color:${C.mute}">Journals 90° apart · banks at ±45°</div>`);++ // ------------------------------------------------------------ transport+ add(`<div class="pn" style="left:35px;top:774px;width:259px;height:111px"></div>`);+ const btn = {};+ btn.pause = add(`<div class="tb" style="left:45px;top:782px;width:99px;height:26px;background:${C.red};color:#fff;border-color:${C.red};font-size:9.6px">❚❚ PAUSE</div>`);+ btn.back = add(`<div class="tb" style="left:149px;top:782px;width:66px;height:26px;font-size:9.6px">−15°</div>`);+ btn.fwd = add(`<div class="tb" style="left:219px;top:782px;width:66px;height:26px;font-size:9.6px">+15°</div>`);+ add(`<div class="cp" style="position:absolute;left:45px;top:818px;font-weight:500">ENGINE SPEED</div>`);+ const speedVal = add(`<div class="cp" style="position:absolute;right:${1600 - 284}px;top:818px;font-weight:700"></div>`);+ const SL = {x: 46, w: 238};+ add(`<div style="position:absolute;left:${SL.x}px;top:836px;width:${SL.w}px;height:2px;background:#e1e3e6"></div>`);+ const speedKnob = add(`<div style="position:absolute;top:831px;width:9px;height:11px;margin-left:-4.5px;background:${C.red}"></div>`);+ add(`<div class="cp" style="position:absolute;left:45px;top:851px;font-weight:500">PLAYBACK</div>`);+ const playVal = add(`<div class="cp" style="position:absolute;right:${1600 - 284}px;top:851px;font-weight:700"></div>`);+ add(`<div style="position:absolute;left:${SL.x}px;top:869px;width:${SL.w}px;height:2px;background:#e1e3e6"></div>`);+ const playKnob = add(`<div style="position:absolute;top:864px;width:9px;height:11px;margin-left:-4.5px;background:${C.red}"></div>`);++ // ------------------------------------------------------------ legend+ add(`<div class="cp" style="position:absolute;left:598px;top:36px;display:flex;gap:16px;font-weight:500;font-size:9.6px">+ ${[['AIR & FUEL', C.blue], ['COMPRESSED', C.grey], ['COMBUSTION', C.orange], ['EXHAUST', C.exh]].map(([n, c]) => `<span><i style="display:inline-block;width:15px;height:2.4px;background:${c};vertical-align:middle;margin-right:6px"></i>${n}</span>`).join('')}</div>`);++ // ------------------------------------------------------------ cylinder state+ add(`<div class="pn" style="left:1318px;top:36px;width:245px;height:209px"></div>`);+ const cylName = add(`<div class="cp" style="position:absolute;left:1329px;top:47px;font-weight:500"></div>`);+ const cylCrank = add(`<div class="cp mu" style="position:absolute;right:${1600 - 1552}px;top:47px;font-weight:500"></div>`);+ const strokeBig = add(`<div style="position:absolute;left:1329px;top:61px;font-size:24px;font-weight:700"></div>`);+ const strokeList = add(`<div style="position:absolute;left:1329px;top:97px"></div>`);+ add(`<div style="position:absolute;left:1329px;top:165px;width:224px;height:1px;background:${C.line}"></div>`);+ const barBig = add(`<div style="position:absolute;left:1328px;top:173px;font-size:36px;font-weight:800;letter-spacing:-1.6px;color:${C.red};line-height:1"></div>`);+ const barUnit = add(`<div style="position:absolute;top:197px;font-size:10.5px;font-weight:500;letter-spacing:1px;line-height:1.35">BAR<br><span style="color:${C.mute};letter-spacing:1.5px">CHAMBER PRESSURE</span></div>`);+ add(`<div style="position:absolute;left:1329px;top:228px;width:224px;height:5px;background:#e6e7e9"></div>`);+ const barFill = add(`<div style="position:absolute;left:1329px;top:228px;height:5px;background:${C.red}"></div>`);++ // ------------------------------------------------------------ valve timing+ add(`<div class="pn" data-g="charts" style="left:1318px;top:252px;width:245px;height:184px"></div>`);+ add(`<div class="cp" data-g="charts" style="position:absolute;left:1329px;top:263px;font-weight:700">VALVE TIMING</div>`);+ add(`<div class="cp mu" data-g="charts" style="position:absolute;right:${1600 - 1552}px;top:263px;font-weight:500">DRAG TO SCRUB</div>`);+ const vtLeg = add(`<div class="cp" data-g="charts" style="position:absolute;left:1329px;top:280px;font-weight:500;font-size:9px"></div>`);+ const vt = add(`<svg data-g="charts" style="position:absolute;left:1326px;top:296px" width="232" height="135"></svg>`);++ // ------------------------------------------------------------ indicator diagram+ add(`<div class="pn" data-g="charts" style="left:1318px;top:443px;width:245px;height:150px"></div>`);+ add(`<div class="cp" data-g="charts" style="position:absolute;left:1329px;top:455px;font-weight:700">INDICATOR DIAGRAM</div>`);+ const idCyl = add(`<div class="cp mu" data-g="charts" style="position:absolute;right:${1600 - 1552}px;top:455px;font-weight:500"></div>`);+ const id = add(`<svg data-g="charts" style="position:absolute;left:1326px;top:470px" width="232" height="120"></svg>`);++ // ------------------------------------------------------------ camera, cutaway, overlays+ add(`<div class="pn" style="left:1296px;top:720px;width:268px;height:165px"></div>`);+ const group = (title, keys, y, labels) => {+ add(`<div class="cp mu" style="position:absolute;left:1305px;top:${y}px;font-weight:500">${title}</div>`);+ let x = 1305;+ let yy = y + 15;+ keys.forEach((k) => {+ const w = Math.round(labels[k].length * 6.2 + 14);+ if (x + w > 1556) {+ x = 1305;+ yy += 23;+ }+ btn[k] = add(`<div class="tb" style="left:${x}px;top:${yy}px;width:${w}px">${labels[k]}</div>`);+ x += w + 4;+ });+ };+ const L = Object.fromEntries([...CAMS, ...CUTS, ...OVERLAYS].map((k) => [k, k.toUpperCase()]));+ group('CAMERA', CAMS, 727, L);+ group('CUTAWAY', CUTS, 771, L);+ group('OVERLAYS', OVERLAYS, 815, L);++ // ------------------------------------------------------------ firing order+ add(`<div class="cp mu" style="position:absolute;left:0;right:0;top:795px;text-align:center;font-weight:500"><span style="color:${C.ink}">FIRING ORDER</span> — CLICK TO TRACK</div>`);+ const fo = add(`<svg style="position:absolute;left:640px;top:815px" width="320" height="34"></svg>`);+ add(`<div class="cp mu" style="position:absolute;left:0;right:0;top:852px;text-align:center;font-weight:500">ONE POWER STROKE EVERY 90° OF CRANK ROTATION</div>`);+ add(`<div class="cp" style="position:absolute;left:0;right:0;top:874px;text-align:center;font-weight:500;color:${C.faint}">DRAG TO ORBIT · SCROLL TO ZOOM · H HIDES THE OVERLAY</div>`);++ // ------------------------------------------------------------ callouts, the pointer+ const callSvg = add(`<svg data-callouts style="position:absolute;inset:0;overflow:visible" width="1600" height="900"></svg>`);+ const callG = add(`<div data-callouts style="position:absolute;inset:0"></div>`);+ const ring = add(`<div class="ring"></div>`);+ const cur = add(`<div class="cur"><svg width="22" height="22" viewBox="0 0 34 34"><path d="M4 3 L30 13.5 L17.5 17.5 L13.5 30 Z" fill="#111" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/></svg></div>`);+ const centre = (n) => {+ const r = n.getBoundingClientRect();+ return [r.left + r.width / 2, r.top + r.height / 2];+ };+ const foSpot = (i) => [640 + 20 + i * 40, 815 + 17];+ const spots = Object.fromEntries(Object.entries(btn).map(([k, n]) => [k, centre(n)]));+ const knobX = (v) => SL.x + v * SL.w;++ const pointer = (c) => {+ cur.style.display = c.x < 0 ? 'none' : 'block';+ cur.style.transform = `translate(${(c.x - 3).toFixed(2)}px, ${(c.y - 2).toFixed(2)}px) scale(${c.press ? 0.88 : 1})`;+ ring.style.left = `${c.ringX}px`;+ ring.style.top = `${c.ringY}px`;+ ring.style.opacity = String(c.ring * 0.85);+ ring.style.transform = `scale(${(0.35 + 0.9 * (1 - c.ring)).toFixed(3)})`;+ };++ return {+ spots,+ foSpot,+ speedKnob: (v) => [knobX(v), 836],+ playKnob: (v) => [knobX(v), 869],+ btn,+ root: ui,+ update(s) {+ rpmBig.textContent = Math.round(s.rpm);+ rpmFill.style.width = `${((s.rpm / RPM_MAX) * 247).toFixed(1)}px`;+ speedVal.textContent = `${Math.round(s.rpm)} RPM`;+ speedKnob.style.left = `${knobX(s.rpmK).toFixed(1)}px`;+ playVal.textContent = s.playText;+ playKnob.style.left = `${knobX(s.playK).toFixed(1)}px`;+ btn.pause.innerHTML = s.paused ? '▶ PLAY' : '❚❚ PAUSE';++ // slider-crank: the tracked cylinder's crank and piston+ const ph = s.psi;+ const ca = ((ph % 360) + 360) % 360;+ scAng.innerHTML = `<b style="color:${C.ink}">${Math.round(ca)}°</b> AFTER TDC`;+ {+ const cx = 40;+ const cy = 62;+ const r = 18;+ const Lr = 60;+ const a = (ca * Math.PI) / 180;+ const px = cx + r * Math.cos(a);+ const py = cy - r * Math.sin(a);+ const sx = cx + r * Math.cos(a) + Math.sqrt(Lr * Lr - (r * Math.sin(a)) ** 2);+ sc.innerHTML = `<circle cx="${cx}" cy="${cy}" r="${r + 18}" fill="none" stroke="${C.line}"/><circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${C.faint}" stroke-dasharray="2 2"/>+ <line x1="${cx}" y1="${cy}" x2="${px.toFixed(1)}" y2="${py.toFixed(1)}" stroke="${C.red}" stroke-width="2"/>+ <line x1="${px.toFixed(1)}" y1="${py.toFixed(1)}" x2="${sx.toFixed(1)}" y2="${cy}" stroke="${C.ink}" stroke-width="1.2"/>+ <rect x="${(sx - 10).toFixed(1)}" y="${cy - 30}" width="20" height="60" fill="#fff" stroke="${C.ink}" stroke-width="1.6"/>+ <line x1="${cx + Lr - r + 10}" x2="226" y1="${cy - 32}" y2="${cy - 32}" stroke="${C.ink}" stroke-width="1"/><line x1="${cx + Lr - r + 10}" x2="226" y1="${cy + 32}" y2="${cy + 32}" stroke="${C.ink}" stroke-width="1"/>+ <circle cx="${cx}" cy="${cy}" r="3.5" fill="#fff" stroke="${C.ink}" stroke-width="1.6"/><circle cx="${px.toFixed(1)}" cy="${py.toFixed(1)}" r="3.5" fill="#fff" stroke="${C.ink}" stroke-width="1.6"/><circle cx="${sx.toFixed(1)}" cy="${cy}" r="3" fill="#fff" stroke="${C.ink}" stroke-width="1.4"/>+ <text x="${(cx + px) / 2 + 4}" y="${(cy + py) / 2 - 3}" font-size="9" fill="${C.ink}">r</text><text x="${(px + sx) / 2}" y="${cy - 6}" font-size="9" fill="${C.ink}">L</text>+ <line x1="${cx + Lr - r}" x2="${cx + Lr + r}" y1="112" y2="112" stroke="${C.ink}" stroke-width=".8"/><line x1="${cx + Lr - r}" x2="${cx + Lr - r}" y1="106" y2="116" stroke="${C.ink}" stroke-width=".8"/><line x1="${cx + Lr + r}" x2="${cx + Lr + r}" y1="106" y2="116" stroke="${C.ink}" stroke-width=".8"/>+ <text x="${cx + Lr + r + 6}" y="126" font-size="9.4" letter-spacing="1.4" fill="${C.mute}">STROKE 89 MM</text>`;+ }+ // cross-plane: four throws at their real angles, the tracked pin lit+ {+ const cx = 113;+ const cy = 70;+ let h = `<circle cx="${cx}" cy="${cy}" r="40" fill="none" stroke="${C.line}"/>`;+ for (const sgn of [-1, 1]) {+ const a = (-90 + sgn * 45) * (Math.PI / 180);+ const bx = cx + Math.cos(a) * 70;+ const by = cy + Math.sin(a) * 70;+ h += `<line x1="${cx}" y1="${cy}" x2="${bx}" y2="${by}" stroke="${C.faint}" stroke-width=".8" stroke-dasharray="3 3"/><g transform="translate(${bx} ${by}) rotate(${sgn * 45})"><rect x="-10" y="-12" width="20" height="16" fill="#fff" stroke="${C.ink}" stroke-width="1.4"/><line x1="-6" x2="6" y1="-1" y2="-1" stroke="${C.ink}" stroke-width="1.2"/></g>`;+ }+ const names = ['1·2', '3·4', '5·6', '7·8'];+ PIN_PHASE.forEach((ph0, p) => {+ const a = ((s.theta + ph0) * Math.PI) / 180;+ const x = cx + Math.sin(a) * 40;+ const y = cy - Math.cos(a) * 40;+ const lit = p === s.pin;+ h += `<line x1="${cx}" y1="${cy}" x2="${x.toFixed(1)}" y2="${y.toFixed(1)}" stroke="${C.ink}" stroke-width=".9"/><circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="9.5" fill="${lit ? C.red : '#fff'}" stroke="${lit ? C.red : C.ink}" stroke-width="1.3"/><text x="${x.toFixed(1)}" y="${(y + 3).toFixed(1)}" font-size="7.6" text-anchor="middle" fill="${lit ? '#fff' : C.ink}" font-weight="600">${names[p]}</text>`;+ });+ h += `<circle cx="${cx}" cy="${cy}" r="6" fill="#fff" stroke="${C.ink}" stroke-width="1.3"/><line x1="${cx - 4}" x2="${cx + 4}" y1="${cy - 4}" y2="${cy + 4}" stroke="${C.ink}"/><line x1="${cx - 4}" x2="${cx + 4}" y1="${cy + 4}" y2="${cy - 4}" stroke="${C.ink}"/><text x="${cx - 12}" y="${cy - 26}" font-size="8" fill="${C.ink}">90°</text>`;+ cp.innerHTML = h;+ }++ // cylinder state+ const stroke = STROKES[Math.floor(((ph % 720) + 720) % 720 / 180)];+ cylName.innerHTML = `CYLINDER <b>${s.cyl}</b>`;+ cylCrank.innerHTML = `<b style="color:${C.ink}">${Math.round(((ph % 720) + 720) % 720)}°</b> CRANK`;+ strokeBig.textContent = stroke.charAt(0) + stroke.slice(1).toLowerCase();+ strokeBig.style.color = stroke === 'POWER' ? C.red : C.ink;+ strokeList.innerHTML = ['INTAKE', 'COMPRESSION', 'POWER', 'EXHAUST']+ .map((n) => `<div class="cp" style="height:16.5px;display:flex;align-items:center;gap:10px;font-weight:500;color:${n === stroke ? C.ink : C.mute}"><i style="display:block;width:31px;height:2px;background:${n === stroke ? C.red : C.line}"></i>${n}</div>`)+ .join('');+ const bar = pressure(ph);+ barBig.textContent = bar < 10 ? bar.toFixed(1) : Math.round(bar);+ barUnit.style.left = `${1334 + barBig.getBoundingClientRect().width + 8}px`;+ barFill.style.width = `${Math.min(224, (bar / 60) * 224).toFixed(1)}px`;++ // valve timing over 720°, the cursor at the tracked cylinder's phase+ {+ const W = 232;+ const X = (d) => 16 + (d / 720) * (W - 24);+ const Y = (v) => 108 - v * 92;+ let h = `<text x="2" y="14" font-size="6.5" fill="${C.mute}">%</text>`;+ for (const [v, l] of [[0, '0'], [0.5, '50'], [1, '100']]) h += `<text x="12" y="${Y(v) + 2}" font-size="6.5" text-anchor="end" fill="${C.mute}">${l}</text>`;+ ['POWER', 'EXHAUST', 'INTAKE', 'COMPR'].forEach((n, i) => (h += `<text x="${X(i * 180 + 90)}" y="10" font-size="6.2" letter-spacing=".8" text-anchor="middle" fill="${C.mute}">${n}</text>`));+ const seg = Math.floor(((ph % 720) + 720) % 720 / 180);+ h += `<rect x="${X(seg * 180)}" y="${Y(1)}" width="${X(180) - X(0)}" height="92" fill="${seg === 0 ? 'rgba(214,24,43,.1)' : 'rgba(20,22,26,.05)'}"/>`;+ for (const d of [180, 360, 540]) h += `<line x1="${X(d)}" x2="${X(d)}" y1="${Y(1)}" y2="${Y(0)}" stroke="${C.line}" stroke-width=".8"/>`;+ h += `<line x1="${X(0)}" x2="${X(720)}" y1="${Y(0)}" y2="${Y(0)}" stroke="${C.ink}" stroke-width=".8"/>`;+ const curve = (fn, col, w) => {+ let p = '';+ for (let d = 0; d <= 720; d += 4) p += `${d ? 'L' : 'M'}${X(d).toFixed(1)} ${Y(fn(d)).toFixed(1)}`;+ return `<path d="${p}" fill="none" stroke="${col}" stroke-width="${w}"/>`;+ };+ h += curve((d) => 1 - pistonFrac(d), C.grey, 1.3) + curve(liftEx, C.orange, 1.5) + curve(liftIn, C.blue, 1.5);+ const cxp = X(((ph % 720) + 720) % 720);+ h += `<line x1="${cxp}" x2="${cxp}" y1="${Y(1) - 4}" y2="${Y(0)}" stroke="${C.red}" stroke-width="1.4"/>`;+ for (const d of [0, 180, 360, 540, 720]) h += `<text x="${X(d)}" y="${Y(0) + 10}" font-size="6.5" text-anchor="middle" fill="${C.mute}">${d}</text>`;+ h += `<text x="${X(720)}" y="${Y(0) + 20}" font-size="6.2" letter-spacing="1" text-anchor="end" fill="${C.mute}">CRANK ANGLE AFTER IGNITION</text>`;+ vt.innerHTML = h;+ vtLeg.innerHTML = `<span style="color:${C.grey}">—</span> PISTON <b>${Math.round((1 - pistonFrac(ph)) * 100)}</b> % <span style="color:${C.blue}">—</span> IN <b>${liftIn(ph).toFixed(2)}</b> <span style="color:${C.orange}">—</span> EX <b>${liftEx(ph).toFixed(2)}</b>`;+ }+ // indicator diagram: pressure against volume over the cycle, the dot at the tracked cylinder's phase+ {+ idCyl.innerHTML = `CYL <b style="color:${C.ink}">${s.cyl}</b>`;+ const W = 232;+ const X = (v) => 18 + ((v - 1) / (E.cr - 1)) * (W - 30);+ const Y = (p) => 98 - Math.min(1, p / 55) * 82;+ let loop = '';+ for (let d = 0; d <= 720; d += 3) loop += `${d ? 'L' : 'M'}${X(volume(d)).toFixed(1)} ${Y(pressure(d)).toFixed(1)}`;+ let h = `<text x="2" y="12" font-size="6.5" fill="${C.mute}">bar</text><text x="12" y="${Y(50) + 2}" font-size="6.5" text-anchor="end" fill="${C.mute}">50</text><text x="12" y="${Y(25) + 2}" font-size="6.5" text-anchor="end" fill="${C.mute}">25</text><text x="12" y="${Y(0) + 2}" font-size="6.5" text-anchor="end" fill="${C.mute}">0</text>`;+ h += `<line x1="${X(1)}" x2="${X(E.cr)}" y1="${Y(0)}" y2="${Y(0)}" stroke="${C.ink}" stroke-width=".8"/><line x1="${X(1)}" x2="${X(1)}" y1="${Y(55)}" y2="${Y(0)}" stroke="${C.ink}" stroke-width=".8"/>`;+ h += `<path d="${loop} Z" fill="rgba(214,24,43,.12)" stroke="${C.ink}" stroke-width="1.3"/>`;+ h += `<text x="${X(1.3)}" y="${Y(52)}" font-size="6.2" letter-spacing=".8" fill="${C.mute}">IGNITION</text><text x="${X(4.2)}" y="${Y(14)}" font-size="6.2" letter-spacing=".8" fill="${C.mute}">EXPANSION</text><text x="${X(6)}" y="${Y(3.5)}" font-size="6.2" letter-spacing=".8" fill="${C.mute}">COMPRESSION</text>`;+ h += `<circle cx="${X(volume(ph)).toFixed(1)}" cy="${Y(pressure(ph)).toFixed(1)}" r="3" fill="${C.red}"/>`;+ h += `<text x="${X(1)}" y="${Y(0) + 10}" font-size="6.2" fill="${C.mute}">TDC</text><text x="${X(E.cr)}" y="${Y(0) + 10}" font-size="6.2" text-anchor="end" fill="${C.mute}">BDC</text><text x="${X(E.cr)}" y="${Y(0) + 19}" font-size="6" letter-spacing=".8" text-anchor="end" fill="${C.mute}">VOLUME ×VC · 1 → 10.2</text>`;+ id.innerHTML = h;+ }++ // firing order: the tracked cylinder ringed, the one firing now lit+ {+ let h = '';+ ORDER.forEach((c, i) => {+ const x = 20 + i * 40;+ if (i) h += `<line x1="${x - 28}" x2="${x - 12}" y1="17" y2="17" stroke="${C.faint}"/>`;+ const firing = c === s.firing;+ const tracked = c === s.cyl;+ h += `<circle cx="${x}" cy="17" r="11.5" fill="${firing ? 'rgba(214,24,43,.55)' : '#fff'}" stroke="${tracked ? C.red : C.faint}" stroke-width="${tracked ? 1.8 : 1}"/>`;+ if (tracked) h += `<circle cx="${x}" cy="17" r="15" fill="none" stroke="${C.red}" stroke-width=".8" opacity=".55"/>`;+ h += `<text x="${x}" y="20.5" font-size="10" text-anchor="middle" font-weight="600" fill="${firing ? '#fff' : C.ink}">${c}</text>`;+ });+ fo.innerHTML = h;+ }++ // toggles+ for (const k of CAMS) {+ const on = s.cam === k;+ btn[k].style.background = on ? C.ink : '#fff';+ btn[k].style.color = on ? '#fff' : C.ink;+ btn[k].style.borderColor = on ? C.ink : C.line;+ }+ for (const k of CUTS) {+ const on = s.cut === k;+ btn[k].style.background = on ? C.ink : '#fff';+ btn[k].style.color = on ? '#fff' : C.ink;+ btn[k].style.borderColor = on ? C.ink : C.line;+ }+ for (const k of OVERLAYS) {+ const on = !!s.overlays[k];+ btn[k].style.background = on ? C.red : '#fff';+ btn[k].style.color = on ? '#fff' : C.ink;+ btn[k].style.borderColor = on ? C.red : C.line;+ }++ // callouts: a label, a thin leader to its point in the engine+ let lh = '';+ let ch = '';+ for (const c of s.callouts) {+ if (c.o < 0.02 || !c.at) continue;+ const [ax, ay] = c.at;+ const [lx, ly] = c.label;+ lh += `<polyline points="${ax.toFixed(1)},${ay.toFixed(1)} ${lx.toFixed(1)},${(ly + 16).toFixed(1)} ${(lx + c.w).toFixed(1)},${(ly + 16).toFixed(1)}" fill="none" stroke="${C.mute}" stroke-width=".8" opacity="${c.o.toFixed(2)}"/>`;+ ch += `<div class="call" style="left:${lx.toFixed(1)}px;top:${(ly - 10).toFixed(1)}px;opacity:${c.o.toFixed(2)}"><b>${c.name}</b><span>${c.sub}</span></div>`;+ }+ callSvg.innerHTML = lh;+ callG.innerHTML = ch;+ pointer(s.cursor);+ },+ pointer,+ };+}diff --git a/sims/v8-shared/engine.js b/sims/v8-shared/engine.jsnew file mode 100644index 0000000..d596eb9--- /dev/null+++ b/sims/v8-shared/engine.js@@ -0,0 +1,624 @@+// The V8 itself, built from code in millimetres in the look of a clean study model: a gloss-black open block of+// V-shaped bulkheads, glass cylinder liners with the charge inside them, polished pistons, black rods, a cross-plane+// crank with counterweights, two valves per cylinder with coil springs under a black rocker cage and a camshaft per+// bank, white spark plugs, black exhaust bends, helical timing gears and a pulley at the front, the flywheel at the+// back, and red overlay arrows. update(th, ops) poses everything for crank angle th (degrees).+import * as THREE from 'three';+import {BANK, chargeOf, CYL, E, FIRE, liftEx, liftIn, piston, pinXY, psi, PIN_PHASE, pressure, VALVE} from './kin.js';++const V3 = THREE.Vector3;+const D2R = Math.PI / 180;+const DECK = E.deck;+const smoother = (x) => {+ const u = Math.min(1, Math.max(0, x));+ return u * u * u * (u * (u * 6 - 15) + 10);+};++// ------------------------------------------------------------ geometry helpers+function gearGeo(teeth, rOut, rRoot, width, helix = 0, holeR = 0) {+ const sh = new THREE.Shape();+ for (let i = 0; i < teeth; i++) {+ const a0 = (i / teeth) * Math.PI * 2;+ const da = (Math.PI * 2) / teeth;+ const pts = [+ [rRoot, a0],+ [rRoot, a0 + da * 0.2],+ [rOut, a0 + da * 0.33],+ [rOut, a0 + da * 0.62],+ [rRoot, a0 + da * 0.75],+ ];+ pts.forEach(([r, a], k) => (i === 0 && k === 0 ? sh.moveTo(r * Math.cos(a), r * Math.sin(a)) : sh.lineTo(r * Math.cos(a), r * Math.sin(a))));+ }+ sh.closePath();+ if (holeR) {+ const h = new THREE.Path();+ h.absarc(0, 0, holeR, 0, Math.PI * 2, true);+ sh.holes.push(h);+ }+ const g = new THREE.ExtrudeGeometry(sh, {depth: width, bevelEnabled: true, bevelThickness: 1.2, bevelSize: 1.0, bevelSegments: 1, curveSegments: 4});+ g.translate(0, 0, -width / 2);+ if (helix) {+ const p = g.attributes.position;+ for (let i = 0; i < p.count; i++) {+ const a = (p.getZ(i) / width) * helix;+ const x = p.getX(i);+ const y = p.getY(i);+ p.setXY(i, x * Math.cos(a) - y * Math.sin(a), x * Math.sin(a) + y * Math.cos(a));+ }+ }+ g.computeVertexNormals();+ return g;+}+// a gear's blank: a plain disc at the pitch radius, the same width, bevel and bore, no teeth+function discGeo(r, width, holeR = 0, seg = 48) {+ const sh = new THREE.Shape();+ sh.absarc(0, 0, r, 0, Math.PI * 2, false);+ if (holeR) {+ const h = new THREE.Path();+ h.absarc(0, 0, holeR, 0, Math.PI * 2, true);+ sh.holes.push(h);+ }+ const g = new THREE.ExtrudeGeometry(sh, {depth: width, bevelEnabled: true, bevelThickness: 1.2, bevelSize: 1.0, bevelSegments: 1, curveSegments: seg});+ g.translate(0, 0, -width / 2);+ return g;+}+function helixGeo(r, wire, turns, len, seg = 220) {+ const pts = [];+ for (let i = 0; i <= seg; i++) {+ const u = i / seg;+ const a = u * turns * Math.PI * 2;+ pts.push(new V3(Math.cos(a) * r, u * len, Math.sin(a) * r));+ }+ return new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), seg, wire, 8, false);+}+// a crank web: the main boss, the pin boss and a counterweight sector opposite the pin, in the XY plane+function webGeo(thick, cs = 28) {+ const sh = new THREE.Shape();+ const R = 76;+ // the counterweight: a fat sector below the axis, flanks running up to the pin boss+ sh.moveTo(-R * Math.sin(1.05), -R * Math.cos(1.05));+ sh.absarc(0, 0, R, -Math.PI / 2 - 1.05, -Math.PI / 2 + 1.05, false);+ sh.lineTo(30, 10);+ sh.absarc(0, E.r, 31, 0, Math.PI, false);+ sh.lineTo(-30, 10);+ sh.closePath();+ const g = new THREE.ExtrudeGeometry(sh, {depth: thick, bevelEnabled: true, bevelThickness: 2, bevelSize: 2, bevelSegments: 2, curveSegments: cs});+ g.translate(0, 0, -thick / 2);+ return g;+}+// a V bulkhead: the crank bore, two arms up to each bank's deck+function bulkheadGeo(thick, cs = 24) {+ const sh = new THREE.Shape();+ const W = 54; // arm half width across the bank+ const pts = [];+ const arm = (bank, w, d) => {+ const B = BANK[bank];+ return [d * B.b[0] + w * B.p[0], d * B.b[1] + w * B.p[1]];+ };+ pts.push([-95, -70], [95, -70]);+ pts.push(arm('L', W + 20, 40), arm('L', W, DECK - 10), arm('L', -W, DECK - 10), [0, 120]);+ pts.push(arm('R', -W, DECK - 10), arm('R', W, DECK - 10), arm('R', W + 20, 40));+ // the R arm's outward side is the -x side; walk the outline in order+ const ordered = [[-95, -70], [95, -70], arm('L', W + 18, 40), arm('L', W, DECK - 12), arm('L', -W, DECK - 12), [0, 118], arm('R', -W, DECK - 12), arm('R', W, DECK - 12), arm('R', W + 18, 40)];+ void pts;+ ordered.forEach(([x, y], i) => (i ? sh.lineTo(x, y) : sh.moveTo(x, y)));+ sh.closePath();+ const hole = new THREE.Path();+ hole.absarc(0, 0, 44, 0, Math.PI * 2, true);+ sh.holes.push(hole);+ const g = new THREE.ExtrudeGeometry(sh, {depth: thick, bevelEnabled: true, bevelThickness: 2, bevelSize: 2, bevelSegments: 2, curveSegments: cs});+ g.translate(0, 0, -thick / 2);+ return g;+}++/** opts.plain: the same engine a notch simpler (the A/B film's version B): gears as toothless discs, each valve's+ * two coil springs as one plain sleeve, no piston rings, no pulley bolts. Absent, the engine is built as before.+ * opts.lo: the teardown A/B's version B, clearly cheaper: everything plain drops, plus flat-shaded Lambert for every+ * material, opaque liners, a sixth of the segments on every round part, polygon discs for gears, boxes for lobes.+ * opts.caps: a colour; with a section on, the cut gets a flat face of it wherever it passes through a solid. */+export function buildEngine(opts = {}) {+ const lo = !!opts.lo;+ const plain = !!opts.plain || lo;+ // segment counts: the film's, or a sixth of them in the low build+ const N = (n, min = 6) => (lo ? Math.max(min, Math.round(n / 6)) : n);+ const gear = (teeth, rOut, rRoot, width, helix = 0, holeR = 0) =>+ plain ? discGeo((rOut + rRoot) / 2, width, holeR, lo ? Math.max(8, Math.round((rOut + rRoot) / 24)) : 48) : gearGeo(teeth, rOut, rRoot, width, helix, holeR);+ const root = new THREE.Group();+ const M = {+ black: new THREE.MeshPhysicalMaterial({color: '#141518', roughness: 0.3, metalness: 0.2, clearcoat: 0.7, clearcoatRoughness: 0.18}),+ blackMatte: new THREE.MeshPhysicalMaterial({color: '#1b1c1f', roughness: 0.55, metalness: 0.15, clearcoat: 0.25}),+ steel: new THREE.MeshStandardMaterial({color: '#cfd2d6', roughness: 0.22, metalness: 1}),+ alu: new THREE.MeshStandardMaterial({color: '#d9dbdf', roughness: 0.3, metalness: 0.85}),+ bronze: new THREE.MeshStandardMaterial({color: '#b98a55', roughness: 0.3, metalness: 0.9}),+ ceramic: new THREE.MeshPhysicalMaterial({color: '#f3f0ea', roughness: 0.35, metalness: 0, clearcoat: 0.6}),+ glass: new THREE.MeshPhysicalMaterial({color: '#ffffff', roughness: 0.05, metalness: 0, transparent: true, opacity: 0.16, depthWrite: false, side: THREE.DoubleSide, envMapIntensity: 1.6}),+ red: new THREE.MeshBasicMaterial({color: '#e3172c', transparent: true, opacity: 0.9, depthWrite: false}),+ };+ if (lo) {+ // flat Lambert: no gloss, nothing to reflect; the blacks lift to graphite so the facets still read without the+ // studio's highlights, and the liners turn opaque+ const flat = (color) => new THREE.MeshLambertMaterial({color, flatShading: true});+ Object.assign(M, {black: flat('#66696f'), blackMatte: flat('#717479'), steel: flat('#b9bdc3'), alu: flat('#cfd2d6'), bronze: flat('#a37b4d'), ceramic: flat('#ece8e0'), glass: flat('#86898f')});+ }+ const add = (parent, geo, mat, cast = true) => {+ const m = new THREE.Mesh(geo, mat);+ m.castShadow = cast;+ m.receiveShadow = true;+ parent.add(m);+ return m;+ };++ // ------------------------------------------------------------ block: bulkheads, rails, pan+ const block = new THREE.Group();+ root.add(block);+ const bh = bulkheadGeo(16, N(24));+ for (const z of [236, 112, 0, -112, -236]) add(block, bh, M.black).position.z = z;+ for (const bank of ['L', 'R']) {+ const B = BANK[bank];+ // deck rails along the bank, both sides of the bores+ for (const w of [-60, 60]) {+ const r = add(block, new THREE.BoxGeometry(14, 16, 488), M.black);+ const [x, y] = [(DECK - 18) * B.b[0] + w * B.p[0], (DECK - 18) * B.b[1] + w * B.p[1]];+ r.position.set(x, y, 0);+ r.rotation.z = Math.atan2(B.b[1], B.b[0]) - Math.PI / 2;+ }+ }+ const pan = add(block, new THREE.BoxGeometry(200, 40, 470), M.blackMatte);+ pan.position.set(0, -92, 0);+ const rail = add(block, new THREE.BoxGeometry(220, 12, 500), M.black);+ rail.position.set(0, -68, 0);++ // ------------------------------------------------------------ cylinders: liner, flange, head pieces, valvetrain, plug, exhaust+ const cyl = CYL.map((cy) => {+ const B = BANK[cy.bank];+ const g = new THREE.Group();+ g.position.z = cy.z;+ g.rotation.z = Math.atan2(B.b[1], B.b[0]) - Math.PI / 2;+ root.add(g);+ // local x points across the bank; the outer side is +x on the left bank, -x on the right+ const out = cy.bank === 'L' ? 1 : -1;+ const liner = add(g, new THREE.CylinderGeometry(E.bore / 2 + 3, E.bore / 2 + 3, 118, N(48), 1, true), M.glass, false);+ liner.position.y = DECK - 59;+ liner.renderOrder = 3;+ for (const y of [DECK - 118, DECK]) {+ const ring = add(g, new THREE.TorusGeometry(E.bore / 2 + 4, 3.2, N(10, 4), N(48)), M.black);+ ring.rotation.x = Math.PI / 2;+ ring.position.y = y;+ }+ // the head: a black flange over the bore with a raised valve block; one group with its valves, plug and exhaust+ const head = new THREE.Group();+ g.add(head);+ const flange = add(head, new THREE.TorusGeometry(64, 10, N(16, 4), N(56)), M.black);+ flange.rotation.x = Math.PI / 2;+ flange.position.y = DECK + 6;+ const cap = add(head, new THREE.CylinderGeometry(60, 64, 12, N(56)), M.black);+ cap.position.y = DECK + 14;+ const vblock = add(head, new THREE.BoxGeometry(70, 14, 46), M.black);+ vblock.position.y = DECK + 27;+ // the charge: a column of gas between the crown and the head+ const charge = new THREE.Mesh(new THREE.CylinderGeometry(E.bore / 2 - 1, E.bore / 2 - 1, 1, N(40)), new THREE.MeshBasicMaterial({color: '#4a90e2', transparent: true, opacity: 0.35, depthWrite: false}));+ charge.renderOrder = 2;+ g.add(charge);+ // valves: intake on the valley side, exhaust outboard+ const valves = [+ {x: -out * 21, kind: 'in'},+ {x: out * 21, kind: 'ex'},+ ].map((v) => {+ const vg = new THREE.Group();+ head.add(vg);+ vg.position.x = v.x;+ const stem = add(vg, new THREE.CylinderGeometry(3.5, 3.5, 120, N(12)), M.steel);+ stem.position.y = DECK + 54;+ const disc = add(vg, new THREE.CylinderGeometry(18, 7, 6, N(28)), M.steel);+ disc.position.y = DECK - 3;+ const spring = new THREE.Group();+ head.add(spring);+ spring.position.set(v.x, DECK + 34, 0);+ if (plain) {+ // a plain sleeve where the coils were, squeezed with the lift the same way+ const sleeve = new THREE.CylinderGeometry(15.5, 15.5, 48, N(24));+ sleeve.translate(0, 24, 0);+ add(spring, sleeve, M.steel);+ } else {+ add(spring, helixGeo(15.5, 2.6, 8, 48), M.steel);+ add(spring, helixGeo(10.5, 1.8, 10, 48), M.bronze);+ }+ const ret = add(vg, new THREE.CylinderGeometry(18, 18, 4, N(24)), M.black);+ ret.position.y = DECK + 84;+ return {...v, vg, spring};+ });+ // the rocker cage: an open black frame over the springs, the camshaft running through it+ const cage = new THREE.Group();+ g.add(cage);+ for (const zz of [-30, 30]) {+ for (const xx of [-44, 44]) {+ const post = add(cage, new THREE.BoxGeometry(6, 100, 6), M.black);+ post.position.set(xx, DECK + 86, zz);+ }+ const bar = add(cage, new THREE.BoxGeometry(94, 6, 6), M.black);+ bar.position.set(0, DECK + 136, zz);+ }+ // the rocker arms: one bar per valve from the cam over the stem+ for (const xx of [-21, 21]) {+ const arm = add(cage, new THREE.BoxGeometry(10, 7, 66), M.black);+ arm.position.set(xx, DECK + 124, 0);+ }+ // spark plug: out of the head between the valves, leaning outboard+ const plug = new THREE.Group();+ head.add(plug);+ plug.position.set(out * 46, DECK + 18, 18);+ plug.rotation.z = -out * 0.62;+ add(plug, new THREE.CylinderGeometry(6.5, 6.5, 40, N(16)), M.ceramic).position.y = 30;+ add(plug, new THREE.CylinderGeometry(8.5, 8.5, 10, 6), M.steel).position.y = 6;+ add(plug, new THREE.CylinderGeometry(2.2, 2.2, 10, N(8, 4)), M.steel).position.y = 55;+ // exhaust: a black bend out of the outboard port, down along the block+ const pts = [new V3(out * 50, DECK + 12, -20), new V3(out * 92, DECK + 6, -24), new V3(out * 122, DECK - 30, -24), new V3(out * 126, DECK - 90, -24)];+ add(head, new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), N(32), 15, N(18), false), M.black);+ return {cy, g, out, charge, valves, liner, head, cage};+ });++ // camshafts: one per bank through the cages, lobes over every valve+ const cams = ['L', 'R'].map((bank) => {+ const B = BANK[bank];+ const g = new THREE.Group();+ const [x, y] = [(DECK + 112) * B.b[0], (DECK + 112) * B.b[1]];+ g.position.set(x, y, 0);+ root.add(g);+ add(g, new THREE.CylinderGeometry(9, 9, 520, N(20)), M.black).rotation.x = Math.PI / 2;+ const lobes = [];+ for (const c of cyl.filter((c) => c.cy.bank === bank)) {+ for (const v of c.valves) {+ const lg = new THREE.Group();+ // two lobes per cylinder on the shaft, phased so each peaks when its valve is fully open+ lg.position.set(0, 0, c.cy.z + (v.kind === 'in' ? -18 : 18));+ const peak = FIRE[c.cy.c] + (v.kind === 'in' ? (VALVE.in[0] + VALVE.in[1]) / 2 : (VALVE.ex[0] + VALVE.ex[1]) / 2);+ lg.rotation.z = (peak / 2) * D2R;+ g.add(lg);+ const sh = new THREE.Shape();+ sh.absellipse(0, 4, 15, 19, 0, Math.PI * 2, false, 0);+ // the low build turns each lobe into a box of the same footprint+ const lobeGeo = lo ? new THREE.BoxGeometry(30, 38, 14).translate(0, 4, 7) : new THREE.ExtrudeGeometry(sh, {depth: 14, bevelEnabled: true, bevelSize: 1, bevelThickness: 1, bevelSegments: 1, curveSegments: 24});+ const lobe = add(lg, lobeGeo, M.black);+ lobe.position.z = -7;+ lobes.push({lg, c, v});+ }+ }+ return {bank, g, lobes};+ });++ // ------------------------------------------------------------ crankshaft+ const crank = new THREE.Group();+ root.add(crank);+ const webG = webGeo(18, N(28));+ const webs = [];+ E.pinZ.forEach((z, p) => {+ for (const dz of [-34, 34]) {+ const w = add(crank, webG, M.black);+ w.position.z = z + dz;+ webs.push({w, p});+ }+ });+ const journals = [236, 112, 0, -112, -236].map((z) => {+ const j = add(crank, new THREE.CylinderGeometry(30, 30, 42, N(32)), M.steel);+ j.rotation.x = Math.PI / 2;+ j.position.z = z;+ return j;+ });+ const pins = E.pinZ.map((z) => {+ const m = add(root, new THREE.CylinderGeometry(25, 25, 52, N(28)), M.steel);+ m.rotation.x = Math.PI / 2;+ m.position.z = z;+ return m;+ });++ // ------------------------------------------------------------ pistons and rods+ const pistonGeo = new THREE.CylinderGeometry(E.bore / 2 - 1.5, E.bore / 2 - 1.5, 62, N(48));+ const ringGeo = new THREE.TorusGeometry(E.bore / 2 - 1.2, 1.6, 8, 48);+ const pist = CYL.map((cy, i) => {+ const g = new THREE.Group();+ cyl[i].g.add(g);+ const body = add(g, pistonGeo, M.alu);+ body.position.y = E.comp - 31;+ for (let k = 0; k < (plain ? 0 : 3); k++) {+ const r = add(g, ringGeo, M.blackMatte);+ r.rotation.x = Math.PI / 2;+ r.position.y = E.comp - 8 - k * 7;+ }+ const pinM = add(g, new THREE.CylinderGeometry(11, 11, E.bore - 10, N(16)), M.steel);+ pinM.rotation.z = Math.PI / 2;+ pinM.rotation.y = Math.PI / 2;+ const rod = new THREE.Group();+ root.add(rod);+ const beam = add(rod, new THREE.BoxGeometry(18, 1, 12), M.black);+ const big = add(rod, new THREE.CylinderGeometry(33, 33, 20, N(32)), M.black);+ big.rotation.x = Math.PI / 2;+ const small = add(rod, new THREE.CylinderGeometry(17, 17, 20, N(24)), M.black);+ small.rotation.x = Math.PI / 2;+ // the red arrow riding beside the liner, pointing the way the piston moves+ const arrow = new THREE.Group();+ cyl[i].g.add(arrow);+ const shaft = new THREE.Mesh(new THREE.CylinderGeometry(4, 4, 46, 12), M.red);+ shaft.position.y = -10;+ const tip = new THREE.Mesh(new THREE.ConeGeometry(11, 26, 18), M.red);+ tip.position.y = 23;+ arrow.add(shaft, tip);+ arrow.position.set(cyl[i].out * 78, 0, 0);+ arrow.renderOrder = 5;+ return {g, rod, beam, big, small, arrow};+ });++ // ------------------------------------------------------------ front: timing gears and the pulley; rear: the flywheel+ const front = 268;+ const crankGear = add(root, gear(24, 37, 33, 22, 0.35, 10), M.black);+ crankGear.position.z = front;+ const camGears = [];+ // a big helical idler per bank, meshing the crank gear below and the cam gear above+ const idlers = ['L', 'R'].map((bank) => {+ const B = BANK[bank];+ const gg = add(root, gear(72, 111, 106, 24, 0.35, 16), M.black);+ gg.position.set(150 * B.b[0], 150 * B.b[1], front - 2);+ return {gg, bank};+ });+ const pulley = new THREE.Group();+ pulley.position.z = front + 44;+ root.add(pulley);+ add(pulley, new THREE.CylinderGeometry(84, 84, 34, N(64)), M.black).rotation.x = Math.PI / 2;+ const groove = add(pulley, new THREE.TorusGeometry(84, 4, N(8, 4), N(64)), M.blackMatte);+ groove.position.z = 0;+ for (let k = 0; k < (plain ? 0 : 6); k++) {+ const b = add(pulley, new THREE.CylinderGeometry(6, 6, 6, 12), M.steel);+ const a = (k / 6) * Math.PI * 2;+ b.rotation.x = Math.PI / 2;+ b.position.set(Math.cos(a) * 52, Math.sin(a) * 52, 18);+ }+ const hub = add(pulley, gear(18, 26, 23, 50, 0, 8), M.steel);+ hub.position.z = 30;+ const flywheel = new THREE.Group();+ flywheel.position.z = -290;+ root.add(flywheel);+ add(flywheel, new THREE.CylinderGeometry(150, 150, 22, N(72)), M.black).rotation.x = Math.PI / 2;+ add(flywheel, gear(120, 166, 158, 20, 0, 140), M.black);+ // red arcs around the pulley, turning with the crank+ const arcs = new THREE.Group();+ arcs.position.z = front + 66;+ root.add(arcs);+ for (const a0 of [0, Math.PI]) {+ const arc = new THREE.Mesh(new THREE.TorusGeometry(108, 5, 8, 48, Math.PI * 0.62), M.red);+ arc.rotation.z = a0;+ const tip = new THREE.Mesh(new THREE.ConeGeometry(13, 30, 16), M.red);+ const ta = a0 + Math.PI * 0.62;+ tip.position.set(Math.cos(ta) * 108, Math.sin(ta) * 108, 0);+ tip.rotation.z = ta;+ arcs.add(arc, tip);+ }+ arcs.renderOrder = 5;++ const CHARGE_COL = [new THREE.Color('#3f8de0'), new THREE.Color('#5d6670'), new THREE.Color('#ff6a1f'), new THREE.Color('#8b8f95')];+ const tmp = new V3();+ // cutaway: 'glass' (clear liners), 'solid' (opaque liners), 'section' (everything on the far side of the plane cut+ // away: ahead of z by default, or past any plane given by its normal); refract: the glass catches the studio or goes+ // nearly clear+ const CLIP = new THREE.Plane(new V3(0, 0, -1), 0);+ const Z_CUT = new V3(0, 0, -1);++ // the isolate fade: a see-through twin of every material, worn by the parts solo puts away while they go+ const GHOST = new Map(+ Object.values(M).map((m) => {+ const g = m.clone();+ g.transparent = true;+ g.depthWrite = false;+ return [m, g];+ }),+ );+ root.traverse((m) => m.isMesh && (m.userData.mat0 = m.material));+ const ghosted = new Set();++ // section caps (opts.caps): every solid part gets two stencil twins that count its faces beyond the cut, and a+ // plane lying on the cut paints the cap colour wherever that count says the cut runs through metal+ let cap = null;+ const helpers = [];+ if (opts.caps) {+ const inc = THREE.IncrementWrapStencilOp;+ const dec = THREE.DecrementWrapStencilOp;+ const count = (side, op) =>+ new THREE.MeshBasicMaterial({side, colorWrite: false, depthWrite: false, depthTest: false, stencilWrite: true, stencilFunc: THREE.AlwaysStencilFunc, stencilFail: op, stencilZFail: op, stencilZPass: op, clippingPlanes: [CLIP]});+ helpers.push(count(THREE.BackSide, inc), count(THREE.FrontSide, dec));+ const solid = new Set([M.black, M.blackMatte, M.steel, M.alu, M.bronze, M.ceramic]);+ const parts = [];+ root.traverse((m) => m.isMesh && solid.has(m.material) && parts.push(m));+ for (const m of parts) {+ for (const mat of helpers) {+ const h = new THREE.Mesh(m.geometry, mat);+ h.renderOrder = 1;+ m.add(h);+ }+ }+ const rep = THREE.ReplaceStencilOp;+ cap = new THREE.Mesh(+ new THREE.PlaneGeometry(2.4, 2.4),+ new THREE.MeshStandardMaterial({color: opts.caps, roughness: 0.55, metalness: 0, side: THREE.DoubleSide, stencilWrite: true, stencilRef: 0, stencilFunc: THREE.NotEqualStencilFunc, stencilFail: rep, stencilZFail: rep, stencilZPass: rep}),+ );+ cap.renderOrder = 1.1;+ cap.onAfterRender = (r) => r.clearStencil();+ for (const mat of [...helpers, cap.material]) mat.visible = false;+ }+ // the cap lies on the cut, centred on the engine, facing the side that was cut away+ const C0 = new V3(0, 0.1, 0);+ const placeCap = () => {+ if (!cap) return;+ cap.position.copy(C0).addScaledVector(CLIP.normal, -CLIP.distanceToPoint(C0));+ cap.quaternion.setFromUnitVectors(new V3(0, 0, 1), tmp.copy(CLIP.normal).negate());+ };++ const clipMats = () => [...Object.values(M), ...GHOST.values(), ...cyl.map((c) => c.charge.material)];+ let cutNow = 'glass';+ const setCut = (mode, zWorld = 0, normal = Z_CUT) => {+ CLIP.normal.copy(normal);+ CLIP.constant = zWorld;+ placeCap();+ if (mode === cutNow) return;+ cutNow = mode;+ for (const m of clipMats()) {+ m.clippingPlanes = mode === 'section' ? [CLIP] : null;+ m.needsUpdate = true;+ }+ if (cap) for (const mat of [...helpers, cap.material]) mat.visible = mode === 'section';+ if (lo) {+ // the low build has no caps: cut parts show their insides, so both faces draw while the section is on+ for (const m of [...Object.values(M), ...GHOST.values()]) m.side = mode === 'section' ? THREE.DoubleSide : THREE.FrontSide;+ return;+ }+ const solid = mode === 'solid';+ M.glass.color.set(solid ? '#2b2d31' : '#ffffff');+ M.glass.opacity = solid ? 0.94 : glassOpacity;+ M.glass.depthWrite = solid;+ };+ let glassOpacity = 0.16;+ const setRefract = (on) => {+ glassOpacity = on ? 0.16 : 0.05;+ M.glass.envMapIntensity = on ? 1.6 : 0.3;+ if (cutNow !== 'solid') M.glass.opacity = glassOpacity;+ };+ /** ops: charge (0..1 visibility), arrows (0..1), solo (cylinder index or -1), glass (liner opacity), fire (0..1: with+ * the charge off, the burn alone still lights the bore for the first 60° of every power stroke), fade (0..1, with+ * solo: how far the rest has gone; 1, the default, hides it as before, below 1 it stays see-through), explode+ * (0..1: the engine apart along its axes) */+ const update = (th, ops = {}) => {+ for (const m of ghosted) m.material = m.userData.mat0;+ ghosted.clear();+ const solo = ops.solo ?? -1;+ const all = solo < 0;+ const aRest = all ? 1 : 1 - Math.min(1, Math.max(0, ops.fade ?? 1));+ // explode: each layer leaves on its own stretch of the move, the outermost first, so nothing passes through+ // anything on the way out or back in: the rocker cage, the camshaft, the head with its valves, the pistons with+ // their rods out along each bank; the sump, then the crank with its gear, pulley and flywheel down. The engine+ // rises with the sump so the dropped parts stay clear of the floor.+ const ex = ops.explode ?? 0;+ const lay = (a) => smoother((ex - a) / 0.45);+ const eSump = lay(0);+ const eCrank = lay(0.12);+ const DG = 390 * lay(0.25);+ const DC = 300 * lay(0.33);+ const DH = 200 * lay(0.42);+ const DP = 110 * lay(0.55);+ const DK = 110 * eCrank;+ const DS = 190 * eSump;+ root.position.y = 0.17 * eSump;+ pan.position.y = -92 - DS;+ rail.position.y = -68 - DS;++ const cAng = -th * D2R; // the crank turns clockwise seen from the front+ crank.rotation.z = 0;+ crank.position.y = -DK;+ for (const {w, p} of webs) w.rotation.z = -(th + PIN_PHASE[p]) * D2R;+ E.pinZ.forEach((z, p) => {+ const [x, y] = pinXY(p, th);+ pins[p].position.set(x, y - DK, z);+ });+ const chargeOn = ops.charge ?? 1;+ const arrowsOn = ops.arrows ?? 1;+ const fireOn = ops.fire ?? 0;+ CYL.forEach((cy, i) => {+ const B = BANK[cy.bank];+ const {s, P, pin} = piston(i, th);+ const pp = pist[i];+ pp.g.position.y = s + DP;+ // the rod: crank pin to piston pin+ const a = new V3(P[0], P[1], cy.z);+ const b = new V3(pin[0], pin[1], cy.z);+ tmp.subVectors(b, a);+ const len = tmp.length();+ pp.rod.position.copy(a).add(b).multiplyScalar(0.5);+ pp.rod.position.x += DP * B.b[0];+ pp.rod.position.y += DP * B.b[1];+ pp.rod.rotation.set(0, 0, Math.atan2(tmp.y, tmp.x) - Math.PI / 2);+ pp.beam.scale.y = len - 30;+ pp.big.position.y = -len / 2;+ pp.small.position.y = len / 2;+ // the charge column and its colour by stroke+ const ps = psi(cy.c, th);+ const crown = s + E.comp;+ const col = cyl[i];+ col.head.position.y = DH;+ col.cage.position.y = DG;+ col.charge.position.y = (crown + DECK) / 2;+ col.charge.scale.y = Math.max(1, DECK - crown);+ const key = chargeOf(ps);+ col.charge.material.color.copy(CHARGE_COL[key]);+ const glow = key === 2 ? Math.min(1, pressure(ps) / 40) : 0;+ col.charge.material.opacity = chargeOn * (key === 2 ? 0.35 + 0.45 * glow : key === 0 ? 0.32 : 0.22);+ col.charge.visible = chargeOn > 0.01;+ if (fireOn > 0 && chargeOn <= 0.01 && key === 2) {+ col.charge.material.opacity = fireOn * (0.35 + 0.45 * glow);+ col.charge.visible = true;+ }+ if (!all && i !== solo) col.charge.material.opacity *= aRest;+ if (ex > 0) col.charge.visible = false;+ // valves open by their lift, springs squeeze with them+ for (const v of col.valves) {+ const L = (v.kind === 'in' ? liftIn(ps) : liftEx(ps)) * VALVE.lift;+ v.vg.position.y = -L;+ v.spring.scale.y = (48 - L) / 48;+ }+ // the arrow: along the bore, the way the piston is heading, strongest mid-stroke+ const {s: s2} = piston(i, th + 2);+ const vel = s2 - s;+ pp.arrow.position.y = DECK - 70;+ pp.arrow.rotation.z = vel > 0 ? 0 : Math.PI;+ pp.arrow.scale.setScalar(arrowsOn * Math.min(1, Math.abs(vel) / 1.2));+ pp.arrow.visible = arrowsOn * Math.abs(vel) > 0.05;+ });+ // cams at half speed, gears in ratio, pulley and flywheel with the crank+ for (const c of cams) {+ const B = BANK[c.bank];+ c.g.position.set((DECK + 112 + DC) * B.b[0], (DECK + 112 + DC) * B.b[1], 0);+ c.g.rotation.z = cAng / 2;+ }+ crankGear.rotation.z = cAng;+ crankGear.position.y = -DK;+ camGears.forEach((g) => (g.rotation.z = cAng / 2));+ idlers.forEach(({gg}) => (gg.rotation.z = -cAng * (24 / 72)));+ pulley.rotation.z = cAng;+ pulley.position.set(0, -DK, front + 44 + 90 * eCrank);+ flywheel.rotation.z = cAng;+ flywheel.position.set(0, -DK, -290 - 90 * eCrank);+ arcs.rotation.z = cAng * 0.25;+ arcs.position.set(0, -DK, front + 66 + 90 * eCrank);++ // solo: one cylinder with its crank and cam, everything else away+ block.visible = all;+ for (const g of [crankGear, pulley, flywheel, arcs, ...idlers.map((x) => x.gg)]) g.visible = all;+ cyl.forEach((c, i) => {+ const on = all || i === solo;+ c.g.visible = on;+ pist[i].rod.visible = on;+ });+ for (const c of cams) c.g.visible = all || CYL[solo].bank === c.bank;+ const soloPin = all ? -1 : CYL[solo].pin;+ for (const {w, p} of webs) w.visible = all || p === soloPin;+ pins.forEach((m, p) => (m.visible = all || p === soloPin));+ for (const j of journals) j.visible = all;+ arcs.visible = all && (ops.arrows ?? 1) > 0.01;+ // while solo fades the rest (fade below 1), it stays in place in the see-through twins+ if (!all && aRest > 0.001) {+ const rest = [block, crankGear, pulley, flywheel, ...idlers.map((x) => x.gg), ...journals];+ cyl.forEach((c, i) => i !== solo && rest.push(c.g, pist[i].rod));+ for (const c of cams) if (CYL[solo].bank !== c.bank) rest.push(c.g);+ for (const {w, p} of webs) if (p !== soloPin) rest.push(w);+ pins.forEach((m, p) => p !== soloPin && rest.push(m));+ for (const [m, g] of GHOST) g.opacity = (m.transparent ? m.opacity : 1) * aRest;+ for (const o of rest) {+ o.visible = true;+ o.traverse((m) => {+ if (m.isMesh && GHOST.has(m.userData.mat0)) {+ m.material = GHOST.get(m.userData.mat0);+ ghosted.add(m);+ }+ });+ }+ }+ };+ // the engine is modelled in mm; one world unit is a metre (the cap lives in world units, outside the root)+ root.scale.setScalar(0.001);+ return {root, update, M, cyl, pist, cams, crank, pulley, flywheel, crankGear, camGears, setCut, setRefract, CLIP, cap};+}diff --git a/sims/v8-shared/film.js b/sims/v8-shared/film.jsnew file mode 100644index 0000000..59c6bad--- /dev/null+++ b/sims/v8-shared/film.js@@ -0,0 +1,239 @@+// V8 · Four-Stroke, the explorer film: the engine (engine.js) on the pale studio (stage.js) under the overlay+// (console.js). The crank runs at engine speed × playback (1/20: 700 rpm turns 210° a second on screen). An operator+// isolates cylinder 1, switches the tracking to cylinder 6 from the firing order, looks down the valley, opens the+// throttle to 2,400 rpm, then walks the side, front and hero views. A pure function of t.+import {runSim} from '../kit/runtime.js';+import {CAMS, createConsole, RPM_MAX} from './console.js';+import {bankXY, CYL, E, ORDER, psi} from './kin.js';+import {createV8Stage} from './stage.js';++// the film opens on the whole engine, a slow orbit and a gentle push in for 3.5 s, then a beat every 2.5-3 s+export const SCRIPT = [+ {t: 0, cam: 'open'},+ {t: 3.5, cam: 'cyl'},+ {t: 6.9, track: 6},+ {t: 9.7, cam: 'valley'},+ {t: 12.1, rpm: [700, 2400, 1.4]},+ {t: 14.7, cam: 'side'},+ {t: 17.3, cam: 'front'},+ {t: 19.9, cam: 'hero'},+ {t: 22.5, track: 1},+];+export const DURATION = 26;+export const DEFAULTS = {duration: DURATION, fps: 60, theme: 'light', hud: {enabled: false, title: 'v8d', subtitle: ''}, director: {enabled: false}, watermark: ''};+const D2R = Math.PI / 180;+const mm = (v) => v * 0.001;+const smoother = (x) => {+ const u = Math.min(1, Math.max(0, x));+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));+const PLAY = 20; // playback divider: 1/20 speed++// ------------------------------------------------------------ engine speed and the crank angle+const RPM_EV = SCRIPT.find((e) => e.rpm);+export const rpmAt = (t) => RPM_EV.rpm[0] + (RPM_EV.rpm[1] - RPM_EV.rpm[0]) * ss(RPM_EV.t, RPM_EV.t + RPM_EV.rpm[2], t);+const DT = 1 / 240;+const TH = [];+{+ let th = 12;+ for (let t = 0; t <= DURATION + 1; t += DT) {+ TH.push(th);+ th += ((rpmAt(t + DT / 2) / 60) * 360 * DT) / PLAY;+ }+}+export const thetaAt = (t) => {+ const u = Math.max(0, Math.min(TH.length - 2, t / DT));+ const i = Math.floor(u);+ return TH[i] + (TH[i + 1] - TH[i]) * (u - i);+};+export const trackAt = (t) => SCRIPT.filter((e) => e.track && e.t <= t).pop()?.track ?? 1;++// ------------------------------------------------------------ views, each a function of u (seconds since it came on)+const cylCentre = (c) => {+ const cy = CYL[c - 1];+ const [x, y] = bankXY(cy.bank, 0, 170);+ return [mm(x), mm(y), mm(cy.z)];+};+export const VIEW_FN = {+ // the opening: a quarter turn round the whole engine, easing in and out, pushing in a little+ open: (u) => {+ const k = smoother(u / 4.1);+ return {tx: 0, ty: 0.11, tz: -0.02, az: 4 + 54 * k, el: 18 + 9 * k, d: 2.2 - 0.25 * k, sx: -50, sy: 10};+ },+ hero: (u) => ({tx: 0, ty: 0.11, tz: -0.02, az: 46 + 5 * u, el: 26, d: 1.95, sx: -50, sy: 10}),+ cyl: (u, c) => {+ const [x, y, z] = cylCentre(c);+ const L = CYL[c - 1].bank === 'L';+ return {tx: x * 0.72, ty: y * 0.72 + 0.02, tz: z, az: (L ? 16 : -16) + (L ? 1 : -1) * 5.5 * u, el: 9 + 1.2 * u, d: 1.18, sx: -40, sy: 14};+ },+ valley: (u) => ({tx: 0, ty: 0.14, tz: 0, az: 14 + 7 * u, el: 60, d: 2.35, sx: -40, sy: -28}),+ side: (u) => ({tx: 0, ty: 0.1, tz: 0, az: 100 - 5 * u, el: 12 + 1.5 * u, d: 1.95, sx: -40, sy: 10}),+ front: (u) => ({tx: 0, ty: 0.12, tz: 0, az: -6 + 5 * u, el: 10 + 2 * u, d: 1.8, sx: -40, sy: 10}),+};+const VIEWS = SCRIPT.filter((e) => e.cam).map((e) => [e.t, e.cam]);+// a camera move: every parameter eased, the azimuth the short way round, backing off through a wide swing+export const camAt = (t, list = VIEWS, track = trackAt) => {+ let i = 0;+ while (i < list.length - 1 && list[i + 1][0] <= t) i++;+ const view = (k, tt) => VIEW_FN[list[k][1]](tt - list[k][0], track(tt));+ const cur = view(i, t);+ // a tracking switch while isolated glides the camera to the new cylinder+ const tr = SCRIPT.find((e) => e.track && e.t <= t && t < e.t + 2);+ let o = cur;+ if (tr && list[i][1] === 'cyl') {+ const prev = VIEW_FN.cyl(t - list[i][0], trackAt(tr.t - 0.01));+ const k = ss(tr.t, tr.t + 1.8, t);+ o = blend(prev, cur, k, false);+ }+ if (i === 0) return o;+ const k = ss(list[i][0], list[i][0] + 1.6, t);+ if (k >= 1) return o;+ return blend(view(i - 1, t), o, k);+};+function blend(a, b, k, backOff = true) {+ const o = {};+ for (const key in b) o[key] = key === 'az' ? a.az + ((((b.az - a.az + 540) % 360) - 180) * k) : a[key] + (b[key] - a[key]) * k;+ const swing = Math.min(1, Math.abs(((b.az - a.az + 540) % 360) - 180) / 90);+ if (backOff) o.d += Math.max(0, Math.max(a.d, b.d) + 0.6 * swing - o.d) * Math.sin(Math.PI * k);+ return o;+}+export const camName = (t) => {+ const v = VIEWS.filter(([t0]) => t0 <= t).pop()[1];+ return v === 'open' ? 'hero' : v;+};+export const firingNow = (th) => {+ let best = 1;+ let bp = 1e9;+ for (const c of ORDER) {+ const p = psi(c, th);+ if (p < bp) {+ bp = p;+ best = c;+ }+ }+ return best;+};++// ------------------------------------------------------------ the operator's pointer+const REST = [[820, 470], [700, 430], [900, 520], [760, 380]];+export function makeCursor(ui) {+ const EV = SCRIPT.filter((e) => e.t > 0).map((e) => {+ if (e.rpm) return {t: e.t, spot: ui.speedKnob(e.rpm[0] / RPM_MAX), to: ui.speedKnob(e.rpm[1] / RPM_MAX), drag: e.rpm[2]};+ if (e.track) return {t: e.t, spot: ui.foSpot(ORDER.indexOf(e.track)), drag: 0};+ return {t: e.t, spot: ui.spots[e.cam], drag: 0};+ });+ const WP = [[0, 980, 640]];+ EV.forEach((e, i) => {+ WP.push([e.t - 0.16, ...e.spot]);+ if (e.drag) {+ for (let k = 0; k <= 12; k++) {+ const tt = e.t + (k / 12) * e.drag;+ WP.push([tt + 0.02, ...ui.speedKnob(rpmAt(tt) / RPM_MAX)]);+ }+ WP.push([e.t + e.drag + 0.3, ...e.to]);+ } else WP.push([e.t + 0.24, ...e.spot]);+ WP.push([e.t + e.drag + 1.6, ...REST[i % REST.length]]);+ });+ WP.sort((a, b) => a[0] - b[0]);+ return (t) => {+ let i = 0;+ while (i < WP.length - 2 && t > WP[i + 1][0]) i++;+ const [t0, x0, y0] = WP[i];+ const [t1, x1, y1] = WP[i + 1];+ const lin = t1 - t0 < 0.2;+ const k = lin ? Math.min(1, Math.max(0, (t - t0) / (t1 - t0))) : ss(t0, t1, t);+ const len = Math.hypot(x1 - x0, y1 - y0);+ const bow = lin ? 0 : Math.sin(Math.PI * k) * Math.min(24, len * 0.07);+ let press = false;+ let ring = 0;+ let rx = 0;+ let ry = 0;+ for (const e of EV) {+ if (t >= e.t - 0.07 && t < e.t + Math.max(0.09, e.drag + 0.1)) press = true;+ if (t >= e.t && t < e.t + 0.55) {+ ring = 1 - (t - e.t) / 0.55;+ [rx, ry] = e.spot;+ }+ }+ return {x: x0 + (x1 - x0) * k + (len ? (-(y1 - y0) / len) * bow : 0), y: y0 + (y1 - y0) * k + (len ? ((x1 - x0) / len) * bow : 0), press, ring, ringX: rx, ringY: ry};+ };+}++// ------------------------------------------------------------ the overlay's data for a frame+export function makeConsoleFrame(ui, st) {+ const P = (x, y, z) => st.project(mm(x), mm(y), mm(z));+ const Lb = [Math.SQRT1_2, Math.SQRT1_2];+ // live: the page's own state (overlays, cutaway, playback, pause, solo); absent in the film+ return (t, {th, cam, cyl, rpm, cursor, since, live}) => {+ const solo = live ? live.solo : cam === 'cyl';+ const cy = CYL[cyl - 1];+ const vis = ss(1.1, 1.8, since) * (live && !live.overlays.callouts ? 0 : 1);+ const callouts = [];+ if (!solo && (cam === 'hero' || cam === 'side')) {+ callouts.push(+ {name: 'Camshaft', sub: 'HALF CRANK SPEED', at: P((E.deck + 112) * Lb[0], (E.deck + 112) * Lb[1], -60), label: [962, 196], w: 120, o: vis},+ {name: 'Flywheel', sub: 'STORES THE PULSES', at: P(120, -40, -290), label: [1168, 572], w: 124, o: vis},+ {name: 'Helical timing gears', sub: '24 : 72', at: P(150 * Lb[0], 150 * Lb[1], 268), label: [306, 704], w: 128, o: vis},+ );+ }+ if (solo) {+ const [x, y] = bankXY(cy.bank, 0, E.deck + 112);+ callouts.push({name: 'Camshaft', sub: 'HALF CRANK SPEED', at: P(x, y, cy.z), label: [720, 226], w: 120, o: vis});+ }+ // leaders from the panels into the engine: the rev counter to the crank, the indicator panel to the tracked bore+ const [bx, by] = bankXY(cy.bank, 0, E.deck - 40);+ const lead = live && !live.overlays.callouts ? 0 : 1;+ callouts.push({name: '', sub: '', at: solo ? P(0, 0, cy.z) : P(0, 0, 312), label: [282, 152], w: 0, o: lead});+ callouts.push({name: '', sub: '', at: P(bx, by, cy.z), label: [1318 - 0.01, 501], w: 0, o: 0.9 * lead * (live && !live.overlays.charts ? 0 : 1)});+ const ps = psi(cyl, th);+ ui.update({+ rpm,+ rpmK: rpm / RPM_MAX,+ playText: live ? live.playText : '1 / 20 SPEED',+ playK: live ? live.playK : 0.33,+ paused: live ? live.paused : false,+ theta: th,+ psi: ps,+ cyl,+ pin: cy.pin,+ firing: firingNow(th),+ cam,+ cut: live ? live.cut : 'glass',+ overlays: live ? live.overlays : {callouts: 1, charge: 1, arrows: 1, isolate: solo ? 1 : 0, refract: 1, charts: 1},+ callouts,+ cursor,+ });+ };+}++export function makeFilm() {+ return async ({canvas, capture}) => {+ const st = createV8Stage({canvas});+ const resize = () => st.resize(1600, 900, capture ? devicePixelRatio || 1 : Math.min(devicePixelRatio || 1, 2));+ resize();+ const ui = createConsole(document.getElementById('app'));+ const cursorAt = makeCursor(ui);+ const frame = makeConsoleFrame(ui, st);+ window.V8 = st;+ return {+ resize,+ render(t) {+ const th = thetaAt(t);+ const cam = camName(t);+ const cyl = trackAt(t);+ const c = camAt(t);+ const t0 = VIEWS.filter(([a]) => a <= t).pop()[0];+ // isolate once the camera has closed in, and keep it until the next move has pulled back a little+ const vi = VIEWS.findIndex(([a]) => a === t0);+ const soloOn = (cam === 'cyl' && t - t0 > 1.25) || (vi > 0 && VIEWS[vi - 1][1] === 'cyl' && t - t0 < 0.6);+ st.frame(th, {...c, az: c.az * D2R, el: c.el * D2R}, {solo: soloOn ? cyl - 1 : -1});+ frame(t, {th, cam, cyl, rpm: rpmAt(t), cursor: cursorAt(t), since: t - t0});+ return {};+ },+ };+ };+}+void CAMS;++export const run = () => runSim(DEFAULTS, makeFilm());diff --git a/sims/v8-shared/kin.js b/sims/v8-shared/kin.jsnew file mode 100644index 0000000..af918c2--- /dev/null+++ b/sims/v8-shared/kin.js@@ -0,0 +1,86 @@+// V8 kinematics for the four-stroke explorer: a 90° cross-plane crank, firing order 1-8-4-3-6-5-7-2, the piston of+// every cylinder from the exact slider-crank, valve lift over the 720° cycle, and a chamber pressure model good+// enough to draw the indicator diagram. Engine space is millimetres: crank axis on z (front = +z), y up.+export const E = {bore: 101.6, r: 44.5, rod: 145, comp: 30, deck: 226, pinZ: [168, 56, -56, -168], rodOff: 11, cr: 10.2};+export const STROKE = 2 * E.r;+const S = Math.SQRT1_2;+// bank frames in the XY plane: b along the cylinder axis, p outward across the bank+export const BANK = {+ L: {b: [S, S], p: [S, -S], sign: 1},+ R: {b: [-S, S], p: [-S, -S], sign: -1},+};+// cylinders 1..8: odd on the left bank (+x), even on the right; 1 at the front+export const CYL = [1, 2, 3, 4, 5, 6, 7, 8].map((c) => {+ const odd = c % 2 === 1;+ const pin = Math.floor((c - 1) / 2);+ return {c, bank: odd ? 'L' : 'R', pin, z: E.pinZ[pin] + (odd ? E.rodOff : -E.rodOff)};+});+export const FIRE = {1: 0, 8: 90, 4: 180, 3: 270, 6: 360, 5: 450, 7: 540, 2: 630};+export const ORDER = [1, 8, 4, 3, 6, 5, 7, 2];+// cross-plane crank: pin angles clockwise from +y, seen from the front+export const PIN_PHASE = [45, 135, -45, 225];+const mod = (a, m) => ((a % m) + m) % m;++export const bankXY = (bank, w, d) => {+ const B = BANK[bank];+ return [d * B.b[0] + w * B.p[0], d * B.b[1] + w * B.p[1]];+};+export const pinXY = (p, th) => {+ const a = ((th + PIN_PHASE[p]) * Math.PI) / 180;+ return [E.r * Math.sin(a), E.r * Math.cos(a)];+};+/** cylinder index i (0-based): the piston pin's distance along the bank axis, the crank pin, the pin point */+export const piston = (i, th) => {+ const cy = CYL[i];+ const B = BANK[cy.bank];+ const P = pinXY(cy.pin, th);+ const pb = P[0] * B.b[0] + P[1] * B.b[1];+ const pp = P[0] * B.p[0] + P[1] * B.p[1];+ const s = pb + Math.sqrt(E.rod * E.rod - pp * pp);+ return {s, P, pin: [s * B.b[0], s * B.b[1]]};+};+// the pin distance at TDC and BDC (the same for every cylinder)+export const S_TDC = E.r + E.rod;+export const S_BDC = E.rod - E.r;+/** four-stroke phase of cylinder c in degrees after its firing TDC: 0-180 power, 180-360 exhaust, 360-540 intake, 540-720 compression */+export const psi = (c, th) => mod(th - FIRE[c], 720);+export const STROKES = ['POWER', 'EXHAUST', 'INTAKE', 'COMPRESSION'];+export const strokeOf = (ps) => STROKES[Math.floor(mod(ps, 720) / 180)];++// valves: lift 0..1 as a smooth bump between opening and closing (degrees after firing TDC)+export const VALVE = {ex: [140, 380], in: [340, 580], lift: 10.5};+const bump = (ps, [a, b]) => {+ const x = (mod(ps - a, 720)) / (b - a);+ return x >= 0 && x <= 1 ? Math.sin(Math.PI * x) ** 2 : 0;+};+export const liftEx = (ps) => bump(ps, VALVE.ex);+export const liftIn = (ps) => bump(ps, VALVE.in);+/** piston position as a fraction of the stroke from TDC (0 at TDC, 1 at BDC), at phase ps */+export const pistonFrac = (ps) => {+ const a = (ps * Math.PI) / 180;+ const sp = E.r * Math.cos(a) + Math.sqrt(E.rod * E.rod - (E.r * Math.sin(a)) ** 2);+ return (S_TDC - sp) / STROKE;+};+/** cylinder volume in units of the clearance volume (1 at TDC, cr at BDC) */+export const volume = (ps) => 1 + (E.cr - 1) * pistonFrac(ps);+/** chamber pressure in bar: a polytropic compression, a fast burn just after TDC, a polytropic expansion */+export const pressure = (ps) => {+ ps = mod(ps, 720);+ const V = volume(ps);+ if (ps >= 360 && ps < 540) return 0.9;+ if (ps >= 180 && ps < 360) return 1.1 + 0.4 * Math.max(0, 1 - (ps - 180) / 40);+ if (ps >= 540) return Math.max(0.9, 0.95 * Math.pow(E.cr / V, 1.32));+ // power: the burn rises over the first 10 degrees, then the gas expands+ const comp = 0.95 * Math.pow(E.cr / V, 1.32);+ const burn = 54 * Math.pow(1 / V, 1.28);+ const k = Math.min(1, ps / 10);+ return Math.max(1.1, comp + (burn - comp) * (k * k * (3 - 2 * k)));+};+/** the charge colour key: 0 air & fuel, 1 compressed, 2 combustion, 3 exhaust */+export const chargeOf = (ps) => {+ ps = mod(ps, 720);+ if (ps < 60) return 2;+ if (ps < 360) return 3;+ if (ps < 540) return 0;+ return 1;+};diff --git a/sims/v8-shared/live.js b/sims/v8-shared/live.jsnew file mode 100644index 0000000..09ff54b--- /dev/null+++ b/sims/v8-shared/live.js@@ -0,0 +1,374 @@+// The V8 as a page you drive: the film's engine and overlay, run in real time. Camera views, the cutaway (glass,+// section through the tracked cylinder, solid), the overlays (callouts, charge, arrows, isolate, refraction, charts),+// the firing order to pick the tracked cylinder, PAUSE and ±15°, the engine speed and playback sliders, an orbit you+// drag, a zoom on the wheel, H to hide the overlay. Left alone it plays the film's script as an auto tour with the+// operator's cursor, looped; a click, drag, wheel or key hands control to the visitor, 25 s of quiet hands it back.+import {warmComposer} from '../kit/warm.js';+import {CAMS, createConsole, CUTS, OVERLAYS, RPM_MAX} from './console.js';+import {makeConsoleFrame, makeCursor, rpmAt, trackAt, camAt, camName, DURATION, SCRIPT, VIEW_FN} from './film.js';+import {CYL, ORDER} from './kin.js';+import {createV8Stage} from './stage.js';++const W = 1600;+const H = 900;+const IDLE = 25;+const D2R = Math.PI / 180;+const clamp = (x, a, b) => Math.min(b, Math.max(a, x));+const smoother = (x) => {+ const u = clamp(x, 0, 1);+ return u * u * u * (u * (u * 6 - 15) + 10);+};+const ss = (a, b, t) => smoother((t - a) / (b - a));+const wrap = (d) => ((((d + 180) % 360) + 360) % 360) - 180;+// playback steps: the film runs at 1/20+const PLAYS = [1 / 60, 1 / 40, 1 / 20, 1 / 10, 1 / 5, 1 / 2, 1];+const playText = (p) => (p >= 1 ? '1× SPEED' : `1 / ${Math.round(1 / p)} SPEED`);++const CSS = (top) => `+html,body{background:#ecedef;overflow:hidden}+#app{position:absolute!important;inset:auto!important;left:0;top:0;width:${W}px;height:${H}px;transform-origin:0 0}+#gl{touch-action:none;cursor:grab}+#gl.drag{cursor:grabbing}+.tb{pointer-events:auto;cursor:pointer}+.tb:hover{filter:brightness(.95)}+.hit{position:absolute;pointer-events:auto;cursor:pointer}+.hit.ew{cursor:ew-resize}+.tourchip{position:absolute;left:800px;top:62px;transform:translateX(-50%);display:flex;align-items:center;gap:7px;height:21px;padding:0 11px;border:1px solid #e1e3e6;background:rgba(255,255,255,.95);color:#16181b;font:600 8.8px Inter,sans-serif;letter-spacing:1.3px;white-space:nowrap;cursor:pointer;pointer-events:auto}+.tourchip i{display:block;width:6px;height:6px;border-radius:50%;background:#d6182b}+.tourchip.on i{animation:blink 1.2s steps(2) infinite}+@keyframes blink{50%{opacity:.15}}+.turn{position:fixed;left:0;right:0;bottom:18px;text-align:center;font:600 12px/1.4 'JetBrains Mono',monospace;letter-spacing:1px;color:#8b8f95;text-transform:uppercase;display:none}+@media (orientation:portrait) and (max-width:820px){.turn{display:block}}+`;++export function runLive() {+ const top = Number(document.body.dataset.top || 0);+ const style = document.createElement('style');+ style.textContent = CSS(top);+ document.head.appendChild(style);+ const app = document.getElementById('app');+ const canvas = document.createElement('canvas');+ canvas.id = 'gl';+ app.appendChild(canvas);+ const st = createV8Stage({canvas});+ const ui = createConsole(app);+ const tourCursor = makeCursor(ui);+ const frameConsole = makeConsoleFrame(ui, st);++ // ------------------------------------------------------------ quality tiers+ const TIERS = [+ {samples: 8, ao: true, shadow: 4096, pr: 2},+ {samples: 4, ao: false, shadow: 2048, pr: 1.5},+ {samples: 2, ao: false, shadow: 1024, pr: 1},+ ];+ const light = matchMedia('(pointer: coarse)').matches || Math.min(innerWidth, innerHeight) < 700;+ let tier = light ? 2 : 0;+ let scale = 1;+ const fit = () => {+ const h = innerHeight - top;+ scale = Math.min(innerWidth / W, h / H);+ app.style.transform = `translate(${(innerWidth - W * scale) / 2}px, ${top + (h - H * scale) / 2}px) scale(${scale})`;+ st.resize(W, H, clamp((devicePixelRatio || 1) * scale, 0.75, TIERS[tier].pr));+ };+ const applyTier = () => {+ const {pr, ...q} = TIERS[tier];+ st.setQuality(q);+ fit();+ };+ applyTier();+ addEventListener('resize', fit);+ const toStage = (cx, cy) => {+ const r = app.getBoundingClientRect();+ return [(cx - r.left) / scale, (cy - r.top) / scale];+ };++ const tourChip = document.createElement('div');+ tourChip.className = 'tourchip';+ ui.root.appendChild(tourChip);+ const note = document.createElement('div');+ note.className = 'turn';+ note.textContent = 'Turn your phone sideways for the full console';+ document.body.appendChild(note);++ // ------------------------------------------------------------ state+ let T = 0;+ let th = 12;+ let rpm = 700;+ let rpmTarget = 700;+ let playI = 2;+ let paused = false;+ let view = 'hero';+ let viewAt = 0;+ let cyl = 1;+ let cut = 'glass';+ const ov = {callouts: 1, charge: 1, arrows: 1, isolate: 0, refract: 1, charts: 1};+ const off = {az: 0, el: 0, k: 1};+ const cam = {...VIEW_FN.open(0)};+ let ring = {t: -9, x: 0, y: 0};+ let hidden = false;+ const pulse = (x, y) => (ring = {t: T, x, y});+ const pulseBtn = (k) => pulse(...ui.spots[k]);++ // ------------------------------------------------------------ the tour+ const AP = {on: true, t0: 0, loop: 0};+ let lastInput = 0;+ const startTour = () => {+ AP.on = true;+ AP.t0 = T;+ AP.loop = 0;+ paused = false;+ playI = 2;+ cut = 'glass';+ Object.assign(ov, {callouts: 1, charge: 1, arrows: 1, isolate: 0, refract: 1, charts: 1});+ Object.assign(off, {az: 0, el: 0, k: 1});+ };+ const takeOver = () => {+ lastInput = T;+ if (!AP.on) return;+ AP.on = false;+ const cyc = (T - AP.t0) % DURATION;+ view = camName(cyc);+ viewAt = T - (cyc - SCRIPT.filter((e) => e.cam && e.t <= cyc).pop().t);+ if (view === 'hero' && cyc < 3.5) viewAt = T - 6;+ ov.isolate = view === 'cyl' ? 1 : 0;+ };+ tourChip.addEventListener('pointerdown', (e) => {+ e.stopPropagation();+ lastInput = T;+ if (AP.on) takeOver();+ else startTour();+ });+ addEventListener('pointerdown', (e) => {+ if (e.target !== tourChip) takeOver();+ });++ // ------------------------------------------------------------ controls+ const setView = (v) => {+ view = v;+ viewAt = T;+ Object.assign(off, {az: 0, el: 0, k: 1});+ ov.isolate = v === 'cyl' ? 1 : 0;+ };+ for (const k of CAMS)+ ui.btn[k].addEventListener('click', () => {+ takeOver();+ pulseBtn(k);+ setView(k);+ });+ for (const k of CUTS)+ ui.btn[k].addEventListener('click', () => {+ takeOver();+ pulseBtn(k);+ cut = k;+ });+ for (const k of OVERLAYS)+ ui.btn[k].addEventListener('click', () => {+ takeOver();+ pulseBtn(k);+ ov[k] = ov[k] ? 0 : 1;+ });+ ui.btn.pause.addEventListener('click', () => {+ takeOver();+ pulseBtn('pause');+ paused = !paused;+ });+ for (const [k, d] of [['back', -15], ['fwd', 15]])+ ui.btn[k].addEventListener('click', () => {+ takeOver();+ pulseBtn(k);+ paused = true;+ th += d;+ });+ // the firing order: click a cylinder to track it+ ORDER.forEach((c, i) => {+ const [x, y] = ui.foSpot(i);+ const d = document.createElement('div');+ d.className = 'hit';+ Object.assign(d.style, {left: `${x - 14}px`, top: `${y - 14}px`, width: '28px', height: '28px', borderRadius: '50%'});+ d.addEventListener('click', () => {+ takeOver();+ pulse(x, y);+ cyl = c;+ if (view === 'cyl') viewAt = T - 0.01;+ });+ ui.root.appendChild(d);+ });+ // the two sliders: drag along their tracks+ const slider = (knobAt, apply) => {+ const [x0, y] = knobAt(0);+ const [x1] = knobAt(1);+ const d = document.createElement('div');+ d.className = 'hit ew';+ Object.assign(d.style, {left: `${x0 - 8}px`, top: `${y - 11}px`, width: `${x1 - x0 + 16}px`, height: '22px'});+ const move = (e) => {+ const [x] = toStage(e.clientX, e.clientY);+ apply(clamp((x - x0) / (x1 - x0), 0, 1));+ lastInput = T;+ };+ d.addEventListener('pointerdown', (e) => {+ takeOver();+ d.setPointerCapture(e.pointerId);+ const up = () => {+ removeEventListener('pointermove', move);+ removeEventListener('pointerup', up);+ };+ addEventListener('pointermove', move);+ addEventListener('pointerup', up);+ move(e);+ });+ ui.root.appendChild(d);+ };+ slider(ui.speedKnob, (k) => (rpmTarget = clamp(k * RPM_MAX, 300, RPM_MAX)));+ slider(ui.playKnob, (k) => (playI = Math.round(k * (PLAYS.length - 1))));+ addEventListener('keydown', (e) => {+ if (e.altKey || e.ctrlKey || e.metaKey) return;+ const key = e.key.toLowerCase();+ const v = {1: 'hero', 2: 'front', 3: 'side', 4: 'valley', 5: 'cyl'}[key];+ takeOver();+ if (v) setView(v);+ else if (key === ' ') paused = !paused;+ else if (key === 'h') hidden = !hidden;+ else if (key === 'arrowleft') {+ paused = true;+ th -= 15;+ } else if (key === 'arrowright') {+ paused = true;+ th += 15;+ } else if (key === 'arrowup') rpmTarget = clamp(rpmTarget + 300, 300, RPM_MAX);+ else if (key === 'arrowdown') rpmTarget = clamp(rpmTarget - 300, 300, RPM_MAX);+ else return;+ e.preventDefault();+ });+ let drag = null;+ canvas.addEventListener('pointerdown', (e) => {+ drag = {x: e.clientX, y: e.clientY};+ canvas.setPointerCapture(e.pointerId);+ canvas.classList.add('drag');+ });+ canvas.addEventListener('pointermove', (e) => {+ if (!drag) return;+ off.az += ((e.clientX - drag.x) / scale) * 0.3;+ off.el = clamp(off.el + ((e.clientY - drag.y) / scale) * 0.2, -20, 60);+ drag = {x: e.clientX, y: e.clientY};+ lastInput = T;+ });+ const endDrag = () => {+ drag = null;+ canvas.classList.remove('drag');+ };+ canvas.addEventListener('pointerup', endDrag);+ canvas.addEventListener('pointercancel', endDrag);+ canvas.addEventListener(+ 'wheel',+ (e) => {+ e.preventDefault();+ takeOver();+ off.k = clamp(off.k * Math.exp(e.deltaY * 0.0012), 0.45, 2.2);+ },+ {passive: false},+ );++ // ------------------------------------------------------------ the frame+ startTour();+ let last = performance.now();+ const perf = {n: 0, sum: 0, slow: 0, age: 0};+ const frame = (now) => {+ const dt = Math.min(0.1, Math.max(0, (now - last) / 1000));+ last = now;+ T += dt;+ if (tier < TIERS.length - 1) {+ perf.age += dt;+ if (perf.age > 0.6) {+ perf.sum += dt;+ perf.n++;+ if (perf.sum >= 0.5 && perf.n >= 6) {+ perf.slow = perf.sum / perf.n > 0.022 ? perf.slow + 1 : 0;+ perf.sum = 0;+ perf.n = 0;+ if (perf.slow >= (perf.age < 6 ? 1 : 2)) {+ tier++;+ applyTier();+ Object.assign(perf, {age: 0, slow: 0});+ }+ }+ }+ }++ let tgt;+ let cursor;+ let since;+ let solo;+ if (AP.on) {+ const c = T - AP.t0;+ const loop = Math.floor(c / DURATION);+ const cyc = c - loop * DURATION;+ if (loop > AP.loop) AP.loop = loop;+ view = camName(cyc);+ cyl = trackAt(cyc);+ rpmTarget = rpmAt(cyc);+ tgt = camAt(cyc);+ const t0 = SCRIPT.filter((e) => e.cam && e.t <= cyc).pop().t;+ since = cyc - t0;+ // the film's isolation timing: on once the camera is close, off once the next move has begun+ const views = SCRIPT.filter((e) => e.cam);+ const vi = views.findIndex((e) => e.t === t0);+ solo = (view === 'cyl' && since > 1.25) || (vi > 0 && views[vi - 1].cam === 'cyl' && since < 0.6);+ ov.isolate = solo ? 1 : 0;+ cursor = tourCursor(cyc);+ if (AP.loop > 0 && cyc < 0.8) {+ const end = tourCursor(DURATION - 0.01);+ const k = ss(0, 0.8, cyc);+ cursor = {...cursor, x: end.x + (cursor.x - end.x) * k, y: end.y + (cursor.y - end.y) * k};+ }+ } else {+ if (T - lastInput > IDLE) startTour();+ since = T - viewAt;+ tgt = VIEW_FN[view](since, cyl);+ tgt.az += off.az;+ tgt.el = clamp(tgt.el + off.el, -10, 80);+ tgt.d *= off.k;+ solo = !!ov.isolate;+ const rk = Math.max(0, 1 - (T - ring.t) / 0.55);+ cursor = {x: -99, y: -99, press: false, ring: rk, ringX: ring.x, ringY: ring.y};+ }+ rpm += (rpmTarget - rpm) * (1 - Math.exp(-dt / 0.35));+ if (!paused) th += (rpm / 60) * 360 * dt * PLAYS[playI];++ // the camera eases toward its target: the tour's own moves pass through, a loop restart or a click glides+ const k = 1 - Math.exp(-dt / (AP.on ? 0.18 : 0.45));+ cam.az += wrap(tgt.az - cam.az) * k;+ for (const key of ['tx', 'ty', 'tz', 'el', 'd', 'sx', 'sy']) cam[key] += (tgt[key] - cam[key]) * k;+ st.setCut(cut, CYL[cyl - 1].z * 0.001);+ st.eng.setRefract(!!ov.refract);+ st.frame(th, {...cam, az: cam.az * D2R, el: cam.el * D2R}, {solo: solo ? cyl - 1 : -1, charge: ov.charge, arrows: ov.arrows});++ ui.root.style.display = hidden ? 'none' : '';+ for (const n of ui.root.querySelectorAll('[data-g="charts"]')) n.style.visibility = ov.charts ? '' : 'hidden';+ frameConsole(T, {+ th,+ cam: view,+ cyl,+ rpm,+ cursor,+ since,+ live: {solo, overlays: {...ov}, cut, paused, playText: playText(PLAYS[playI]), playK: playI / (PLAYS.length - 1)},+ });+ if (tourChip.classList.contains('on') !== AP.on || !tourChip.firstChild) {+ tourChip.classList.toggle('on', AP.on);+ tourChip.innerHTML = AP.on ? '<i></i>AUTO TOUR · CLICK TO TAKE OVER' : '▶ RESUME TOUR';+ }+ // the site page swaps its poster for the canvas on this+ if (!window.SIM_SHOWN) {+ window.SIM_SHOWN = true;+ dispatchEvent(new Event('simframe'));+ }+ requestAnimationFrame(frame);+ };+ // every shader compiles at once off the main thread before the first frame (kit/warm.js)+ warmComposer(st.renderer, st.composer, st.scene, st.camera).then(() => requestAnimationFrame(frame));+ window.LIVE = {st, cam, startTour, takeOver, get tier() {+ return tier;+ }, get T() {+ return T;+ }};+}diff --git a/sims/v8-shared/score.py b/sims/v8-shared/score.pynew file mode 100644index 0000000..04d108a--- /dev/null+++ b/sims/v8-shared/score.py@@ -0,0 +1,60 @@+"""Score for the V8 four-stroke explorer: a cool bed (Am9 chords, 92 bpm) at one level the whole way, a soft low thump+on every power stroke (one every 90 degrees of crank, so the beat tightens when the operator opens the throttle), a+quiet click on every button press and a rising air under the throttle drag.++ python run_sfx.py sims/v8-shared/score.py++Times and the crank model mirror v8-shared/film.js (SCRIPT, rpmAt, 1/20 playback).+"""++import os++from sfx.score_kit import airy, bed, chords, hz, thud+from sfx.synth import click++TIMELINE = "../v8-film/timeline.json"+OUT = os.path.join(os.environ.get("TEARDOWN_OUT", "teardown-out"), "v8-score.wav")+TARGET_LUFS = -14.0+SEED = 13++CHORDS = chords("Am9:A2 E3 G3 B3 C4/A1", "Fmaj7:F2 C3 E3 A3/F1", "Cmaj7:C3 E3 G3 B3/C2", "G6:G2 D3 E3 B3/G1")+MOTIF = [(0.5, hz("E5")), (1.5, hz("C5")), (2.5, hz("B4"))]+CLICKS = (3.5, 6.9, 9.7, 12.1, 14.7, 17.3, 19.9, 22.5)+RPM = (12.1, 700.0, 2400.0, 1.4)+++def smoother(x):+ u = min(1.0, max(0.0, x))+ return u * u * u * (u * (u * 6 - 15) + 10)+++def rpm_at(t):+ t0, a, b, d = RPM+ return a + (b - a) * smoother((t - t0) / d)+++def firings(dur, dt=1 / 480):+ out, th, t, nxt = [], 12.0, 0.0, 90.0+ while t < dur:+ th += rpm_at(t) / 60 * 360 * dt / 20+ if th >= nxt:+ out.append(t)+ nxt += 90+ t += dt+ return out+++def score(mix, tl):+ dur = tl["duration"]+ left, right, low, drums = bed(dur, 92, CHORDS, MOTIF, motif_voice="epiano", kicks=(0, 2.5), snares=(), hats=8, swing=0.0, keys_vel=0.7, keys_lp=3600)+ mix.put_stereo(0, left, right, 0.12)+ mix.put(0, low, 0.12)+ mix.put(0, drums, 0.04)+ for t in firings(dur - 0.3):+ mix.put(t, thud(62, 0.05, 0.3), 0.045)+ for t in CLICKS:+ mix.put(t, click(2400, 0.025), 0.055)+ mix.put(RPM[0], airy(RPM[3] + 0.6, 400, 1600, 0.6), 0.03)+ # every camera move gets a soft air+ for t in (3.5, 9.7, 14.7, 17.3, 19.9):+ mix.put(t, airy(1.2, 700, 1500, 0.6), 0.018)diff --git a/sims/v8-shared/stage.js b/sims/v8-shared/stage.jsnew file mode 100644index 0000000..fa9f696--- /dev/null+++ b/sims/v8-shared/stage.js@@ -0,0 +1,173 @@+// The V8's stage: a pale grey studio, a soft shadow on an invisible floor, bright soft boxes for the gloss-black parts+// to catch, GTAO kept off the floor. frame(th, cam, ops) poses the engine for crank angle th and draws one frame.+import * as THREE from 'three';+import {EffectComposer} from 'three/addons/postprocessing/EffectComposer.js';+import {GTAOPass} from 'three/addons/postprocessing/GTAOPass.js';+import {OutputPass} from 'three/addons/postprocessing/OutputPass.js';+import {Pass} from 'three/addons/postprocessing/Pass.js';+import {RenderPass} from 'three/addons/postprocessing/RenderPass.js';+import {buildEngine} from './engine.js';++const V3 = THREE.Vector3;+export const BG = {top: '#f3f3f4', mid: '#e9eaec', low: '#e3e4e6'};++// look (every field optional, the film's stage when absent): ao, the GTAO blend (0.75); shadow, 'soft' (VSM, a wide+// blur) or 'hard' (PCF, a crisp edge); studio, 'full' (four soft boxes) or 'plain' (the top box alone, a flatter read+// on the gloss); engine, the options for buildEngine. The A/B film's version B is the one caller that sets them.+// lo: the teardown A/B's version B, cheaper all at once: no environment, no AO, no MSAA, basic hard-edged shadows and+// a brighter sky light so the flat-shaded parts still read. engine.caps asks for a stencil buffer for the section caps.+export function createV8Stage({canvas, look = {}}) {+ const lo = !!look.lo;+ const hard = look.shadow === 'hard';+ const renderer = new THREE.WebGLRenderer({canvas, antialias: false, preserveDrawingBuffer: true, powerPreference: 'high-performance'});+ renderer.toneMapping = THREE.NeutralToneMapping;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = lo ? THREE.BasicShadowMap : hard ? THREE.PCFShadowMap : THREE.VSMShadowMap;+ renderer.localClippingEnabled = true;+ const scene = new THREE.Scene();+ {+ // a screen-space backdrop: pale at the top, a touch darker toward the floor+ const c = document.createElement('canvas');+ c.width = 4;+ c.height = 512;+ const g = c.getContext('2d');+ const gr = g.createLinearGradient(0, 0, 0, 512);+ gr.addColorStop(0, BG.top);+ gr.addColorStop(0.55, BG.mid);+ gr.addColorStop(1, BG.low);+ g.fillStyle = gr;+ g.fillRect(0, 0, 4, 512);+ const tex = new THREE.CanvasTexture(c);+ tex.colorSpace = THREE.SRGBColorSpace;+ scene.background = tex;+ }+ const camera = new THREE.PerspectiveCamera(26, 16 / 9, 0.02, 60);+ const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, {type: THREE.HalfFloatType, samples: lo ? 0 : 8, stencilBuffer: !!look.engine?.caps}));+ composer.addPass(new RenderPass(scene, camera));+ const gtao = new GTAOPass(scene, camera, 4, 4);+ gtao.output = GTAOPass.OUTPUT.Default;+ gtao.blendIntensity = look.ao ?? 0.75;+ gtao.updateGtaoMaterial({radius: 0.05, distanceExponent: 1.4, thickness: 0.6, scale: 1.0, samples: 16, distanceFallOff: 1.0, screenSpaceRadius: false});+ gtao.updatePdMaterial({lumaPhi: 10, depthPhi: 2, normalPhi: 3, radius: 6, rings: 2, samples: 16});+ class Toggle extends Pass {+ constructor(fn) {+ super();+ this.needsSwap = false;+ this.fn = fn;+ }+ render() {+ this.fn();+ }+ }+ // the floor's shadow catcher and the section cap stay out of the AO pass+ const aoSkip = (on) => {+ shade.visible = on;+ if (eng.cap) eng.cap.visible = on;+ };+ composer.addPass(new Toggle(() => aoSkip(false)));+ composer.addPass(gtao);+ composer.addPass(new Toggle(() => aoSkip(true)));+ if (lo) gtao.enabled = false;+ composer.addPass(new OutputPass());++ // a bright studio for the gloss to read: a big top softbox, two side strips, a warm kicker+ if (!lo) {+ const env = new THREE.Scene();+ env.background = new THREE.Color('#d9dadd');+ const box = (w, h, pos, k) => {+ const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({color: new THREE.Color(1, 1, 1).multiplyScalar(k), side: THREE.DoubleSide}));+ m.position.copy(pos);+ m.lookAt(0, 0, 0);+ env.add(m);+ };+ box(12, 12, new V3(0, 14, 2), 2.6);+ if (look.studio !== 'plain') {+ box(3, 14, new V3(-12, 4, 6), 3.4);+ box(3, 14, new V3(12, 4, -4), 2.2);+ box(18, 2, new V3(0, 2, 14), 1.6);+ }+ const g = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({color: '#c9cacd', side: THREE.DoubleSide}));+ g.rotation.x = -Math.PI / 2;+ g.position.y = -2;+ env.add(g);+ const pm = new THREE.PMREMGenerator(renderer);+ scene.environment = pm.fromScene(env, 0.02).texture;+ scene.environmentIntensity = 1.0;+ pm.dispose();+ }+ const sun = new THREE.DirectionalLight('#ffffff', 2.2);+ sun.position.set(-1.2, 3.2, 1.6);+ sun.castShadow = true;+ Object.assign(sun.shadow.camera, {left: -0.8, right: 0.8, top: 0.8, bottom: -0.8, near: 0.5, far: 8});+ sun.shadow.mapSize.set(hard || lo ? 2048 : 4096, hard || lo ? 2048 : 4096);+ sun.shadow.radius = hard ? 1 : 14;+ sun.shadow.blurSamples = 24;+ sun.shadow.bias = -0.0004;+ sun.shadow.normalBias = 0.002;+ scene.add(sun, sun.target);+ scene.add(new THREE.HemisphereLight('#ffffff', '#cfd0d3', lo ? 2.2 : 0.7));++ // the floor: shadow only, on a plane just under the pan+ const FLOOR_Y = -0.14;+ const shade = new THREE.Mesh(+ new THREE.PlaneGeometry(20, 20),+ new THREE.ShadowMaterial({color: '#5d636c', opacity: 0.28, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -8}),+ );+ shade.rotation.x = -Math.PI / 2;+ shade.position.y = FLOOR_Y;+ shade.receiveShadow = true;+ scene.add(shade);++ const eng = buildEngine(look.engine);+ scene.add(eng.root);+ if (eng.cap) scene.add(eng.cap);++ const size = {w: 1600, h: 900};+ const resize = (w, h, pr) => {+ size.w = w;+ size.h = h;+ renderer.setPixelRatio(pr);+ renderer.setSize(w, h, false);+ composer.setPixelRatio(pr);+ composer.setSize(w, h);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ };+ // cam: target (tx, ty, tz), azimuth from +z toward +x, elevation, distance (radians, metres), sx/sy screen shift+ const frame = (th, cam, ops = {}) => {+ eng.update(th, ops);+ const {tx, ty, tz, az, el, d} = cam;+ camera.position.set(tx + d * Math.cos(el) * Math.sin(az), ty + d * Math.sin(el), tz + d * Math.cos(el) * Math.cos(az));+ camera.lookAt(tx, ty, tz);+ camera.setViewOffset(size.w, size.h, -(cam.sx ?? 0), -(cam.sy ?? 0), size.w, size.h);+ camera.updateMatrixWorld();+ composer.render();+ };+ const pv = new V3();+ const project = (x, y, z) => {+ pv.set(x, y, z).project(camera);+ if (pv.z > 1) return null;+ return [(pv.x * 0.5 + 0.5) * size.w, (-pv.y * 0.5 + 0.5) * size.h];+ };+ const setQuality = ({samples, ao, shadow}) => {+ if (samples !== undefined) {+ for (const t of [composer.renderTarget1, composer.renderTarget2]) {+ t.samples = samples;+ t.dispose();+ }+ }+ if (ao !== undefined) gtao.enabled = ao;+ if (shadow !== undefined) {+ sun.shadow.mapSize.set(shadow, shadow);+ sun.shadow.map?.dispose();+ sun.shadow.map = null;+ }+ };+ const setCut = (mode, zWorld, normal) => {+ eng.setCut(mode, zWorld, normal);+ gtao.normalMaterial.clippingPlanes = mode === 'section' ? [eng.CLIP] : null;+ gtao.normalMaterial.needsUpdate = true;+ };+ return {renderer, scene, camera, eng, composer, gtao, sun, resize, frame, project, size, FLOOR_Y, setQuality, setCut};+}diff --git a/wave.mjs b/wave.mjsnew file mode 100644index 0000000..12f7c69--- /dev/null+++ b/wave.mjs@@ -0,0 +1,67 @@+#!/usr/bin/env node+// Sound check: waveform with every timeline beat drawn on top, plus loudness.+//+// node wave.mjs teardown-out/effort.wav --timeline sfx/cues/effort_timeline.json+// node wave.mjs final.mp4 --timeline timeline.json measure what you will actually post+// without --timeline: waveform and loudness only, no beat lines+// → <input>_wave.png next to the input+//+// Every hit in the waveform should sit on (or a hair after) a beat line.+import {execFileSync, spawnSync} from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import {FFMPEG, FFPROBE} from './paths.mjs';++const argv = process.argv.slice(2);+const ti = argv.indexOf('--timeline');+const timelinePath = ti === -1 ? null : path.resolve(argv.splice(ti, 2)[1]);+if (!argv[0] || !fs.existsSync(argv[0])) {+ console.error('usage: node wave.mjs <file.wav|file.mp4> [--timeline timeline.json]');+ process.exit(1);+}+const input = path.resolve(argv[0]);++const TARGET_LUFS = -14;+const MAX_TRUE_PEAK = -1;+const W = 1800;+const H = 280;++const probed = Number(execFileSync(FFPROBE, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', input]).toString());+const tl = timelinePath ? JSON.parse(fs.readFileSync(timelinePath, 'utf8')) : {duration: probed};+tl.duration ??= probed;+const beats = [];+const walk = (v, key) => {+ if (key === 'fps' || key === 'duration') return;+ if (typeof v === 'number') beats.push(v);+ else if (Array.isArray(v)) v.forEach((x) => walk(x));+ else if (v && typeof v === 'object') Object.entries(v).forEach(([k, x]) => walk(x, k));+};+walk(tl);++const marks = [...new Set(beats)]+ .map((t) => `drawbox=x=${Math.round((t / tl.duration) * W)}:y=0:w=2:h=ih:[email protected]:t=fill`)+ .join(',');+const seconds = `drawgrid=w=${W / tl.duration}:h=${H}:[email protected]`;++const png = input.replace(/\.[^.]+$/, '') + '_wave.png';+execFileSync(FFMPEG, [+ '-loglevel', 'error', '-y', '-i', input,+ '-filter_complex',+ `color=c=0x141413:s=${W}x${H}:d=1[bg];` ++ `[0:a]aformat=channel_layouts=mono,showwavespic=s=${W}x${H}:scale=sqrt:colors=0x8A877F[w];` ++ `[bg][w]overlay=format=auto,${seconds}${marks ? ',' + marks : ''}`,+ '-frames:v', '1', png,+]);++const r = spawnSync(FFMPEG, ['-hide_banner', '-nostats', '-i', input, '-af', 'ebur128=peak=true', '-f', 'null', '-'], {+ encoding: 'utf8',+});+const summary = r.stderr.slice(r.stderr.lastIndexOf('Summary'));+const lufs = Number(summary.match(/I:\s+(-?[\d.]+) LUFS/)?.[1]);+const peak = Number(summary.match(/Peak:\s+(-?[\d.]+) dBFS/)?.[1]);++console.log(`waveform: ${png} (${beats.length} beats in coral, grid = 1s)`);+console.log(`loudness: ${lufs} LUFS integrated (target ${TARGET_LUFS} ±1)`);+console.log(`true peak: ${peak} dBFS (keep ≤ ${MAX_TRUE_PEAK})`);+if (Math.abs(lufs - TARGET_LUFS) > 1) console.warn('WARN loudness off target: re-run the cue sheet, check TARGET_LUFS');+if (peak > MAX_TRUE_PEAK) console.warn('WARN true peak too hot: AAC encoding may clip, lower the master ceiling');