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