182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 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).
5import type { Params } from "../../core/params.ts";
6import type { BodyModel } from "../../core/types.ts";
7import { STRING_NAMES } from "../../core/types.ts";
8import type { Recording, RecordSpec } from "../../core/engine.ts";
9import { fingering, stringConst, stringModes } from "../../core/strings.ts";
10import { noteName } from "../../core/sf2.ts";
11import { decodeShapes, type FEShapes } from "../../fe/shapes.ts";
12import { BassScene, type Frame, type Scales, type StringSetup } from "./scene.ts";
13import { tracePlot, traceTimeAt } from "./traces.ts";
15export 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}
33interface 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}
53type Mode = { kind: "replay" } | { kind: "body"; idx: number } | { kind: "partial"; n: number };
55const 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"]];
56const WINDOWS: [string, string][] = [["all", "whole note"], ["dense", "pluck (detail window)"], ["50", "±50 ms"], ["5", "±5 ms"], ["0.5", "±0.5 ms"]];
57const MODE_HZ = 0.6; // display rate of a mode animation
59const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || "#888";
61export 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";
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 }
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; }
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 }
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 }
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 }
210 // ------------------------------------------------------------ data
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 }
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 }
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 }
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 }
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 }
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 }
358 private tEnd(): number { const R = this.rec?.R; return R ? R.nSteps * R.dt : 1; }
360 // ------------------------------------------------------------ transport
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 }
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 }
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 }
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 }
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 }
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 }
423 // ------------------------------------------------------------ per frame
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 }
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 }
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 }
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 }
570 // ------------------------------------------------------------ mode explorer
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 }
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}
616function fmtX(v: number): string { return v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toPrecision(2); }
617function 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`; }
618function fmtP(p: number): string { return p >= 1 ? `${p.toPrecision(2)} Pa` : `${(p * 1e3).toPrecision(2)} mPa`; }