/ music / acoustic-base
Sign in
music / acoustic-base
Add a Physics 3D tab: slow-motion 3D replay of the simulation
The engine can record its state during a render (strings, notches, body modal coordinates, forces, energies; every step in a detail window, every 0.5 ms elsewhere) without changing the sound. The FE solver can export mode shapes (plate normal displacement, mid-depth cavity pressure, f-hole plug displacement); the default body's shapes ship in bodies/fe_default_shapes.bin. The new tab (three.js, loaded on demand) replays a recorded note in 3D from 1/10000 speed to real time, with synced force/energy/sound plots, detail re-recording, sound from the playhead, and a mode explorer for body modes and string partials. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 182eaafb20aa parent 14b3daa Browse files
17 changed files+1842−16
README.mdmodified+37−2View file
@@ -26,9 +26,43 @@ The app is also deployed as this repository's site on vault1 (built by `.mochi/w
2626 - *Spectrogram:* simulation and reference.
2727 - *Partials:* level and T60 per partial, simulation vs reference.
2828 - *Body:* bridge admittance (vertical and lateral) and radiation transfer at the played string's notch, plus the mode list.
29+ - *Physics 3D:* the simulation in 3D and in slow motion (see below).
2930 - *SF2:* build the SoundFont in the browser on all cores (about 20–30 s), then download it or play it on the keys.
3031 - **Parameters** (left) are grouped: Engine, Strings, Right hand, Left hand, Body (parametric), Body (FE), Output, SF2. Hover a parameter for an explanation. Parameters persist in the browser; *Save* / *Load* exchange them as JSON, the same format `scripts/build_sf2.ts --params` reads. *Compute FE body* takes about 15 s. The FE body is recomputed automatically when its inputs change.
3132
33+### The Physics 3D tab
34+
35+The tab records the current note with the engine's full state, then replays it. Three.js loads only when the tab is first opened.
36+
37+- **What is drawn.**
38+ - The played string (gold) and the other strings, both polarisations.
39+ - The plucking finger, which sticks, pulls, then lets the string slip off; and the stopping finger.
40+ - The bridge, which rocks and slides with the notches.
41+ - The top and back plates, displaced and coloured by their normal motion.
42+ - The air pressure on a mid-depth slice of the cavity.
43+ - The f-hole air plugs, drawn as arrows.
44+ - The ribs, neck and tailpiece are static.
45+- **Exaggeration.** Motion is scaled automatically so it shows. The string part of the strings' motion uses the string scale. The body, the bridge, and the bridge end of each string use the body scale. The legend gives both factors and the colour range.
46+- **Recording.**
47+ - Every engine step is kept from the start of the pull until 50 ms after the release. Elsewhere a frame is kept every 0.5 ms.
48+ - The view interpolates between frames, and the time readout says which kind of frame you are on.
49+ - *record detail here* re-records with every step kept for the 50 ms from the playhead.
50+ - Forces, energies, and the mic and pickup signals are kept at every step.
51+ - A 1 s note at the default settings is about 17 MB of frames.
52+- **Playback.** Speeds run from 1/10000 to real time. Scrub with the time bar, or click and drag on a plot. Keys: space plays and pauses, ← and → step one frame, Home goes to the start. Playback is silent; *sound from here* plays the note at real speed from the playhead while the view follows.
53+- **Plots.**
54+ - Finger force on the string, and string force on the bridge.
55+ - Energy in the played string, the other strings, the body structure and the air, in dB.
56+ - The mic and pickup signals.
57+ - They can show the whole note, the detail window, or ±50, ±5 or ±0.5 ms around the playhead.
58+- **Mode explorer.**
59+ - *Body modes* lists each FE mode with its frequency, Q, T60, coupling at the played string's notch, share of air energy, and radiation. Click a mode to animate its shape at 0.6 Hz: plates, air, plugs and bridge.
60+ - *String partials* lists the played string's partials, with inharmonicity and T60. Click one to animate its shape.
61+- **Mode shapes.**
62+ - The FE solver can export each mode's normal displacement at the plate nodes, the pressure on the mid-depth air layer, and the plug displacement (`src/fe/shapes.ts`).
63+ - `scripts/fe_body.ts` writes them for the default body to `bodies/fe_default_shapes.bin` (3.3 MB, int8 per mode). For other FE parameters the browser computes them, in about 20 s.
64+ - The parametric body has no spatial shapes, so only the bridge moves.
65+
3266 ## Physics
3367
3468 ### Strings (`src/core/strings.ts`, `src/core/engine.ts`)
@@ -115,7 +149,7 @@ The reference is pitch-shifted, looped samples shaped by envelopes and filters,
115149 | `node scripts/render_reference.ts [file.sf2] [--program 32] note:vel …` | Renders the reference to `refs/` |
116150 | `node scripts/compare.ts note:vel …` | Envelope, centroid, and partial levels and T60s, simulation vs reference |
117151 | `node scripts/build_sf2.ts [--params p.json] [--body body.json] [--out x.sf2] [--workers N]` | Builds the SF2 (parallel), with WAVs in `renders/sf2wav/` |
118-| `node scripts/fe_body.ts [params.json] [out.json]` | Computes the FE body (`bodies/fe_default.json`); scripts cache bodies for other params in `bodies/fe_<hash>.json` |
152+| `node scripts/fe_body.ts [params.json] [out.json]` | Computes the FE body (`bodies/fe_default.json`) and its mode shapes for the 3D view (`bodies/fe_default_shapes.bin`); scripts cache bodies for other params in `bodies/fe_<hash>.json` |
119153 | `node scripts/test_engine.ts`, `node scripts/test_fe.ts` | Verification |
120154
121155 ## Files
@@ -130,8 +164,9 @@ The reference is pitch-shifted, looped samples shaped by envelopes and filters,
130164 | `src/core/sf2.ts` | SF2 layout, sample processing and leveling, SF2 writer (browser and Node) |
131165 | `src/core/dsp.ts` | Decimation, WAV, FFT, analyses |
132166 | `src/core/reference.ts` | Reference rendering (spessasynth_core) |
133-| `src/fe/` | The FE body (see above) |
167+| `src/fe/` | The FE body (see above); `shapes.ts` holds the mode shapes for the 3D view |
134168 | `src/app/` | The browser app (`main.ts`, `worker.ts`, `plots.ts`, `synth.ts`) |
169+| `src/app/viz/` | The Physics 3D tab: `index.ts` (recording, playback, mode explorer), `scene.ts` (three.js scene), `traces.ts` (time plots) |
135170
136171 ## Limitations
137172
bodies/fe_default_shapes.binadded+0−0View file
Binary file not shown.
package-lock.jsonmodified+59−1View file
@@ -7,14 +7,23 @@
77 "name": "acoustic-base",
88 "dependencies": {
99 "spessasynth_core": "^4.0.0",
10- "spessasynth_lib": "^4.4.7"
10+ "spessasynth_lib": "^4.4.7",
11+ "three": "^0.187.0"
1112 },
1213 "devDependencies": {
1314 "@types/node": "^24.0.0",
15+ "@types/three": "^0.187.0",
1416 "typescript": "^6.0.3",
1517 "vite": "^8.2.6"
1618 }
1719 },
20+ "node_modules/@dimforge/rapier3d-compat": {
21+ "version": "0.12.0",
22+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
23+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
24+ "dev": true,
25+ "license": "Apache-2.0"
26+ },
1827 "node_modules/@emnapi/core": {
1928 "version": "2.0.0-beta.2",
2029 "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
@@ -380,6 +389,13 @@
380389 "dev": true,
381390 "license": "MIT"
382391 },
392+ "node_modules/@tweenjs/tween.js": {
393+ "version": "23.1.3",
394+ "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
395+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
396+ "dev": true,
397+ "license": "MIT"
398+ },
383399 "node_modules/@tybys/wasm-util": {
384400 "version": "0.10.5",
385401 "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
@@ -401,6 +417,35 @@
401417 "undici-types": ">=7.24.0 <7.24.7"
402418 }
403419 },
420+ "node_modules/@types/stats.js": {
421+ "version": "0.17.4",
422+ "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
423+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
424+ "dev": true,
425+ "license": "MIT"
426+ },
427+ "node_modules/@types/three": {
428+ "version": "0.187.0",
429+ "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz",
430+ "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==",
431+ "dev": true,
432+ "license": "MIT",
433+ "dependencies": {
434+ "@dimforge/rapier3d-compat": "~0.12.0",
435+ "@tweenjs/tween.js": "~23.1.3",
436+ "@types/stats.js": "*",
437+ "@types/webxr": ">=0.5.17",
438+ "fflate": "~0.8.3",
439+ "meshoptimizer": "~1.1.1"
440+ }
441+ },
442+ "node_modules/@types/webxr": {
443+ "version": "0.5.24",
444+ "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
445+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
446+ "dev": true,
447+ "license": "MIT"
448+ },
404449 "node_modules/detect-libc": {
405450 "version": "2.1.2",
406451 "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -723,6 +768,13 @@
723768 "url": "https://opencollective.com/parcel"
724769 }
725770 },
771+ "node_modules/meshoptimizer": {
772+ "version": "1.1.1",
773+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
774+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==",
775+ "dev": true,
776+ "license": "MIT"
777+ },
726778 "node_modules/nanoid": {
727779 "version": "3.3.20",
728780 "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
@@ -864,6 +916,12 @@
864916 "node": ">=18"
865917 }
866918 },
919+ "node_modules/three": {
920+ "version": "0.187.0",
921+ "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz",
922+ "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==",
923+ "license": "MIT"
924+ },
867925 "node_modules/tinyglobby": {
868926 "version": "0.2.17",
869927 "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
package.jsonmodified+3−1View file
@@ -15,10 +15,12 @@
1515 },
1616 "dependencies": {
1717 "spessasynth_core": "^4.0.0",
18- "spessasynth_lib": "^4.4.7"
18+ "spessasynth_lib": "^4.4.7",
19+ "three": "^0.187.0"
1920 },
2021 "devDependencies": {
2122 "@types/node": "^24.0.0",
23+ "@types/three": "^0.187.0",
2224 "typescript": "^6.0.3",
2325 "vite": "^8.2.6"
2426 }
scripts/fe_body.tsmodified+8−2View file
@@ -1,10 +1,12 @@
1-// Compute the finite-element body from params and save it as JSON.
1+// Compute the finite-element body from params and save it as JSON, and its mode shapes for the
2+// 3D view next to it (<out>_shapes.bin).
23 // node scripts/fe_body.ts [params.json] [out.json] (default out: bodies/fe_default.json)
34 import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
45 import { dirname } from "node:path";
56 import { defaultParams, mergeParams } from "../src/core/params.ts";
67 import { bridgeAdmittance, STRING_NAMES } from "../src/core/types.ts";
78 import { computeFEBody } from "../src/fe/index.ts";
9+import { encodeShapes, type FEShapes } from "../src/fe/shapes.ts";
810
911 const args = process.argv.slice(2);
1012 let params = defaultParams();
@@ -16,16 +18,20 @@ if (args.length >= 1) {
1618
1719 let lastMsg = "";
1820 const t0 = performance.now();
21+let shapes: FEShapes | null = null;
1922 const body = computeFEBody(params, (msg, frac) => {
2023 if (msg !== lastMsg) {
2124 process.stdout.write(`\r[${(frac * 100).toFixed(0).padStart(3)}%] ${msg}`.padEnd(100));
2225 lastMsg = msg;
2326 }
24-});
27+}, { shapes: (s) => { shapes = s; } });
2528 process.stdout.write("\n");
2629 const elapsed = (performance.now() - t0) / 1000;
2730 mkdirSync(dirname(outPath), { recursive: true });
2831 writeFileSync(outPath, JSON.stringify(body));
32+const shapesPath = outPath.replace(/\.json$/, "") + "_shapes.bin";
33+writeFileSync(shapesPath, encodeShapes(shapes!));
34+console.log(`wrote ${outPath} and ${shapesPath}`);
2935
3036 const meta = body.meta as Record<string, any>;
3137 const fe = body.modes.filter((m) => m.label !== "stat");
scripts/test_engine.tsmodified+21−0View file
@@ -118,5 +118,26 @@ for (const model of ["modal", "fd"] as const) {
118118 }
119119 }
120120 }
121+// 6. recording for the physics view: does not change the sound; frames in time order; the energy
122+// balance after the pluck (no source) only falls
123+{
124+ const { parametricBody } = await import("../src/core/body.ts");
125+ const p = defaultParams();
126+ p.engine.bodyModel = "parametric";
127+ const body = parametricBody(p);
128+ const plain = renderNote(p, body, { note: 33, velocity: 90, duration: 0.5 });
129+ const r = renderNote(p, body, { note: 33, velocity: 90, duration: 0.5, record: { denseFrom: 0, denseTo: Infinity, denseAfterRelease: 0.02, maxDense: 4000, sparseDt: 0.001, stringPoints: 64, sympPoints: 16, shapeModes: 0 } });
130+ const R = r.recording!;
131+ let same = plain.audio.length === r.audio.length;
132+ for (let i = 0; same && i < plain.audio.length; i++) same = plain.audio[i] === r.audio[i];
133+ let sorted = true;
134+ for (let i = 1; i < R.frameTimes.length; i++) if (!(R.frameTimes[i] > R.frameTimes[i - 1])) sorted = false;
135+ const E = (j: number) => R.channels.eString[j] + R.channels.eSymp[j] + R.channels.eBody[j] + R.channels.eAir[j];
136+ const j0 = Math.ceil((R.tRelease + R.slipTime + 0.005) / R.dt), j1 = R.nSteps - 1;
137+ const step = Math.round(0.05 / R.dt);
138+ let falls = true;
139+ for (let j = j0 + step; j <= j1; j += step) if (E(j) > E(j - step) * 1.02) falls = false;
140+ check("recording", same && sorted && falls && R.dense[0] >= 0, `audio identical ${same}, ${R.frameTimes.length} frames in order ${sorted}, energy ${E(j0).toExponential(2)} -> ${E(j1).toExponential(2)} J, falling ${falls}`);
141+}
121142 console.log(fails ? `${fails} FAILED` : "all passed");
122143 process.exit(fails ? 1 : 0);
src/app/assets.d.tsmodified+4−0View file
@@ -2,3 +2,7 @@ declare module "*.sf2?url" {
22 const url: string;
33 export default url;
44 }
5+declare module "*.bin?url" {
6+ const url: string;
7+ export default url;
8+}
src/app/main.tsmodified+41−2View file
@@ -12,6 +12,10 @@ import { linePlot, spectrogramPlot } from "./plots.ts";
1212 import { Audio } from "./synth.ts";
1313 import feDefaultUrl from "../../bodies/fe_default.json?url";
1414 import prebuiltSf2Url from "../../acoustic-bass.sf2?url";
15+import feDefaultShapesUrl from "../../bodies/fe_default_shapes.bin?url";
16+import type { PhysicsView, VizHost } from "./viz/index.ts";
17+import type { Recording } from "../core/engine.ts";
18+import type { FEShapes } from "../fe/shapes.ts";
1519
1620 // ---------------------------------------------------------------- workers
1721
@@ -215,6 +219,7 @@ function onParamsChanged() {
215219 updateNoteInfo();
216220 if (ui.tab === "body") drawBody();
217221 if (ui.tab === "sf2") drawSf2Panel();
222+ physics?.noteChanged();
218223 if (ui.auto && last && last.key !== renderKey(ui.note, ui.velocity)) void renderCurrent(false);
219224 }
220225
@@ -404,6 +409,7 @@ async function renderCurrent(play: boolean) {
404409 status(`${noteName(note)} v${vel}: rendered in ${Number(info.elapsed).toFixed(2)} s (${(info.modeCounts as { body: number }).body} body modes)`);
405410 updateNoteInfo();
406411 analyse();
412+ physics?.noteChanged();
407413 if (play) void playSim();
408414 } catch (e) { status(`Render failed: ${(e as Error).message.split("\n")[0]}`, true); }
409415 }
@@ -460,12 +466,43 @@ async function playRef() {
460466
461467 // ---------------------------------------------------------------- analysis panels
462468
463-const TABS: [string, string][] = [["sound", "Sound"], ["spectro", "Spectrogram"], ["partials", "Partials"], ["body", "Body"], ["sf2", "SF2"]];
469+const TABS: [string, string][] = [["sound", "Sound"], ["spectro", "Spectrogram"], ["partials", "Partials"], ["body", "Body"], ["physics", "Physics 3D"], ["sf2", "SF2"]];
470+
471+// The physics view (3D, slow motion) is loaded on first use: three.js is large.
472+const physicsRoot = el("div");
473+let physics: PhysicsView | null = null;
474+let physicsLoading: Promise<PhysicsView> | null = null;
475+const vizHost: VizHost = {
476+ params: () => params,
477+ note: () => ui.note,
478+ velocity: () => ui.velocity,
479+ useFE,
480+ feKey: () => feInputsKey(params),
481+ body: async () => { await ensureFE(); return body(); },
482+ record: async (p, b, note, velocity, duration, spec, prog) => {
483+ const r = await renderPool.call({ type: "record", params: p, body: b, note, velocity, duration, spec }, [], prog);
484+ return { recording: r.recording as Recording, mic: r.mic as Float32Array, pickup: r.pickup as Float32Array, sampleRate: Number((r.info as { sampleRate: number }).sampleRate) };
485+ },
486+ computeShapes: async (p, prog) => (await bulkPool.call({ type: "feShapes", params: p }, [], prog)).shapes as FEShapes,
487+ defaultShapesUrl: feDefaultShapesUrl,
488+ status,
489+ progress,
490+ playAudio: (x, fs) => { void audio.play(x, fs, SIM_PLAY_GAIN); },
491+ stopAudio: () => audio.stop(),
492+ mix: (mic, pickup) => mixOutput(params, mic, pickup),
493+};
494+async function showPhysics() {
495+ if (!physicsLoading) physicsLoading = import("./viz/index.ts").then((m) => (physics = new m.PhysicsView(physicsRoot, vizHost)));
496+ status("Loading the 3D view…");
497+ const v = await physicsLoading;
498+ if (ui.tab === "physics") await v.show();
499+}
500+
464501 function buildTabs() {
465502 const nav = $("#tabs"), panels = $("#panels");
466503 nav.innerHTML = ""; panels.innerHTML = "";
467504 for (const [id, label] of TABS) {
468- nav.append(el("button", { class: ui.tab === id ? "on" : "", onclick: () => { ui.tab = id; saveUi(); buildTabs(); } }, label));
505+ nav.append(el("button", { class: ui.tab === id ? "on" : "", onclick: () => { if (ui.tab === "physics" && id !== "physics") physics?.hide(); ui.tab = id; saveUi(); buildTabs(); } }, label));
469506 const p = el("div", { class: "panel", id: `panel-${id}` });
470507 p.hidden = ui.tab !== id;
471508 panels.append(p);
@@ -475,10 +512,12 @@ function buildTabs() {
475512 $("#panel-partials").innerHTML = `<div class="plots"><figure><figcaption>Partial level, dB re partial 1</figcaption><canvas id="cPL"></canvas></figure><figure><figcaption>Partial T60, s</figcaption><canvas id="cPT"></canvas></figure></div><div id="ptable"></div>`;
476513 $("#panel-body").innerHTML = `<div class="bodyctl"><label>String <select id="bStr">${STRING_NAMES.map((s, i) => `<option value="${i}">${s}</option>`).join("")}</select></label><span id="bodyInfo" class="sub"></span></div><div class="plots"><figure><figcaption>Bridge admittance at the notch |Y|, dB re 1 s/kg</figcaption><canvas id="cY"></canvas></figure><figure><figcaption>Radiation: pressure at the mic per newton at the notch, dB re 1 Pa/N</figcaption><canvas id="cH"></canvas></figure></div><div id="modeList" class="modelist"></div>`;
477514 $("#panel-sf2").innerHTML = `<div id="sf2Info"></div>`;
515+ $("#panel-physics").append(physicsRoot);
478516 ($("#bStr") as HTMLSelectElement).value = String(fingering(params, ui.note).string);
479517 $("#bStr").addEventListener("change", drawBody);
480518 if (ui.tab === "body") drawBody();
481519 else if (ui.tab === "sf2") drawSf2Panel();
520+ else if (ui.tab === "physics") void showPhysics();
482521 else analyse();
483522 }
484523
src/app/style.cssmodified+32−0View file
@@ -97,3 +97,35 @@ canvas.tall { height: 260px; }
9797 aside { max-height: 45vh; border-right: none; border-bottom: 1px solid var(--line); }
9898 .plots { grid-template-columns: 1fr; }
9999 }
100+
101+/* physics view */
102+.phys-top { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 8px; }
103+.phys-top label { color: var(--muted); display: flex; gap: 5px; align-items: center; }
104+.phys-main { display: grid; grid-template-columns: minmax(0, 1fr) 300px; gap: 10px; }
105+.phys-view { position: relative; border: 1px solid var(--line); border-radius: 8px; overflow: hidden; background: var(--panel); }
106+.phys-canvas { height: 520px; }
107+.phys-canvas canvas { width: 100% !important; height: 100% !important; display: block; }
108+.phys-legend { position: absolute; left: 10px; top: 8px; font-size: 12px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 6px; border-radius: 5px; pointer-events: auto; }
109+.phys-views { position: absolute; right: 8px; top: 8px; display: flex; gap: 3px; flex-wrap: wrap; justify-content: flex-end; max-width: 60%; }
110+.phys-side { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
111+.phys-layers { display: grid; grid-template-columns: 1fr; gap: 2px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 8px; }
112+.phys-layers label { display: flex; align-items: center; gap: 6px; color: var(--muted); }
113+.phys-layers label.rng { justify-content: space-between; }
114+.phys-layers input[type="range"] { accent-color: var(--accent); width: 130px; }
115+.phys-modehdr { display: flex; gap: 4px; }
116+.phys-modehdr button.on { border-color: var(--accent); color: var(--accent); }
117+.phys-modes { flex: 1; overflow-y: auto; max-height: 300px; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 0 6px; }
118+.ptab.modes { margin-top: 4px; width: 100%; }
119+.ptab.modes td, .ptab.modes th { padding: 1px 5px; }
120+.ptab.modes tr[data-k], .ptab.modes tr[data-n] { cursor: pointer; }
121+.ptab.modes tr:hover td { background: var(--grid); }
122+.ptab.modes tr.on td { background: color-mix(in srgb, var(--sel) 45%, transparent); }
123+.phys-transport { display: flex; align-items: center; gap: 6px 10px; flex-wrap: wrap; margin: 10px 0 6px; }
124+.phys-transport label { color: var(--muted); display: flex; gap: 5px; align-items: center; }
125+.phys-transport #phT { flex: 1; min-width: 200px; accent-color: var(--accent); }
126+.phys-time { font-variant-numeric: tabular-nums; color: var(--muted); min-width: 330px; }
127+.phys-time .warn { color: #b8860b; }
128+.phys-plothdr { display: flex; gap: 14px; align-items: center; margin-bottom: 4px; }
129+.phys-plothdr label { color: var(--muted); display: flex; gap: 5px; align-items: center; }
130+.phys-plots canvas { height: 120px; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; margin-bottom: 4px; cursor: crosshair; touch-action: none; }
131+@media (max-width: 1100px) { .phys-main { grid-template-columns: 1fr; } .phys-canvas { height: 380px; } }
src/app/viz/index.tsadded+618−0View file
@@ -0,0 +1,618 @@
1+// The "Physics" tab: records one note with the engine's state (strings, bridge, body modes,
2+// forces, energies) and replays it in 3D at any speed, with synced time traces and a mode
3+// explorer for the body modes and the string partials. Loaded on demand (three.js is large).
4+
5+import type { Params } from "../../core/params.ts";
6+import type { BodyModel } from "../../core/types.ts";
7+import { STRING_NAMES } from "../../core/types.ts";
8+import type { Recording, RecordSpec } from "../../core/engine.ts";
9+import { fingering, stringConst, stringModes } from "../../core/strings.ts";
10+import { noteName } from "../../core/sf2.ts";
11+import { decodeShapes, type FEShapes } from "../../fe/shapes.ts";
12+import { BassScene, type Frame, type Scales, type StringSetup } from "./scene.ts";
13+import { tracePlot, traceTimeAt } from "./traces.ts";
14+
15+export interface VizHost {
16+ params(): Params;
17+ note(): number;
18+ velocity(): number;
19+ useFE(): boolean;
20+ feKey(): string;
21+ /** the body in use (loads / computes the FE body if needed) */
22+ body(): Promise<BodyModel>;
23+ record(params: Params, body: BodyModel, note: number, velocity: number, duration: number, spec: RecordSpec, progress: (f: number) => void): Promise<{ recording: Recording; mic: Float32Array; pickup: Float32Array; sampleRate: number }>;
24+ computeShapes(params: Params, progress: (f: number, msg?: string) => void): Promise<FEShapes>;
25+ defaultShapesUrl: string;
26+ status(s: string, err?: boolean): void;
27+ progress(f: number): void;
28+ playAudio(x: Float32Array, fs: number): void;
29+ stopAudio(): void;
30+ mix(mic: Float32Array, pickup: Float32Array): Float32Array;
31+}
32+
33+interface Rec {
34+ R: Recording;
35+ mic: Float32Array;
36+ pickup: Float32Array;
37+ fs: number;
38+ note: number;
39+ velocity: number;
40+ duration: number;
41+ params: Params;
42+ body: BodyModel;
43+ shapes: FEShapes | null;
44+ key: string;
45+ /** maxima for automatic scaling */
46+ maxString: number;
47+ maxBody: number;
48+ maxPlate: number;
49+ maxAir: number;
50+ eMax: number;
51+}
52+
53+type Mode = { kind: "replay" } | { kind: "body"; idx: number } | { kind: "partial"; n: number };
54+
55+const SPEEDS: [number, string][] = [[1e-4, "1/10000"], [3e-4, "1/3000"], [1e-3, "1/1000"], [3e-3, "1/300"], [1e-2, "1/100"], [3e-2, "1/30"], [0.1, "1/10"], [0.3, "1/3"], [1, "real time"]];
56+const WINDOWS: [string, string][] = [["all", "whole note"], ["dense", "pluck (detail window)"], ["50", "±50 ms"], ["5", "±5 ms"], ["0.5", "±0.5 ms"]];
57+const MODE_HZ = 0.6; // display rate of a mode animation
58+
59+const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || "#888";
60+
61+export class PhysicsView {
62+ private host: VizHost;
63+ private root: HTMLElement;
64+ private scene: BassScene | null = null;
65+ private sceneKey = "";
66+ private rec: Rec | null = null;
67+ private recording: Promise<void> | null = null;
68+ private shapesCache = new Map<string, FEShapes>();
69+ private t = 0;
70+ private playing = false;
71+ private speed = 1e-3;
72+ private win = "dense";
73+ private mode: Mode = { kind: "replay" };
74+ private modeT0 = performance.now();
75+ private gain = { string: 1, body: 1, color: 1 };
76+ private lastWall = 0;
77+ private lastPlot = 0;
78+ private dirty = true;
79+ private visible = false;
80+ private work: Float32Array = new Float32Array(0);
81+ private fields = { top: new Float32Array(0), back: new Float32Array(0), air: new Float32Array(0), plug: new Float32Array(0) };
82+ private duration = 1;
83+ private modeTab: "body" | "partials" = "body";
84+
85+ constructor(root: HTMLElement, host: VizHost) {
86+ this.root = root;
87+ this.host = host;
88+ root.innerHTML = `
89+<div class="phys">
90+ <div class="phys-top">
91+ <button id="phRec" class="primary"></button>
92+ <label>Length <select id="phDur">${[0.5, 1, 2, 4].map((d) => `<option value="${d}">${d} s</option>`).join("")}</select></label>
93+ <span id="phInfo" class="sub"></span>
94+ </div>
95+ <div class="phys-main">
96+ <div class="phys-view">
97+ <div id="phCanvas" class="phys-canvas"></div>
98+ <div id="phLegend" class="phys-legend"></div>
99+ <div class="phys-views">${["overview", "top", "side", "bridge", "string", "below"].map((v) => `<button class="small" data-view="${v}">${v}</button>`).join("")}</div>
100+ </div>
101+ <div class="phys-side">
102+ <div class="phys-layers">
103+ <label><input type="checkbox" id="lyTop" checked /> top plate</label><input type="range" id="lyTopOp" min="0" max="1" step="0.05" value="1" title="top plate opacity" />
104+ <label><input type="checkbox" id="lyBack" checked /> back plate</label>
105+ <label><input type="checkbox" id="lyAir" /> air pressure (mid-depth)</label>
106+ <label><input type="checkbox" id="lyPlugs" checked /> f-hole flow</label>
107+ <label><input type="checkbox" id="lyRibs" checked /> ribs</label>
108+ <label><input type="checkbox" id="lySymp" checked /> other strings</label>
109+ <label class="rng">string motion ×<input type="range" id="gStr" min="-2" max="2" step="0.05" value="0" /></label>
110+ <label class="rng">body motion ×<input type="range" id="gBody" min="-2" max="2" step="0.05" value="0" /></label>
111+ <label class="rng">colour gain<input type="range" id="gCol" min="-1" max="2" step="0.05" value="0" /></label>
112+ </div>
113+ <div class="phys-modehdr"><button id="mtBody" class="small">Body modes</button><button id="mtPart" class="small">String partials</button></div>
114+ <div id="phModes" class="phys-modes"></div>
115+ </div>
116+ </div>
117+ <div class="phys-transport">
118+ <button id="phStart" title="Back to the start (Home)">⏮</button>
119+ <button id="phBack" title="Previous frame (←)">◀︎</button>
120+ <button id="phPlay" class="primary" title="Play / pause (space)">▶︎</button>
121+ <button id="phFwd" title="Next frame (→)">▶︎|</button>
122+ <label>Speed <select id="phSpeed">${SPEEDS.map(([v, l]) => `<option value="${v}">${l}</option>`).join("")}</select></label>
123+ <input type="range" id="phT" min="0" max="100000" step="1" value="0" />
124+ <span id="phTime" class="phys-time"></span>
125+ <button id="phRel" title="Jump to just before the release">release</button>
126+ <button id="phSound" title="Play the sound from here at real speed (the view follows)">▶︎ sound from here</button>
127+ <button id="phDetail" title="Re-record with every time step kept for 50 ms from here">record detail here</button>
128+ </div>
129+ <div class="phys-plots">
130+ <div class="phys-plothdr"><label>Plots show <select id="phWin">${WINDOWS.map(([v, l]) => `<option value="${v}">${l}</option>`).join("")}</select></label><span class="sub">click or drag on a plot to move the playhead · shaded: every time step recorded</span></div>
131+ <canvas id="pc0"></canvas><canvas id="pc1"></canvas><canvas id="pc2"></canvas><canvas id="pc3"></canvas>
132+ </div>
133+</div>`;
134+ const $ = <T extends HTMLElement>(id: string) => root.querySelector(`#${id}`) as T;
135+ ($("phSpeed") as HTMLSelectElement).value = String(this.speed);
136+ ($("phWin") as HTMLSelectElement).value = this.win;
137+ ($("phDur") as HTMLSelectElement).value = String(this.duration);
138+ $("phRec").addEventListener("click", () => void this.record());
139+ $("phDur").addEventListener("change", () => { this.duration = Number(($("phDur") as HTMLSelectElement).value); void this.record(); });
140+ $("phPlay").addEventListener("click", () => this.togglePlay());
141+ $("phStart").addEventListener("click", () => this.seek(0));
142+ $("phBack").addEventListener("click", () => this.stepFrame(-1));
143+ $("phFwd").addEventListener("click", () => this.stepFrame(1));
144+ $("phRel").addEventListener("click", () => { if (this.rec) this.seek(Math.max(0, this.rec.R.tRelease - 0.001)); });
145+ $("phSpeed").addEventListener("change", () => { this.speed = Number(($("phSpeed") as HTMLSelectElement).value); });
146+ $("phWin").addEventListener("change", () => { this.win = ($("phWin") as HTMLSelectElement).value; this.dirty = true; });
147+ $("phT").addEventListener("input", () => { const R = this.rec?.R; if (R) this.seek((Number(($("phT") as HTMLInputElement).value) / 100000) * this.tEnd()); });
148+ $("phSound").addEventListener("click", () => this.soundFromHere());
149+ $("phDetail").addEventListener("click", () => void this.record(this.t));
150+ $("mtBody").addEventListener("click", () => { this.modeTab = "body"; this.drawModeList(); });
151+ $("mtPart").addEventListener("click", () => { this.modeTab = "partials"; this.drawModeList(); });
152+ root.querySelectorAll<HTMLButtonElement>("[data-view]").forEach((b) => b.addEventListener("click", () => this.scene?.view(b.dataset.view as never)));
153+ const layer = () => {
154+ this.scene?.setLayers({
155+ top: ($("lyTop") as HTMLInputElement).checked, topOpacity: Number(($("lyTopOp") as HTMLInputElement).value),
156+ back: ($("lyBack") as HTMLInputElement).checked, air: ($("lyAir") as HTMLInputElement).checked,
157+ plugs: ($("lyPlugs") as HTMLInputElement).checked, ribs: ($("lyRibs") as HTMLInputElement).checked, symp: ($("lySymp") as HTMLInputElement).checked,
158+ });
159+ this.dirty = true;
160+ };
161+ for (const id of ["lyTop", "lyTopOp", "lyBack", "lyAir", "lyPlugs", "lyRibs", "lySymp"]) $(id).addEventListener("input", layer);
162+ $("lyAir").addEventListener("change", () => { if (($("lyAir") as HTMLInputElement).checked) { ($("lyTopOp") as HTMLInputElement).value = "0.25"; layer(); } });
163+ for (const [id, k] of [["gStr", "string"], ["gBody", "body"], ["gCol", "color"]] as const)
164+ $(id).addEventListener("input", () => { this.gain[k] = Math.pow(10, Number(($(id) as HTMLInputElement).value)); this.dirty = true; });
165+ for (let q = 0; q < 4; q++) {
166+ const c = $(`pc${q}`) as HTMLCanvasElement;
167+ const go = (e: PointerEvent) => { const [t0, t1] = this.window(); this.seek(traceTimeAt(c, e.clientX, t0, t1)); };
168+ c.addEventListener("pointerdown", (e) => { c.setPointerCapture(e.pointerId); this.playing = false; go(e); });
169+ c.addEventListener("pointermove", (e) => { if (c.hasPointerCapture(e.pointerId)) go(e); });
170+ }
171+ window.addEventListener("keydown", (e) => {
172+ if (!this.visible || (e.target as HTMLElement).closest("input, select, textarea")) return;
173+ if (e.key === " ") { e.preventDefault(); this.togglePlay(); }
174+ else if (e.key === "ArrowRight") { e.preventDefault(); this.stepFrame(1); }
175+ else if (e.key === "ArrowLeft") { e.preventDefault(); this.stepFrame(-1); }
176+ else if (e.key === "Home") { e.preventDefault(); this.seek(0); }
177+ });
178+ this.updateRecButton();
179+ this.drawModeList();
180+ const loop = (now: number) => { this.tick(now); requestAnimationFrame(loop); };
181+ requestAnimationFrame(loop);
182+ }
183+
184+ /** The tab became visible (or the note changed while it is). */
185+ async show(): Promise<void> {
186+ this.visible = true;
187+ this.updateRecButton();
188+ const key = this.recKey();
189+ if (!this.rec || this.rec.key !== key) await this.record();
190+ else this.dirty = true;
191+ }
192+ hide(): void { this.visible = false; this.playing = false; }
193+
194+ /** A note was played on the keyboard / the parameters changed. */
195+ noteChanged(): void {
196+ this.updateRecButton();
197+ if (this.visible && (!this.rec || this.rec.key !== this.recKey())) void this.record();
198+ }
199+
200+ private recKey(): string {
201+ const p = this.host.params();
202+ return JSON.stringify([p.engine, p.strings, p.pluck, p.stop, this.host.useFE() ? this.host.feKey() : p.body, p.fe.stringSpacing, p.fe.bridgeHeight, p.output, this.host.note(), this.host.velocity(), this.duration]);
203+ }
204+
205+ private updateRecButton(): void {
206+ const b = this.root.querySelector("#phRec") as HTMLButtonElement;
207+ b.textContent = `● Record ${noteName(this.host.note())} v${this.host.velocity()}`;
208+ }
209+
210+ // ------------------------------------------------------------ data
211+
212+ private async shapesFor(p: Params): Promise<FEShapes | null> {
213+ if (!this.host.useFE()) return null;
214+ const key = this.host.feKey();
215+ const hit = this.shapesCache.get(key);
216+ if (hit) return hit;
217+ let s: FEShapes | null = null;
218+ try {
219+ const r = await fetch(this.host.defaultShapesUrl);
220+ if (r.ok) { const d = decodeShapes(await r.arrayBuffer()); if (d.feKey === key) s = d; }
221+ } catch { /* not served */ }
222+ if (!s) {
223+ this.host.status("Computing the FE mode shapes for the 3D view…");
224+ s = await this.host.computeShapes(p, (f, msg) => { this.host.progress(f); if (msg) this.host.status(`FE shapes: ${msg}`); });
225+ }
226+ this.shapesCache.set(key, s);
227+ return s;
228+ }
229+
230+ private async record(detailFrom?: number): Promise<void> {
231+ if (this.recording) return this.recording;
232+ this.recording = (async () => {
233+ const p = JSON.parse(JSON.stringify(this.host.params())) as Params;
234+ const note = this.host.note(), vel = this.host.velocity(), duration = this.duration;
235+ try {
236+ const body = await this.host.body();
237+ const shapes = await this.shapesFor(p);
238+ const diag = (body.meta?.diag as { ke: number[] }[] | undefined) ?? null;
239+ const spec: RecordSpec = {
240+ denseFrom: detailFrom !== undefined ? Math.max(0, detailFrom - 0.001) : 0,
241+ denseTo: detailFrom !== undefined ? detailFrom + 0.05 : Infinity,
242+ denseAfterRelease: 0.05,
243+ maxDense: 9000,
244+ sparseDt: 0.0005,
245+ stringPoints: 128,
246+ sympPoints: 48,
247+ shapeModes: shapes ? shapes.nModes : 0,
248+ airFrac: diag ? diag.map((d) => (d.ke[3] ?? 0) + (d.ke[4] ?? 0)) : undefined,
249+ };
250+ this.host.status(`Recording ${noteName(note)} v${vel} for the physics view…`);
251+ this.host.progress(0);
252+ const r = await this.host.record(p, body, note, vel, duration, spec, (f) => this.host.progress(f));
253+ const rec: Rec = { R: r.recording, mic: r.mic, pickup: r.pickup, fs: r.sampleRate, note, velocity: vel, duration, params: p, body, shapes, key: this.recKey(), maxString: 0, maxBody: 0, maxPlate: 0, maxAir: 0, eMax: 0 };
254+ this.analyse(rec);
255+ const keepT = detailFrom !== undefined ? detailFrom : this.rec && this.rec.note === note ? this.t : 0;
256+ this.rec = rec;
257+ this.mode = { kind: "replay" };
258+ this.ensureScene();
259+ this.t = Math.min(keepT, this.tEnd());
260+ if (detailFrom === undefined && keepT === 0) this.t = 0;
261+ this.host.progress(1);
262+ this.host.status(`Recorded ${noteName(note)} v${vel}: ${r.recording.frameTimes.length} frames (${(r.recording.frames.byteLength / 1e6).toFixed(0)} MB). Play it, or scrub the time bar.`);
263+ this.drawModeList();
264+ this.dirty = true;
265+ } catch (e) {
266+ this.host.status(`Recording failed: ${(e as Error).message.split("\n")[0]}`, true);
267+ }
268+ })().finally(() => {
269+ this.recording = null;
270+ // the note or the parameters changed while recording: record again
271+ if (this.visible && this.rec && this.rec.key !== this.recKey()) void this.record();
272+ });
273+ return this.recording;
274+ }
275+
276+ /** Maxima for automatic display scaling. */
277+ private analyse(rec: Rec): void {
278+ const R = rec.R, F = R.frameSize, n = R.frameTimes.length;
279+ let ms = 0, mb = 0;
280+ for (let f = 0; f < n; f++) {
281+ const o = f * F;
282+ for (const s of R.strings) {
283+ const P = s.points;
284+ for (let j = 0; j < P; j++) {
285+ const xi = j / (P - 1);
286+ ms = Math.max(ms, Math.abs(R.frames[o + s.offset + j] - xi * R.frames[o + s.offset + P - 1]), Math.abs(R.frames[o + s.offset + P + j] - xi * R.frames[o + s.offset + 2 * P - 1]));
287+ }
288+ }
289+ for (let i = 0; i < 8; i++) mb = Math.max(mb, Math.abs(R.frames[o + R.notchOffset + i]));
290+ }
291+ rec.maxString = ms;
292+ let mp = 0, ma = 0;
293+ if (rec.shapes) {
294+ const step = Math.max(1, Math.floor(n / 150));
295+ this.allocFields(rec);
296+ for (let f = 0; f < n; f += step) {
297+ this.bodyFields(rec, R.frames.subarray(f * F, (f + 1) * F));
298+ for (const v of this.fields.top) mp = Math.max(mp, Math.abs(v));
299+ for (const v of this.fields.back) mp = Math.max(mp, Math.abs(v));
300+ for (const v of this.fields.air) ma = Math.max(ma, Math.abs(v));
301+ }
302+ }
303+ rec.maxPlate = mp;
304+ rec.maxAir = ma;
305+ rec.maxBody = Math.max(mb, mp);
306+ let e = 0;
307+ for (const c of ["eString", "eSymp", "eBody", "eAir"] as const) for (const v of R.channels[c]) e = Math.max(e, v);
308+ rec.eMax = e;
309+ }
310+
311+ private allocFields(rec: Rec): void {
312+ const s = rec.shapes;
313+ if (!s) return;
314+ if (this.fields.top.length !== s.topNodes.length) this.fields.top = new Float32Array(s.topNodes.length);
315+ if (this.fields.back.length !== s.backNodes.length) this.fields.back = new Float32Array(s.backNodes.length);
316+ if (this.fields.air.length !== s.cav.colH.length) this.fields.air = new Float32Array(s.cav.colH.length);
317+ if (this.fields.plug.length !== s.plugs.length) this.fields.plug = new Float32Array(s.plugs.length);
318+ }
319+
320+ /** Plate, air and plug fields from the recorded body coordinates of one frame. */
321+ private bodyFields(rec: Rec, frame: Float32Array): void {
322+ const s = rec.shapes!, R = rec.R;
323+ const { top, back, air, plug } = this.fields;
324+ top.fill(0); back.fill(0); air.fill(0); plug.fill(0);
325+ const nT = top.length, nB = back.length, nA = air.length, nP = plug.length;
326+ for (let q = 0; q < R.etaModes.length; q++) {
327+ const e = frame[R.etaOffset + q];
328+ if (e === 0) continue;
329+ const m = R.etaModes[q];
330+ let o = m * nT;
331+ for (let a = 0; a < nT; a++) top[a] += e * s.top[o + a];
332+ o = m * nB;
333+ for (let a = 0; a < nB; a++) back[a] += e * s.back[o + a];
334+ o = m * nA;
335+ for (let a = 0; a < nA; a++) air[a] += e * s.air[o + a];
336+ o = m * nP;
337+ for (let a = 0; a < nP; a++) plug[a] += e * s.plug[o + a];
338+ }
339+ }
340+
341+ private ensureScene(): void {
342+ const rec = this.rec!;
343+ const key = JSON.stringify([rec.params.fe, rec.params.strings.scaleLength, !!rec.shapes]);
344+ const box = this.root.querySelector("#phCanvas") as HTMLElement;
345+ if (!this.scene || this.sceneKey !== key) {
346+ this.scene?.dispose();
347+ this.scene = new BassScene(box, rec.params, rec.shapes);
348+ this.sceneKey = key;
349+ if (!rec.shapes) (this.root.querySelector("#lyAir") as HTMLInputElement).disabled = true;
350+ }
351+ const fg = fingering(rec.params, rec.note);
352+ const played = rec.R.strings.find((s) => s.played)!;
353+ const setups: StringSetup[] = rec.R.strings.map((s) => ({ string: s.string, length: s.length, points: s.points, played: s.played }));
354+ this.scene.setupStrings(setups, { string: played.string, length: played.length, stopped: fg.stopped, pluckX: rec.R.pull.x, dirY: rec.R.pull.dirY, dirZ: rec.R.pull.dirZ });
355+ this.work = new Float32Array(rec.R.frameSize);
356+ }
357+
358+ private tEnd(): number { const R = this.rec?.R; return R ? R.nSteps * R.dt : 1; }
359+
360+ // ------------------------------------------------------------ transport
361+
362+ private togglePlay(): void {
363+ if (!this.rec) return;
364+ if (this.mode.kind !== "replay") { this.mode = { kind: "replay" }; this.drawModeList(); }
365+ if (!this.playing && this.t >= this.tEnd() - 1e-9) this.t = 0;
366+ this.playing = !this.playing;
367+ this.lastWall = performance.now();
368+ if (!this.playing) this.host.stopAudio();
369+ }
370+
371+ private seek(t: number): void {
372+ this.t = Math.max(0, Math.min(this.tEnd(), t));
373+ if (this.mode.kind !== "replay") { this.mode = { kind: "replay" }; this.drawModeList(); }
374+ this.dirty = true;
375+ }
376+
377+ private stepFrame(d: number): void {
378+ const R = this.rec?.R;
379+ if (!R) return;
380+ this.playing = false;
381+ const ft = R.frameTimes;
382+ let i = this.frameIndex(this.t);
383+ if (d > 0) { if (ft[i] <= this.t + 1e-12) i++; } else if (ft[i] >= this.t - 1e-12) i--;
384+ i = Math.max(0, Math.min(ft.length - 1, i));
385+ this.seek(ft[i]);
386+ }
387+
388+ /** Index of the last frame at or before t. */
389+ private frameIndex(t: number): number {
390+ const ft = this.rec!.R.frameTimes;
391+ let lo = 0, hi = ft.length - 1;
392+ if (t <= ft[0]) return 0;
393+ while (hi - lo > 1) { const m = (lo + hi) >> 1; if (ft[m] <= t) lo = m; else hi = m; }
394+ return ft[hi] <= t ? hi : lo;
395+ }
396+
397+ private soundFromHere(): void {
398+ const rec = this.rec;
399+ if (!rec) return;
400+ if (this.mode.kind !== "replay") { this.mode = { kind: "replay" }; this.drawModeList(); }
401+ const x = this.host.mix(rec.mic, rec.pickup);
402+ const i0 = Math.max(0, Math.round((this.t - rec.R.audioT0) * rec.fs));
403+ if (i0 >= x.length) return;
404+ this.speed = 1;
405+ (this.root.querySelector("#phSpeed") as HTMLSelectElement).value = "1";
406+ this.playing = true;
407+ this.lastWall = performance.now();
408+ this.host.playAudio(x.subarray(i0), rec.fs);
409+ }
410+
411+ private window(): [number, number] {
412+ const R = this.rec?.R, T = this.tEnd();
413+ if (!R) return [0, 1];
414+ if (this.win === "all") return [0, T];
415+ if (this.win === "dense") return R.dense[0] >= 0 ? [Math.max(0, R.dense[0] - 0.001), Math.min(T, R.dense[1] + 0.001)] : [0, T];
416+ const half = Number(this.win) / 1000;
417+ let a = this.t - half, b = this.t + half;
418+ if (a < 0) { b -= a; a = 0; }
419+ if (b > T) { a -= b - T; b = T; }
420+ return [Math.max(0, a), b];
421+ }
422+
423+ // ------------------------------------------------------------ per frame
424+
425+ private tick(now: number): void {
426+ if (!this.visible || !this.rec || !this.scene) { this.lastWall = now; return; }
427+ if (this.playing) {
428+ const dt = Math.min(0.1, (now - this.lastWall) / 1000);
429+ this.t += this.speed * dt;
430+ if (this.t >= this.tEnd()) { this.t = this.tEnd(); this.playing = false; }
431+ this.dirty = true;
432+ }
433+ this.lastWall = now;
434+ if (this.mode.kind !== "replay") this.dirty = true;
435+ if (!this.dirty) return;
436+ this.dirty = false;
437+ this.drawFrame(now);
438+ if (now - this.lastPlot > 45 || !this.playing) { this.lastPlot = now; this.drawPlots(); }
439+ this.updateTransport();
440+ }
441+
442+ private drawFrame(now: number): void {
443+ const rec = this.rec!, R = rec.R, F = R.frameSize;
444+ const sc: Scales = {
445+ string: Math.min(400, Math.max(1, 0.03 / Math.max(rec.maxString, 1e-9))) * this.gain.string,
446+ body: (0.02 / Math.max(rec.maxBody, 1e-12)) * this.gain.body,
447+ plate: (0.6 * Math.max(rec.maxPlate, 1e-15)) / this.gain.color,
448+ air: (0.6 * Math.max(rec.maxAir, 1e-15)) / this.gain.color,
449+ };
450+ let frame: Frame;
451+ const legend: string[] = [];
452+ if (this.mode.kind === "replay") {
453+ // interpolate between the frames around t
454+ const ft = R.frameTimes, i = this.frameIndex(this.t), j = Math.min(ft.length - 1, i + 1);
455+ const a = j > i && ft[j] > ft[i] ? Math.max(0, Math.min(1, (this.t - ft[i]) / (ft[j] - ft[i]))) : 0;
456+ const w = this.work, A = R.frames;
457+ for (let k = 0; k < F; k++) w[k] = A[i * F + k] * (1 - a) + A[j * F + k] * a;
458+ if (rec.shapes) this.bodyFields(rec, w);
459+ const pullEnd = R.tRelease + R.slipTime;
460+ const alpha = this.t <= pullEnd ? 1 : Math.max(0, 1 - (this.t - pullEnd) / 0.03);
461+ frame = {
462+ top: rec.shapes ? this.fields.top : null, back: rec.shapes ? this.fields.back : null,
463+ air: rec.shapes ? this.fields.air : null, plug: rec.shapes ? this.fields.plug : null,
464+ notch: w.subarray(R.notchOffset, R.notchOffset + 8),
465+ strings: R.strings.map((s) => ({ string: s.string, length: s.length, y: w.subarray(s.offset, s.offset + s.points), z: w.subarray(s.offset + s.points, s.offset + 2 * s.points) })),
466+ finger: { travel: R.pull.speed * this.t, alpha },
467+ };
468+ legend.push(`strings ×${fmtX(sc.string)} · body ×${fmtX(sc.body)}`);
469+ if (rec.shapes) legend.push(`plate colour ±${fmtLen(sc.plate)}${(this.root.querySelector("#lyAir") as HTMLInputElement).checked ? ` · air ±${fmtP(sc.air)}` : ""}`);
470+ else legend.push("parametric body: plates not modelled in space (bridge motion only)");
471+ } else if (this.mode.kind === "body") {
472+ const m = rec.body.modes[this.mode.idx];
473+ const c = Math.cos(2 * Math.PI * MODE_HZ * ((now - this.modeT0) / 1000));
474+ const sh = rec.shapes && this.mode.idx < rec.shapes.nModes ? rec.shapes : null;
475+ this.allocFields(rec);
476+ let mx = 0, mA = 0;
477+ for (let i = 0; i < 4; i++) mx = Math.max(mx, Math.abs(m.by[i]), Math.abs(m.bz[i]));
478+ if (sh) {
479+ const k = this.mode.idx, f = this.fields;
480+ const fill = (dst: Float32Array, src: Float32Array) => { const n = dst.length; for (let a = 0; a < n; a++) dst[a] = src[k * n + a] * c; };
481+ fill(f.top, sh.top); fill(f.back, sh.back); fill(f.air, sh.air); fill(f.plug, sh.plug);
482+ for (let a = 0; a < f.top.length; a++) mx = Math.max(mx, Math.abs(sh.top[k * f.top.length + a]));
483+ for (let a = 0; a < f.back.length; a++) mx = Math.max(mx, Math.abs(sh.back[k * f.back.length + a]));
484+ for (let a = 0; a < f.air.length; a++) mA = Math.max(mA, Math.abs(sh.air[k * f.air.length + a]));
485+ }
486+ const notch = [...m.by.map((v) => v * c), ...m.bz.map((v) => v * c)];
487+ frame = {
488+ top: sh ? this.fields.top : null, back: sh ? this.fields.back : null, air: sh ? this.fields.air : null, plug: sh ? this.fields.plug : null,
489+ notch,
490+ strings: R.strings.map((s) => {
491+ const y = new Float32Array(s.points), z = new Float32Array(s.points);
492+ for (let j = 0; j < s.points; j++) { const xi = j / (s.points - 1); y[j] = notch[s.string] * xi; z[j] = notch[4 + s.string] * xi; }
493+ return { string: s.string, length: s.length, y, z };
494+ }),
495+ finger: null,
496+ };
497+ sc.body = (0.03 / Math.max(mx, 1e-12)) * this.gain.body;
498+ sc.plate = (0.7 * mx) / this.gain.color;
499+ sc.air = (0.7 * Math.max(mA, 1e-12)) / this.gain.color;
500+ legend.push(`body mode ${m.label ?? ""} ${m.f.toFixed(1)} Hz, Q ${(1 / (2 * m.zeta)).toFixed(0)} — shown at ${MODE_HZ} Hz${sh ? "" : " (no mesh shape: bridge only)"}`);
501+ } else {
502+ const n = this.mode.n;
503+ const played = R.strings.find((s) => s.played)!;
504+ const c = Math.cos(2 * Math.PI * MODE_HZ * ((now - this.modeT0) / 1000));
505+ const amp = 0.001;
506+ frame = {
507+ top: null, back: null, air: null, plug: null, notch: new Float32Array(8),
508+ strings: R.strings.map((s) => {
509+ const y = new Float32Array(s.points), z = new Float32Array(s.points);
510+ if (s === played) for (let j = 0; j < s.points; j++) z[j] = amp * c * Math.sin((n * Math.PI * j) / (s.points - 1));
511+ return { string: s.string, length: s.length, y, z };
512+ }),
513+ finger: null,
514+ };
515+ sc.string = (0.03 / amp) * this.gain.string;
516+ const pi = this.partials()[n - 1];
517+ legend.push(`string partial ${n} of ${STRING_NAMES[played.string]}: ${pi ? `${pi.f.toFixed(1)} Hz, ${pi.cents >= 0 ? "+" : ""}${pi.cents.toFixed(1)} cents, T60 ${pi.t60.toFixed(2)} s` : ""} — shown at ${MODE_HZ} Hz`);
518+ }
519+ if (this.mode.kind !== "replay") legend.push(`<button class="small" id="phBackRec">back to the recording</button>`);
520+ this.scene!.update(frame, sc);
521+ const lg = this.root.querySelector("#phLegend") as HTMLElement;
522+ const htmlL = legend.join("<br>");
523+ if (lg.dataset.h !== htmlL) {
524+ lg.innerHTML = htmlL; lg.dataset.h = htmlL;
525+ lg.querySelector("#phBackRec")?.addEventListener("click", () => { this.mode = { kind: "replay" }; this.drawModeList(); this.dirty = true; });
526+ }
527+ }
528+
529+ private updateTransport(): void {
530+ const R = this.rec!.R, t = this.t;
531+ (this.root.querySelector("#phPlay") as HTMLElement).textContent = this.playing ? "⏸" : "▶︎";
532+ (this.root.querySelector("#phT") as HTMLInputElement).value = String(Math.round((t / this.tEnd()) * 100000));
533+ const phase = t < R.tRelease ? "finger sticks, pulling the string" : t < R.tRelease + R.slipTime ? "string slips off the finger" : "free vibration";
534+ const dense = R.dense[0] >= 0 && t >= R.dense[0] - 1e-12 && t <= R.dense[1] + 1e-12;
535+ (this.root.querySelector("#phTime") as HTMLElement).innerHTML = `t = <b>${(t * 1000).toFixed(t < 0.1 ? 3 : 1)} ms</b> · ${phase} · ${dense ? "every step" : `<span class="warn">coarse frames (0.5 ms)</span>`}`;
536+ const det = this.root.querySelector("#phDetail") as HTMLButtonElement;
537+ det.disabled = dense || !!this.recording;
538+ }
539+
540+ private drawPlots(): void {
541+ const rec = this.rec!, R = rec.R, ch = R.channels;
542+ const [t0, t1] = this.window();
543+ const shade = R.dense[0] >= 0 ? ([R.dense[0], R.dense[1]] as [number, number]) : null;
544+ const marks = [{ t: R.tRelease, label: "release" }, { t: R.tRelease + R.slipTime, label: "" }];
545+ const ax = { t0, t1, playhead: this.t, shade, marks };
546+ const c = (q: number) => this.root.querySelector(`#pc${q}`) as HTMLCanvasElement;
547+ const dt = R.dt;
548+ tracePlot(c(0), [
549+ { data: ch.fingerFz, dt, color: css("--sim"), label: "across" },
550+ { data: ch.fingerFy, dt, color: css("--ref"), label: "vertical" },
551+ ], { ...ax, ylabel: "finger force on the string, N" });
552+ tracePlot(c(1), [
553+ { data: ch.bridgeFy, dt, color: css("--sim"), label: "vertical" },
554+ { data: ch.bridgeFz, dt, color: css("--alt"), label: "lateral" },
555+ ], { ...ax, ylabel: "string force on the bridge, N" });
556+ const e0 = Math.max(rec.eMax, 1e-30);
557+ const db = (v: number) => (v > 0 ? 10 * Math.log10(v / e0) : -200);
558+ tracePlot(c(2), [
559+ { data: ch.eString, dt, color: css("--sim"), label: "played string", map: db },
560+ { data: ch.eSymp, dt, color: css("--mark"), label: "other strings", map: db },
561+ { data: ch.eBody, dt, color: css("--alt"), label: "body structure", map: db },
562+ { data: ch.eAir, dt, color: css("--ref"), label: "air", map: db },
563+ ], { ...ax, ylabel: "energy, dB re max", ymin: -90, ymax: 3 });
564+ tracePlot(c(3), [
565+ { data: ch.mic, dt, color: css("--ref"), label: "mic (Pa)" },
566+ { data: ch.pickup, dt, color: css("--alt"), label: "pickup (Pa equiv.)" },
567+ ], { ...ax, ylabel: "sound" });
568+ }
569+
570+ // ------------------------------------------------------------ mode explorer
571+
572+ private partials(): { n: number; f: number; cents: number; t60: number }[] {
573+ const rec = this.rec;
574+ const p = rec?.params ?? this.host.params();
575+ const fg = fingering(p, rec?.note ?? this.host.note());
576+ const L = rec ? rec.R.strings.find((s) => s.played)!.length : fg.length;
577+ const sc = stringConst(p, fg.string);
578+ const m = stringModes(p, sc, L, Math.min(p.engine.stringFmax, 5000));
579+ const f1 = m.w[0] / (2 * Math.PI);
580+ return Array.from(m.w, (w, i) => { const f = w / (2 * Math.PI); return { n: i + 1, f, cents: 1200 * Math.log2(f / ((i + 1) * f1)), t60: Math.log(1000) / m.sigma[i] }; });
581+ }
582+
583+ private drawModeList(): void {
584+ const box = this.root.querySelector("#phModes") as HTMLElement;
585+ (this.root.querySelector("#mtBody") as HTMLElement).classList.toggle("on", this.modeTab === "body");
586+ (this.root.querySelector("#mtPart") as HTMLElement).classList.toggle("on", this.modeTab === "partials");
587+ const rec = this.rec;
588+ if (!rec) { box.innerHTML = `<p class="sub">Record a note first.</p>`; return; }
589+ const sel = this.mode;
590+ if (this.modeTab === "body") {
591+ const b = rec.body, si = rec.R.strings.find((s) => s.played)!.string;
592+ const nSh = rec.shapes?.nModes ?? 0;
593+ const diag = (b.meta?.diag as { ke: number[] }[] | undefined) ?? null;
594+ let radMax = 0;
595+ for (const m of b.modes) radMax = Math.max(radMax, Math.hypot(m.radRe, m.radIm) * (2 * Math.PI * m.f) ** 2);
596+ const rows: string[] = [];
597+ const limit = nSh > 0 ? nSh : Math.min(b.modes.length, 200);
598+ for (let k = 0; k < limit; k++) {
599+ const m = b.modes[k];
600+ const air = diag?.[k] ? (diag[k].ke[3] + diag[k].ke[4]) * 100 : m.label === "A0" ? 100 : NaN;
601+ const rad = 20 * Math.log10((Math.hypot(m.radRe, m.radIm) * (2 * Math.PI * m.f) ** 2) / radMax + 1e-12);
602+ rows.push(`<tr data-k="${k}" class="${sel.kind === "body" && sel.idx === k ? "on" : ""}"><td>${m.label ?? ""}</td><td>${m.f.toFixed(1)}</td><td>${(1 / (2 * m.zeta)).toFixed(0)}</td><td>${(Math.log(1000) / (m.zeta * 2 * Math.PI * m.f)).toFixed(2)}</td><td>${(Math.abs(m.by[si]) * 1000).toFixed(0)}</td><td>${isFinite(air) ? air.toFixed(0) : ""}</td><td>${rad.toFixed(0)}</td></tr>`);
603+ }
604+ const more = b.modes.length - limit;
605+ box.innerHTML = `<table class="ptab modes"><tr><th></th><th>f Hz</th><th>Q</th><th>T60 s</th><th title="vertical mode shape at the ${STRING_NAMES[si]} notch, 1/sqrt(g)">bridge</th><th title="share of the kinetic energy in the air and f-hole plugs">air %</th><th title="radiated pressure at the mic per unit modal amplitude at the mode frequency, dB re the strongest">rad dB</th></tr>${rows.join("")}</table>${more > 0 ? `<p class="sub">+ ${more} ${nSh > 0 ? "statistical modes above the FE range (no mesh shape)" : "more modes"}.</p>` : ""}<p class="sub">Click a mode to see it move (slowed to ${MODE_HZ} Hz).</p>`;
606+ box.querySelectorAll<HTMLElement>("tr[data-k]").forEach((tr) => tr.addEventListener("click", () => { this.mode = { kind: "body", idx: Number(tr.dataset.k) }; this.playing = false; this.modeT0 = performance.now(); this.drawModeList(); this.dirty = true; }));
607+ } else {
608+ const ps = this.partials().slice(0, 60);
609+ const rows = ps.map((q) => `<tr data-n="${q.n}" class="${sel.kind === "partial" && sel.n === q.n ? "on" : ""}"><td>${q.n}</td><td>${q.f.toFixed(1)}</td><td>${q.cents >= 0 ? "+" : ""}${q.cents.toFixed(1)}</td><td>${q.t60.toFixed(2)}</td></tr>`).join("");
610+ box.innerHTML = `<table class="ptab modes"><tr><th>n</th><th>f Hz</th><th title="inharmonicity: cents above n × f1">cents</th><th>T60 s</th></tr>${rows}</table><p class="sub">Partials of the played string (stiff string, Valette damping, rigid ends). Click one to see its shape.</p>`;
611+ box.querySelectorAll<HTMLElement>("tr[data-n]").forEach((tr) => tr.addEventListener("click", () => { this.mode = { kind: "partial", n: Number(tr.dataset.n) }; this.playing = false; this.modeT0 = performance.now(); this.drawModeList(); this.dirty = true; }));
612+ }
613+ }
614+}
615+
616+function fmtX(v: number): string { return v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toPrecision(2); }
617+function fmtLen(m: number): string { return m >= 1e-3 ? `${(m * 1e3).toPrecision(2)} mm` : m >= 1e-6 ? `${(m * 1e6).toPrecision(2)} µm` : `${(m * 1e9).toPrecision(2)} nm`; }
618+function fmtP(p: number): string { return p >= 1 ? `${p.toPrecision(2)} Pa` : `${(p * 1e3).toPrecision(2)} mPa`; }
src/app/viz/scene.tsadded+523−0View file
@@ -0,0 +1,523 @@
1+// The 3D view of the bass: plates (coloured and displaced by their normal motion), ribs, the air
2+// cavity slice (coloured by pressure), the f-hole air plugs (arrows), the bridge, the strings, the
3+// plucking and stopping fingers, and the static neck / fingerboard / tailpiece.
4+//
5+// Body coordinates (x along the body toward the neck, s across toward the treble side, z out of
6+// the top, back plate at z = 0) map to three.js as X = x, Y = z, Z = -s. Displacements are drawn
7+// exaggerated: the strings by `string`, the body (plates, bridge, the bridge end of the strings)
8+// by `body`.
9+
10+import * as THREE from "three";
11+import { OrbitControls } from "three/addons/controls/OrbitControls.js";
12+import type { Params } from "../../core/params.ts";
13+import { makeArch, makeBodyGrid, makeFHoles, makeOutline, markFHoles, HOLE, IN, type Outline } from "../../fe/geometry.ts";
14+import type { FEShapes } from "../../fe/shapes.ts";
15+
16+export interface StringFrame { string: number; length: number; y: Float32Array; z: Float32Array }
17+
18+export interface Frame {
19+ /** per top / back plate node (m), per air column (Pa), per f-hole plug (m); null = not shown */
20+ top: Float32Array | null;
21+ back: Float32Array | null;
22+ air: Float32Array | null;
23+ plug: Float32Array | null;
24+ /** notch displacement: y of strings 0..3, z of strings 0..3 (m) */
25+ notch: ArrayLike<number>;
26+ strings: StringFrame[];
27+ /** the plucking finger: pad travel along the pull direction (m, real), visibility 0..1 */
28+ finger: { travel: number; alpha: number } | null;
29+}
30+
31+export interface Scales {
32+ /** display exaggeration of string and body motion */
33+ string: number;
34+ body: number;
35+ /** displacement (m) and pressure (Pa) shown at full colour */
36+ plate: number;
37+ air: number;
38+}
39+
40+export interface StringSetup {
41+ string: number;
42+ length: number;
43+ points: number;
44+ played: boolean;
45+}
46+
47+export interface PlayedSetup {
48+ string: number;
49+ length: number;
50+ stopped: boolean;
51+ /** pluck point, m from the stop; pull direction (y, z) */
52+ pluckX: number;
53+ dirY: number;
54+ dirZ: number;
55+}
56+
57+export interface Layers { top: boolean; topOpacity: number; back: boolean; air: boolean; ribs: boolean; plugs: boolean; symp: boolean }
58+
59+const WOOD = new THREE.Color(0.80, 0.62, 0.40);
60+const WOOD_DARK = new THREE.Color(0.45, 0.27, 0.13);
61+const POS = new THREE.Color(0.86, 0.16, 0.10);
62+const NEG = new THREE.Color(0.12, 0.36, 0.86);
63+const AIR0 = new THREE.Color(0.93, 0.93, 0.90);
64+const EBONY = 0x1c1a18;
65+
66+/** Diverging colour: v in [-1, 1] from NEG through base to POS. */
67+function diverge(out: Float32Array, o: number, v: number, base: THREE.Color): void {
68+ const a = Math.min(1, Math.abs(v)), c = v >= 0 ? POS : NEG;
69+ out[o] = base.r + (c.r - base.r) * a;
70+ out[o + 1] = base.g + (c.g - base.g) * a;
71+ out[o + 2] = base.b + (c.b - base.b) * a;
72+}
73+
74+interface PlateMesh { mesh: THREE.Mesh; src: Int32Array; rest: Float32Array; n: number }
75+
76+export class BassScene {
77+ readonly renderer: THREE.WebGLRenderer;
78+ private scene = new THREE.Scene();
79+ private camera: THREE.PerspectiveCamera;
80+ private controls: OrbitControls;
81+ private root = new THREE.Group();
82+ private outline: Outline;
83+ private topZ: (x: number, s: number) => number;
84+ private xb: number;
85+ private notchY: number[];
86+ private zNotch: number;
87+ private xNut: number;
88+ private nutFactor = 0.42;
89+ private top: PlateMesh | null = null;
90+ private back: PlateMesh | null = null;
91+ private airMesh: THREE.Mesh | null = null;
92+ private airCols: Int32Array | null = null; // per air-quad vertex: column
93+ private ribs: THREE.Mesh;
94+ private plugArrows: THREE.ArrowHelper[] = [];
95+ private plugInfo: { x: number; s: number; z: number }[] = [];
96+ private bridge: THREE.Mesh;
97+ private bridgeRest: Float32Array;
98+ private bridgeFoot: [number, number] = [-1, -1]; // top-plate node index under each foot
99+ private strings: { setup: StringSetup; mesh: THREE.Mesh; rest: THREE.Vector3; dir: THREE.Vector3; radius: number }[] = [];
100+ private staticStrings = new THREE.Group();
101+ private played: PlayedSetup | null = null;
102+ private fingerMesh: THREE.Mesh;
103+ private stopMesh: THREE.Mesh;
104+ private resizeObs: ResizeObserver;
105+ private layers: Layers = { top: true, topOpacity: 1, back: true, air: false, ribs: true, plugs: true, symp: true };
106+ private needsRender = true;
107+
108+ private container: HTMLElement;
109+
110+ constructor(container: HTMLElement, p: Params, shapes: FEShapes | null) {
111+ this.container = container;
112+ const fe = p.fe;
113+ this.renderer = new THREE.WebGLRenderer({ antialias: true });
114+ this.renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));
115+ container.append(this.renderer.domElement);
116+ const bg = getComputedStyle(document.documentElement).getPropertyValue("--panel").trim() || "#ffffff";
117+ this.scene.background = new THREE.Color(bg);
118+ this.camera = new THREE.PerspectiveCamera(35, 1, 0.01, 50);
119+ this.controls = new OrbitControls(this.camera, this.renderer.domElement);
120+ this.controls.enableDamping = true;
121+ this.controls.addEventListener("change", () => { this.needsRender = true; });
122+ this.scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.6));
123+ const sun = new THREE.DirectionalLight(0xffffff, 1.6);
124+ sun.position.set(-1, 3, 2);
125+ this.scene.add(sun);
126+ this.scene.add(this.root);
127+
128+ this.outline = makeOutline(fe);
129+ const arch = makeArch(fe, this.outline);
130+ this.topZ = (x, s) => fe.ribDepth + arch(x, s);
131+ this.xb = fe.bridgePos * fe.bodyLength;
132+ this.notchY = [0, 1, 2, 3].map((i) => (i - 1.5) * fe.stringSpacing);
133+ this.zNotch = this.topZ(this.xb, 0) + fe.bridgeHeight;
134+ this.xNut = this.xb + p.strings.scaleLength;
135+
136+ // ---- plates
137+ let grid: FEShapes["grid"], topNodes: Int32Array, backNodes: Int32Array;
138+ if (shapes) ({ grid, topNodes, backNodes } = shapes);
139+ else {
140+ const g = makeBodyGrid(fe, this.outline, arch, fe.gridH);
141+ markFHoles(g, makeFHoles(fe));
142+ grid = { nx: g.nx, ns: g.ns, h: g.h, x0: g.x0, s0: g.s0 };
143+ const t: number[] = [], b: number[] = [];
144+ for (let k = 0; k < g.nx * g.ns; k++) { if (g.type[k] === IN) t.push(k); if (g.type[k] === IN || g.type[k] === HOLE) b.push(k); }
145+ topNodes = Int32Array.from(t); backNodes = Int32Array.from(b);
146+ }
147+ const topSet = new Set(topNodes), holes = new Set([...backNodes].filter((k) => !topSet.has(k)));
148+ this.top = this.plate(grid, topNodes, holes, (x, s) => this.topZ(x, s));
149+ this.back = this.plate(grid, backNodes, new Set(), () => 0);
150+ this.root.add(this.top.mesh, this.back.mesh);
151+ // the nodes under the bridge feet
152+ for (const [q, sf] of [[0, -fe.footSpan / 2], [1, fe.footSpan / 2]] as const) {
153+ let best = -1, bd = Infinity;
154+ topNodes.forEach((k, a) => {
155+ const x = grid.x0 + Math.floor(k / grid.ns) * grid.h, s = grid.s0 + (k % grid.ns) * grid.h;
156+ const d = (x - this.xb) ** 2 + (s - sf) ** 2;
157+ if (d < bd) { bd = d; best = a; }
158+ });
159+ this.bridgeFoot[q] = best;
160+ }
161+
162+ // ---- ribs
163+ this.ribs = this.makeRibs(fe.ribDepth);
164+ this.root.add(this.ribs);
165+
166+ // ---- air slice and plugs
167+ if (shapes) {
168+ this.airMesh = this.makeAir(shapes);
169+ this.root.add(this.airMesh);
170+ for (const pl of shapes.plugs) {
171+ const z = this.topZ(pl.xc, pl.sc);
172+ this.plugInfo.push({ x: pl.xc, s: pl.sc, z });
173+ const a = new THREE.ArrowHelper(new THREE.Vector3(0, 1, 0), new THREE.Vector3(pl.xc, z, -pl.sc), 0.001, 0x2a9d8f, 0.03, 0.025);
174+ this.plugArrows.push(a);
175+ this.root.add(a);
176+ }
177+ }
178+
179+ // ---- bridge (tapered slab across the strings)
180+ {
181+ const wB = fe.footSpan + 0.05, wT = 3 * fe.stringSpacing + 0.035, th = 0.022;
182+ const z0 = this.topZ(this.xb, 0), z1 = this.zNotch;
183+ const v: number[] = [];
184+ for (const [z, w] of [[z0, wB], [z1, wT]] as const)
185+ for (const s of [-w / 2, w / 2]) for (const dx of [-th / 2, th / 2]) v.push(this.xb + dx, z, -s);
186+ const geo = new THREE.BufferGeometry();
187+ this.bridgeRest = Float32Array.from(v);
188+ geo.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(v), 3));
189+ // vertices: bottom (0..3), top (4..7); within each: s-, dx- / dx+, s+, dx- / dx+
190+ geo.setIndex([0, 1, 3, 0, 3, 2, 4, 6, 7, 4, 7, 5, 0, 4, 5, 0, 5, 1, 2, 3, 7, 2, 7, 6, 0, 2, 6, 0, 6, 4, 1, 5, 7, 1, 7, 3]);
191+ geo.computeVertexNormals();
192+ this.bridge = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0xd9b98a, roughness: 0.8, side: THREE.DoubleSide, flatShading: true }));
193+ this.root.add(this.bridge);
194+ }
195+
196+ // ---- neck, fingerboard, tailpiece, end pin (static)
197+ const ebony = new THREE.MeshStandardMaterial({ color: EBONY, roughness: 0.6 });
198+ {
199+ const xEnd = Math.max(fe.bodyLength * 0.72, this.xb + 0.3);
200+ const len = this.xNut - xEnd;
201+ const zTopEnd = this.zNotch - 0.022, zTopNut = this.zNotch - 0.006;
202+ const board = new THREE.Mesh(new THREE.BoxGeometry(len, 0.02, 0.1), ebony);
203+ board.position.set((xEnd + this.xNut) / 2, (zTopEnd + zTopNut) / 2 - 0.01, 0);
204+ board.rotation.z = Math.atan2(zTopNut - zTopEnd, len);
205+ board.scale.set(1, 1, 1);
206+ this.root.add(board);
207+ const neck = new THREE.Mesh(new THREE.BoxGeometry(this.xNut - fe.bodyLength + 0.05, 0.05, 0.06), new THREE.MeshStandardMaterial({ color: WOOD_DARK, roughness: 0.7 }));
208+ neck.position.set((fe.bodyLength + this.xNut) / 2, zTopNut - 0.045, 0);
209+ this.root.add(neck);
210+ const scroll = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.07, 0.08), new THREE.MeshStandardMaterial({ color: WOOD_DARK, roughness: 0.7 }));
211+ scroll.position.set(this.xNut + 0.12, zTopNut - 0.02, 0);
212+ this.root.add(scroll);
213+ const tail = new THREE.Mesh(new THREE.BoxGeometry(0.28, 0.015, 0.09), ebony);
214+ const xTail0 = 0.06, xTail1 = xTail0 + 0.28;
215+ tail.position.set((xTail0 + xTail1) / 2, this.topZ(0.2, 0) + 0.05, 0);
216+ this.root.add(tail);
217+ // afterlengths (bridge to tailpiece) and the strings behind the stop are drawn by setupStrings
218+ this.staticStrings.userData.tailX = xTail1;
219+ this.staticStrings.userData.tailZ = this.topZ(0.2, 0) + 0.06;
220+ this.root.add(this.staticStrings);
221+ }
222+
223+ // ---- fingers
224+ const skin = new THREE.MeshStandardMaterial({ color: 0xe0a98a, roughness: 0.55, transparent: true });
225+ this.fingerMesh = new THREE.Mesh(new THREE.CapsuleGeometry(0.009, 0.05, 6, 12), skin);
226+ this.stopMesh = new THREE.Mesh(new THREE.CapsuleGeometry(0.009, 0.04, 6, 12), skin.clone());
227+ this.stopMesh.rotation.x = Math.PI / 2;
228+ this.root.add(this.fingerMesh, this.stopMesh);
229+ this.fingerMesh.visible = false;
230+ this.stopMesh.visible = false;
231+
232+ // ---- camera
233+ this.root.position.set(-(this.xNut + 0.1) / 2, -0.15, 0);
234+ this.view("overview");
235+
236+ this.resizeObs = new ResizeObserver(() => this.resize());
237+ this.resizeObs.observe(container);
238+ this.resize();
239+ const loop = () => {
240+ if (!this.renderer.domElement.isConnected) return;
241+ this.controls.update();
242+ if (this.needsRender) { this.renderer.render(this.scene, this.camera); this.needsRender = false; }
243+ requestAnimationFrame(loop);
244+ };
245+ requestAnimationFrame(loop);
246+ }
247+
248+ dispose(): void {
249+ this.resizeObs.disconnect();
250+ this.renderer.dispose();
251+ this.renderer.domElement.remove();
252+ }
253+
254+ private resize(): void {
255+ const w = this.container.clientWidth, h = this.container.clientHeight;
256+ if (!(w > 0 && h > 0)) return;
257+ this.renderer.setSize(w, h, false);
258+ this.camera.aspect = w / h;
259+ this.camera.updateProjectionMatrix();
260+ this.needsRender = true;
261+ }
262+
263+ /** Preset views. */
264+ view(which: "overview" | "top" | "side" | "bridge" | "string" | "below"): void {
265+ const c = this.root.position;
266+ const at = (x: number, y: number, z: number) => new THREE.Vector3(x + c.x, y + c.y, z + c.z);
267+ const xs = this.played ? this.xb + (this.played.length - this.played.pluckX) : this.xb + 0.2;
268+ const presets = {
269+ overview: [new THREE.Vector3(-1.35, 1.05, 1.0), new THREE.Vector3(-0.1, 0.1, 0)],
270+ top: [at(this.xNut / 2, 2.6, 0.001), at(this.xNut / 2, 0, 0)],
271+ side: [at(this.xNut / 2, 0.25, 2.2), at(this.xNut / 2, 0.2, 0)],
272+ bridge: [at(this.xb - 0.25, this.zNotch + 0.25, 0.35), at(this.xb, this.zNotch - 0.05, 0)],
273+ string: [at(xs - 0.12, this.zNotch + 0.32, 0.1), at(xs + 0.02, this.zNotch, 0)],
274+ below: [at(this.xNut / 2 - 0.2, -1.6, 1.0), at(this.xNut / 2 - 0.2, 0, 0)],
275+ } as const;
276+ const [pos, tgt] = presets[which];
277+ this.camera.position.copy(pos);
278+ this.controls.target.copy(tgt);
279+ this.controls.update();
280+ this.needsRender = true;
281+ }
282+
283+ setLayers(l: Partial<Layers>): void {
284+ Object.assign(this.layers, l);
285+ const L = this.layers;
286+ if (this.top) {
287+ this.top.mesh.visible = L.top && L.topOpacity > 0.02;
288+ const m = this.top.mesh.material as THREE.MeshStandardMaterial;
289+ m.transparent = L.topOpacity < 0.99; m.opacity = L.topOpacity; m.depthWrite = L.topOpacity >= 0.99;
290+ }
291+ if (this.back) this.back.mesh.visible = L.back;
292+ if (this.airMesh) this.airMesh.visible = L.air;
293+ this.ribs.visible = L.ribs;
294+ for (const a of this.plugArrows) a.visible = L.plugs;
295+ for (const s of this.strings) if (!s.setup.played) s.mesh.visible = L.symp;
296+ this.needsRender = true;
297+ }
298+
299+ private plate(grid: FEShapes["grid"], nodes: Int32Array, holes: Set<number>, zf: (x: number, s: number) => number): PlateMesh {
300+ const { nx, ns, h, x0, s0 } = grid;
301+ const srcOf = new Map<number, number>();
302+ nodes.forEach((k, a) => srcOf.set(k, a));
303+ const vid = new Map<number, number>();
304+ const src: number[] = [], rest: number[] = [], idx: number[] = [];
305+ const vert = (k: number) => {
306+ let v = vid.get(k);
307+ if (v !== undefined) return v;
308+ const i = Math.floor(k / ns), j = k % ns;
309+ let x = x0 + i * h, s = s0 + j * h;
310+ const a = srcOf.get(k);
311+ if (a === undefined) {
312+ // a constrained node: pull it onto the rim so the plate edge follows the outline
313+ x = Math.min(this.outline.L, Math.max(0, x));
314+ const hw = this.outline.halfWidth(x);
315+ s = Math.max(-hw, Math.min(hw, s));
316+ }
317+ v = src.length;
318+ vid.set(k, v);
319+ src.push(a ?? -1);
320+ rest.push(x, zf(x, s), -s);
321+ return v;
322+ };
323+ for (let i = 0; i + 1 < nx; i++)
324+ for (let j = 0; j + 1 < ns; j++) {
325+ const ks = [i * ns + j, (i + 1) * ns + j, (i + 1) * ns + j + 1, i * ns + j + 1];
326+ if (!ks.some((k) => srcOf.has(k)) || ks.some((k) => holes.has(k))) continue;
327+ const [a, b, c, d] = ks.map(vert);
328+ idx.push(a, b, c, a, c, d);
329+ }
330+ const geo = new THREE.BufferGeometry();
331+ const restA = Float32Array.from(rest);
332+ geo.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(restA), 3));
333+ const col = new Float32Array(src.length * 3);
334+ for (let v = 0; v < src.length; v++) diverge(col, 3 * v, 0, WOOD);
335+ geo.setAttribute("color", new THREE.BufferAttribute(col, 3));
336+ geo.setIndex(idx);
337+ geo.computeVertexNormals();
338+ const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.75, side: THREE.DoubleSide }));
339+ return { mesh, src: Int32Array.from(src), rest: restA, n: src.length };
340+ }
341+
342+ private makeRibs(depth: number): THREE.Mesh {
343+ const { px, ps } = this.outline;
344+ const n = px.length, step = Math.max(1, Math.floor(n / 240));
345+ const pts: [number, number][] = [];
346+ for (let k = 0; k < n; k += step) pts.push([px[k], ps[k]]);
347+ const pos: number[] = [], idx: number[] = [];
348+ pts.forEach(([x, s]) => { pos.push(x, 0, -s, x, depth, -s); });
349+ const m = pts.length;
350+ for (let k = 0; k < m; k++) { const a = 2 * k, b = 2 * ((k + 1) % m); idx.push(a, b, b + 1, a, b + 1, a + 1); }
351+ const geo = new THREE.BufferGeometry();
352+ geo.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(pos), 3));
353+ geo.setIndex(idx);
354+ geo.computeVertexNormals();
355+ return new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: WOOD_DARK, roughness: 0.8, side: THREE.DoubleSide, transparent: true, opacity: 0.45, depthWrite: false }));
356+ }
357+
358+ private makeAir(sh: FEShapes): THREE.Mesh {
359+ const { nxA, nsA, x0, s0, ha, col, colH } = sh.cav;
360+ const pos: number[] = [], cols: number[] = [], idx: number[] = [];
361+ for (let i = 0; i < nxA; i++)
362+ for (let j = 0; j < nsA; j++) {
363+ const c = col[i * nsA + j];
364+ if (c < 0) continue;
365+ const y = colH[c] / 2, v = pos.length / 3;
366+ for (const [dx, ds] of [[0, 0], [1, 0], [1, 1], [0, 1]]) { pos.push(x0 + (i + dx) * ha, y, -(s0 + (j + ds) * ha)); cols.push(c); }
367+ idx.push(v, v + 1, v + 2, v, v + 2, v + 3);
368+ }
369+ this.airCols = Int32Array.from(cols);
370+ const geo = new THREE.BufferGeometry();
371+ geo.setAttribute("position", new THREE.BufferAttribute(Float32Array.from(pos), 3));
372+ const c = new Float32Array(cols.length * 3);
373+ for (let v = 0; v < cols.length; v++) diverge(c, 3 * v, 0, AIR0);
374+ geo.setAttribute("color", new THREE.BufferAttribute(c, 3));
375+ geo.setIndex(idx);
376+ geo.computeVertexNormals();
377+ const mesh = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ vertexColors: true, side: THREE.DoubleSide }));
378+ mesh.visible = false;
379+ return mesh;
380+ }
381+
382+ /** The strings to draw: the recorded ones (vibrating parts) plus static afterlengths and the part behind the stop. */
383+ setupStrings(list: StringSetup[], played: PlayedSetup): void {
384+ for (const s of this.strings) { this.root.remove(s.mesh); s.mesh.geometry.dispose(); }
385+ this.strings = [];
386+ this.staticStrings.clear();
387+ this.played = played;
388+ const R = 8;
389+ const metal = new THREE.MeshStandardMaterial({ color: 0xb8b4ac, metalness: 0.85, roughness: 0.3 });
390+ const metalPlayed = new THREE.MeshStandardMaterial({ color: 0xe8c47a, metalness: 0.8, roughness: 0.3 });
391+ const radius = (i: number) => 0.0042 - 0.0005 * i;
392+ const recorded = new Set(list.map((s) => s.string));
393+ for (let i = 0; i < 4; i++) {
394+ const rest = this.notchPos(i);
395+ const nut = new THREE.Vector3(this.xNut, this.zNotch, -this.notchY[i] * this.nutFactor);
396+ const dir = nut.clone().sub(rest).normalize();
397+ const setup = list.find((s) => s.string === i) ?? { string: i, length: this.xNut - this.xb, points: 2, played: false };
398+ if (recorded.has(i)) {
399+ const P = setup.points;
400+ const geo = new THREE.BufferGeometry();
401+ geo.setAttribute("position", new THREE.BufferAttribute(new Float32Array(P * R * 3), 3));
402+ const idx: number[] = [];
403+ for (let j = 0; j + 1 < P; j++) for (let r = 0; r < R; r++) { const a = j * R + r, b = j * R + ((r + 1) % R); idx.push(a, a + R, b + R, a, b + R, b); }
404+ geo.setIndex(idx);
405+ const mesh = new THREE.Mesh(geo, setup.played ? metalPlayed : metal);
406+ this.root.add(mesh);
407+ this.strings.push({ setup, mesh, rest, dir, radius: radius(i) });
408+ }
409+ // static parts: bridge -> tailpiece, and stop -> nut (for the stopped played string, or every non-recorded string from the bridge)
410+ const tail = new THREE.Vector3(this.staticStrings.userData.tailX, this.staticStrings.userData.tailZ, -this.notchY[i] * 0.7);
411+ const segs: [THREE.Vector3, THREE.Vector3][] = [[rest, tail]];
412+ const L = recorded.has(i) ? setup.length : 0;
413+ const stopPt = rest.clone().addScaledVector(dir, L);
414+ if (L < nut.distanceTo(rest) - 1e-3) segs.push([stopPt, nut]);
415+ for (const [a, b] of segs) {
416+ const len = a.distanceTo(b);
417+ const cyl = new THREE.Mesh(new THREE.CylinderGeometry(radius(i), radius(i), len, 8), metal);
418+ cyl.position.copy(a.clone().add(b).multiplyScalar(0.5));
419+ cyl.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), b.clone().sub(a).normalize());
420+ this.staticStrings.add(cyl);
421+ }
422+ }
423+ const ps = this.strings.find((s) => s.setup.played);
424+ if (played.stopped && ps) {
425+ const pt = ps.rest.clone().addScaledVector(ps.dir, played.length + 0.006);
426+ this.stopMesh.position.copy(pt).add(new THREE.Vector3(0, 0.012, 0));
427+ this.stopMesh.visible = true;
428+ } else this.stopMesh.visible = false;
429+ this.setLayers({});
430+ }
431+
432+ private notchPos(i: number): THREE.Vector3 { return new THREE.Vector3(this.xb, this.zNotch, -this.notchY[i]); }
433+
434+ update(f: Frame, sc: Scales): void {
435+ // plates
436+ for (const [pm, field] of [[this.top, f.top], [this.back, f.back]] as const) {
437+ if (!pm) continue;
438+ const pos = pm.mesh.geometry.getAttribute("position") as THREE.BufferAttribute;
439+ const col = pm.mesh.geometry.getAttribute("color") as THREE.BufferAttribute;
440+ const P = pos.array as Float32Array, C = col.array as Float32Array;
441+ for (let v = 0; v < pm.n; v++) {
442+ const a = pm.src[v];
443+ const w = field && a >= 0 ? field[a] : 0;
444+ P[3 * v + 1] = pm.rest[3 * v + 1] + sc.body * w;
445+ diverge(C, 3 * v, w / sc.plate, WOOD);
446+ }
447+ pos.needsUpdate = true; col.needsUpdate = true;
448+ pm.mesh.geometry.computeVertexNormals();
449+ }
450+ // air
451+ if (this.airMesh && this.airCols && f.air) {
452+ const col = this.airMesh.geometry.getAttribute("color") as THREE.BufferAttribute;
453+ const C = col.array as Float32Array;
454+ for (let v = 0; v < this.airCols.length; v++) diverge(C, 3 * v, f.air[this.airCols[v]] / sc.air, AIR0);
455+ col.needsUpdate = true;
456+ }
457+ // f-hole plugs: arrows along the outward flow, length ~ displacement (clamped)
458+ this.plugArrows.forEach((a, q) => {
459+ const d = f.plug ? f.plug[q] * sc.body : 0;
460+ const len = Math.min(0.25, Math.abs(d));
461+ a.setDirection(new THREE.Vector3(0, d >= 0 ? 1 : -1, 0));
462+ a.setLength(Math.max(1e-4, len), Math.min(0.03, 0.4 * len + 1e-4), Math.min(0.025, 0.3 * len + 1e-4));
463+ a.visible = this.layers.plugs && len > 2e-3;
464+ });
465+ // bridge: line fit of the notch verticals across the strings, mean lateral
466+ const ny = this.notchY;
467+ let sy = 0, sty = 0, ss = 0, sz = 0;
468+ for (let i = 0; i < 4; i++) { sy += f.notch[i]; sty += f.notch[i] * ny[i]; ss += ny[i] * ny[i]; sz += f.notch[4 + i]; }
469+ const bV = sy / 4, bT = sty / ss, bZ = sz / 4;
470+ {
471+ const pos = this.bridge.geometry.getAttribute("position") as THREE.BufferAttribute;
472+ const P = pos.array as Float32Array, R = this.bridgeRest;
473+ const feet = [this.bridgeFoot[0], this.bridgeFoot[1]].map((a) => (f.top && a >= 0 ? f.top[a] : bV));
474+ for (let v = 0; v < 8; v++) {
475+ const s = -R[3 * v + 2], topV = v >= 4;
476+ P[3 * v] = R[3 * v];
477+ if (topV) { P[3 * v + 1] = R[3 * v + 1] + sc.body * (bV + bT * s); P[3 * v + 2] = R[3 * v + 2] - sc.body * bZ; }
478+ else { P[3 * v + 1] = R[3 * v + 1] + sc.body * (s < 0 ? feet[0] : feet[1]); P[3 * v + 2] = R[3 * v + 2]; }
479+ }
480+ pos.needsUpdate = true;
481+ this.bridge.geometry.computeVertexNormals();
482+ }
483+ // strings: string part exaggerated by sc.string, the bridge end (w x / L) by sc.body
484+ const R = 8;
485+ const V = new THREE.Vector3(0, 1, 0), W = new THREE.Vector3(0, 0, -1);
486+ for (const st of this.strings) {
487+ const fr = f.strings.find((s) => s.string === st.setup.string);
488+ const P = st.setup.points, L = st.setup.length;
489+ const pos = st.mesh.geometry.getAttribute("position") as THREE.BufferAttribute;
490+ const A = pos.array as Float32Array;
491+ const wy = fr ? fr.y[P - 1] : 0, wz = fr ? fr.z[P - 1] : 0;
492+ for (let j = 0; j < P; j++) {
493+ const x = (j / (P - 1)) * L, xi = x / L;
494+ const uy = fr ? fr.y[j] : 0, uz = fr ? fr.z[j] : 0;
495+ const dy = sc.string * (uy - wy * xi) + sc.body * wy * xi;
496+ const dz = sc.string * (uz - wz * xi) + sc.body * wz * xi;
497+ const cx = st.rest.x + st.dir.x * (L - x), cy = st.rest.y + st.dir.y * (L - x) + dy, cz = st.rest.z + st.dir.z * (L - x) - dz;
498+ for (let r = 0; r < R; r++) {
499+ const th = (2 * Math.PI * r) / R, c = Math.cos(th) * st.radius, s = Math.sin(th) * st.radius;
500+ const o = 3 * (j * R + r);
501+ A[o] = cx + c * V.x + s * W.x; A[o + 1] = cy + c * V.y + s * W.y; A[o + 2] = cz + c * V.z + s * W.z;
502+ }
503+ }
504+ pos.needsUpdate = true;
505+ st.mesh.geometry.computeVertexNormals();
506+ }
507+ // plucking finger: beside the string on the side away from the pull, moving with the pad
508+ // (string part exaggerated like the string, plus the bridge-end part like the body)
509+ const ps = this.strings.find((s) => s.setup.played);
510+ if (f.finger && this.played && ps && f.finger.alpha > 0) {
511+ const pl = this.played, L = pl.length, xi = pl.pluckX / L;
512+ const fr = f.strings.find((s) => s.string === pl.string);
513+ const P = ps.setup.points;
514+ const wy = fr ? fr.y[P - 1] : 0, wz = fr ? fr.z[P - 1] : 0;
515+ const base = ps.rest.clone().addScaledVector(ps.dir, L - pl.pluckX).addScaledVector(V, sc.body * wy * xi).addScaledVector(W, sc.body * wz * xi);
516+ const dDisp = new THREE.Vector3().addScaledVector(V, pl.dirY).addScaledVector(W, pl.dirZ).normalize();
517+ this.fingerMesh.position.copy(base).addScaledVector(dDisp, sc.string * f.finger.travel - (0.009 + ps.radius));
518+ (this.fingerMesh.material as THREE.MeshStandardMaterial).opacity = f.finger.alpha;
519+ this.fingerMesh.visible = true;
520+ } else this.fingerMesh.visible = false;
521+ this.needsRender = true;
522+ }
523+}
src/app/viz/traces.tsadded+127−0View file
@@ -0,0 +1,127 @@
1+// Time-trace plots for the physics view: long channels drawn as min/max per pixel column, a
2+// playhead, shaded dense-recording window, and click/drag to seek.
3+
4+export interface Trace {
5+ data: Float32Array;
6+ /** sample j is at t = t0 + j dt */
7+ dt: number;
8+ t0?: number;
9+ color: string;
10+ label: string;
11+ /** map a sample value to the plotted value (e.g. dB) */
12+ map?: (v: number) => number;
13+}
14+
15+export interface TraceAxes { t0: number; t1: number; ymin?: number; ymax?: number; ylabel: string; playhead: number; shade?: [number, number] | null; marks?: { t: number; label: string }[] }
16+
17+const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || "#888";
18+
19+const fmtT = (t: number, span: number) => (span < 0.02 ? `${(t * 1000).toFixed(span < 0.002 ? 2 : 1)}` : span < 2 ? `${(t * 1000).toFixed(0)}` : `${t.toFixed(1)}s`);
20+
21+export function tracePlot(c: HTMLCanvasElement, traces: Trace[], ax: TraceAxes): void {
22+ const dpr = window.devicePixelRatio || 1;
23+ const w = c.clientWidth, h = c.clientHeight;
24+ if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); }
25+ const ctx = c.getContext("2d")!;
26+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
27+ ctx.clearRect(0, 0, w, h);
28+ const padL = 48, padR = 8, padT = 14, padB = 16;
29+ const pw = w - padL - padR, ph = h - padT - padB;
30+ const { t0, t1 } = ax;
31+ const X = (t: number) => padL + (pw * (t - t0)) / (t1 - t0);
32+ // per-column min/max
33+ const cols = Math.max(1, Math.floor(pw));
34+ const env = traces.map((tr) => {
35+ const lo = new Float32Array(cols).fill(Infinity), hi = new Float32Array(cols).fill(-Infinity);
36+ const tb = tr.t0 ?? 0, n = tr.data.length, map = tr.map;
37+ for (let px = 0; px < cols; px++) {
38+ const ta = t0 + ((t1 - t0) * px) / cols, tc = t0 + ((t1 - t0) * (px + 1)) / cols;
39+ let j0 = Math.floor((ta - tb) / tr.dt), j1 = Math.ceil((tc - tb) / tr.dt);
40+ j0 = Math.max(0, j0); j1 = Math.min(n - 1, Math.max(j1, j0 + 1));
41+ if (j0 >= n) break;
42+ for (let j = j0; j <= j1; j++) { const v = map ? map(tr.data[j]) : tr.data[j]; if (!isFinite(v)) continue; if (v < lo[px]) lo[px] = v; if (v > hi[px]) hi[px] = v; }
43+ }
44+ return { lo, hi };
45+ });
46+ let ymin = ax.ymin ?? Infinity, ymax = ax.ymax ?? -Infinity;
47+ if (ax.ymin === undefined || ax.ymax === undefined)
48+ for (const e of env) for (let px = 0; px < cols; px++) {
49+ if (ax.ymin === undefined && isFinite(e.lo[px])) ymin = Math.min(ymin, e.lo[px]);
50+ if (ax.ymax === undefined && isFinite(e.hi[px])) ymax = Math.max(ymax, e.hi[px]);
51+ }
52+ if (!isFinite(ymin) || !isFinite(ymax)) { ymin = -1; ymax = 1; }
53+ if (ymax - ymin < 1e-30) { ymax += 1e-12; ymin -= 1e-12; }
54+ const pad = 0.06 * (ymax - ymin);
55+ if (ax.ymax === undefined) ymax += pad;
56+ if (ax.ymin === undefined) ymin -= pad;
57+ const Y = (v: number) => padT + ph * (1 - (v - ymin) / (ymax - ymin));
58+ ctx.font = "11px system-ui, sans-serif";
59+ // shaded dense window
60+ if (ax.shade) {
61+ const a = Math.max(padL, X(ax.shade[0])), b = Math.min(padL + pw, X(ax.shade[1]));
62+ if (b > a) { ctx.fillStyle = css("--grid"); ctx.fillRect(a, padT, b - a, ph); }
63+ }
64+ // grid + ticks
65+ ctx.strokeStyle = css("--grid"); ctx.fillStyle = css("--muted"); ctx.lineWidth = 1;
66+ const ticks = (lo: number, hi: number, n: number) => {
67+ const span = hi - lo, st0 = span / n, mag = Math.pow(10, Math.floor(Math.log10(st0)));
68+ const st = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= st0) ?? mag * 10;
69+ const out: number[] = [];
70+ for (let v = Math.ceil(lo / st) * st; v <= hi + 1e-9 * st; v += st) out.push(+v.toPrecision(12));
71+ return out;
72+ };
73+ for (const t of ticks(t0, t1, 8)) {
74+ const x = X(t);
75+ ctx.beginPath(); ctx.moveTo(x, padT); ctx.lineTo(x, padT + ph); ctx.stroke();
76+ ctx.textAlign = "center"; ctx.fillText(fmtT(t, t1 - t0), x, h - 3);
77+ }
78+ for (const v of ticks(ymin, ymax, 4)) {
79+ const y = Y(v);
80+ ctx.beginPath(); ctx.moveTo(padL, y); ctx.lineTo(padL + pw, y); ctx.stroke();
81+ ctx.textAlign = "right"; ctx.fillText(Math.abs(v) >= 1000 || (Math.abs(v) < 0.01 && v !== 0) ? v.toExponential(0) : String(+v.toPrecision(3)), padL - 4, y + 4);
82+ }
83+ ctx.textAlign = "left"; ctx.fillText(`${ax.ylabel} (t in ${t1 - t0 < 2 ? "ms" : "s"})`, padL, 10);
84+ // traces
85+ ctx.save();
86+ ctx.beginPath(); ctx.rect(padL, padT, pw, ph); ctx.clip();
87+ for (const m of ax.marks ?? []) {
88+ if (m.t < t0 || m.t > t1) continue;
89+ ctx.strokeStyle = css("--mark"); ctx.setLineDash([2, 3]);
90+ ctx.beginPath(); ctx.moveTo(X(m.t), padT); ctx.lineTo(X(m.t), padT + ph); ctx.stroke(); ctx.setLineDash([]);
91+ ctx.fillStyle = css("--muted"); ctx.fillText(m.label, X(m.t) + 3, padT + 10);
92+ }
93+ traces.forEach((tr, q) => {
94+ const { lo, hi } = env[q];
95+ ctx.strokeStyle = tr.color; ctx.fillStyle = tr.color; ctx.lineWidth = 1.3;
96+ ctx.beginPath();
97+ let pen = false;
98+ for (let px = 0; px < cols; px++) {
99+ if (!isFinite(lo[px])) { pen = false; continue; }
100+ const x = padL + px + 0.5, ya = Y(hi[px]), yb = Y(lo[px]);
101+ if (pen) ctx.lineTo(x, (ya + yb) / 2); else { ctx.moveTo(x, (ya + yb) / 2); pen = true; }
102+ if (yb - ya > 1.5) { ctx.moveTo(x, ya); ctx.lineTo(x, yb); ctx.moveTo(x, (ya + yb) / 2); }
103+ }
104+ ctx.stroke();
105+ });
106+ // playhead
107+ if (ax.playhead >= t0 && ax.playhead <= t1) {
108+ ctx.strokeStyle = css("--accent"); ctx.lineWidth = 1.5;
109+ ctx.beginPath(); ctx.moveTo(X(ax.playhead), padT); ctx.lineTo(X(ax.playhead), padT + ph); ctx.stroke();
110+ }
111+ ctx.restore();
112+ // legend, right-aligned above the plot
113+ ctx.font = "11px system-ui, sans-serif";
114+ let lx = w - padR - traces.reduce((s, tr) => s + 22 + ctx.measureText(tr.label).width, 0);
115+ for (const tr of traces) {
116+ ctx.fillStyle = tr.color; ctx.fillRect(lx, 4, 10, 3);
117+ ctx.fillStyle = css("--fg"); ctx.textAlign = "left"; ctx.fillText(tr.label, lx + 13, 10);
118+ lx += 22 + ctx.measureText(tr.label).width;
119+ }
120+}
121+
122+/** Time under the pointer for a plot drawn with tracePlot over [t0, t1]. */
123+export function traceTimeAt(c: HTMLCanvasElement, clientX: number, t0: number, t1: number): number {
124+ const r = c.getBoundingClientRect();
125+ const padL = 48, padR = 8, pw = r.width - padL - padR;
126+ return t0 + ((t1 - t0) * (clientX - r.left - padL)) / pw;
127+}
src/app/worker.tsmodified+15−2View file
@@ -1,6 +1,7 @@
11 // Compute worker: note renders, the FE body, reference renders. One message in, one reply out
22 // (plus progress messages), all tagged with the request id.
3-import { renderNote } from "../core/engine.ts";
3+import { CHANNELS, renderNote, type RecordSpec } from "../core/engine.ts";
4+import type { FEShapes } from "../fe/shapes.ts";
45 import { parametricBody } from "../core/body.ts";
56 import { renderReference } from "../core/reference.ts";
67 import type { Params } from "../core/params.ts";
@@ -10,12 +11,24 @@ let refBank: ArrayBuffer | null = null;
1011 const post = (m: unknown, t: Transferable[] = []) => (self as unknown as Worker).postMessage(m, t);
1112
1213 self.onmessage = async (e: MessageEvent) => {
13- const m = e.data as { type: string; id: number; params: Params; body?: BodyModel; note: number; velocity: number; duration?: number; buffer?: ArrayBuffer; program?: number; bank?: number; len?: number; hold?: number };
14+ const m = e.data as { type: string; id: number; params: Params; body?: BodyModel; note: number; velocity: number; duration?: number; buffer?: ArrayBuffer; program?: number; bank?: number; len?: number; hold?: number; spec?: RecordSpec };
1415 try {
1516 if (m.type === "render") {
1617 const body = m.body ?? parametricBody(m.params);
1718 const r = renderNote(m.params, body, { note: m.note, velocity: m.velocity, duration: m.duration, onProgress: (f) => post({ type: "progress", id: m.id, frac: f }) });
1819 post({ type: "done", id: m.id, mic: r.mic, pickup: r.pickup, info: { fingering: r.fingering, releaseForce: r.releaseForce, slipTime: r.slipTime, stickTime: r.stickTime, elapsed: r.elapsed, modeCounts: r.modeCounts, sampleRate: r.sampleRate } }, [r.mic.buffer as ArrayBuffer, r.pickup.buffer as ArrayBuffer]);
20+ } else if (m.type === "record") {
21+ const body = m.body ?? parametricBody(m.params);
22+ const r = renderNote(m.params, body, { note: m.note, velocity: m.velocity, duration: m.duration, record: m.spec, onProgress: (f) => post({ type: "progress", id: m.id, frac: f }) });
23+ const rec = r.recording!;
24+ const bufs = [r.mic.buffer, r.pickup.buffer, rec.frames.buffer, rec.frameTimes.buffer, ...CHANNELS.map((c) => rec.channels[c].buffer)] as ArrayBuffer[];
25+ post({ type: "done", id: m.id, mic: r.mic, pickup: r.pickup, recording: rec, info: { fingering: r.fingering, elapsed: r.elapsed, modeCounts: r.modeCounts, sampleRate: r.sampleRate } }, bufs);
26+ } else if (m.type === "feShapes") {
27+ const { computeFEBody } = await import("../fe/index.ts");
28+ let shapes: FEShapes | null = null;
29+ const body = computeFEBody(m.params, (msg: string, frac: number) => post({ type: "progress", id: m.id, frac, msg }), { shapes: (s) => { shapes = s; } });
30+ const s = shapes! as FEShapes;
31+ post({ type: "done", id: m.id, body, shapes: s }, [s.top.buffer, s.back.buffer, s.air.buffer, s.plug.buffer] as ArrayBuffer[]);
1932 } else if (m.type === "fe") {
2033 const t0 = performance.now();
2134 const { computeFEBody } = await import("../fe/index.ts");
src/core/engine.tsmodified+225−4View file
@@ -46,6 +46,59 @@ export interface RenderOpts {
4646 onProgress?: (frac: number) => void;
4747 /** explicit tuning (open-string tension factors, stopped-length factor); default: tuneByEar */
4848 tuning?: Tuning;
49+ /** record the state for visualisation (see Recording) */
50+ record?: RecordSpec;
51+}
52+
53+/**
54+ * What to record for the physics visualisation. Time t is simulation time from the start of the
55+ * pull (t = 0), not the audio time. "Dense" frames are taken every internal step inside
56+ * [denseFrom, denseTo] (denseTo = Infinity: until denseAfterRelease after the release), "sparse"
57+ * frames every sparseDt elsewhere. Scalar channels are recorded at every step.
58+ */
59+export interface RecordSpec {
60+ denseFrom: number;
61+ denseTo: number;
62+ denseAfterRelease: number;
63+ maxDense: number;
64+ sparseDt: number;
65+ /** points along the played string and along each sympathetic string */
66+ stringPoints: number;
67+ sympPoints: number;
68+ /** body modes with index < shapeModes have mesh shapes: their coordinates go into the frames */
69+ shapeModes: number;
70+ /** per body mode: share of the energy in the air (cavity + f-hole plugs); default 0 (A0: 1) */
71+ airFrac?: ArrayLike<number>;
72+}
73+
74+export const CHANNELS = ["fingerFy", "fingerFz", "bridgeFy", "bridgeFz", "eString", "eSymp", "eBody", "eAir", "mic", "pickup"] as const;
75+export type Channel = (typeof CHANNELS)[number];
76+
77+export interface Recording {
78+ /** internal time step, s; channel sample j is at t = j dt */
79+ dt: number;
80+ nSteps: number;
81+ channels: Record<Channel, Float32Array>;
82+ /** frames: nFrames x frameSize, at frameTimes (s, ascending) */
83+ frameTimes: Float64Array;
84+ frames: Float32Array;
85+ frameSize: number;
86+ /** per recorded string: which string, vibrating length, points, offset of its y block (z block follows) */
87+ strings: { string: number; length: number; points: number; offset: number; played: boolean }[];
88+ /** offset of the 8 notch displacements (y of strings 0..3, then z of strings 0..3), m */
89+ notchOffset: number;
90+ /** offset and body-mode indices of the recorded body coordinates (already scaled by any mode thinning) */
91+ etaOffset: number;
92+ etaModes: Int32Array;
93+ /** the dense window actually recorded, s */
94+ dense: [number, number];
95+ tRelease: number;
96+ slipTime: number;
97+ releaseForce: number;
98+ /** pull direction (y = away from the fingerboard, z = across) and speed m/s, pluck point (m from the stop) */
99+ pull: { dirY: number; dirZ: number; speed: number; x: number; padWidth: number };
100+ /** audio sample 0 is at this simulation time */
101+ audioT0: number;
49102 }
50103
51104 export interface Tuning { tensionScale: number[]; lengthScale: number }
@@ -66,6 +119,7 @@ export interface RenderResult {
66119 /** cpu time, s */
67120 elapsed: number;
68121 modeCounts: { strings: number[]; body: number };
122+ recording?: Recording;
69123 }
70124
71125 /** One string-polarisation's contribution to the notch solve, common to modal and FD strings. */
@@ -84,6 +138,10 @@ interface StringPol {
84138 /** the notch displacement now and one step ago */
85139 w: number;
86140 wPrev: number;
141+ /** displacement at n evenly spaced points, x_j = j L / (n - 1) (stop to bridge), into out[off..] */
142+ sample(n: number, out: Float32Array, off: number): void;
143+ /** vibrational energy (kinetic + potential of the string's own motion), J */
144+ energy(): number;
87145 }
88146
89147 const HANN_PTS = 9;
@@ -112,6 +170,7 @@ class ModalPol implements StringPol {
112170 private L: number; private mu: number; private T: number;
113171 private xfOverL: number; private rho: number; private damp: boolean;
114172 private aD = 0; private bD = 0; private sEE: number;
173+ private sinTab: Float32Array | null = null; private sinN = 0;
115174
116175 constructor(sc: StringConst, L: number, modes: { w: Float64Array; sigma: Float64Array }, k: number, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) {
117176 const N = modes.w.length;
@@ -199,6 +258,28 @@ class ModalPol implements StringPol {
199258 for (let n = 0; n < this.N; n++) s += this.kn2[n] * this.q[n] * this.q[n];
200259 return (s * this.L) / 2 + (this.w * this.w) / this.L;
201260 }
261+ sample(np: number, out: Float32Array, off: number): void {
262+ const N = this.N;
263+ if (!this.sinTab || this.sinN !== np) {
264+ this.sinN = np;
265+ this.sinTab = new Float32Array(N * np);
266+ for (let n = 0; n < N; n++) for (let j = 0; j < np; j++) this.sinTab[n * np + j] = Math.sin(((n + 1) * Math.PI * j) / (np - 1));
267+ }
268+ const tab = this.sinTab, q = this.q;
269+ for (let j = 0; j < np; j++) out[off + j] = (this.w * j) / (np - 1);
270+ for (let n = 0; n < N; n++) {
271+ const qn = q[n];
272+ if (qn === 0) continue;
273+ const o = n * np;
274+ for (let j = 1; j < np - 1; j++) out[off + j] += qn * tab[o + j];
275+ }
276+ }
277+ energy(): number {
278+ const { N, q, qp, a } = this;
279+ let s = 0;
280+ for (let n = 0; n < N; n++) { const v = q[n] - qp[n]; s += v * v + a[n] * q[n] * q[n]; }
281+ return ((this.mu * this.L) / 4) * s / this.k2;
282+ }
202283 }
203284
204285 class FDPol implements StringPol {
@@ -276,6 +357,20 @@ class FDPol implements StringPol {
276357 this.wPrev = this.w; this.w = wNext;
277358 }
278359
360+ sample(np: number, out: Float32Array, off: number): void {
361+ const { u, N } = this;
362+ for (let j = 0; j < np; j++) {
363+ const xl = (j * N) / (np - 1), l0 = Math.min(N - 1, Math.floor(xl)), fr = xl - l0;
364+ out[off + j] = u[l0] * (1 - fr) + u[l0 + 1] * fr;
365+ }
366+ }
367+ energy(): number {
368+ const { u, up, N, h, k } = this;
369+ let ke = 0, pe = 0;
370+ for (let l = 0; l <= N; l++) { const v = u[l] - up[l]; ke += v * v; }
371+ for (let l = 0; l < N; l++) { const d = u[l + 1] - u[l]; pe += d * d; }
372+ return (0.5 * this.mu * h * ke) / (k * k) + (0.5 * this.T * pe) / h;
373+ }
279374 uFinger(): number { let s = 0; for (let j = 0; j < this.fIdxN; j++) { const l = this.fIdx[j]; s += this.fwt[l] * this.u[l]; } return s; }
280375 uFingerPrev(): number { let s = 0; for (let j = 0; j < this.fIdxN; j++) { const l = this.fIdx[j]; s += this.fwt[l] * this.up[l]; } return s; }
281376 e2(): number {
@@ -320,7 +415,8 @@ export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderRes
320415 const preRoll = o.preRoll ?? 0.004;
321416
322417 // ---- body
323- const bm = thinModes(body.modes.filter((m) => m.f > 0 && m.f < 0.45 * fsi), p.engine.bodyOverlap);
418+ const srcModes: TaggedMode[] = o.record ? body.modes.map((m, i) => ({ ...m, src: i })) : body.modes;
419+ const bm = thinModes(srcModes.filter((m) => m.f > 0 && m.f < 0.45 * fsi), p.engine.bodyOverlap);
324420 const M = bm.length;
325421 const bA = new Float64Array(M), bOm = new Float64Array(M), bInv = new Float64Array(M);
326422 const rr = new Float64Array(M), ri = new Float64Array(M);
@@ -416,6 +512,9 @@ export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderRes
416512 const dTs = new Float64Array(N_STRINGS);
417513 let cur = eta, prev = etaP, next = etaN;
418514 let lastProg = 0;
515+ const rec = o.record
516+ ? new Recorder(o.record, { k, maxSteps, bm, bA, pols, polDir, active, Ls, played: fing.string })
517+ : null;
419518
420519 for (let step = 0; step < maxSteps; step++) {
421520 const t = step * k;
@@ -485,6 +584,7 @@ export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderRes
485584 const pk = -pick * pickScale;
486585 for (let c = 0; c < C; c++) pols[c].post(wN[c]);
487586 const tmp = prev; prev = cur; cur = next; next = tmp;
587+ if (rec) rec.step(step, Fy, Fz, fc, pr, pk, cur, prev, relStep >= 0 ? tRel : -1);
488588
489589 // output: keep a ring of the last preSteps samples until the release, then record
490590 if (relStep < 0) { ring[ringPos] = pr; ring2[ringPos] = pk; ringPos = (ringPos + 1) % (preSteps + 1); }
@@ -514,6 +614,10 @@ export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderRes
514614 stickTime: tRel,
515615 elapsed: (performance.now() - t0) / 1000,
516616 modeCounts: { strings: strModeCounts, body: M },
617+ recording: rec?.finish({
618+ tRelease: tRel, slipTime: slip, releaseForce: fRel, audioT0: relStep >= 0 ? (relStep - preSteps) * k : 0,
619+ pull: { dirY, dirZ, speed: p.pluck.pullSpeed, x: finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0), padWidth: p.pluck.padWidth },
620+ }),
517621 };
518622 }
519623
@@ -581,10 +685,10 @@ function cloneForTuning(p: Params): Params {
581685 * band's mean bridge admittance (sum of b^2) and radiated power (sum of b^2 rad^2), and leaves the
582686 * overlap at about `target`, so the response stays smooth. target <= 0 keeps every mode.
583687 */
584-export function thinModes(modes: BodyMode[], target: number): BodyMode[] {
688+export function thinModes<T extends TaggedMode>(modes: T[], target: number): T[] {
585689 if (!(target > 0)) return modes;
586690 const sorted = [...modes].sort((a, b) => a.f - b.f);
587- const out: BodyMode[] = [];
691+ const out: T[] = [];
588692 let i = 0;
589693 while (i < sorted.length) {
590694 const f0 = sorted[i].f, f1 = f0 * Math.pow(2, 1 / 6);
@@ -600,7 +704,7 @@ export function thinModes(modes: BodyMode[], target: number): BodyMode[] {
600704 const g = Math.sqrt(k);
601705 for (let q = Math.floor(k / 2); q < band.length; q += k) {
602706 const m = band[q];
603- out.push({ ...m, by: m.by.map((v) => v * g), bz: m.bz.map((v) => v * g) });
707+ out.push({ ...m, by: m.by.map((v) => v * g), bz: m.bz.map((v) => v * g), thin: g });
604708 }
605709 }
606710 i = j;
@@ -608,6 +712,123 @@ export function thinModes(modes: BodyMode[], target: number): BodyMode[] {
608712 return out;
609713 }
610714
715+/** A body mode as the engine uses it: its index in the body model, and the thinning gain. */
716+type TaggedMode = BodyMode & { src?: number; thin?: number };
717+
718+interface RecorderEnv { k: number; maxSteps: number; bm: TaggedMode[]; bA: Float64Array; pols: StringPol[]; polDir: number[]; active: number[]; Ls: number[]; played: number }
719+
720+/** Collects the frames and channels of a Recording during renderNote. */
721+class Recorder {
722+ private ch: Record<Channel, Float32Array>;
723+ private frames: Float32Array[] = [];
724+ private times: number[] = [];
725+ private nSteps = 0;
726+ private nDense = 0;
727+ private denseStart = -1;
728+ private denseLast = -1;
729+ private nextSparse = 0;
730+ private readonly F: number;
731+ private readonly strings: Recording["strings"] = [];
732+ private readonly notchOffset: number;
733+ private readonly etaOffset: number;
734+ private readonly etaIdx: Int32Array; // engine mode index of each recorded coordinate
735+ private readonly etaModes: Int32Array;
736+ private readonly etaGain: Float32Array;
737+ private readonly BY: Float64Array; private readonly BZ: Float64Array; // M x 4
738+ private readonly air: Float64Array; // per engine mode
739+ private readonly spec: RecordSpec;
740+ private readonly e: RecorderEnv;
741+ constructor(spec: RecordSpec, e: RecorderEnv) {
742+ this.spec = spec; this.e = e;
743+ this.ch = Object.fromEntries(CHANNELS.map((c) => [c, new Float32Array(e.maxSteps)])) as Record<Channel, Float32Array>;
744+ let off = 0;
745+ for (const si of e.active) {
746+ const played = si === e.played;
747+ const points = played ? spec.stringPoints : spec.sympPoints;
748+ this.strings.push({ string: si, length: e.Ls[si], points, offset: off, played });
749+ off += 2 * points;
750+ }
751+ this.notchOffset = off; off += 8;
752+ this.etaOffset = off;
753+ const idx: number[] = [];
754+ e.bm.forEach((m, j) => { if (m.src !== undefined && m.src < spec.shapeModes) idx.push(j); });
755+ this.etaIdx = Int32Array.from(idx);
756+ this.etaModes = Int32Array.from(idx, (j) => e.bm[j].src!);
757+ this.etaGain = Float32Array.from(idx, (j) => e.bm[j].thin ?? 1);
758+ this.F = off + idx.length;
759+ const M = e.bm.length;
760+ this.BY = new Float64Array(M * 4); this.BZ = new Float64Array(M * 4); this.air = new Float64Array(M);
761+ e.bm.forEach((m, j) => {
762+ for (let i = 0; i < 4; i++) { this.BY[j * 4 + i] = m.by[i]; this.BZ[j * 4 + i] = m.bz[i]; }
763+ const src = m.src ?? -1;
764+ this.air[j] = spec.airFrac && src >= 0 && src < spec.airFrac.length ? spec.airFrac[src] : m.label === "A0" ? 1 : 0;
765+ });
766+ }
767+
768+ step(n: number, Fy: number, Fz: number, fc: Float64Array, pr: number, pk: number, cur: Float64Array, prev: Float64Array, tRel: number): void {
769+ const { k, pols, polDir, bA } = this.e;
770+ const ch = this.ch, k2 = k * k;
771+ ch.fingerFy[n] = Fy; ch.fingerFz[n] = Fz;
772+ let by = 0, bz = 0;
773+ for (let c = 0; c < fc.length; c++) { if (polDir[c] === 0) by -= fc[c]; else bz -= fc[c]; }
774+ ch.bridgeFy[n] = by / k2; ch.bridgeFz[n] = bz / k2;
775+ let eS = 0, eY = 0;
776+ for (let c = 0; c < pols.length; c++) { const en = pols[c].energy(); if (c < 2) eS += en; else eY += en; }
777+ ch.eString[n] = eS; ch.eSymp[n] = eY;
778+ let eB = 0, eA = 0;
779+ for (let m = 0; m < cur.length; m++) {
780+ const v = cur[m] - prev[m];
781+ const en = (0.5 * (v * v + bA[m] * cur[m] * cur[m])) / k2;
782+ const a = this.air[m];
783+ eA += a * en; eB += (1 - a) * en;
784+ }
785+ ch.eBody[n] = eB; ch.eAir[n] = eA;
786+ ch.mic[n] = pr; ch.pickup[n] = pk;
787+ this.nSteps = n + 1;
788+ // frames: the state after this step, at t = (n + 1) k
789+ const t = (n + 1) * k, sp = this.spec;
790+ const denseTo = Number.isFinite(sp.denseTo) ? sp.denseTo : tRel >= 0 ? tRel + sp.denseAfterRelease : Infinity;
791+ const dense = t >= sp.denseFrom && t <= denseTo && this.nDense < sp.maxDense;
792+ if (dense || t >= this.nextSparse) {
793+ if (dense) { this.nDense++; if (this.denseStart < 0) this.denseStart = t; this.denseLast = t; }
794+ while (this.nextSparse <= t) this.nextSparse += sp.sparseDt;
795+ this.capture(t, cur);
796+ }
797+ }
798+
799+ private capture(t: number, eta: Float64Array): void {
800+ const f = new Float32Array(this.F);
801+ const { pols } = this.e;
802+ this.strings.forEach((s, a) => {
803+ pols[2 * a].sample(s.points, f, s.offset);
804+ pols[2 * a + 1].sample(s.points, f, s.offset + s.points);
805+ });
806+ const M = eta.length, o = this.notchOffset;
807+ for (let m = 0; m < M; m++) {
808+ const v = eta[m];
809+ if (v === 0) continue;
810+ for (let i = 0; i < 4; i++) { f[o + i] += this.BY[m * 4 + i] * v; f[o + 4 + i] += this.BZ[m * 4 + i] * v; }
811+ }
812+ for (let q = 0; q < this.etaIdx.length; q++) f[this.etaOffset + q] = eta[this.etaIdx[q]] * this.etaGain[q];
813+ this.frames.push(f);
814+ this.times.push(t);
815+ }
816+
817+ finish(x: Pick<Recording, "tRelease" | "slipTime" | "releaseForce" | "audioT0" | "pull">): Recording {
818+ const n = this.nSteps;
819+ const channels = Object.fromEntries(CHANNELS.map((c) => [c, this.ch[c].slice(0, n)])) as Record<Channel, Float32Array>;
820+ const frames = new Float32Array(this.frames.length * this.F);
821+ this.frames.forEach((f, i) => frames.set(f, i * this.F));
822+ return {
823+ dt: this.e.k, nSteps: n, channels,
824+ frameTimes: Float64Array.from(this.times), frames, frameSize: this.F,
825+ strings: this.strings, notchOffset: this.notchOffset, etaOffset: this.etaOffset, etaModes: this.etaModes,
826+ dense: [this.denseStart, this.denseLast],
827+ ...x,
828+ };
829+ }
830+}
831+
611832 /** The output: micMix * mic + pickupMix * pickup (with its trim), times the output gain. */
612833 export function mixOutput(p: Params, mic: Float32Array, pickup: Float32Array): Float32Array {
613834 const g = Math.pow(10, p.output.gainDb / 20);
src/fe/index.tsmodified+52−1View file
@@ -23,6 +23,7 @@ import { HOLE, makeArch, makeBodyGrid, makeFHoles, makeOutline, markFHoles, node
2323 import { buildStructure, modeInfo, GROUP_NAMES } from "./structure.ts";
2424 import { buildCavity, cavityModes, makePlug, surfaceStencil } from "./air.ts";
2525 import { solveCoupled } from "./coupling.ts";
26+import type { FEShapes } from "./shapes.ts";
2627
2728 export type { FEExtra } from "./structure.ts";
2829
@@ -30,7 +31,8 @@ const AIR_MU = 1.81e-5;
3031
3132 const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
3233
33-export function computeFEBody(p: Params, onProgress?: (msg: string, frac: number) => void): BodyModel {
34+/** opts.shapes: also compute the mode shapes for the 3D view (FEShapes) and hand them over. */
35+export function computeFEBody(p: Params, onProgress?: (msg: string, frac: number) => void, opts: { shapes?: (s: FEShapes) => void } = {}): BodyModel {
3436 const fe = p.fe;
3537 const T0 = now();
3638 const timings: Record<string, number> = {};
@@ -245,6 +247,7 @@ export function computeFEBody(p: Params, onProgress?: (msg: string, frac: number
245247 const modes: BodyMode[] = [];
246248 const diag: { f: number; ke: number[]; pe: number[]; zParts: number[] }[] = [];
247249 const nc = cr.nc;
250+ const kept: number[] = [];
248251 let dropped = 0;
249252 for (let k = 0; k < nc; k++) {
250253 const w2 = cr.omega2[k];
@@ -330,6 +333,7 @@ export function computeFEBody(p: Params, onProgress?: (msg: string, frac: number
330333 const zRad = Math.max(0, (rho0 * w * (1 + gk) * pw) / (8 * Math.PI * c0));
331334 const zeta = zMat + zVisc + zRad;
332335 modes.push({ f, zeta, by, bz, radRe: pRe, radIm: pIm });
336+ kept.push(k);
333337 diag.push({ f, ke: [keG[0], keG[1], keG[2], kePlug, keAir], pe: [...peG, peAir], zParts: [zMat, zVisc, zRad] });
334338 }
335339 // labels
@@ -359,6 +363,53 @@ export function computeFEBody(p: Params, onProgress?: (msg: string, frac: number
359363 lap("modes");
360364 const nFE = modes.length;
361365
366+ // ---------------------------------------------------------------- mode shapes for the 3D view
367+ if (opts.shapes) {
368+ prog("mode shapes", 0.95);
369+ const nCols = cav.nCols, kz = Math.floor(cav.nz / 2);
370+ const top = new Float32Array(nFE * nTop), back = new Float32Array(nFE * nBack);
371+ const air = new Float32Array(nFE * nCols), plug = new Float32Array(nFE * np);
372+ const Pj = new Float64Array(na);
373+ const tt = new Float64Array(nTop), bb = new Float64Array(nBack);
374+ for (let q = 0; q < nFE; q++) {
375+ const y = cr.Y.subarray(kept[q] * nc, (kept[q] + 1) * nc);
376+ tt.fill(0); bb.fill(0);
377+ for (let m = 0; m < ns; m++) {
378+ const e = y[m];
379+ if (e === 0) continue;
380+ const ot = m * nTop, ob = m * nBack;
381+ for (let a = 0; a < nTop; a++) tt[a] += e * Wt[ot + a];
382+ for (let a = 0; a < nBack; a++) bb[a] += e * Wb[ob + a];
383+ }
384+ top.set(tt, q * nTop); back.set(bb, q * nBack);
385+ // cavity pressure P_j = -D_j (S_j^T eta - r_j), r_j = Y_r omega_j / sqrt(D_j) (0 for the static mode)
386+ for (let j = 0; j < na; j++) {
387+ let sv = 0;
388+ for (let m = 0; m < nm; m++) sv += Smat[m * na + j] * y[m];
389+ Pj[j] = -Dj[j] * sv;
390+ }
391+ for (let r = 0; r < cr.rj.length; r++) { const j = cr.rj[r]; Pj[j] += Dj[j] * (y[nm + r] * am.omega[j]) / Math.sqrt(Dj[j]); }
392+ for (let c = 0; c < nCols; c++) {
393+ let v = 0;
394+ const cell = c * cav.nz + kz;
395+ for (let j = 0; j < na; j++) v += Pj[j] * am.psi[j][cell];
396+ air[q * nCols + c] = v;
397+ }
398+ for (let qq = 0; qq < np; qq++) plug[q * np + qq] = y[ns + qq] / Math.sqrt(plugs[qq].mp);
399+ }
400+ opts.shapes({
401+ feKey: feInputsKey(p),
402+ nModes: nFE,
403+ grid: { nx: g.nx, ns: g.ns, h: g.h, x0: g.x0, s0: g.s0 },
404+ topNodes: Int32Array.from(topNodes),
405+ backNodes: Int32Array.from(backNodes),
406+ cav: { nxA: cav.nxA, nsA: cav.nsA, x0: cav.x0, s0: cav.s0, ha: cav.ha, col: Int32Array.from(cav.col), colH: Float32Array.from(cav.colH) },
407+ plugs: plugs.map((pl) => ({ xc: pl.fh.xc, sc: pl.fh.sc, tilt: pl.fh.tilt, length: pl.fh.length, width: pl.fh.width })),
408+ top, back, air, plug,
409+ });
410+ lap("shapes");
411+ }
412+
362413 // ---------------------------------------------------------------- statistical continuation
363414 let nStat = 0;
364415 let statInfo: Record<string, number> = {};
src/fe/shapes.tsadded+76−0View file
@@ -0,0 +1,76 @@
1+// Mode shapes of the FE body for the 3D view: for each FE (coupled) mode, the normal displacement
2+// of the top and back plate nodes, the cavity pressure on the mid-depth layer of air cells and the
3+// displacement of the f-hole air plugs, all per unit modal coordinate (mass-normalised, like
4+// BodyMode.by). They line up with the first nModes entries of BodyModel.modes.
5+//
6+// Binary form (for shipping the default body's shapes): a 4-byte header length, a JSON header,
7+// padding to 4 bytes, then the arrays. The plate and air fields are quantised to int8 per mode
8+// (one scale for both plates, one for the air), which is plenty for a picture.
9+
10+export interface FEShapes {
11+ feKey: string;
12+ nModes: number;
13+ /** the plate grid: node k = i * ns + j at x = x0 + i h, s = s0 + j h */
14+ grid: { nx: number; ns: number; h: number; x0: number; s0: number };
15+ topNodes: Int32Array;
16+ backNodes: Int32Array;
17+ /** air cells: horizontal cell (i * nsA + j) -> column or -1; column height (top surface z) */
18+ cav: { nxA: number; nsA: number; x0: number; s0: number; ha: number; col: Int32Array; colH: Float32Array };
19+ plugs: { xc: number; sc: number; tilt: number; length: number; width: number }[];
20+ /** nModes x nTop, nModes x nBack (m per unit eta, +z up), nModes x nCols (Pa per unit eta), nModes x nPlugs (m, outward) */
21+ top: Float32Array;
22+ back: Float32Array;
23+ air: Float32Array;
24+ plug: Float32Array;
25+}
26+
27+export function encodeShapes(s: FEShapes): Uint8Array {
28+ const nTop = s.topNodes.length, nBack = s.backNodes.length, nCols = s.cav.colH.length, np = s.plugs.length, n = s.nModes;
29+ const header = JSON.stringify({ v: 1, feKey: s.feKey, nModes: n, grid: s.grid, cav: { nxA: s.cav.nxA, nsA: s.cav.nsA, x0: s.cav.x0, s0: s.cav.s0, ha: s.cav.ha }, plugs: s.plugs, nTop, nBack, nCols });
30+ const hb = new TextEncoder().encode(header);
31+ const hLen = 4 + Math.ceil(hb.length / 4) * 4;
32+ const f32 = s.topNodes.length + s.backNodes.length + s.cav.col.length + nCols + 2 * n + n * np;
33+ const total = hLen + 4 * f32 + n * (nTop + nBack + nCols);
34+ const out = new Uint8Array(total);
35+ const dv = new DataView(out.buffer);
36+ dv.setUint32(0, hb.length, true);
37+ out.set(hb, 4);
38+ let o = hLen;
39+ const putI = (a: ArrayLike<number>) => { for (let i = 0; i < a.length; i++, o += 4) dv.setInt32(o, a[i], true); };
40+ const putF = (a: ArrayLike<number>) => { for (let i = 0; i < a.length; i++, o += 4) dv.setFloat32(o, a[i], true); };
41+ putI(s.topNodes); putI(s.backNodes); putI(s.cav.col); putF(s.cav.colH);
42+ const scP = new Float32Array(n), scA = new Float32Array(n);
43+ for (let m = 0; m < n; m++) {
44+ let mp = 0, ma = 0;
45+ for (let a = 0; a < nTop; a++) mp = Math.max(mp, Math.abs(s.top[m * nTop + a]));
46+ for (let a = 0; a < nBack; a++) mp = Math.max(mp, Math.abs(s.back[m * nBack + a]));
47+ for (let a = 0; a < nCols; a++) ma = Math.max(ma, Math.abs(s.air[m * nCols + a]));
48+ scP[m] = mp / 127; scA[m] = ma / 127;
49+ }
50+ putF(scP); putF(scA); putF(s.plug);
51+ const q = (v: number, sc: number) => (sc > 0 ? Math.max(-127, Math.min(127, Math.round(v / sc))) : 0);
52+ for (let m = 0; m < n; m++) for (let a = 0; a < nTop; a++) out[o++] = q(s.top[m * nTop + a], scP[m]) & 255;
53+ for (let m = 0; m < n; m++) for (let a = 0; a < nBack; a++) out[o++] = q(s.back[m * nBack + a], scP[m]) & 255;
54+ for (let m = 0; m < n; m++) for (let a = 0; a < nCols; a++) out[o++] = q(s.air[m * nCols + a], scA[m]) & 255;
55+ return out;
56+}
57+
58+export function decodeShapes(buf: ArrayBuffer): FEShapes {
59+ const dv = new DataView(buf);
60+ const hl = dv.getUint32(0, true);
61+ const h = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 4, hl)));
62+ let o = 4 + Math.ceil(hl / 4) * 4;
63+ const n = h.nModes as number, nTop = h.nTop as number, nBack = h.nBack as number, nCols = h.nCols as number, np = (h.plugs as unknown[]).length;
64+ const getI = (len: number) => { const a = new Int32Array(len); for (let i = 0; i < len; i++, o += 4) a[i] = dv.getInt32(o, true); return a; };
65+ const getF = (len: number) => { const a = new Float32Array(len); for (let i = 0; i < len; i++, o += 4) a[i] = dv.getFloat32(o, true); return a; };
66+ const topNodes = getI(nTop), backNodes = getI(nBack), col = getI(h.cav.nxA * h.cav.nsA), colH = getF(nCols);
67+ const scP = getF(n), scA = getF(n), plug = getF(n * np);
68+ const i8 = new Int8Array(buf);
69+ const deq = (len: number, sc: Float32Array) => {
70+ const a = new Float32Array(n * len);
71+ for (let m = 0; m < n; m++) for (let j = 0; j < len; j++) a[m * len + j] = i8[o++] * sc[m];
72+ return a;
73+ };
74+ const top = deq(nTop, scP), back = deq(nBack, scP), air = deq(nCols, scA);
75+ return { feKey: h.feKey, nModes: n, grid: h.grid, topNodes, backNodes, cav: { ...h.cav, col, colH }, plugs: h.plugs, top, back, air, plug };
76+}
vite.config.tsmodified+1−1View file
@@ -23,7 +23,7 @@ export default defineConfig({
2323 // the vault's site base path (set by configure-pages in the deploy workflow), "/" locally
2424 base: process.env.MOCHI_SITE_BASE_PATH || "/",
2525 plugins: [refSf2],
26- assetsInclude: ["**/*.sf2"],
26+ assetsInclude: ["**/*.sf2", "**/*.bin"],
2727 worker: { format: "es" },
2828 build: { target: "es2022" },
2929 });
↑↓ move↵openescclose