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 { runInWorker } from '../sim/run';
9import { CPU_RATE, parseSettings, runCost, settingsQuery, simOptions, type Settings } from './settings';
10import { checkPasscode, getPasscode, loadResult, probeResult, resultKey, setPasscode, storeResult, type Backend } from '../sim/cache';
11import type { BeadSystem, Excitation, SimResult } from '../sim/types';
13// The page every instrument shares: presets and control panel, 3D model,
14// setup summary, run summary, audio, waveform, spectrogram, spectrum, energy.
15// An instrument adds its own setup rows, extra result cards and views.
17export interface SimParams {
18 duration: number;
19 fs: number;
20 cfl: number;
21 frameRate: number;
22}
24export interface Built {
25 sys: BeadSystem;
26 exc: Excitation;
27 pickup: Float64Array;
28 pickupDelay?: Float64Array; // per bead, in samples (a microphone)
29 scene: SceneSpec;
30}
32export interface Preset<P> {
33 name: string;
34 description: string;
35 params: P;
36}
38export interface Extras<P> {
39 show(p: P, built: Built, r: SimResult): void;
40}
42export interface InstrumentConfig<P extends SimParams> {
43 title: string;
44 wavName: string;
45 audioQuantity?: { label: string; unit: string }; // default: acceleration, m/s²
46 presets: Preset<P>[];
47 sections: Section<P>[];
48 // WebGPU on by default (default true); off where the systems are too small to gain from it
49 webgpuDefault?: boolean;
50 // instrument-specific summary of the setup; built = null when the parameters are invalid
51 setup(p: P): { rows: [string, string][]; warnings: string[]; built: Built | null };
52 summaryRows?(p: P, built: Built, r: SimResult): [string, string][];
53 spectrumMarkers?(p: P): { markers: Marker[]; legend: string };
54 extraCards?: string; // cards with data-r="out" hidden, shown after a run
55 mountExtras?(q: <T extends HTMLElement>(r: string) => T, timeline: Timeline): Extras<P>;
56}
58const statRows = (rows: [string, string][]) => rows.map(([k, v]) => `<div><span>${k}</span><b>${v}</b></div>`).join('');
60export function mountInstrumentPage<P extends SimParams>(root: HTMLElement, cfg: InstrumentConfig<P>) {
61 root.innerHTML = `
62 <div class="instrument">
63 <aside class="panel">
64 <a href="#/" class="back">← All instruments</a>
65 <h1>${cfg.title}</h1>
66 <label class="ctl preset"><span class="ctl-name">Preset</span><select data-r="preset"></select></label>
67 <p class="sub" data-r="preset-desc"></p>
68 <div class="share-row"><button class="btn-small" data-r="share" title="Copy a link that opens this page with the current settings">Copy link to these settings</button><span class="note" data-r="share-msg"></span></div>
69 <input class="share-url" data-r="share-url" readonly hidden aria-label="link to these settings">
70 <div class="run-row top">
71 <button class="btn" data-r="run">Run simulation</button>
72 <button class="btn-small" data-r="cancel" hidden>Cancel</button>
73 <button class="btn-small" data-r="load-cached" hidden>Load cached</button>
74 <label class="inline gpu-toggle" data-r="gpu-label"><input type="checkbox" data-r="gpu"> WebGPU</label>
75 </div>
76 <p class="note" data-r="cached-avail" hidden></p>
77 <progress data-r="progress" max="1" value="0" hidden></progress>
78 <p class="error" data-r="error" hidden></p>
79 <details class="cache-ctl">
80 <summary data-r="cache-state"></summary>
81 <p class="note">Results are shared: when someone has already computed a run with these settings, you can load it instead of running it again. With the passcode, this browser also stores its runs there.</p>
82 <div class="cache-form"><input type="password" data-r="cache-pass" placeholder="Passcode" autocomplete="off"><button class="btn-small" data-r="cache-save">Save</button><button class="btn-small" data-r="cache-forget">Forget</button></div>
83 <p class="note" data-r="cache-msg"></p>
84 </details>
85 <div data-r="controls"></div>
86 </aside>
87 <main class="results">
88 <section class="card"><h2>Model</h2><div data-r="scene"></div></section>
89 <section class="card"><h2>Setup</h2><div data-r="derived" class="stats"></div><ul data-r="warnings" class="warnings"></ul></section>
90 <section class="card" data-r="out" hidden>
91 <h2>Run</h2><div data-r="summary" class="stats"></div>
92 <p class="note" data-r="cache-note"></p>
93 <div class="audio-row"><audio controls data-r="audio"></audio><a class="btn-small" data-r="download" download="${cfg.wavName}">Download .wav</a></div>
94 <p class="note" data-r="audio-note"></p>
95 </section>
96 <section class="card" data-r="out" hidden>
97 <div class="card-head"><h2>${cap((cfg.audioQuantity ?? { label: 'pickup acceleration' }).label)}</h2>
98 <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>
99 <div class="canvas-wrap"><canvas data-r="wave"></canvas></div>
100 </section>
101 <section class="card" data-r="out" hidden>
102 <div class="card-head"><h2>Spectrogram</h2>
103 <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>
104 <div class="canvas-wrap tall"><canvas data-r="spec"></canvas></div>
105 </section>
106 <section class="card" data-r="out" hidden>
107 <div class="card-head"><h2>Spectrum</h2><div class="legend" data-r="spec-legend"></div></div>
108 <div class="canvas-wrap"><canvas data-r="spectrum"></canvas></div>
109 </section>
110 ${cfg.extraCards ?? ''}
111 <section class="card" data-r="out-contact" hidden>
112 <h2>Contact force</h2>
113 <div class="canvas-wrap short"><canvas data-r="contact"></canvas></div>
114 <p class="note" data-r="contact-note"></p>
115 </section>
116 <section class="card" data-r="out" hidden>
117 <h2>Energy</h2>
118 <div class="canvas-wrap short"><canvas data-r="energy"></canvas></div>
119 <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>
120 </section>
121 </main>
122 </div>`;
123 const q = <T extends HTMLElement>(r: string) => root.querySelector(`[data-r="${r}"]`) as T;
124 const presetSel = q<HTMLSelectElement>('preset');
125 cfg.presets.forEach((p, i) => presetSel.add(new Option(p.name, String(i))));
126 const presetDesc = q<HTMLParagraphElement>('preset-desc');
127 const runBtn = q<HTMLButtonElement>('run');
128 const cancelBtn = q<HTMLButtonElement>('cancel');
129 const progress = q<HTMLProgressElement>('progress');
130 const errorBox = q<HTMLParagraphElement>('error');
131 const gpuBox = q<HTMLInputElement>('gpu');
132 const loadBtn = q<HTMLButtonElement>('load-cached');
133 const availNote = q<HTMLParagraphElement>('cached-avail');
134 const cacheNote = q<HTMLParagraphElement>('cache-note');
135 const instrumentId = cfg.wavName.replace(/\.wav$/, ''); // e.g. bead-cymbal
136 const hasGpu = 'gpu' in navigator;
137 const gpuKey = `toy-instruments.webgpu.${cfg.wavName}`;
138 let gpuPref: string | null = null;
139 try {
140 gpuPref = localStorage.getItem(gpuKey);
141 } catch {
142 /* storage unavailable */
143 }
144 gpuBox.checked = hasGpu && (gpuPref ? gpuPref === 'on' : cfg.webgpuDefault !== false);
145 gpuBox.disabled = !hasGpu;
146 q('gpu-label').title = hasGpu
147 ? 'Run the solver on the GPU (single precision). Faster for meshes of a few hundred beads or more; slower for small systems. Falls back to the CPU if the GPU cannot run it.'
148 : 'This browser does not offer WebGPU; the solver runs on the CPU.';
149 gpuBox.addEventListener('change', () => {
150 try {
151 localStorage.setItem(gpuKey, gpuBox.checked ? 'on' : 'off');
152 } catch {
153 /* storage unavailable */
154 }
155 checkCache();
156 });
158 const wave = new LinePlot(q('wave'));
159 const spec = new Spectrogram(q('spec'));
160 const specPlot = new LinePlot(q('spectrum'));
161 const energyPlot = new LinePlot(q('energy'));
162 const contactPlot = new LinePlot(q('contact'));
163 const quantity = cfg.audioQuantity ?? { label: 'acceleration', unit: 'm/s²' };
164 const timeline = new Timeline();
165 const scene = new BeadScene(q('scene'), timeline);
166 const extras = cfg.mountExtras?.(q, timeline);
167 let waveRange = 0;
168 let last: { p: P; r: SimResult } | null = null;
169 let cancelRun: (() => void) | null = null; // set while a run (or a cache download) is in progress
170 // the cached result for the current settings, if there is one
171 let cached: { p: P; built: Built; key: string; stored?: Date } | null = null;
172 let probeSeq = 0;
173 let probeTimer = 0;
174 let audioUrl: string | null = null;
175 let pendingAudio: Blob | null = null; // a newer partial result's audio, held back while the player plays
177 // settings from a shared link, applied once and then removed from the address
178 const shared = readSharedLink(cfg);
179 if (shared) {
180 presetSel.value = String(shared.preset);
181 if (shared.gpu !== undefined && hasGpu) gpuBox.checked = shared.gpu;
182 }
183 const controls = renderControls(q('controls'), cfg.sections, shared?.params ?? cfg.presets[0].params, () => updateSetup());
184 presetDesc.textContent = cfg.presets[Number(presetSel.value)].description;
185 presetSel.addEventListener('change', () => {
186 const pr = cfg.presets[Number(presetSel.value)];
187 presetDesc.textContent = pr.description;
188 shareMsg.textContent = '';
189 controls.set(pr.params);
190 });
192 const shareMsg = q<HTMLSpanElement>('share-msg');
193 const shareUrl = q<HTMLInputElement>('share-url');
194 if (shared) shareMsg.textContent = 'Settings loaded from a shared link.';
195 q('share').addEventListener('click', async () => {
196 const url = sharedLink(controls.get(), Number(presetSel.value), gpuBox.checked);
197 shareUrl.hidden = true;
198 try {
199 await navigator.clipboard.writeText(url);
200 shareMsg.textContent = 'Link copied.';
201 } catch {
202 // no clipboard access: show the link to copy by hand
203 shareMsg.textContent = 'Copy this link:';
204 shareUrl.value = url;
205 shareUrl.hidden = false;
206 shareUrl.select();
207 }
208 });
210 function updateSetup() {
211 const p = controls.get();
212 const { rows, warnings, built } = cfg.setup(p);
213 if (built) {
214 scene.showSetup(built.scene);
215 const { omegaMax: wmax, stepsPerSample: spp, work } = runCost(p, built);
216 rows.push(['Highest frequency', `${fmtNum(wmax / (2 * Math.PI))} Hz`]);
217 rows.push(['Time step', `${fmtNum(1 / (p.fs * spp))} s (${spp} per sample)`]);
218 rows.push(['Element updates', fmtNum(work)]);
219 const frameMB = (Math.round(p.duration * p.frameRate) * 3 * built.sys.n * 4) / 1e6;
220 if (frameMB > 400) warnings.push(`Replay frames would take ${fmtNum(frameMB)} MB; lower the replay frame rate or the duration.`);
221 if (work > 3e9) warnings.push(`This run is large (${fmtNum(work)} element updates): expect roughly ${fmtNum(work / CPU_RATE / 60)} min on a desktop CPU (WebGPU is usually much faster).`);
222 }
223 q('derived').innerHTML = statRows(rows);
224 q('warnings').innerHTML = warnings.map((w) => `<li>${w}</li>`).join('');
225 runBtn.disabled = !built || !!cancelRun;
226 checkCache();
227 }
229 // what the solver gets for parameters p; null when they are invalid
230 function inputs(p: P) {
231 const { built } = cfg.setup(p);
232 if (!built) return null;
233 return { built, opt: simOptions(p, built), backend: (gpuBox.checked ? 'gpu' : 'cpu') as Backend };
234 }
236 // Look up (debounced) whether the shared cache has a result for the current settings,
237 // and offer to load it next to Run.
238 function checkCache() {
239 const seq = ++probeSeq;
240 cached = null;
241 loadBtn.hidden = availNote.hidden = true;
242 clearTimeout(probeTimer);
243 probeTimer = window.setTimeout(async () => {
244 const p = controls.get();
245 const inp = inputs(p);
246 if (!inp) return;
247 try {
248 const key = await resultKey(instrumentId, inp.built.sys, inp.built.exc, inp.opt, inp.backend);
249 const hit = await probeResult(key);
250 if (seq !== probeSeq || !hit) return;
251 cached = { p, built: inp.built, key, stored: hit.stored };
252 const when = hit.stored ? `computed ${hit.stored.toISOString().slice(0, 10)}, ` : '';
253 availNote.textContent = `A cached result exists for these settings (${when}${fmtNum(hit.bytes / 1e6)} MB). Load it, or run the simulation again.`;
254 loadBtn.hidden = availNote.hidden = false;
255 loadBtn.disabled = !!cancelRun;
256 } catch {
257 /* cache unreachable: just don't offer it */
258 }
259 }, 250);
260 }
261 updateSetup();
263 q('wave-range').addEventListener('click', (e) => {
264 const b = (e.target as HTMLElement).closest('button');
265 if (!b) return;
266 waveRange = Number(b.dataset.v);
267 q('wave-range').querySelectorAll('button').forEach((x) => x.classList.toggle('on', x === b));
268 drawWave();
269 });
270 q<HTMLSelectElement>('fmax').addEventListener('change', (e) => {
271 spec.fmax = Number((e.target as HTMLSelectElement).value);
272 spec.draw();
273 drawSpectrum();
274 });
276 function drawWave() {
277 if (!last) return;
278 const { p, r } = last;
279 const t = new Float64Array(r.audio.length);
280 for (let i = 0; i < t.length; i++) t[i] = i / r.fs;
281 wave.set([{ x: t, y: r.audio, color: css('--series-1'), label: 'a' }], {
282 xLabel: 'time (s)',
283 yLabel: `${quantity.label} (${quantity.unit})`,
284 // a partial result is drawn on the axis of the whole run
285 xRange: [0, waveRange ? Math.min(waveRange, p.duration) : Math.max(p.duration, t[t.length - 1])],
286 });
287 }
289 function drawSpectrum() {
290 if (!last) return;
291 const { p, r } = last;
292 const s = spectrum(r.audio, r.fs);
293 let top = -Infinity;
294 for (const v of s.db) top = Math.max(top, v);
295 const db = s.db.map((v) => Math.max(v - top, -100));
296 const m = cfg.spectrumMarkers?.(p);
297 q('spec-legend').innerHTML =
298 `<span><i class="sw" style="background:var(--series-1)"></i>pickup signal</span>` + (m?.legend ?? '');
299 specPlot.set([{ x: s.freq, y: db, color: css('--series-1'), label: 'level (dB)' }], {
300 xLabel: 'frequency (Hz)',
301 yLabel: 'level (dB re max)',
302 xRange: [0, Math.min(spec.fmax, r.fs / 2)],
303 yRange: [-100, 5],
304 markers: m?.markers,
305 });
306 }
308 // partial: r covers only the start of a run still in progress. update: r
309 // extends the result already shown (same run), so the replay position, the
310 // exaggeration and the audio player's position are kept.
311 function show(p: P, built: Built, r: SimResult, partial = false, update = false) {
312 last = { p, r };
313 const simulated = r.audio.length / r.fs;
314 cacheNote.textContent = partial
315 ? `Partial result: ${fmtNum(simulated)} s of ${fmtNum(p.duration)} s simulated so far. It updates every few seconds while the run continues; the audio player picks up the newer sound when it is paused.`
316 : '';
317 root.querySelectorAll<HTMLElement>('[data-r="out"]').forEach((e) => (e.hidden = false));
318 let peak = 0;
319 for (const v of r.audio) peak = Math.max(peak, Math.abs(v));
320 const emax = Math.max(...r.energy);
321 let bal = 0;
322 for (const b of r.balance) bal = Math.max(bal, Math.abs(b));
323 const rt = simulated / r.wallSeconds;
324 q('summary').innerHTML = statRows([
325 ...(partial ? ([['Simulated so far', `${fmtNum(simulated)} s of ${fmtNum(p.duration)} s`]] as [string, string][]) : []),
326 ['Solver', (r.backend ?? 'CPU') + (r.fallback ? ` (WebGPU failed: ${r.fallback})` : '')],
327 ['Time step', `${fmtNum(r.dt)} s, ${r.stepsPerSample} per sample`],
328 [partial ? 'Wall time so far' : 'Wall time', `${fmtNum(r.wallSeconds)} s (${rt >= 1 ? fmtNum(rt) + '× faster than' : fmtNum(1 / rt) + '× slower than'} real time)`],
329 ['Energy balance error', emax > 0 ? `${fmtNum((bal / emax) * 100)}% of peak energy` : '–'],
330 ...(cfg.summaryRows?.(p, built, r) ?? []),
331 ...contactRows(r),
332 [`Peak ${quantity.label}`, `${fmtNum(peak)} ${quantity.unit}`],
333 ]);
334 setAudio(encodeWav(r.audio, r.fs), update);
335 q('audio-note').textContent = `16-bit mono, ${r.fs} Hz, normalized so the peak is −1 dBFS${partial ? ' (of the sound so far)' : ''}.`;
336 drawWave();
337 spec.setSignal(r.audio, r.fs);
338 drawSpectrum();
339 if (update) timeline.extend(r.frameTimes);
340 else timeline.setTimes(r.frameTimes);
341 scene.showReplay({ ...built.scene, frames: r.frames, malletPos: r.malletPos }, update);
342 extras?.show(p, built, r);
343 showContact(r);
344 energyPlot.set([{ x: r.frameTimes, y: r.energy, color: css('--series-1'), label: 'energy (J)' }], {
345 xLabel: 'time (s)',
346 xRange: [0, Math.max(p.duration, r.frameTimes[r.frameTimes.length - 1])],
347 yLabel: 'energy (J)',
348 yRange: [0, emax * 1.05 || 1],
349 });
350 }
352 // Give the player new audio. While it plays, a partial result's audio waits
353 // until it pauses or ends (swapping the source would stop it); when it is
354 // paused partway, the new audio resumes from the same point.
355 const player = q<HTMLAudioElement>('audio');
356 function setAudio(wav: Blob, update: boolean) {
357 pendingAudio = null;
358 if (update && audioUrl && !player.paused && !player.ended) {
359 pendingAudio = wav;
360 return;
361 }
362 const at = update && !player.ended ? player.currentTime : 0;
363 if (audioUrl) URL.revokeObjectURL(audioUrl);
364 audioUrl = URL.createObjectURL(wav);
365 player.src = audioUrl;
366 q<HTMLAnchorElement>('download').href = audioUrl;
367 if (at > 0) player.addEventListener('loadedmetadata', () => (player.currentTime = Math.min(at, player.duration)), { once: true });
368 }
369 const flushAudio = () => {
370 if (pendingAudio) setAudio(pendingAudio, true);
371 };
372 player.addEventListener('pause', flushAudio);
373 player.addEventListener('ended', flushAudio);
375 function showContact(r: SimResult) {
376 const card = q('out-contact');
377 card.hidden = !r.contactForce;
378 if (!r.contactForce) return;
379 const cf = r.contactForce;
380 const c = contacts(cf, r.fs);
381 const end = c.length ? c[c.length - 1].start + c[c.length - 1].ms / 1000 : 0.01;
382 const nShow = Math.min(cf.length, Math.ceil((end * 1.3 + 0.002) * r.fs));
383 const t = new Float64Array(nShow);
384 for (let i = 0; i < nShow; i++) t[i] = (i / r.fs) * 1000;
385 contactPlot.set([{ x: t, y: cf.subarray(0, nShow), color: css('--series-2'), label: 'force (N)' }], {
386 xLabel: 'time (ms)',
387 yLabel: 'contact force (N)',
388 yRange: [0, Math.max(...cf.subarray(0, nShow)) * 1.08 || 1],
389 });
390 q('contact-note').textContent = c.length
391 ? `${c.length} contact${c.length > 1 ? 's' : ''}: ` +
392 c.map((k) => `${fmtNum(k.ms)} ms from ${fmtNum(k.start * 1000)} ms, peak ${fmtNum(k.peak)} N`).join('; ') +
393 '. 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).'
394 : 'The mallet never touched the instrument.';
395 }
397 function setBusy(cancel: (() => void) | null) {
398 cancelRun = cancel;
399 runBtn.disabled = loadBtn.disabled = !!cancel;
400 cancelBtn.hidden = !cancel;
401 progress.hidden = !cancel;
402 progress.value = 0;
403 if (cancel) errorBox.hidden = true;
404 }
406 // Run the simulation and, if this browser has the passcode, store the result.
407 async function run() {
408 const p = controls.get();
409 const inp = inputs(p);
410 if (!inp) return;
411 const { built, opt, backend } = inp;
412 // Partial results are shown as they come; when they arrive faster than the
413 // page draws them, only the newest is drawn.
414 let shown = false; // a partial result of this run is on the page
415 let latest: SimResult | null = null;
416 let finished = false;
417 const onPartial = (r: SimResult) => {
418 if (!latest)
419 setTimeout(() => {
420 if (!latest || finished) return;
421 show(p, built, latest, true, shown);
422 shown = true;
423 latest = null;
424 });
425 latest = r;
426 };
427 const running = runInWorker(pageWorker, built.sys, built.exc, opt, backend === 'gpu', (f) => (progress.value = f), onPartial);
428 setBusy(running.cancel);
429 try {
430 const r = await running.promise;
431 finished = true;
432 show(p, built, r, false, shown);
433 if (getPasscode()) {
434 // a WebGPU run that fell back to the CPU is stored as a CPU result
435 const actual: Backend = r.backend?.startsWith('WebGPU') ? 'gpu' : 'cpu';
436 const key = await resultKey(instrumentId, built.sys, built.exc, opt, actual);
437 cacheNote.textContent = 'Storing in the shared cache…';
438 storeResult(key, r, { instrument: instrumentId, backend: r.backend, wallSeconds: r.wallSeconds })
439 .then(() => {
440 if (last?.r === r) cacheNote.textContent = 'Stored in the shared cache.';
441 checkCache();
442 })
443 .catch((e) => {
444 if (last?.r === r) cacheNote.textContent = `Not stored in the shared cache: ${(e as Error).message}`;
445 });
446 }
447 } catch (e) {
448 finished = true;
449 if (shown) cacheNote.textContent = `The run ${(e as Error).message === 'cancelled' ? 'was cancelled' : 'stopped'}; this is the partial result up to ${fmtNum(last!.r.audio.length / last!.r.fs)} s.`;
450 if ((e as Error).message !== 'cancelled') {
451 errorBox.textContent = `The simulation failed: ${(e as Error).message}`;
452 errorBox.hidden = false;
453 }
454 } finally {
455 setBusy(null);
456 }
457 }
459 // Download and show the cached result for the current settings.
460 async function loadCached() {
461 if (!cached) return;
462 const { p, built, key } = cached;
463 const abort = new AbortController();
464 setBusy(() => abort.abort());
465 try {
466 const hit = await loadResult(key, (f) => (progress.value = f), abort.signal);
467 if (!hit) throw new Error('the entry is no longer in the cache');
468 show(p, built, hit.result);
469 const when = hit.stored ? ` on ${hit.stored.toISOString().slice(0, 10)}` : '';
470 cacheNote.textContent = `Loaded from the shared cache (computed${when}; the wall time is that of the original run).`;
471 } catch (e) {
472 if (!abort.signal.aborted) {
473 errorBox.textContent = `Could not load the cached result: ${(e as Error).message}`;
474 errorBox.hidden = false;
475 checkCache();
476 }
477 } finally {
478 setBusy(null);
479 }
480 }
481 runBtn.addEventListener('click', run);
482 loadBtn.addEventListener('click', loadCached);
483 cancelBtn.addEventListener('click', () => cancelRun?.());
485 // passcode for writing to the shared cache
486 const passInput = q<HTMLInputElement>('cache-pass');
487 const cacheMsg = q<HTMLParagraphElement>('cache-msg');
488 const showCacheState = () =>
489 (q('cache-state').textContent = getPasscode() ? 'Shared cache: runs are stored' : 'Shared cache: read only');
490 showCacheState();
491 q('cache-save').addEventListener('click', async () => {
492 const pass = passInput.value.trim();
493 if (!pass) return;
494 cacheMsg.textContent = 'Checking…';
495 try {
496 const { valid, reason } = await checkPasscode(pass);
497 if (!valid) {
498 cacheMsg.textContent = `Not saved: ${reason ?? 'invalid passcode'}.`;
499 return;
500 }
501 setPasscode(pass);
502 passInput.value = '';
503 cacheMsg.textContent = 'Saved in this browser. Runs from now on are stored in the cache.';
504 } catch (e) {
505 cacheMsg.textContent = `Could not check the passcode: ${(e as Error).message}`;
506 }
507 showCacheState();
508 });
509 q('cache-forget').addEventListener('click', () => {
510 setPasscode(null);
511 cacheMsg.textContent = 'Passcode removed from this browser.';
512 showCacheState();
513 });
514}
516// A link to this page with settings p (see settings.ts).
517function sharedLink<P extends SimParams>(p: P, preset: number, gpu: boolean): string {
518 const route = location.hash.split('?')[0];
519 return `${location.origin}${location.pathname}${route}?${settingsQuery(p, preset, gpu)}`;
520}
522// Settings from a shared link in the address (#/<instrument>?...), which is then removed.
523function readSharedLink<P extends SimParams>(cfg: InstrumentConfig<P>): Settings<P> | null {
524 const [route, query] = location.hash.split('?');
525 if (query === undefined) return null;
526 history.replaceState(history.state, '', `${location.pathname}${location.search}${route}`);
527 return parseSettings(cfg, query);
528}
530const pageWorker = () => new Worker(new URL('../sim/worker.ts', import.meta.url), { type: 'module' });
532// separate contact intervals in the contact-force record
533function contacts(cf: Float32Array, fs: number): { start: number; ms: number; peak: number }[] {
534 const out: { start: number; ms: number; peak: number }[] = [];
535 let i = 0;
536 while (i < cf.length) {
537 if (cf[i] > 0) {
538 const a = i;
539 let peak = 0;
540 while (i < cf.length && cf[i] > 0) peak = Math.max(peak, cf[i++]);
541 out.push({ start: a / fs, ms: ((i - a) / fs) * 1000, peak });
542 } else i++;
543 }
544 return out;
545}
547function contactRows(r: SimResult): [string, string][] {
548 if (!r.contactForce) return [];
549 const c = contacts(r.contactForce, r.fs);
550 return [
551 [
552 'Contact',
553 c.length
554 ? `${fmtNum(c[0].ms)} ms, peak ${fmtNum(c[0].peak)} N${c.length > 1 ? ` (+${c.length - 1} more contact${c.length > 2 ? 's' : ''})` : ''}`
555 : 'none',
556 ],
557 ];
558}
560const cap = (s: string) => s[0].toUpperCase() + s.slice(1);