1// The application: the design script, the two run modes (the linear modal
2// model on the CPU workers and the full nonlinear simulation on the GPU),
3// the plate view, the movie, the audio, and the spectrogram.
5import { compileDesign, evaluatePlate, isFlat, profileStats, type Design, DesignError } from "./design.ts";
6import { PRESETS, DEFAULT_PRESET, presetById } from "./presets.ts";
7import {
8 type Plate,
9 type SimParams,
10 defaultParams,
11 countInside,
12 massProperties,
13 meanThickness,
14 thicknessRange,
15 standRates,
16 strikePoint,
17 strikePatch,
18 listenerPosition,
19 dispersionFrequency,
20 inPlaneSpeed,
21 CFL,
22} from "./params.ts";
23import { fitSigma, fittedRate, t60At, LN1000, decayRate } from "./loss.ts";
24import { assemble, type LinearSystem } from "./model/assemble.ts";
25import { maxAngularFrequency, fullLoss, type FullLoss } from "./model/reference.ts";
26import { type ModeSet } from "./modal/modes.ts";
27import { WorkerPool } from "./modal/pool.ts";
28import { modalModel, modeShapeOnGrid, type ModalModel, type ContactResult } from "./modal/synth.ts";
29import { Simulation } from "./sim/simulation.ts";
30import { runSelfTest } from "./sim/selftest.ts";
31import { PlateRenderer, type ViewMode, type ColorMode } from "./render/renderer.ts";
32import { Spectrogram } from "./audio/spectrogram.ts";
33import { Player } from "./audio/player.ts";
34import { encodeWav } from "./audio/wav.ts";
35import { levelGain, applyLevel, peakDbfs, peakSpl, type LevelMode } from "./audio/level.ts";
36import { DesignEditor } from "./ui/editor.ts";
37import { ParamForm, formatNumber } from "./ui/form.ts";
38import { ModeBrowser } from "./ui/modes.ts";
39import { Tutorial } from "./tutorial/tutorial.ts";
40import { type Memo, type TutorialContext, type TutorialHost } from "./tutorial/steps.ts";
42type RunMode = "linear" | "full";
43type ViewState = "design" | "mode" | "live" | "movie";
45const $ = <T extends HTMLElement>(id: string): T => document.getElementById(id) as T;
47/** A recording: the listener signal and the movie of one run, from either model. */
48interface Recording {
49 audio: Float32Array;
50 samples: number;
51 fs: number;
52 frames: Float32Array[];
53 fps: number;
54 source: RunMode;
55}
57class App {
58 // GPU
59 device: GPUDevice | null = null;
60 // Design and plate
61 design: Design | null = null;
62 plate: Plate | null = null;
63 plateSpacing = 0;
64 designGeneration = 0;
65 // Linear model
66 pool: WorkerPool | null = null;
67 sys: LinearSystem | null = null;
68 modes: ModeSet | null = null;
69 model: ModalModel | null = null;
70 modesBusy: Promise<void> = Promise.resolve();
71 /** Modes of recent designs, keyed by the script, the spacing and the cutoff; the newest entry is last. */
72 modesCache = new Map<string, { sys: LinearSystem; modes: ModeSet; model: ModalModel }>();
73 headProgress!: HTMLDivElement;
74 /** The cache key of the modes the pool currently holds. */
75 currentModesKey: string | null = null;
76 headProgressBar!: HTMLDivElement;
77 synthBusy = false;
78 synthPending = false;
79 synthesized = false;
80 lastContact: ContactResult | null = null;
81 // Full simulation
82 sim: Simulation | null = null;
83 running = false;
84 paused = false;
85 // Recording and view
86 rec: Recording | null = null;
87 view: ViewState = "design";
88 frameIndex = 0;
89 runMode: RunMode = "linear";
90 // UI
91 editor!: DesignEditor;
92 form!: ParamForm;
93 modeBrowser!: ModeBrowser;
94 renderer!: PlateRenderer;
95 spec!: Spectrogram;
96 tutorial: Tutorial | null = null;
97 tutorialMemo: Memo = {};
98 specOpts = { window: 2048, logFreq: false };
99 specWinSel!: HTMLSelectElement;
100 specLogChk!: HTMLInputElement;
101 colorSel!: HTMLSelectElement;
102 player = new Player();
103 levelMode: LevelMode = "absolute";
104 gainDb = -40;
105 showTicks = true;
106 viewOpts = { mode: "3d" as ViewMode, color: "height" as ColorMode, showProfile: true, exaggeration: 1, range: 0 };
107 // Controls
108 runModeSel!: HTMLSelectElement;
109 durationInput!: HTMLInputElement;
110 startBtn!: HTMLButtonElement;
111 pauseBtn!: HTMLButtonElement;
112 stopBtn!: HTMLButtonElement;
113 continueBtn!: HTMLButtonElement;
114 runStatus!: HTMLDivElement;
115 scrub!: HTMLInputElement;
116 timeLabel!: HTMLSpanElement;
117 playBtn!: HTMLButtonElement;
118 liveBtn!: HTMLButtonElement;
119 designBtn!: HTMLButtonElement;
120 peakLabel!: HTMLSpanElement;
121 downloadBtn!: HTMLButtonElement;
122 overlay!: HTMLDivElement;
123 synthTimer: number | null = null;
125 async init(): Promise<void> {
126 const url = new URLSearchParams(location.search);
127 if (!url.has("nogpu") && navigator.gpu) {
128 try {
129 const adapter = await navigator.gpu.requestAdapter();
130 if (adapter) this.device = await adapter.requestDevice();
131 } catch (e) {
132 console.warn("WebGPU unavailable", e);
133 }
134 }
135 if (typeof Worker !== "undefined") this.pool = new WorkerPool(WorkerPool.defaultSize());
137 this.buildControls();
138 this.buildForm();
139 this.buildViewToolbar();
140 this.buildMovieToolbar();
141 this.buildSpecToolbar();
142 this.buildSplitter();
144 this.renderer = new PlateRenderer($("view"), this.device);
145 if (!this.renderer.has3d) this.viewOpts.mode = "2d";
146 this.renderer.setOptions(this.viewOpts);
147 this.overlay = $("viewOverlay");
148 const p = this.form.get();
149 this.spec = new Spectrogram($("spec"), { fs: p.fs, window: 2048, hop: 256, maxHz: 12000, dbRange: 80, logFreq: false });
150 this.spec.setDuration(p.duration);
151 this.modeBrowser = new ModeBrowser($("modes"), (m) => this.showMode(m));
152 this.editor = new DesignEditor($("design"), { onSource: (src) => this.onSource(src) });
153 this.tutorial = new Tutorial($("tutorial"), this.tutorialHost(), (open) => {
154 $("tutorialBtn").classList.toggle("active", open);
155 this.renderer.resize(); this.spec.resize();
156 });
157 $("tutorialBtn").addEventListener("click", () => this.tutorial?.toggle());
159 if (url.has("mode")) this.setRunMode(url.get("mode") === "full" ? "full" : "linear");
160 else this.setRunMode(this.device ? "linear" : "linear");
161 // The parameters come first, so that the preset is evaluated at the requested spacing.
162 this.form.applyUrl(url);
163 this.durationInput.value = String(this.form.get().duration);
164 const preset = url.get("preset");
165 this.editor.selectPreset(preset && presetById(preset) ? preset : DEFAULT_PRESET);
166 // The tutorial opens on request (?tutorial=1 or ?tutorial=<step id>) or when it was open last time.
167 const tut = url.get("tutorial");
168 if (tut !== null) this.tutorial.open(tut === "1" || tut === "" ? undefined : tut);
169 else if (this.tutorial.wasOpen()) this.tutorial.open();
171 const loop = () => {
172 this.renderer.render();
173 requestAnimationFrame(loop);
174 };
175 requestAnimationFrame(loop);
176 window.addEventListener("resize", () => { this.renderer.resize(); this.spec.resize(); });
177 this.renderer.resize();
178 this.spec.resize();
180 // Test hooks.
181 (window as unknown as { cymbalsim: unknown }).cymbalsim = {
182 app: this,
183 selftest: () => this.selfTest(),
184 runLinear: () => this.runLinear(),
185 runFull: () => this.runFull(),
186 modesReady: () => this.modesBusy,
187 status: () => this.testStatus(),
188 tutorial: this.tutorial,
189 };
190 if (url.has("selftest")) {
191 const r = await this.selfTest();
192 this.overlay.textContent = r;
193 }
194 if (url.has("autostart")) {
195 await this.modesBusy;
196 this.start();
197 }
198 }
200 // ---------- Controls ----------
202 private buildControls(): void {
203 const c = $("controls");
204 this.runModeSel = document.createElement("select");
205 this.runModeSel.innerHTML = `<option value="linear">Linear (modal)</option><option value="full">Full (nonlinear, GPU)</option>`;
206 this.runModeSel.addEventListener("change", () => this.setRunMode(this.runModeSel.value as RunMode));
207 const durLabel = document.createElement("label");
208 durLabel.textContent = "Duration";
209 this.durationInput = document.createElement("input");
210 this.durationInput.type = "number"; this.durationInput.min = "0.1"; this.durationInput.step = "0.5"; this.durationInput.style.width = "60px";
211 this.durationInput.addEventListener("change", () => {
212 const d = Math.max(0.1, Number(this.durationInput.value) || 1);
213 this.form.set("duration", d);
214 this.spec.setDuration(d);
215 if (this.sim) this.sim.setDuration(d);
216 this.updateButtons();
217 });
218 const s = document.createElement("span"); s.textContent = " s";
219 durLabel.append(this.durationInput, s);
220 this.startBtn = this.button("Start", () => this.start(), "primary");
221 this.pauseBtn = this.button("Pause", () => this.pause());
222 this.stopBtn = this.button("Stop", () => this.stopRun());
223 this.continueBtn = this.button("Continue", () => this.continueRun());
224 c.append(this.runModeSel, durLabel, this.startBtn, this.pauseBtn, this.stopBtn, this.continueBtn);
225 this.headProgress = document.createElement("div");
226 this.headProgress.className = "progress";
227 this.headProgress.hidden = true;
228 this.headProgressBar = document.createElement("div");
229 this.headProgress.append(this.headProgressBar);
230 this.runStatus = document.createElement("div");
231 this.runStatus.className = "status";
232 $("sidebarHead").append(this.headProgress, this.runStatus);
233 }
235 /** The progress bar under the run controls (fraction 0..1, or null to hide) with a status message. */
236 private setProgress(fraction: number | null, message?: string): void {
237 this.headProgress.hidden = fraction === null;
238 if (fraction !== null) this.headProgressBar.style.width = `${Math.round(100 * fraction)}%`;
239 if (message !== undefined) this.runStatus.textContent = message;
240 }
242 private button(label: string, onClick: () => void, cls = ""): HTMLButtonElement {
243 const b = document.createElement("button");
244 b.textContent = label;
245 if (cls) b.className = cls;
246 b.addEventListener("click", onClick);
247 return b;
248 }
250 private buildForm(): void {
251 this.form = new ParamForm(
252 $("params"),
253 [
254 {
255 title: "Strike",
256 notes: true,
257 fields: [
258 { key: "strikeFracX", label: "Position x (fraction of width)", step: 0.05, min: 0, max: 1 },
259 { key: "strikeFracY", label: "Position y (fraction of height)", step: 0.05, min: 0, max: 1 },
260 { key: "strikeVelocity", label: "Stick speed", unit: "m/s", step: 0.5, min: 0.01 },
261 { key: "stickMass", label: "Stick mass", unit: "g", scale: 1e-3, step: 5, min: 1 },
262 { key: "contactStiffness", label: "Contact stiffness K", unit: "N/m^a", step: 1e8, min: 1e5 },
263 { key: "contactExponent", label: "Contact exponent a", step: 0.1, min: 1, max: 3 },
264 { key: "contactRadius", label: "Tip radius", unit: "mm", scale: 1e-3, step: 1, min: 0.5 },
265 ],
266 },
267 {
268 title: "Listener",
269 fields: [
270 { key: "listenerDist", label: "Distance", unit: "m", step: 0.1, min: 0.05, live: true },
271 { key: "listenerAngle", label: "Angle from the normal", unit: "deg", step: 5, min: 0, max: 90, live: true },
272 { key: "listenerAzimuth", label: "Azimuth", unit: "deg", step: 15, min: -180, max: 180, live: true },
273 ],
274 },
275 {
276 title: "Grid and numerics",
277 notes: true,
278 fields: [
279 { key: "spacing", label: "Grid spacing", unit: "mm", scale: 1e-3, step: 1, min: 2 },
280 { key: "modeMaxFreq", label: "Modes up to", unit: "Hz", step: 1000, min: 200 },
281 { key: "padLiftoff", label: "Pads lift off (full model)", kind: "checkbox" },
282 { key: "fs", label: "Sample rate", kind: "select", options: [{ value: 44100, label: "44.1 kHz" }, { value: 48000, label: "48 kHz" }, { value: 96000, label: "96 kHz" }] },
283 { key: "fps", label: "Movie frame rate", kind: "select", options: [{ value: 60, label: "60" }, { value: 120, label: "120" }, { value: 240, label: "240" }] },
284 ],
285 },
286 ],
287 defaultParams,
288 (key, _value, live) => this.onParam(key, live),
289 );
290 }
292 private onParam(key: keyof SimParams, live: boolean): void {
293 const p = this.form.get();
294 if (key === "spacing" || key === "modeMaxFreq" || key === "fs") {
295 if (this.design) this.rebuildPlate(this.design);
296 return;
297 }
298 if (key === "fps") { this.updateNotes(); return; }
299 if (key === "padLiftoff") { this.updateNotes(); return; }
300 if (live && this.sim) this.sim.setListener(p);
301 if (key.startsWith("strike") || key.startsWith("stick") || key.startsWith("contact") || key.startsWith("listener")) {
302 this.updateMarkers();
303 this.updateNotes();
304 if (this.runMode === "linear" && this.synthesized) this.scheduleSynth();
305 }
306 this.tutorial?.refresh();
307 }
309 private buildViewToolbar(): void {
310 const t = $("viewToolbar");
311 const modeSel = document.createElement("select");
312 modeSel.innerHTML = `<option value="3d">3D</option><option value="2d">2D</option>`;
313 modeSel.addEventListener("change", () => { this.viewOpts.mode = modeSel.value as ViewMode; this.renderer.setOptions(this.viewOpts); });
314 const colorSel = document.createElement("select");
315 colorSel.innerHTML = `<option value="height">Height</option><option value="thickness">Thickness</option>`;
316 colorSel.addEventListener("change", () => { this.viewOpts.color = colorSel.value as ColorMode; this.renderer.setOptions(this.viewOpts); });
317 this.colorSel = colorSel;
318 const exag = document.createElement("input");
319 exag.type = "number"; exag.min = "1"; exag.step = "5"; exag.value = String(this.viewOpts.exaggeration); exag.style.width = "60px";
320 exag.addEventListener("change", () => { this.viewOpts.exaggeration = Math.max(0.1, Number(exag.value) || 1); this.renderer.setOptions(this.viewOpts); });
321 const range = document.createElement("input");
322 range.type = "number"; range.min = "0"; range.step = "0.1"; range.value = "0"; range.style.width = "60px";
323 range.addEventListener("change", () => { this.viewOpts.range = Math.max(0, Number(range.value) || 0) * 1e-3; this.renderer.setOptions(this.viewOpts); });
324 const prof = document.createElement("input");
325 prof.type = "checkbox"; prof.checked = this.viewOpts.showProfile;
326 prof.addEventListener("change", () => { this.viewOpts.showProfile = prof.checked; this.renderer.setOptions(this.viewOpts); });
327 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
328 t.append(lab("View", modeSel), lab("Color", colorSel), lab("Exaggeration", exag), lab("Range (mm, 0 = auto)", range), lab("Show profile", prof));
329 if (!this.device) {
330 modeSel.value = "2d"; modeSel.disabled = true;
331 const w = document.createElement("span"); w.id = "nogpu"; w.textContent = "WebGPU is not available: the 2D view and the linear model only.";
332 t.append(w);
333 }
334 }
336 private buildMovieToolbar(): void {
337 const t = $("movieToolbar");
338 this.playBtn = this.button("Play", () => this.togglePlay());
339 this.liveBtn = this.button("Live", () => this.setView("live"));
340 this.designBtn = this.button("Design", () => this.setView("design"));
341 this.scrub = document.createElement("input");
342 this.scrub.type = "range"; this.scrub.className = "scrub"; this.scrub.min = "0"; this.scrub.max = "0"; this.scrub.value = "0";
343 this.scrub.addEventListener("input", () => { this.frameIndex = Number(this.scrub.value); this.setView("movie"); this.showFrame(); });
344 this.timeLabel = document.createElement("span");
345 this.timeLabel.textContent = "0.000 s";
346 const levelSel = document.createElement("select");
347 levelSel.innerHTML = `<option value="absolute">Absolute level</option><option value="loudness">Normalize loudness</option><option value="peak">Normalize peak</option>`;
348 levelSel.addEventListener("change", () => { this.levelMode = levelSel.value as LevelMode; this.updatePeak(); });
349 const gain = document.createElement("input");
350 gain.type = "range"; gain.min = "-60"; gain.max = "40"; gain.step = "1"; gain.value = String(this.gainDb);
351 const gainLabel = document.createElement("span"); gainLabel.textContent = `${this.gainDb} dB`;
352 gain.addEventListener("input", () => { this.gainDb = Number(gain.value); gainLabel.textContent = `${this.gainDb} dB`; this.updatePeak(); });
353 this.peakLabel = document.createElement("span");
354 this.downloadBtn = this.button("Download .wav", () => this.download());
355 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
356 t.append(this.playBtn, this.liveBtn, this.designBtn, this.scrub, this.timeLabel, levelSel, lab("Gain", gain, gainLabel), this.peakLabel, this.downloadBtn);
357 }
359 private buildSpecToolbar(): void {
360 const t = $("specToolbar");
361 const sel = (opts: [string, string][], value: string, onChange: (v: string) => void) => {
362 const s = document.createElement("select");
363 for (const [v, l] of opts) { const o = document.createElement("option"); o.value = v; o.textContent = l; s.append(o); }
364 s.value = value;
365 s.addEventListener("change", () => onChange(s.value));
366 return s;
367 };
368 const lab = (text: string, ...els: HTMLElement[]) => { const l = document.createElement("label"); l.append(text, ...els); return l; };
369 const win = sel([["512", "512"], ["1024", "1024"], ["2048", "2048"], ["4096", "4096"]], "2048", (v) => { this.specOpts.window = Number(v); this.spec.setOptions({ window: Number(v), hop: Number(v) / 8 }); this.tutorial?.refresh(); });
370 const maxHz = sel([["4000", "4 kHz"], ["8000", "8 kHz"], ["12000", "12 kHz"], ["16000", "16 kHz"], ["20000", "20 kHz"]], "12000", (v) => this.spec.setOptions({ maxHz: Number(v) }));
371 const db = sel([["60", "60 dB"], ["80", "80 dB"], ["100", "100 dB"]], "80", (v) => this.spec.setOptions({ dbRange: Number(v) }));
372 const log = document.createElement("input"); log.type = "checkbox";
373 log.addEventListener("change", () => { this.specOpts.logFreq = log.checked; this.spec.setOptions({ logFreq: log.checked }); this.tutorial?.refresh(); });
374 this.specWinSel = win; this.specLogChk = log;
375 const ticks = document.createElement("input"); ticks.type = "checkbox"; ticks.checked = this.showTicks;
376 ticks.addEventListener("change", () => { this.showTicks = ticks.checked; this.updateTicks(); });
377 t.append(lab("Spectrogram window", win), lab("Max", maxHz), lab("Range", db), lab("Log frequency", log), lab("Modal frequencies", ticks));
378 }
380 private buildSplitter(): void {
381 const sp = $("splitter"), sb = $("sidebar");
382 const saved = localStorage.getItem("cymbalsim.sidebar");
383 if (saved) sb.style.width = saved;
384 let dragging = false;
385 sp.addEventListener("mousedown", (e) => { dragging = true; e.preventDefault(); });
386 window.addEventListener("mousemove", (e) => {
387 if (!dragging) return;
388 const w = Math.max(280, Math.min(window.innerWidth - 300, e.clientX));
389 sb.style.width = `${w}px`;
390 this.renderer.resize(); this.spec.resize();
391 });
392 window.addEventListener("mouseup", () => { if (dragging) { dragging = false; localStorage.setItem("cymbalsim.sidebar", sb.style.width); } });
393 sp.addEventListener("dblclick", () => { sb.style.width = ""; localStorage.removeItem("cymbalsim.sidebar"); this.renderer.resize(); this.spec.resize(); });
394 }
396 // ---------- Design ----------
398 private onSource(source: string): void {
399 if (this.running) return;
400 let d: Design;
401 try {
402 d = compileDesign(source);
403 } catch (e) {
404 this.editor.setStatus(e instanceof Error ? e.message : String(e), "error");
405 return;
406 }
407 this.editor.setStatus(`Compiled: ${d.name}`, "ok");
408 this.rebuildPlate(d);
409 }
411 private rebuildPlate(d: Design): void {
412 const p = this.form.get();
413 let plate: Plate;
414 try {
415 plate = evaluatePlate(d, p.spacing);
416 } catch (e) {
417 this.editor.setStatus(e instanceof DesignError ? e.message : String(e), "error");
418 return;
419 }
420 this.design = d;
421 this.plate = plate;
422 this.plateSpacing = p.spacing;
423 this.designGeneration++;
424 this.modes = null; this.model = null; this.sys = null;
425 this.synthesized = false;
426 this.lastContact = null;
427 this.rec = null;
428 this.spec.reset();
429 this.spec.setOptions({ fs: p.fs });
430 this.renderer.setPlate(plate);
431 this.setView("design");
432 this.updateMarkers();
433 this.updateDesignInfo();
434 this.updateNotes();
435 this.updateButtons();
436 if (this.runMode === "linear") this.useCachedModes();
437 else this.modeBrowser.clear("Switch to the linear model to compute the modes.");
438 this.tutorial?.refresh();
439 }
441 /** The cache key of the modes of the current design and numerics. */
442 private modesKey(): string | null {
443 if (!this.design || !this.plate) return null;
444 const p = this.form.get();
445 return `${this.plateSpacing}|${Math.min(p.modeMaxFreq, p.fs / 2)}|${this.design.source}`;
446 }
448 /** Installs cached modes for the current design if there are any; otherwise leaves the browser empty. */
449 private useCachedModes(): void {
450 const key = this.modesKey();
451 const hit = key ? this.modesCache.get(key) : undefined;
452 if (hit && this.plate) {
453 this.installModes(hit.sys, hit.modes, hit.model, null);
454 if (this.pool) void this.pool.setModel(hit.model);
455 } else this.modeBrowser.clear("Press Synthesize to compute the modes of this design.");
456 }
458 /** Shows a mode set in the browser, the notes and the spectrogram ticks. */
459 private installModes(sys: LinearSystem, modes: ModeSet, model: ModalModel, secs: number | null): void {
460 const pl = this.plate!;
461 const p = this.form.get();
462 const fMax = Math.min(p.modeMaxFreq, p.fs / 2);
463 this.sys = sys; this.modes = modes; this.model = model;
464 const rows = Array.from(modes.freqs).map((f, m) => ({ freq: f, t60: LN1000 / Math.min(decayRate(pl.loss, f) + model.padSigma[m], 0.99 * 2 * Math.PI * f) }));
465 const kind = sys.fields === 1 ? "bending modes" : "modes (bending coupled to stretching)";
466 const when = secs === null ? "cached" : `in ${secs.toFixed(1)} s`;
467 this.modeBrowser.setModes(rows, `${modes.count} ${kind} up to ${(fMax / 1e3).toFixed(1)} kHz, ${when} (${sys.n} unknowns${modes.missing ? `, ${modes.missing} missing` : ""}). Click a mode to see its shape.`);
468 this.updateNotes();
469 this.updateTicks();
470 this.updateButtons();
471 this.tutorial?.refresh();
472 }
474 private updateDesignInfo(): void {
475 const pl = this.plate;
476 if (!pl) return;
477 const p = this.form.get();
478 const g = pl.grid;
479 const { mass } = massProperties(pl);
480 const hr = thicknessRange(pl);
481 const ps = profileStats(pl);
482 const sr = standRates(pl);
483 const lines: string[] = [];
484 lines.push(`${pl.name}: ${(pl.Lx * 1e3).toFixed(0)} x ${(pl.Ly * 1e3).toFixed(0)} mm, E = ${(pl.mat.E / 1e9).toFixed(0)} GPa, nu = ${pl.mat.nu}, rho = ${pl.mat.rho} kg/m^3`);
485 lines.push(`Thickness ${(hr.min * 1e3).toFixed(2)} to ${(hr.max * 1e3).toFixed(2)} mm, mass ${(mass * 1e3).toFixed(0)} g, grid ${g.nx} x ${g.ny} at ${(g.hx * 1e3).toFixed(2)} mm (${countInside(g)} nodes)`);
486 if (ps.peakToPeak > 0) {
487 const warn = ps.maxSlope > 0.1 ? ` <span class="warn">(above the shallow-shell range of about 0.1)</span>` : "";
488 lines.push(`Profile ${(ps.peakToPeak * 1e3).toFixed(1)} mm peak to peak, largest slope ${ps.maxSlope.toFixed(3)}${warn}`);
489 } else lines.push("Flat plate (no profile): the linear model is bending only");
490 if (pl.stand && sr) {
491 const pad = pl.stand.pad;
492 lines.push(`Stand: ${pl.stand.topPad ? "two pads" : "bottom pad only"}, ${(pad.innerRadius * 1e3).toFixed(0)} to ${(pad.outerRadius * 1e3).toFixed(0)} mm, ${(pad.thickness * 1e3).toFixed(0)} mm felt at ${(pad.E / 1e6).toFixed(2)} MPa; ${(sr.totalKw / 1e3).toFixed(0)} kN/m, bounce ${sr.bounceHz.toFixed(0)} Hz, ${sr.nodes.length} pad nodes, preload ${(sr.preloadTop * 1e3).toFixed(2)} / ${(sr.preloadBottom * 1e3).toFixed(2)} mm`);
493 } else lines.push("Free plate (no stand)");
494 lines.push(`Decay T60: ${t60At(pl.loss, 100).toFixed(2)} s at 100 Hz, ${t60At(pl.loss, 1000).toFixed(2)} s at 1 kHz, ${t60At(pl.loss, 5000).toFixed(2)} s at 5 kHz`);
495 void p;
496 $("designInfo").innerHTML = lines.join("\n");
497 }
499 private updateNotes(): void {
500 const pl = this.plate;
501 if (!pl) return;
502 const p = this.form.get();
503 const g = pl.grid;
504 const hm = meanThickness(pl);
505 const f3 = dispersionFrequency(pl.mat, hm, g.hx, 0.03), f10 = dispersionFrequency(pl.mat, hm, g.hx, 0.1);
506 const wmax = maxAngularFrequency(g, pl.mat, thicknessRange(pl).max);
507 const dtMax = (CFL * 2) / wmax;
508 const sps = Math.ceil(1 / (p.fs * dtMax));
509 const dt = 1 / (p.fs * sps);
510 const fit = fitSigma(pl.loss, pl.mat, hm);
511 const t60f = (f: number) => (LN1000 / fittedRate(fit, f)).toFixed(2);
512 const lines = [
513 `Grid ${g.nx} x ${g.ny}, ${countInside(g)} plate nodes. Grid dispersion lowers the bending partials by 3% near ${(f3 / 1e3).toFixed(1)} kHz and by 10% near ${(f10 / 1e3).toFixed(1)} kHz (at the mean thickness).`,
514 `Linear model: modes up to ${(p.modeMaxFreq / 1e3).toFixed(1)} kHz${this.modes ? `, ${this.modes.count} found in ${this.modes.seconds.toFixed(1)} s` : ""}${this.modes && this.modes.missing ? ` <span class="warn">(${this.modes.missing} missing)</span>` : ""}.`,
515 `Full model: time step ${(dt * 1e6).toFixed(2)} us (${sps} per sample, in-plane wave speed ${inPlaneSpeed(pl.mat).toFixed(0)} m/s), ${((p.duration * p.fs * sps) / 1e6).toFixed(1)} million steps for ${p.duration} s. Losses fitted as sigma0 = ${fit.sigma0.toFixed(2)} 1/s, sigma1 = ${fit.sigma1.toExponential(2)} m^2/s: T60 ${t60f(100)} / ${t60f(1000)} / ${t60f(5000)} s at 100 Hz / 1 kHz / 5 kHz (requested ${t60At(pl.loss, 100).toFixed(2)} / ${t60At(pl.loss, 1000).toFixed(2)} / ${t60At(pl.loss, 5000).toFixed(2)}).`,
516 ];
517 this.form.setNotes("Grid and numerics", lines.join("\n"));
518 const patch = strikePatch(pl, p);
519 const sp = strikePoint(pl, p);
520 const sl = [`Strike at (${(sp.x * 1e3).toFixed(0)}, ${(sp.y * 1e3).toFixed(0)}) mm on ${patch.nodes.length} node${patch.nodes.length === 1 ? "" : "s"} (${(patch.mass * 1e3).toFixed(2)} g).`];
521 if (this.lastContact) sl.push(`Last linear strike: peak force ${this.lastContact.peakForce.toFixed(0)} N, contact ${(this.lastContact.contactTime * 1e3).toFixed(2)} ms.`);
522 if (this.sim) { const st = this.sim.status().stick; sl.push(`Full simulation: peak force ${st.maxForce.toFixed(0)} N${st.withdrawn ? ", stick withdrawn" : ""}.`); }
523 this.form.setNotes("Strike", sl.join("\n"));
524 }
526 private updateMarkers(): void {
527 const pl = this.plate;
528 if (!pl) return;
529 const p = this.form.get();
530 const sp = strikePoint(pl, p);
531 const L = listenerPosition(p);
532 this.renderer.setMarkers({
533 strike: { x: sp.x, y: sp.y, radius: p.contactRadius },
534 stand: pl.stand ? { x: pl.stand.x, y: pl.stand.y, innerRadius: pl.stand.pad.innerRadius, outerRadius: pl.stand.pad.outerRadius } : null,
535 listener: L,
536 });
537 }
539 // ---------- Linear model ----------
541 /** Computes the modes of the current design unless they are cached; resolves when they are installed (or with an error). */
542 private computeModes(): Promise<void> {
543 const pl = this.plate, gen = this.designGeneration, key = this.modesKey();
544 if (!pl || !key) return Promise.resolve();
545 const hit = this.modesCache.get(key);
546 if (hit) {
547 if (this.model !== hit.model) { this.installModes(hit.sys, hit.modes, hit.model, null); if (this.pool) return this.pool.setModel(hit.model); }
548 return Promise.resolve();
549 }
550 const p = this.form.get();
551 const fMax = Math.min(p.modeMaxFreq, p.fs / 2);
552 this.modeBrowser.clear("Computing the modes...");
553 this.setProgress(0, "Computing the modes...");
554 this.updateButtons();
555 this.modesBusy = this.modesBusy.then(async () => {
556 if (gen !== this.designGeneration) return;
557 const t0 = performance.now();
558 let sys: LinearSystem;
559 try {
560 sys = assemble(pl);
561 } catch (e) {
562 this.setProgress(null, `Assembly failed: ${e instanceof Error ? e.message : String(e)}`);
563 throw e;
564 }
565 let modes: ModeSet;
566 try {
567 if (this.pool) modes = await this.pool.modes(sys, fMax, (d, t) => { if (gen === this.designGeneration) this.setProgress(t ? d / t : 0, `Computing the modes: slice ${d} of ${t}`); });
568 else {
569 const { computeModes, localRunner } = await import("./modal/modes.ts");
570 modes = await computeModes(sys, fMax, localRunner(sys));
571 }
572 } catch (e) {
573 this.setProgress(null, `Mode computation failed: ${e instanceof Error ? e.message : String(e)}`);
574 throw e;
575 }
576 const model = modalModel(pl, sys, modes);
577 this.modesCache.set(key, { sys, modes, model });
578 while (this.modesCache.size > 4) this.modesCache.delete(this.modesCache.keys().next().value!);
579 if (gen !== this.designGeneration) { this.setProgress(null); return; }
580 if (this.pool) await this.pool.setModel(model);
581 this.setProgress(null, "");
582 this.installModes(sys, modes, model, (performance.now() - t0) / 1000);
583 });
584 return this.modesBusy;
585 }
587 private showMode(m: number | null): void {
588 if (m === null) { this.setView(this.rec ? "movie" : "design"); return; }
589 if (!this.model) return;
590 this.view = "mode";
591 const shape = modeShapeOnGrid(this.model, m);
592 // Scale the mass-normalized shape to a visible amplitude: 1 mm peak.
593 let peak = 0;
594 for (const v of shape) peak = Math.max(peak, Math.abs(v));
595 const w = new Float32Array(shape.length);
596 for (let k = 0; k < w.length; k++) w[k] = (shape[k] / (peak || 1)) * 1e-3;
597 this.renderer.setField(w);
598 this.overlay.textContent = `Mode ${m + 1}: ${this.model.freqs[m].toFixed(1)} Hz (shape scaled to 1 mm)`;
599 }
601 private scheduleSynth(): void {
602 if (this.synthTimer !== null) clearTimeout(this.synthTimer);
603 this.synthTimer = window.setTimeout(() => { this.synthTimer = null; void this.runLinear(); }, 250);
604 }
606 /** Makes sure the modes of the current design are computed and installed in the pool. */
607 async ensureModes(): Promise<void> {
608 if (!this.plate) return;
609 if (!this.model || this.modesKey() !== this.currentModesKey) {
610 await this.computeModes();
611 this.currentModesKey = this.modesKey();
612 }
613 }
615 /** Synthesizes the strike with the current parameters (linear model). */
616 async runLinear(): Promise<void> {
617 if (!this.plate) return;
618 if (this.synthBusy) { this.synthPending = true; return; }
619 try {
620 await this.ensureModes();
621 } catch {
622 return;
623 }
624 const pl = this.plate, model = this.model;
625 if (!pl || !model) return;
626 this.synthBusy = true;
627 const p = this.form.get();
628 const gen = this.designGeneration;
629 const t0 = performance.now();
630 this.runStatus.textContent = "Synthesizing...";
631 try {
632 let audio: Float32Array, frames: Float32Array, nFrames: number, contact: ContactResult;
633 if (this.pool) {
634 const r = await this.pool.synthesize(model, pl, pl.loss, p, (a, c) => {
635 if (gen !== this.designGeneration) return;
636 this.installRecording(a, [], p, "linear");
637 this.lastContact = c;
638 this.runStatus.textContent = `Audio ready in ${((performance.now() - t0) / 1000).toFixed(2)} s; movie frames...`;
639 });
640 audio = r.audio; frames = r.frames; nFrames = r.nFrames; contact = r.contact;
641 } else {
642 const { synthesize } = await import("./modal/synth.ts");
643 const r = synthesize(model, pl, pl.loss, p, true);
644 audio = r.audio; frames = r.frames; nFrames = r.nFrames; contact = r.contact;
645 }
646 if (gen !== this.designGeneration) return;
647 const n = pl.grid.n;
648 const frameList: Float32Array[] = [];
649 for (let f = 0; f < nFrames; f++) frameList.push(frames.subarray(f * n, (f + 1) * n));
650 this.installRecording(audio, frameList, p, "linear");
651 this.lastContact = contact;
652 this.synthesized = true;
653 const secs = (performance.now() - t0) / 1000;
654 this.runStatus.textContent = `Linear model: ${model.count} modes, ${p.duration} s synthesized in ${secs.toFixed(2)} s. Peak ${peakSpl(audio).toFixed(0)} dB SPL, contact ${(contact.contactTime * 1e3).toFixed(2)} ms, peak force ${contact.peakForce.toFixed(0)} N.`;
655 this.updateNotes();
656 } catch (e) {
657 this.runStatus.textContent = `Synthesis failed: ${e instanceof Error ? e.message : String(e)}`;
658 } finally {
659 this.synthBusy = false;
660 this.tutorial?.refresh();
661 if (this.synthPending) { this.synthPending = false; void this.runLinear(); }
662 }
663 }
665 // ---------- Full simulation ----------
667 async runFull(): Promise<void> {
668 const pl = this.plate;
669 if (!pl || !this.device || this.running) return;
670 const p = this.form.get();
671 this.sim?.destroy();
672 const hm = meanThickness(pl);
673 const fit = fitSigma(pl.loss, pl.mat, hm);
674 const loss: FullLoss = fullLoss(fit, standRates(pl), decayRate(pl.loss, 5000));
675 this.sim = new Simulation(this.device, pl, p, loss);
676 this.rec = { audio: new Float32Array(0), samples: 0, fs: p.fs, frames: [new Float32Array(pl.grid.n)], fps: p.fps, source: "full" };
677 this.spec.reset();
678 this.spec.setOptions({ fs: p.fs });
679 this.spec.setDuration(p.duration);
680 this.running = true;
681 this.paused = false;
682 this.setLocked(true);
683 this.setView("live");
684 this.updateButtons();
685 await this.fullLoop();
686 }
688 private async fullLoop(): Promise<void> {
689 const sim = this.sim;
690 if (!sim) return;
691 const t0 = performance.now();
692 let lastUi = 0;
693 while (this.running && sim.phase === "recording") {
694 if (this.paused) { await new Promise((r) => setTimeout(r, 50)); continue; }
695 await sim.runBatch();
696 if (!this.rec || this.sim !== sim) break;
697 // New audio and frames.
698 const rec = this.rec;
699 const newSamples = sim.samples - rec.samples;
700 if (newSamples > 0) {
701 const chunk = sim.audio.subarray(rec.samples, sim.samples);
702 this.spec.append(chunk);
703 rec.audio = sim.audio; rec.samples = sim.samples;
704 }
705 rec.frames = sim.frames;
706 if (this.view === "live") this.renderer.setField(sim.frames[sim.frames.length - 1]);
707 const now = performance.now();
708 if (now - lastUi > 100) {
709 lastUi = now;
710 const st = sim.status();
711 const elapsed = (now - t0) / 1000;
712 this.runStatus.textContent = `Full model: t = ${st.t.toFixed(3)} s, ${(st.totalSteps / elapsed / 1000).toFixed(0)}k steps/s (${(elapsed / Math.max(st.t, 1e-3)).toFixed(0)} s per second of sound), peak ${peakSpl(sim.recordedAudio()).toFixed(0)} dB SPL, stick force ${st.stick.force.toFixed(0)} N${st.delayClamped ? ", delay spread clamped" : ""}`;
713 this.scrub.max = String(Math.max(0, rec.frames.length - 1));
714 this.updatePeak();
715 }
716 }
717 if (this.sim === sim) {
718 this.running = false;
719 this.setLocked(false);
720 const st = sim.status();
721 this.runStatus.textContent = `Full model: ${st.t.toFixed(2)} s recorded, peak ${peakSpl(sim.recordedAudio()).toFixed(0)} dB SPL, peak force ${st.stick.maxForce.toFixed(0)} N, largest displacement ${(st.wmax * 1e3).toFixed(2)} mm.`;
722 if (this.rec) { this.rec.audio = sim.recordedAudio(); this.rec.samples = sim.samples; this.rec.frames = sim.frames; }
723 this.updateNotes();
724 this.updateButtons();
725 this.updatePeak();
726 this.tutorial?.refresh();
727 }
728 }
730 // ---------- Run control ----------
732 private setRunMode(mode: RunMode): void {
733 if (mode === "full" && !this.device) mode = "linear";
734 this.runMode = mode;
735 this.runModeSel.value = mode;
736 if (mode === "linear" && this.plate && !this.modes) this.useCachedModes();
737 if (mode === "full") this.modeBrowser.clear("Switch to the linear model to compute the modes.");
738 this.updateButtons();
739 this.tutorial?.refresh();
740 }
742 private start(): void {
743 if (this.runMode === "linear") void this.runLinear();
744 else void this.runFull();
745 }
746 private pause(): void {
747 if (!this.running) return;
748 this.paused = !this.paused;
749 this.pauseBtn.textContent = this.paused ? "Resume" : "Pause";
750 }
751 private stopRun(): void {
752 if (this.sim && this.running) { this.sim.stop(); this.running = false; }
753 this.paused = false;
754 this.pauseBtn.textContent = "Pause";
755 this.setLocked(false);
756 this.updateButtons();
757 }
758 private continueRun(): void {
759 const sim = this.sim;
760 if (!sim || this.running || !sim.canContinue()) return;
761 sim.setDuration(this.form.get().duration);
762 this.running = true;
763 this.setLocked(true);
764 this.setView("live");
765 this.updateButtons();
766 void this.fullLoop();
767 }
769 private setLocked(locked: boolean): void {
770 this.editor.setLocked(locked);
771 this.form.setLocked(locked);
772 this.runModeSel.disabled = locked;
773 }
775 private updateButtons(): void {
776 const linear = this.runMode === "linear";
777 const canLinear = linear && !!this.plate && !this.synthBusy;
778 const canFull = !linear && !!this.plate && !!this.device && !this.running;
779 this.startBtn.disabled = !(canLinear || canFull);
780 this.startBtn.textContent = linear ? "Synthesize" : "Start";
781 this.pauseBtn.disabled = linear || !this.running;
782 this.stopBtn.disabled = linear || !this.running;
783 this.continueBtn.disabled = linear || this.running || !this.sim || !this.sim.canContinue() || this.sim.samples >= Math.round(this.form.get().duration * this.form.get().fs);
784 this.pauseBtn.hidden = linear; this.stopBtn.hidden = linear; this.continueBtn.hidden = linear;
785 this.liveBtn.hidden = linear;
786 }
788 // ---------- Recording, view, playback ----------
790 private installRecording(audio: Float32Array, frames: Float32Array[], p: SimParams, source: RunMode): void {
791 this.rec = { audio, samples: audio.length, fs: p.fs, frames, fps: p.fps, source };
792 this.spec.setOptions({ fs: p.fs });
793 this.spec.setDuration(p.duration);
794 this.spec.setSignal(audio);
795 this.scrub.max = String(Math.max(0, frames.length - 1));
796 if (frames.length > 0) {
797 this.frameIndex = 0;
798 if (this.view !== "mode") { this.setView("movie"); this.showFrame(); }
799 }
800 this.updatePeak();
801 this.updateButtons();
802 }
804 private setView(v: ViewState): void {
805 this.view = v;
806 if (v === "design") { this.renderer.setField(null); this.overlay.textContent = this.plate ? "Stress-free shape" : ""; }
807 else if (v === "live") { this.overlay.textContent = "Live"; if (this.sim) this.renderer.setField(this.sim.frames[this.sim.frames.length - 1]); }
808 else if (v === "movie") this.showFrame();
809 }
811 private showFrame(): void {
812 const rec = this.rec;
813 if (!rec || rec.frames.length === 0) return;
814 const f = Math.max(0, Math.min(rec.frames.length - 1, this.frameIndex));
815 this.frameIndex = f;
816 this.scrub.value = String(f);
817 this.timeLabel.textContent = `${(f / rec.fps).toFixed(3)} s`;
818 this.renderer.setField(rec.frames[f]);
819 this.overlay.textContent = `${rec.source === "linear" ? "Linear" : "Full"} model, t = ${(f / rec.fps).toFixed(3)} s`;
820 }
822 private playable(): Float32Array | null {
823 const rec = this.rec;
824 if (!rec || rec.samples === 0) return null;
825 const sig = rec.audio.subarray(0, rec.samples);
826 return applyLevel(sig, levelGain(sig, rec.fs, this.levelMode, this.gainDb));
827 }
829 private updatePeak(): void {
830 const s = this.playable();
831 if (!s) { this.peakLabel.textContent = ""; this.downloadBtn.disabled = true; this.playBtn.disabled = true; return; }
832 const db = peakDbfs(s);
833 this.peakLabel.textContent = `Peak ${db.toFixed(1)} dBFS${db > -0.5 ? " (clipping)" : ""}`;
834 this.peakLabel.className = db > -0.5 ? "badge warn" : "badge";
835 this.downloadBtn.disabled = false;
836 this.playBtn.disabled = false;
837 }
839 private togglePlay(): void {
840 if (this.player.playing) { this.player.stop(); this.playBtn.textContent = "Play"; this.spec.setCursor(null); return; }
841 const s = this.playable(), rec = this.rec;
842 if (!s || !rec) return;
843 // Play from the scrubbed position only when the user has scrubbed to one; from the live
844 // view, or from the end of the recording, start over.
845 const atEnd = rec.frames.length > 1 && this.frameIndex >= rec.frames.length - 1;
846 const start = this.view === "movie" && rec.frames.length > 1 && !atEnd ? this.frameIndex / rec.fps : 0;
847 this.playBtn.textContent = "Stop";
848 const prevView = this.view;
849 this.player.play(s, rec.fs, start, () => { this.playBtn.textContent = "Play"; this.spec.setCursor(null); if (prevView === "live") this.setView("live"); });
850 const tick = () => {
851 if (!this.player.playing) return;
852 const t = this.player.position();
853 this.spec.setCursor(t);
854 if (rec.frames.length > 1) { this.frameIndex = Math.round(t * rec.fps); this.view = "movie"; this.showFrame(); }
855 requestAnimationFrame(tick);
856 };
857 requestAnimationFrame(tick);
858 }
860 private download(): void {
861 const s = this.playable(), rec = this.rec;
862 if (!s || !rec) return;
863 const blob = encodeWav(s, rec.fs);
864 const a = document.createElement("a");
865 a.href = URL.createObjectURL(blob);
866 a.download = `${(this.plate?.name ?? "cymbalsim").replace(/[^a-z0-9]+/gi, "-").toLowerCase()}-${rec.source}.wav`;
867 a.click();
868 setTimeout(() => URL.revokeObjectURL(a.href), 1000);
869 }
871 private updateTicks(): void {
872 this.spec.setTicks(this.showTicks && this.modes ? Array.from(this.modes.freqs) : null);
873 }
875 // ---------- Tutorial ----------
877 /** The state the tutorial's pages read. */
878 private tutorialContext(): TutorialContext {
879 const rec = this.rec;
880 const st = this.sim ? this.sim.status() : null;
881 return {
882 plate: this.plate,
883 design: this.design,
884 params: this.form.get(),
885 spacing: this.plateSpacing,
886 sys: this.sys,
887 modes: this.modes,
888 model: this.model,
889 lastContact: this.lastContact,
890 recording: rec && rec.samples > 0 ? { source: rec.source, seconds: rec.samples / rec.fs } : null,
891 full: st && st.totalSteps > 0 ? { peakForce: st.stick.maxForce, wmax: st.wmax, t: st.t, done: st.phase === "done" } : null,
892 gpu: this.device !== null,
893 runMode: this.runMode,
894 spectrogram: { ...this.specOpts },
895 memo: this.tutorialMemo,
896 };
897 }
899 /** The actions the tutorial's pages can take. */
900 private tutorialHost(): TutorialHost {
901 return {
902 ctx: () => this.tutorialContext(),
903 loadPreset: async (id) => { this.editor.selectPreset(id); },
904 loadScript: async (src) => { this.editor.setSource(src); this.onSource(src); },
905 setParam: (key, value) => {
906 if (key === "duration") {
907 this.durationInput.value = String(value);
908 this.durationInput.dispatchEvent(new Event("change"));
909 return;
910 }
911 this.form.set(key, value);
912 this.onParam(key, false);
913 },
914 computeModes: () => this.ensureModes(),
915 showMode: (m) => this.modeBrowser.select(m),
916 synthesize: async () => {
917 if (this.runMode !== "linear") this.setRunMode("linear");
918 await this.runLinear();
919 },
920 play: () => { if (!this.player.playing) this.togglePlay(); },
921 setRunMode: (mode) => this.setRunMode(mode),
922 runFull: () => this.runFull(),
923 setSpectrogram: (o) => {
924 if (o.window !== undefined) { this.specOpts.window = o.window; this.specWinSel.value = String(o.window); this.spec.setOptions({ window: o.window, hop: o.window / 8 }); }
925 if (o.logFreq !== undefined) { this.specOpts.logFreq = o.logFreq; this.specLogChk.checked = o.logFreq; this.spec.setOptions({ logFreq: o.logFreq }); }
926 this.tutorial?.refresh();
927 },
928 setViewOptions: (o) => {
929 if (o.color !== undefined) { this.viewOpts.color = o.color; this.colorSel.value = o.color; }
930 if (o.exaggeration !== undefined) this.viewOpts.exaggeration = o.exaggeration;
931 this.renderer.setOptions(this.viewOpts);
932 },
933 };
934 }
936 // ---------- Tests ----------
938 async selfTest(): Promise<string> {
939 if (!this.device) return "no WebGPU";
940 const lines: string[] = [];
941 for (const id of ["flat-rectangle", "bowed-rectangle", "crash-16", "crash-bell-16", "ellipse"]) {
942 const pr = presetById(id)!;
943 const d = compileDesign(pr.source);
944 const pl = evaluatePlate(d, 0.012);
945 const r = await runSelfTest(this.device, pl, this.form.get());
946 lines.push(`${id}: max relative error ${r.maxRel.toExponential(2)} (${r.n} nodes)`);
947 }
948 return lines.join("\n");
949 }
951 private testStatus(): unknown {
952 return {
953 design: this.design?.name ?? null,
954 modes: this.modes ? { count: this.modes.count, missing: this.modes.missing, first: Array.from(this.modes.freqs.slice(0, 5)) } : null,
955 synthesized: this.synthesized,
956 running: this.running,
957 samples: this.rec?.samples ?? 0,
958 frames: this.rec?.frames.length ?? 0,
959 source: this.rec?.source ?? null,
960 peakPressure: this.rec ? Array.from(this.rec.audio.subarray(0, this.rec.samples)).reduce((m, v) => Math.max(m, Math.abs(v)), 0) : 0,
961 sim: this.sim ? this.sim.status() : null,
962 contact: this.lastContact ? { peakForce: this.lastContact.peakForce, contactTime: this.lastContact.contactTime } : null,
963 editorStatus: ($("design").querySelector(".editor-status") as HTMLElement | null)?.textContent ?? "",
964 };
965 }
966}
968const app = new App();
969app.init().catch((e) => {
970 console.error(e);
971 $("viewOverlay").textContent = `Failed to start: ${e instanceof Error ? e.message : String(e)}`;
972});
974export { app, PRESETS, isFlat, formatNumber };