1// Web Worker: runs the numbl script, computes linear modes, and simulates.
3import { growthRate, relDiff } from "./sim/analysis";
4import { computeModes, isPlanar, modalDamping } from "./sim/modes";
5import { numblEig, runScript } from "./sim/runScript";
6import { simulate } from "./sim/solver";
7import { runTwin } from "./sim/twin";
8import type { BeadSystem, SimResult } from "./sim/types";
10const helperSources = import.meta.glob("../matlab/helpers/*.m", { query: "?raw", import: "default", eager: true }) as Record<string, string>;
11const helpers = Object.entries(helperSources).map(([path, source]) => ({ name: path.split("/").pop()!, source }));
13const MAX_MODE_BEADS = 1500;
14const MAX_TWIN_BYTES = 400e6;
16export interface RunPayload {
17 sys: {
18 n: number;
19 pos0: Float64Array;
20 pinned: Uint8Array;
21 si: Int32Array;
22 sj: Int32Array;
23 nDashpots: number;
24 nBends: number;
25 listenBeads: Int32Array;
26 hitBeads: Int32Array;
27 method: string;
28 duration: number;
29 };
30 result: SimResult;
31 modeFreqs: Float64Array | null;
32 modeDecay: Float64Array | null; // small-amplitude amplitude decay rate of each mode (1/s)
33 notes: string[];
34 check: { dt: number; windows: { t: number; rel: number }[] } | null;
35 // the same run with every hit scaled by 1e-3, its output scaled back up
36 linear: { audio: Float32Array; windows: { t: number; rel: number }[] } | null;
37 // the same run with every hit scaled by (1 + eps): separation of the bead
38 // positions (max over coordinates, relative to the largest displacement)
39 twin: { eps: number; audio: Float32Array; times: Float64Array; sep: Float64Array; rate: number | null } | null;
40}
42export interface RunRequest {
43 type: "run";
44 script: string;
45 dtCheck: boolean;
46 linear: boolean;
47 twin: boolean;
48}
50export type FromWorker =
51 | { type: "log"; text: string }
52 | { type: "stage"; text: string }
53 | { type: "progress"; t: number; duration: number; label: string }
54 | { type: "result"; payload: RunPayload }
55 | { type: "error"; message: string };
57const post = (m: FromWorker, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(m, transfer);
59const windowsOf = (duration: number) =>
60 [0.01, 0.03, 0.1, 0.3, 1, duration].filter((t, i, a) => t <= duration && a.indexOf(t) === i);
62self.onmessage = (ev: MessageEvent<RunRequest>) => {
63 const { script, dtCheck, linear, twin } = ev.data;
64 try {
65 post({ type: "stage", text: "Running script" });
66 const { sys, warnings } = runScript(script, helpers, text => post({ type: "log", text }));
67 const notes = [...warnings];
69 let modes = null;
70 const nFree = sys.pinned.reduce((a, p) => a + (p ? 0 : 1), 0);
71 if (sys.modes) {
72 if (!isPlanar(sys)) notes.push("Linear modes skipped: the beads do not rest in a plane z = const.");
73 else if (nFree > MAX_MODE_BEADS) notes.push(`Linear modes skipped: ${nFree} free beads (limit ${MAX_MODE_BEADS}).`);
74 else {
75 post({ type: "stage", text: `Computing linear modes (${nFree} free beads)` });
76 modes = computeModes(sys, numblEig);
77 const fTop = modes.freqs[modes.freqs.length - 1];
78 const nZero = modes.freqs.filter(f => f < 1e-4 * fTop).length;
79 if (nZero > 0) {
80 notes.push(
81 `${nZero} transverse mode${nZero > 1 ? "s are" : " is"} at (nearly) 0 Hz: the beads can move or tilt freely as a whole. ` +
82 "Pin more beads (a cluster rather than one bead), or tie the object to pinned anchor beads with soft springs."
83 );
84 }
85 }
86 }
88 // positions at every frame, kept for the perturbed twin
89 const saved: Float64Array[] = [];
90 const savedBytes = Math.round(sys.duration * sys.frameRate + 1) * 3 * sys.n * 8;
91 const keep = twin && savedBytes <= MAX_TWIN_BYTES;
92 if (twin && !keep) notes.push(`Perturbed twin skipped: it would store ${(savedBytes / 1e6).toFixed(0)} MB of positions (limit ${MAX_TWIN_BYTES / 1e6} MB). Lower sys.frameRate or sys.duration.`);
94 post({ type: "stage", text: "Simulating" });
95 const result = simulate(sys, {
96 modes,
97 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Simulating" }),
98 onFrame: keep ? (_f, _t, x) => saved.push(x.slice()) : undefined,
99 });
101 let checkOut: RunPayload["check"] = null;
102 if (dtCheck && !result.aborted) {
103 post({ type: "stage", text: "Simulating again with dt/2" });
104 const half: BeadSystem = { ...sys, dt: result.dt / 2 };
105 const r2 = simulate(half, {
106 maxAnimBytes: 0,
107 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Simulating with dt/2" }),
108 });
109 const fs = result.sampleRate;
110 const windows = windowsOf(sys.duration).map(t => ({ t, rel: relDiff(r2.audio, result.audio, Math.round(t * fs)) }));
111 checkOut = { dt: r2.dt, windows };
112 }
114 let linearOut: RunPayload["linear"] = null;
115 if (linear && !result.aborted) {
116 post({ type: "stage", text: "Simulating the small-strike reference" });
117 const s = 1e-3;
118 const small: BeadSystem = {
119 ...sys,
120 dt: result.dt,
121 hits: sys.hits.map(h => ({
122 ...h,
123 velocity: [h.velocity[0] * s, h.velocity[1] * s, h.velocity[2] * s],
124 force: [h.force[0] * s, h.force[1] * s, h.force[2] * s],
125 })),
126 };
127 const r3 = simulate(small, {
128 maxAnimBytes: 0,
129 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Small-strike reference" }),
130 });
131 const audio = r3.audio.map(v => v / s);
132 const fs = result.sampleRate;
133 const windows = windowsOf(sys.duration).map(t => ({ t, rel: relDiff(audio, result.audio, Math.round(t * fs)) }));
134 linearOut = { audio, windows };
135 }
137 let twinOut: RunPayload["twin"] = null;
138 if (keep && !result.aborted) {
139 post({ type: "stage", text: "Simulating the perturbed twin" });
140 const eps = 1e-9;
141 const { audio, sep } = runTwin(sys, saved, result.dt, eps, t =>
142 post({ type: "progress", t, duration: sys.duration, label: "Perturbed twin" })
143 );
144 const times = result.frameTimes.slice(0, saved.length);
145 twinOut = { eps, audio, times, sep, rate: growthRate(times, sep, eps) };
146 }
148 const hitBeads = Int32Array.from(new Set(sys.hits.flatMap(h => Array.from(h.beads))));
149 const payload: RunPayload = {
150 sys: {
151 n: sys.n,
152 pos0: sys.pos0,
153 pinned: sys.pinned,
154 si: sys.si,
155 sj: sys.sj,
156 nDashpots: sys.dc.filter(c => c !== 0).length,
157 nBends: sys.bi.length,
158 listenBeads: sys.listenBeads,
159 hitBeads,
160 method: sys.method,
161 duration: sys.duration,
162 },
163 result,
164 modeFreqs: modes ? modes.freqs : null,
165 modeDecay: modes ? modalDamping(sys, modes) : null,
166 notes,
167 check: checkOut,
168 linear: linearOut,
169 twin: twinOut,
170 };
171 const transfer: Transferable[] = [result.audio.buffer, ...result.animFrames.map(f => f.buffer)];
172 if (result.modeEnergy) transfer.push(result.modeEnergy.buffer);
173 if (linearOut) transfer.push(linearOut.audio.buffer);
174 if (twinOut) transfer.push(twinOut.audio.buffer, twinOut.sep.buffer);
175 post({ type: "result", payload }, transfer);
176 } catch (e) {
177 const err = e as { message?: string; line?: number; file?: string };
178 const where = err.line ? ` (line ${err.line})` : "";
179 post({ type: "error", message: `${err.message ?? String(e)}${where}` });
180 }
181};