1import { renderControls, type Section } from './controls';
2import { LinePlot, css, fmtNum, type Marker } from './plot';
3import { Spectrogram } from './spectrogram';
4import { spectrum } from './fft';
5import { encodeWav } from './wav';
6import { BeadScene, type SceneSpec } from './scene3d';
7import { Timeline } from './timeline';
8import { timeStep } from '../sim/solver';
9import { runInWorker } from '../sim/run';
10import { checkPasscode, getPasscode, loadResult, probeResult, resultKey, setPasscode, storeResult, type Backend } from '../sim/cache';
11import type { BeadSystem, Excitation, SimResult } from '../sim/types';
13// The page every instrument shares: presets and control panel, 3D model,
14// setup summary, run summary, audio, waveform, spectrogram, spectrum, energy.
15// An instrument adds its own setup rows, extra result cards and views.
17export interface SimParams {
18 duration: number;
19 fs: number;
20 cfl: number;
21 frameRate: number;
22}
24export interface Built {
25 sys: BeadSystem;
26 exc: Excitation;
27 pickup: Float64Array;
28 pickupDelay?: Float64Array; // per bead, in samples (a microphone)
29 scene: SceneSpec;
30}
32export interface Preset<P> {
33 name: string;
34 description: string;
35 params: P;
36}
38export interface Extras<P> {
39 show(p: P, built: Built, r: SimResult): void;
40}
42export interface InstrumentConfig<P extends SimParams> {
43 title: string;
44 wavName: string;
45 audioQuantity?: { label: string; unit: string }; // default: acceleration, m/s²
46 presets: Preset<P>[];
47 sections: Section<P>[];
48 // WebGPU on by default (default true); off where the systems are too small to gain from it
49 webgpuDefault?: boolean;
50 // instrument-specific summary of the setup; built = null when the parameters are invalid
51 setup(p: P): { rows: [string, string][]; warnings: string[]; built: Built | null };
52 summaryRows?(p: P, built: Built, r: SimResult): [string, string][];
53 spectrumMarkers?(p: P): { markers: Marker[]; legend: string };
54 extraCards?: string; // cards with data-r="out" hidden, shown after a run
55 mountExtras?(q: <T extends HTMLElement>(r: string) => T, timeline: Timeline): Extras<P>;
56}
58const statRows = (rows: [string, string][]) => rows.map(([k, v]) => `<div><span>${k}</span><b>${v}</b></div>`).join('');
60export function mountInstrumentPage<P extends SimParams>(root: HTMLElement, cfg: InstrumentConfig<P>) {
61 root.innerHTML = `
62 <div class="instrument">
63 <aside class="panel">
64 <a href="#/" class="back">← All instruments</a>
65 <h1>${cfg.title}</h1>
66 <label class="ctl preset"><span class="ctl-name">Preset</span><select data-r="preset"></select></label>
67 <p class="sub" data-r="preset-desc"></p>
68 <div class="run-row top">
69 <button class="btn" data-r="run">Run simulation</button>
70 <button class="btn-small" data-r="cancel" hidden>Cancel</button>
71 <button class="btn-small" data-r="load-cached" hidden>Load cached</button>
72 <label class="inline gpu-toggle" data-r="gpu-label"><input type="checkbox" data-r="gpu"> WebGPU</label>
73 </div>
74 <p class="note" data-r="cached-avail" hidden></p>
75 <progress data-r="progress" max="1" value="0" hidden></progress>
76 <p class="error" data-r="error" hidden></p>
77 <details class="cache-ctl">
78 <summary data-r="cache-state"></summary>
79 <p class="note">Results are shared: when someone has already computed a run with these settings, you can load it instead of running it again. With the passcode, this browser also stores its runs there.</p>
80 <div class="cache-form"><input type="password" data-r="cache-pass" placeholder="Passcode" autocomplete="off"><button class="btn-small" data-r="cache-save">Save</button><button class="btn-small" data-r="cache-forget">Forget</button></div>
81 <p class="note" data-r="cache-msg"></p>
82 </details>
83 <div data-r="controls"></div>
84 </aside>
85 <main class="results">
86 <section class="card"><h2>Model</h2><div data-r="scene"></div></section>
87 <section class="card"><h2>Setup</h2><div data-r="derived" class="stats"></div><ul data-r="warnings" class="warnings"></ul></section>
88 <section class="card" data-r="out" hidden>
89 <h2>Run</h2><div data-r="summary" class="stats"></div>
90 <p class="note" data-r="cache-note"></p>
91 <div class="audio-row"><audio controls data-r="audio"></audio><a class="btn-small" data-r="download" download="${cfg.wavName}">Download .wav</a></div>
92 <p class="note" data-r="audio-note"></p>
93 </section>
94 <section class="card" data-r="out" hidden>
95 <div class="card-head"><h2>${cap((cfg.audioQuantity ?? { label: 'pickup acceleration' }).label)}</h2>
96 <div class="seg" data-r="wave-range"><button data-v="0" class="on">Full</button><button data-v="0.05">First 50 ms</button><button data-v="0.005">First 5 ms</button></div></div>
97 <div class="canvas-wrap"><canvas data-r="wave"></canvas></div>
98 </section>
99 <section class="card" data-r="out" hidden>
100 <div class="card-head"><h2>Spectrogram</h2>
101 <label class="inline">up to <select data-r="fmax"><option>1000</option><option>2500</option><option selected>5000</option><option>10000</option><option>24000</option></select> Hz</label></div>
102 <div class="canvas-wrap tall"><canvas data-r="spec"></canvas></div>
103 </section>
104 <section class="card" data-r="out" hidden>
105 <div class="card-head"><h2>Spectrum</h2><div class="legend" data-r="spec-legend"></div></div>
106 <div class="canvas-wrap"><canvas data-r="spectrum"></canvas></div>
107 </section>
108 ${cfg.extraCards ?? ''}
109 <section class="card" data-r="out-contact" hidden>
110 <h2>Contact force</h2>
111 <div class="canvas-wrap short"><canvas data-r="contact"></canvas></div>
112 <p class="note" data-r="contact-note"></p>
113 </section>
114 <section class="card" data-r="out" hidden>
115 <h2>Energy</h2>
116 <div class="canvas-wrap short"><canvas data-r="energy"></canvas></div>
117 <p class="note">Kinetic plus spring energy of the instrument, minus the energy stored by pre-tension at equilibrium. Without damping or forcing it stays flat; the run summary gives the error of the energy balance (energy + dissipated − work in − initial, mallet included).</p>
118 </section>
119 </main>
120 </div>`;
121 const q = <T extends HTMLElement>(r: string) => root.querySelector(`[data-r="${r}"]`) as T;
122 const presetSel = q<HTMLSelectElement>('preset');
123 cfg.presets.forEach((p, i) => presetSel.add(new Option(p.name, String(i))));
124 const presetDesc = q<HTMLParagraphElement>('preset-desc');
125 const runBtn = q<HTMLButtonElement>('run');
126 const cancelBtn = q<HTMLButtonElement>('cancel');
127 const progress = q<HTMLProgressElement>('progress');
128 const errorBox = q<HTMLParagraphElement>('error');
129 const gpuBox = q<HTMLInputElement>('gpu');
130 const loadBtn = q<HTMLButtonElement>('load-cached');
131 const availNote = q<HTMLParagraphElement>('cached-avail');
132 const cacheNote = q<HTMLParagraphElement>('cache-note');
133 const instrumentId = cfg.wavName.replace(/\.wav$/, ''); // e.g. bead-cymbal
134 const hasGpu = 'gpu' in navigator;
135 const gpuKey = `toy-instruments.webgpu.${cfg.wavName}`;
136 let gpuPref: string | null = null;
137 try {
138 gpuPref = localStorage.getItem(gpuKey);
139 } catch {
140 /* storage unavailable */
141 }
142 gpuBox.checked = hasGpu && (gpuPref ? gpuPref === 'on' : cfg.webgpuDefault !== false);
143 gpuBox.disabled = !hasGpu;
144 q('gpu-label').title = hasGpu
145 ? 'Run the solver on the GPU (single precision). Faster for meshes of a few hundred beads or more; slower for small systems. Falls back to the CPU if the GPU cannot run it.'
146 : 'This browser does not offer WebGPU; the solver runs on the CPU.';
147 gpuBox.addEventListener('change', () => {
148 try {
149 localStorage.setItem(gpuKey, gpuBox.checked ? 'on' : 'off');
150 } catch {
151 /* storage unavailable */
152 }
153 checkCache();
154 });
156 const wave = new LinePlot(q('wave'));
157 const spec = new Spectrogram(q('spec'));
158 const specPlot = new LinePlot(q('spectrum'));
159 const energyPlot = new LinePlot(q('energy'));
160 const contactPlot = new LinePlot(q('contact'));
161 const quantity = cfg.audioQuantity ?? { label: 'acceleration', unit: 'm/s²' };
162 const timeline = new Timeline();
163 const scene = new BeadScene(q('scene'), timeline);
164 const extras = cfg.mountExtras?.(q, timeline);
165 let waveRange = 0;
166 let last: { p: P; r: SimResult } | null = null;
167 let cancelRun: (() => void) | null = null; // set while a run (or a cache download) is in progress
168 // the cached result for the current settings, if there is one
169 let cached: { p: P; built: Built; key: string; stored?: Date } | null = null;
170 let probeSeq = 0;
171 let probeTimer = 0;
172 let audioUrl: string | null = null;
174 const controls = renderControls(q('controls'), cfg.sections, cfg.presets[0].params, () => updateSetup());
175 presetDesc.textContent = cfg.presets[0].description;
176 presetSel.addEventListener('change', () => {
177 const pr = cfg.presets[Number(presetSel.value)];
178 presetDesc.textContent = pr.description;
179 controls.set(pr.params);
180 });
182 function updateSetup() {
183 const p = controls.get();
184 const { rows, warnings, built } = cfg.setup(p);
185 if (built) {
186 scene.showSetup(built.scene);
187 const { omegaMax: wmax, stepsPerSample: spp } = timeStep(built.sys, built.exc.mallet, p.fs, p.cfl);
188 rows.push(['Highest frequency', `${fmtNum(wmax / (2 * Math.PI))} Hz`]);
189 rows.push(['Time step', `${fmtNum(1 / (p.fs * spp))} s (${spp} per sample)`]);
190 // a bending hinge costs about four springs
191 const elements = built.sys.si.length + 4 * (built.sys.bending?.w0.length ?? 0);
192 const work = spp * p.fs * p.duration * elements;
193 rows.push(['Element updates', fmtNum(work)]);
194 const frameMB = (Math.round(p.duration * p.frameRate) * 3 * built.sys.n * 4) / 1e6;
195 if (frameMB > 400) warnings.push(`Replay frames would take ${fmtNum(frameMB)} MB; lower the replay frame rate or the duration.`);
196 if (work > 3e9) warnings.push(`This run is large (${fmtNum(work)} element updates): expect roughly ${fmtNum(work / 2.2e7 / 60)} min on a desktop CPU (WebGPU is usually much faster).`);
197 }
198 q('derived').innerHTML = statRows(rows);
199 q('warnings').innerHTML = warnings.map((w) => `<li>${w}</li>`).join('');
200 runBtn.disabled = !built || !!cancelRun;
201 checkCache();
202 }
204 // what the solver gets for parameters p; null when they are invalid
205 function inputs(p: P) {
206 const { built } = cfg.setup(p);
207 if (!built) return null;
208 const opt = { duration: p.duration, fs: p.fs, cfl: p.cfl, frameRate: p.frameRate, pickup: built.pickup, pickupDelay: built.pickupDelay };
209 return { built, opt, backend: (gpuBox.checked ? 'gpu' : 'cpu') as Backend };
210 }
212 // Look up (debounced) whether the shared cache has a result for the current settings,
213 // and offer to load it next to Run.
214 function checkCache() {
215 const seq = ++probeSeq;
216 cached = null;
217 loadBtn.hidden = availNote.hidden = true;
218 clearTimeout(probeTimer);
219 probeTimer = window.setTimeout(async () => {
220 const p = controls.get();
221 const inp = inputs(p);
222 if (!inp) return;
223 try {
224 const key = await resultKey(instrumentId, inp.built.sys, inp.built.exc, inp.opt, inp.backend);
225 const hit = await probeResult(key);
226 if (seq !== probeSeq || !hit) return;
227 cached = { p, built: inp.built, key, stored: hit.stored };
228 const when = hit.stored ? `computed ${hit.stored.toISOString().slice(0, 10)}, ` : '';
229 availNote.textContent = `A cached result exists for these settings (${when}${fmtNum(hit.bytes / 1e6)} MB). Load it, or run the simulation again.`;
230 loadBtn.hidden = availNote.hidden = false;
231 loadBtn.disabled = !!cancelRun;
232 } catch {
233 /* cache unreachable: just don't offer it */
234 }
235 }, 250);
236 }
237 updateSetup();
239 q('wave-range').addEventListener('click', (e) => {
240 const b = (e.target as HTMLElement).closest('button');
241 if (!b) return;
242 waveRange = Number(b.dataset.v);
243 q('wave-range').querySelectorAll('button').forEach((x) => x.classList.toggle('on', x === b));
244 drawWave();
245 });
246 q<HTMLSelectElement>('fmax').addEventListener('change', (e) => {
247 spec.fmax = Number((e.target as HTMLSelectElement).value);
248 spec.draw();
249 drawSpectrum();
250 });
252 function drawWave() {
253 if (!last) return;
254 const { r } = last;
255 const t = new Float64Array(r.audio.length);
256 for (let i = 0; i < t.length; i++) t[i] = i / r.fs;
257 wave.set([{ x: t, y: r.audio, color: css('--series-1'), label: 'a' }], {
258 xLabel: 'time (s)',
259 yLabel: `${quantity.label} (${quantity.unit})`,
260 xRange: waveRange ? [0, Math.min(waveRange, t[t.length - 1])] : undefined,
261 });
262 }
264 function drawSpectrum() {
265 if (!last) return;
266 const { p, r } = last;
267 const s = spectrum(r.audio, r.fs);
268 let top = -Infinity;
269 for (const v of s.db) top = Math.max(top, v);
270 const db = s.db.map((v) => Math.max(v - top, -100));
271 const m = cfg.spectrumMarkers?.(p);
272 q('spec-legend').innerHTML =
273 `<span><i class="sw" style="background:var(--series-1)"></i>pickup signal</span>` + (m?.legend ?? '');
274 specPlot.set([{ x: s.freq, y: db, color: css('--series-1'), label: 'level (dB)' }], {
275 xLabel: 'frequency (Hz)',
276 yLabel: 'level (dB re max)',
277 xRange: [0, Math.min(spec.fmax, r.fs / 2)],
278 yRange: [-100, 5],
279 markers: m?.markers,
280 });
281 }
283 function show(p: P, built: Built, r: SimResult) {
284 last = { p, r };
285 cacheNote.textContent = '';
286 root.querySelectorAll<HTMLElement>('[data-r="out"]').forEach((e) => (e.hidden = false));
287 let peak = 0;
288 for (const v of r.audio) peak = Math.max(peak, Math.abs(v));
289 const emax = Math.max(...r.energy);
290 let bal = 0;
291 for (const b of r.balance) bal = Math.max(bal, Math.abs(b));
292 const rt = p.duration / r.wallSeconds;
293 q('summary').innerHTML = statRows([
294 ['Solver', (r.backend ?? 'CPU') + (r.fallback ? ` (WebGPU failed: ${r.fallback})` : '')],
295 ['Time step', `${fmtNum(r.dt)} s, ${r.stepsPerSample} per sample`],
296 ['Wall time', `${fmtNum(r.wallSeconds)} s (${rt >= 1 ? fmtNum(rt) + '× faster than' : fmtNum(1 / rt) + '× slower than'} real time)`],
297 ['Energy balance error', emax > 0 ? `${fmtNum((bal / emax) * 100)}% of peak energy` : '–'],
298 ...(cfg.summaryRows?.(p, built, r) ?? []),
299 ...contactRows(r),
300 [`Peak ${quantity.label}`, `${fmtNum(peak)} ${quantity.unit}`],
301 ]);
302 if (audioUrl) URL.revokeObjectURL(audioUrl);
303 audioUrl = URL.createObjectURL(encodeWav(r.audio, r.fs));
304 q<HTMLAudioElement>('audio').src = audioUrl;
305 q<HTMLAnchorElement>('download').href = audioUrl;
306 q('audio-note').textContent = `16-bit mono, ${r.fs} Hz, normalized so the peak is −1 dBFS.`;
307 drawWave();
308 spec.setSignal(r.audio, r.fs);
309 drawSpectrum();
310 timeline.setTimes(r.frameTimes);
311 scene.showReplay({ ...built.scene, frames: r.frames, malletPos: r.malletPos });
312 extras?.show(p, built, r);
313 showContact(r);
314 energyPlot.set([{ x: r.frameTimes, y: r.energy, color: css('--series-1'), label: 'energy (J)' }], {
315 xLabel: 'time (s)',
316 yLabel: 'energy (J)',
317 yRange: [0, emax * 1.05 || 1],
318 });
319 }
321 function showContact(r: SimResult) {
322 const card = q('out-contact');
323 card.hidden = !r.contactForce;
324 if (!r.contactForce) return;
325 const cf = r.contactForce;
326 const c = contacts(cf, r.fs);
327 const end = c.length ? c[c.length - 1].start + c[c.length - 1].ms / 1000 : 0.01;
328 const nShow = Math.min(cf.length, Math.ceil((end * 1.3 + 0.002) * r.fs));
329 const t = new Float64Array(nShow);
330 for (let i = 0; i < nShow; i++) t[i] = (i / r.fs) * 1000;
331 contactPlot.set([{ x: t, y: cf.subarray(0, nShow), color: css('--series-2'), label: 'force (N)' }], {
332 xLabel: 'time (ms)',
333 yLabel: 'contact force (N)',
334 yRange: [0, Math.max(...cf.subarray(0, nShow)) * 1.08 || 1],
335 });
336 q('contact-note').textContent = c.length
337 ? `${c.length} contact${c.length > 1 ? 's' : ''}: ` +
338 c.map((k) => `${fmtNum(k.ms)} ms from ${fmtNum(k.start * 1000)} ms, peak ${fmtNum(k.peak)} N`).join('; ') +
339 '. During contact the instrument takes energy from the mallet and gives part of it back as the mallet rebounds, so the energy plot can spike first; the mallet then leaves at constant speed (no gravity).'
340 : 'The mallet never touched the instrument.';
341 }
343 function setBusy(cancel: (() => void) | null) {
344 cancelRun = cancel;
345 runBtn.disabled = loadBtn.disabled = !!cancel;
346 cancelBtn.hidden = !cancel;
347 progress.hidden = !cancel;
348 progress.value = 0;
349 if (cancel) errorBox.hidden = true;
350 }
352 // Run the simulation and, if this browser has the passcode, store the result.
353 async function run() {
354 const p = controls.get();
355 const inp = inputs(p);
356 if (!inp) return;
357 const { built, opt, backend } = inp;
358 const running = runInWorker(built.sys, built.exc, opt, backend === 'gpu', (f) => (progress.value = f));
359 setBusy(running.cancel);
360 try {
361 const r = await running.promise;
362 show(p, built, r);
363 if (getPasscode()) {
364 // a WebGPU run that fell back to the CPU is stored as a CPU result
365 const actual: Backend = r.backend?.startsWith('WebGPU') ? 'gpu' : 'cpu';
366 const key = await resultKey(instrumentId, built.sys, built.exc, opt, actual);
367 cacheNote.textContent = 'Storing in the shared cache…';
368 storeResult(key, r, { instrument: instrumentId, backend: r.backend, wallSeconds: r.wallSeconds })
369 .then(() => {
370 if (last?.r === r) cacheNote.textContent = 'Stored in the shared cache.';
371 checkCache();
372 })
373 .catch((e) => {
374 if (last?.r === r) cacheNote.textContent = `Not stored in the shared cache: ${(e as Error).message}`;
375 });
376 }
377 } catch (e) {
378 if ((e as Error).message !== 'cancelled') {
379 errorBox.textContent = `The simulation failed: ${(e as Error).message}`;
380 errorBox.hidden = false;
381 }
382 } finally {
383 setBusy(null);
384 }
385 }
387 // Download and show the cached result for the current settings.
388 async function loadCached() {
389 if (!cached) return;
390 const { p, built, key } = cached;
391 const abort = new AbortController();
392 setBusy(() => abort.abort());
393 try {
394 const hit = await loadResult(key, (f) => (progress.value = f), abort.signal);
395 if (!hit) throw new Error('the entry is no longer in the cache');
396 show(p, built, hit.result);
397 const when = hit.stored ? ` on ${hit.stored.toISOString().slice(0, 10)}` : '';
398 cacheNote.textContent = `Loaded from the shared cache (computed${when}; the wall time is that of the original run).`;
399 } catch (e) {
400 if (!abort.signal.aborted) {
401 errorBox.textContent = `Could not load the cached result: ${(e as Error).message}`;
402 errorBox.hidden = false;
403 checkCache();
404 }
405 } finally {
406 setBusy(null);
407 }
408 }
409 runBtn.addEventListener('click', run);
410 loadBtn.addEventListener('click', loadCached);
411 cancelBtn.addEventListener('click', () => cancelRun?.());
413 // passcode for writing to the shared cache
414 const passInput = q<HTMLInputElement>('cache-pass');
415 const cacheMsg = q<HTMLParagraphElement>('cache-msg');
416 const showCacheState = () =>
417 (q('cache-state').textContent = getPasscode() ? 'Shared cache: runs are stored' : 'Shared cache: read only');
418 showCacheState();
419 q('cache-save').addEventListener('click', async () => {
420 const pass = passInput.value.trim();
421 if (!pass) return;
422 cacheMsg.textContent = 'Checking…';
423 try {
424 const { valid, reason } = await checkPasscode(pass);
425 if (!valid) {
426 cacheMsg.textContent = `Not saved: ${reason ?? 'invalid passcode'}.`;
427 return;
428 }
429 setPasscode(pass);
430 passInput.value = '';
431 cacheMsg.textContent = 'Saved in this browser. Runs from now on are stored in the cache.';
432 } catch (e) {
433 cacheMsg.textContent = `Could not check the passcode: ${(e as Error).message}`;
434 }
435 showCacheState();
436 });
437 q('cache-forget').addEventListener('click', () => {
438 setPasscode(null);
439 cacheMsg.textContent = 'Passcode removed from this browser.';
440 showCacheState();
441 });
442}
444// separate contact intervals in the contact-force record
445function contacts(cf: Float32Array, fs: number): { start: number; ms: number; peak: number }[] {
446 const out: { start: number; ms: number; peak: number }[] = [];
447 let i = 0;
448 while (i < cf.length) {
449 if (cf[i] > 0) {
450 const a = i;
451 let peak = 0;
452 while (i < cf.length && cf[i] > 0) peak = Math.max(peak, cf[i++]);
453 out.push({ start: a / fs, ms: ((i - a) / fs) * 1000, peak });
454 } else i++;
455 }
456 return out;
457}
459function contactRows(r: SimResult): [string, string][] {
460 if (!r.contactForce) return [];
461 const c = contacts(r.contactForce, r.fs);
462 return [
463 [
464 'Contact',
465 c.length
466 ? `${fmtNum(c[0].ms)} ms, peak ${fmtNum(c[0].peak)} N${c.length > 1 ? ` (+${c.length - 1} more contact${c.length > 2 ? 's' : ''})` : ''}`
467 : 'none',
468 ],
469 ];
470}
472const cap = (s: string) => s[0].toUpperCase() + s.slice(1);