/ proof-of-concept / toy-instruments
Sign in
proof-of-concept / toy-instruments
toy-instruments / src / ui / instrumentPage.ts
320 lines · 13.9 KBBlameHistoryRaw
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 { omegaMaxBound } from '../sim/solver';
9import { runInWorker, type Running } from '../sim/run';
10import type { BeadSystem, Excitation, SimResult } from '../sim/types';
12// The page every instrument shares: presets and control panel, 3D model,
13// setup summary, run summary, audio, waveform, spectrogram, spectrum, energy.
14// An instrument adds its own setup rows, extra result cards and views.
16export interface SimParams {
17 duration: number;
18 fs: number;
19 cfl: number;
20 frameRate: number;
23export interface Built {
24 sys: BeadSystem;
25 exc: Excitation;
26 pickup: Float64Array;
27 pickupDelay?: Float64Array; // per bead, in samples (a microphone)
28 scene: SceneSpec;
31export interface Preset<P> {
32 name: string;
33 description: string;
34 params: P;
37export interface Extras<P> {
38 show(p: P, built: Built, r: SimResult): void;
41export interface InstrumentConfig<P extends SimParams> {
42 title: string;
43 wavName: string;
44 audioQuantity?: { label: string; unit: string }; // default: acceleration, m/s²
45 presets: Preset<P>[];
46 sections: Section<P>[];
47 // instrument-specific summary of the setup; built = null when the parameters are invalid
48 setup(p: P): { rows: [string, string][]; warnings: string[]; built: Built | null };
49 summaryRows?(p: P, built: Built, r: SimResult): [string, string][];
50 spectrumMarkers?(p: P): { markers: Marker[]; legend: string };
51 extraCards?: string; // cards with data-r="out" hidden, shown after a run
52 mountExtras?(q: <T extends HTMLElement>(r: string) => T, timeline: Timeline): Extras<P>;
55const statRows = (rows: [string, string][]) => rows.map(([k, v]) => `<div><span>${k}</span><b>${v}</b></div>`).join('');
57export function mountInstrumentPage<P extends SimParams>(root: HTMLElement, cfg: InstrumentConfig<P>) {
58 root.innerHTML = `
59 <div class="instrument">
60 <aside class="panel">
61 <a href="#/" class="back">← All instruments</a>
62 <h1>${cfg.title}</h1>
63 <label class="ctl preset"><span class="ctl-name">Preset</span><select data-r="preset"></select></label>
64 <p class="sub" data-r="preset-desc"></p>
65 <div data-r="controls"></div>
66 <div class="run-row">
67 <button class="btn" data-r="run">Run simulation</button>
68 <button class="btn-small" data-r="cancel" hidden>Cancel</button>
69 </div>
70 <progress data-r="progress" max="1" value="0" hidden></progress>
71 <p class="error" data-r="error" hidden></p>
72 </aside>
73 <main class="results">
74 <section class="card"><h2>Model</h2><div data-r="scene"></div></section>
75 <section class="card"><h2>Setup</h2><div data-r="derived" class="stats"></div><ul data-r="warnings" class="warnings"></ul></section>
76 <section class="card" data-r="out" hidden>
77 <h2>Run</h2><div data-r="summary" class="stats"></div>
78 <div class="audio-row"><audio controls data-r="audio"></audio><a class="btn-small" data-r="download" download="${cfg.wavName}">Download .wav</a></div>
79 <p class="note" data-r="audio-note"></p>
80 </section>
81 <section class="card" data-r="out" hidden>
82 <div class="card-head"><h2>${cap((cfg.audioQuantity ?? { label: 'pickup acceleration' }).label)}</h2>
83 <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>
84 <div class="canvas-wrap"><canvas data-r="wave"></canvas></div>
85 </section>
86 <section class="card" data-r="out" hidden>
87 <div class="card-head"><h2>Spectrogram</h2>
88 <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>
89 <div class="canvas-wrap tall"><canvas data-r="spec"></canvas></div>
90 </section>
91 <section class="card" data-r="out" hidden>
92 <div class="card-head"><h2>Spectrum</h2><div class="legend" data-r="spec-legend"></div></div>
93 <div class="canvas-wrap"><canvas data-r="spectrum"></canvas></div>
94 </section>
95 ${cfg.extraCards ?? ''}
96 <section class="card" data-r="out-contact" hidden>
97 <h2>Contact force</h2>
98 <div class="canvas-wrap short"><canvas data-r="contact"></canvas></div>
99 <p class="note" data-r="contact-note"></p>
100 </section>
101 <section class="card" data-r="out" hidden>
102 <h2>Energy</h2>
103 <div class="canvas-wrap short"><canvas data-r="energy"></canvas></div>
104 <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>
105 </section>
106 </main>
107 </div>`;
108 const q = <T extends HTMLElement>(r: string) => root.querySelector(`[data-r="${r}"]`) as T;
109 const presetSel = q<HTMLSelectElement>('preset');
110 cfg.presets.forEach((p, i) => presetSel.add(new Option(p.name, String(i))));
111 const presetDesc = q<HTMLParagraphElement>('preset-desc');
112 const runBtn = q<HTMLButtonElement>('run');
113 const cancelBtn = q<HTMLButtonElement>('cancel');
114 const progress = q<HTMLProgressElement>('progress');
115 const errorBox = q<HTMLParagraphElement>('error');
117 const wave = new LinePlot(q('wave'));
118 const spec = new Spectrogram(q('spec'));
119 const specPlot = new LinePlot(q('spectrum'));
120 const energyPlot = new LinePlot(q('energy'));
121 const contactPlot = new LinePlot(q('contact'));
122 const quantity = cfg.audioQuantity ?? { label: 'acceleration', unit: 'm/s²' };
123 const timeline = new Timeline();
124 const scene = new BeadScene(q('scene'), timeline);
125 const extras = cfg.mountExtras?.(q, timeline);
126 let waveRange = 0;
127 let last: { p: P; r: SimResult } | null = null;
128 let running: Running | null = null;
129 let audioUrl: string | null = null;
131 const controls = renderControls(q('controls'), cfg.sections, cfg.presets[0].params, () => updateSetup());
132 presetDesc.textContent = cfg.presets[0].description;
133 presetSel.addEventListener('change', () => {
134 const pr = cfg.presets[Number(presetSel.value)];
135 presetDesc.textContent = pr.description;
136 controls.set(pr.params);
137 });
139 function updateSetup() {
140 const p = controls.get();
141 const { rows, warnings, built } = cfg.setup(p);
142 if (built) {
143 scene.showSetup(built.scene);
144 const wmax = omegaMaxBound(built.sys, built.exc.mallet);
145 const spp = Math.max(1, Math.ceil(1 / (p.fs * ((p.cfl * 2) / wmax))));
146 rows.push(['Highest frequency bound', `${fmtNum(wmax / (2 * Math.PI))} Hz`]);
147 rows.push(['Time step', `${fmtNum(1 / (p.fs * spp))} s (${spp} per sample)`]);
148 // a bending hinge costs about four springs
149 const elements = built.sys.si.length + 4 * (built.sys.bending?.w0.length ?? 0);
150 const work = spp * p.fs * p.duration * elements;
151 rows.push(['Element updates', fmtNum(work)]);
152 const frameMB = (Math.round(p.duration * p.frameRate) * 3 * built.sys.n * 4) / 1e6;
153 if (frameMB > 400) warnings.push(`Replay frames would take ${fmtNum(frameMB)} MB; lower the replay frame rate or the duration.`);
154 if (work > 3e9) warnings.push(`This run is large (${fmtNum(work)} element updates): expect roughly ${fmtNum(work / 2.2e7 / 60)} min on a desktop.`);
155 }
156 q('derived').innerHTML = statRows(rows);
157 q('warnings').innerHTML = warnings.map((w) => `<li>${w}</li>`).join('');
158 runBtn.disabled = !built || !!running;
159 }
160 updateSetup();
162 q('wave-range').addEventListener('click', (e) => {
163 const b = (e.target as HTMLElement).closest('button');
164 if (!b) return;
165 waveRange = Number(b.dataset.v);
166 q('wave-range').querySelectorAll('button').forEach((x) => x.classList.toggle('on', x === b));
167 drawWave();
168 });
169 q<HTMLSelectElement>('fmax').addEventListener('change', (e) => {
170 spec.fmax = Number((e.target as HTMLSelectElement).value);
171 spec.draw();
172 drawSpectrum();
173 });
175 function drawWave() {
176 if (!last) return;
177 const { r } = last;
178 const t = new Float64Array(r.audio.length);
179 for (let i = 0; i < t.length; i++) t[i] = i / r.fs;
180 wave.set([{ x: t, y: r.audio, color: css('--series-1'), label: 'a' }], {
181 xLabel: 'time (s)',
182 yLabel: `${quantity.label} (${quantity.unit})`,
183 xRange: waveRange ? [0, Math.min(waveRange, t[t.length - 1])] : undefined,
184 });
185 }
187 function drawSpectrum() {
188 if (!last) return;
189 const { p, r } = last;
190 const s = spectrum(r.audio, r.fs);
191 let top = -Infinity;
192 for (const v of s.db) top = Math.max(top, v);
193 const db = s.db.map((v) => Math.max(v - top, -100));
194 const m = cfg.spectrumMarkers?.(p);
195 q('spec-legend').innerHTML =
196 `<span><i class="sw" style="background:var(--series-1)"></i>pickup signal</span>` + (m?.legend ?? '');
197 specPlot.set([{ x: s.freq, y: db, color: css('--series-1'), label: 'level (dB)' }], {
198 xLabel: 'frequency (Hz)',
199 yLabel: 'level (dB re max)',
200 xRange: [0, Math.min(spec.fmax, r.fs / 2)],
201 yRange: [-100, 5],
202 markers: m?.markers,
203 });
204 }
206 function show(p: P, built: Built, r: SimResult) {
207 last = { p, r };
208 root.querySelectorAll<HTMLElement>('[data-r="out"]').forEach((e) => (e.hidden = false));
209 let peak = 0;
210 for (const v of r.audio) peak = Math.max(peak, Math.abs(v));
211 const emax = Math.max(...r.energy);
212 let bal = 0;
213 for (const b of r.balance) bal = Math.max(bal, Math.abs(b));
214 const rt = p.duration / r.wallSeconds;
215 q('summary').innerHTML = statRows([
216 ['Time step', `${fmtNum(r.dt)} s, ${r.stepsPerSample} per sample`],
217 ['Wall time', `${fmtNum(r.wallSeconds)} s (${rt >= 1 ? fmtNum(rt) + '× faster than' : fmtNum(1 / rt) + '× slower than'} real time)`],
218 ['Energy balance error', emax > 0 ? `${fmtNum((bal / emax) * 100)}% of peak energy` : '–'],
219 ...(cfg.summaryRows?.(p, built, r) ?? []),
220 ...contactRows(r),
221 [`Peak ${quantity.label}`, `${fmtNum(peak)} ${quantity.unit}`],
222 ]);
223 if (audioUrl) URL.revokeObjectURL(audioUrl);
224 audioUrl = URL.createObjectURL(encodeWav(r.audio, r.fs));
225 q<HTMLAudioElement>('audio').src = audioUrl;
226 q<HTMLAnchorElement>('download').href = audioUrl;
227 q('audio-note').textContent = `16-bit mono, ${r.fs} Hz, normalized so the peak is −1 dBFS.`;
228 drawWave();
229 spec.setSignal(r.audio, r.fs);
230 drawSpectrum();
231 timeline.setTimes(r.frameTimes);
232 scene.showReplay({ ...built.scene, frames: r.frames, malletPos: r.malletPos });
233 extras?.show(p, built, r);
234 showContact(r);
235 energyPlot.set([{ x: r.frameTimes, y: r.energy, color: css('--series-1'), label: 'energy (J)' }], {
236 xLabel: 'time (s)',
237 yLabel: 'energy (J)',
238 yRange: [0, emax * 1.05 || 1],
239 });
240 }
242 function showContact(r: SimResult) {
243 const card = q('out-contact');
244 card.hidden = !r.contactForce;
245 if (!r.contactForce) return;
246 const cf = r.contactForce;
247 const c = contacts(cf, r.fs);
248 const end = c.length ? c[c.length - 1].start + c[c.length - 1].ms / 1000 : 0.01;
249 const nShow = Math.min(cf.length, Math.ceil((end * 1.3 + 0.002) * r.fs));
250 const t = new Float64Array(nShow);
251 for (let i = 0; i < nShow; i++) t[i] = (i / r.fs) * 1000;
252 contactPlot.set([{ x: t, y: cf.subarray(0, nShow), color: css('--series-2'), label: 'force (N)' }], {
253 xLabel: 'time (ms)',
254 yLabel: 'contact force (N)',
255 yRange: [0, Math.max(...cf.subarray(0, nShow)) * 1.08 || 1],
256 });
257 q('contact-note').textContent = c.length
258 ? `${c.length} contact${c.length > 1 ? 's' : ''}: ` +
259 c.map((k) => `${fmtNum(k.ms)} ms from ${fmtNum(k.start * 1000)} ms, peak ${fmtNum(k.peak)} N`).join('; ') +
260 '. 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).'
261 : 'The mallet never touched the instrument.';
262 }
264 runBtn.addEventListener('click', async () => {
265 const p = controls.get();
266 const { built } = cfg.setup(p);
267 if (!built) return;
268 const opt = { duration: p.duration, fs: p.fs, cfl: p.cfl, frameRate: p.frameRate, pickup: built.pickup, pickupDelay: built.pickupDelay };
269 runBtn.disabled = true;
270 errorBox.hidden = true;
271 cancelBtn.hidden = false;
272 progress.hidden = false;
273 progress.value = 0;
274 running = runInWorker(built.sys, built.exc, opt, (f) => (progress.value = f));
275 try {
276 show(p, built, await running.promise);
277 } catch (e) {
278 if ((e as Error).message !== 'cancelled') {
279 errorBox.textContent = `The simulation failed: ${(e as Error).message}`;
280 errorBox.hidden = false;
281 }
282 } finally {
283 running = null;
284 runBtn.disabled = false;
285 cancelBtn.hidden = true;
286 progress.hidden = true;
287 }
288 });
289 cancelBtn.addEventListener('click', () => running?.cancel());
292// separate contact intervals in the contact-force record
293function contacts(cf: Float32Array, fs: number): { start: number; ms: number; peak: number }[] {
294 const out: { start: number; ms: number; peak: number }[] = [];
295 let i = 0;
296 while (i < cf.length) {
297 if (cf[i] > 0) {
298 const a = i;
299 let peak = 0;
300 while (i < cf.length && cf[i] > 0) peak = Math.max(peak, cf[i++]);
301 out.push({ start: a / fs, ms: ((i - a) / fs) * 1000, peak });
302 } else i++;
303 }
304 return out;
307function contactRows(r: SimResult): [string, string][] {
308 if (!r.contactForce) return [];
309 const c = contacts(r.contactForce, r.fs);
310 return [
311 [
312 'Contact',
313 c.length
314 ? `${fmtNum(c[0].ms)} ms, peak ${fmtNum(c[0].peak)} N${c.length > 1 ? ` (+${c.length - 1} more contact${c.length > 2 ? 's' : ''})` : ''}`
315 : 'none',
316 ],
317 ];
320const cap = (s: string) => s[0].toUpperCase() + s.slice(1);
↑↓ move↵openescclose