/ proof-of-concept / bead-percussion
Sign in
proof-of-concept / bead-percussion
bead-percussion / src / worker.ts
175 lines · 7.0 KBBlameHistoryRaw
1// Web Worker: runs the numbl script, computes linear modes, and simulates.
3import { growthRate, relDiff } from "./sim/analysis";
4import { computeModes, isPlanar, modalDamping, modeSize } from "./sim/modes";
5import { numblEig, prepareSystem, 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_DOF = 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 listenBeads: Int32Array;
25 hitBeads: Int32Array;
26 method: string;
27 duration: number;
28 };
29 result: SimResult;
30 modeFreqs: Float64Array | null;
31 modeDecay: Float64Array | null;
32 modeKind: "transverse" | "full" | 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;
42export interface RunRequest {
43 type: "run";
44 script: string;
45 dtCheck: boolean;
46 linear: boolean;
47 twin: boolean;
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];
68 if (sys.relax) post({ type: "stage", text: "Relaxing to equilibrium" });
69 notes.push(...prepareSystem(sys));
71 let modes = null;
72 if (sys.modes) {
73 const size = modeSize(sys);
74 const what = isPlanar(sys) ? "transverse modes of a flat net" : "3D modes";
75 if (size > MAX_MODE_DOF) notes.push(`Linear modes skipped: ${size} degrees of freedom (${what}; limit ${MAX_MODE_DOF}).`);
76 else {
77 post({ type: "stage", text: `Computing linear modes (${size} degrees of freedom)` });
78 modes = computeModes(sys, numblEig);
79 }
80 }
82 // positions at every frame, kept for the perturbed twin
83 const saved: Float64Array[] = [];
84 const savedBytes = Math.round(sys.duration * sys.frameRate + 1) * 3 * sys.n * 8;
85 const keep = twin && savedBytes <= MAX_TWIN_BYTES;
86 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.`);
88 post({ type: "stage", text: "Simulating" });
89 const result = simulate(sys, {
90 modes,
91 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Simulating" }),
92 onFrame: keep ? (_f, _t, x) => saved.push(x.slice()) : undefined,
93 });
95 let checkOut: RunPayload["check"] = null;
96 if (dtCheck && !result.aborted) {
97 post({ type: "stage", text: "Simulating again with dt/2" });
98 const half: BeadSystem = { ...sys, dt: result.dt / 2 };
99 const r2 = simulate(half, {
100 maxAnimBytes: 0,
101 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Simulating with dt/2" }),
102 });
103 const fs = result.sampleRate;
104 const windows = windowsOf(sys.duration).map(t => ({ t, rel: relDiff(r2.audio, result.audio, Math.round(t * fs)) }));
105 checkOut = { dt: r2.dt, windows };
106 }
108 let linearOut: RunPayload["linear"] = null;
109 if (linear && !result.aborted) {
110 post({ type: "stage", text: "Simulating the small-strike reference" });
111 const s = 1e-3;
112 const small: BeadSystem = {
113 ...sys,
114 dt: result.dt,
115 hits: sys.hits.map(h => ({
116 ...h,
117 velocity: [h.velocity[0] * s, h.velocity[1] * s, h.velocity[2] * s],
118 force: [h.force[0] * s, h.force[1] * s, h.force[2] * s],
119 })),
120 };
121 const r3 = simulate(small, {
122 maxAnimBytes: 0,
123 onProgress: t => post({ type: "progress", t, duration: sys.duration, label: "Small-strike reference" }),
124 });
125 const audio = r3.audio.map(v => v / s);
126 const fs = result.sampleRate;
127 const windows = windowsOf(sys.duration).map(t => ({ t, rel: relDiff(audio, result.audio, Math.round(t * fs)) }));
128 linearOut = { audio, windows };
129 }
131 let twinOut: RunPayload["twin"] = null;
132 if (keep && !result.aborted) {
133 post({ type: "stage", text: "Simulating the perturbed twin" });
134 const eps = 1e-9;
135 const { audio, sep } = runTwin(sys, saved, result.dt, eps, t =>
136 post({ type: "progress", t, duration: sys.duration, label: "Perturbed twin" })
137 );
138 const times = result.frameTimes.slice(0, saved.length);
139 twinOut = { eps, audio, times, sep, rate: growthRate(times, sep, eps) };
140 }
142 const hitBeads = Int32Array.from(new Set(sys.hits.flatMap(h => Array.from(h.beads))));
143 const payload: RunPayload = {
144 sys: {
145 n: sys.n,
146 pos0: sys.pos0,
147 pinned: sys.pinned,
148 si: sys.si,
149 sj: sys.sj,
150 nDashpots: sys.di.length,
151 listenBeads: sys.listenBeads,
152 hitBeads,
153 method: sys.method,
154 duration: sys.duration,
155 },
156 result,
157 modeFreqs: modes ? modes.freqs : null,
158 modeDecay: modes ? modalDamping(sys, modes) : null,
159 modeKind: modes ? modes.kind : null,
160 notes,
161 check: checkOut,
162 linear: linearOut,
163 twin: twinOut,
164 };
165 const transfer: Transferable[] = [result.audio.buffer, ...result.animFrames.map(f => f.buffer)];
166 if (result.modeEnergy) transfer.push(result.modeEnergy.buffer);
167 if (linearOut) transfer.push(linearOut.audio.buffer);
168 if (twinOut) transfer.push(twinOut.audio.buffer, twinOut.sep.buffer);
169 post({ type: "result", payload }, transfer);
170 } catch (e) {
171 const err = e as { message?: string; line?: number; file?: string };
172 const where = err.line ? ` (line ${err.line})` : "";
173 post({ type: "error", message: `${err.message ?? String(e)}${where}` });
174 }
175};
↑↓ move↵openescclose