/ proof-of-concept / toy-instruments
Sign in
proof-of-concept / toy-instruments
toy-instruments / src / sim / worker.ts
44 lines · 1.8 KBBlameHistoryRaw
1import { simulate } from './solver';
2import { simulateGPU } from './gpu';
3import { decimateResult, oversampledOptions, oversampling } from './antialias';
4import type { BeadSystem, Excitation, SimOptions, SimResult } from './types';
6export interface WorkerRequest {
7 sys: BeadSystem;
8 exc: Excitation;
9 opt: SimOptions;
10 gpu: boolean;
13const buffers = (r: SimResult) =>
14 [r.audio, r.frames, r.frameTimes, r.energy, r.balance, r.contactForce, r.malletPos].filter((a) => a).map((a) => a!.buffer) as ArrayBuffer[];
16self.onmessage = async (ev: MessageEvent<WorkerRequest>) => {
17 const { sys, exc, gpu } = ev.data;
18 const out = ev.data.opt;
19 // solve at R times the sample rate; the pickup is filtered back down to fs (antialias.ts)
20 const R = oversampling(sys, exc, out);
21 const opt = oversampledOptions(out, R);
22 const progress = (f: number) => self.postMessage({ type: 'progress', fraction: f });
23 const partial = (r: SimResult) => {
24 const result = decimateResult(r, R, false);
25 self.postMessage({ type: 'partial', result }, { transfer: buffers(result) });
26 };
27 try {
28 let result: SimResult | undefined;
29 let fallback: string | undefined;
30 if (gpu) {
31 try {
32 const r = await simulateGPU(sys, exc, opt, progress, (p) => partial({ ...p, backend: `WebGPU (${(p as SimResult & { device: string }).device})` }));
33 result = { ...r, backend: `WebGPU (${r.device})` };
34 } catch (e) {
35 fallback = (e as Error).message ?? String(e);
36 }
37 }
38 result ??= { ...simulate(sys, exc, opt, progress, (p) => partial({ ...p, backend: 'CPU', fallback })), backend: 'CPU', fallback };
39 result = decimateResult(result, R, true);
40 self.postMessage({ type: 'done', result }, { transfer: buffers(result) });
41 } catch (e) {
42 self.postMessage({ type: 'error', message: String(e) });
43 }
44};
↑↓ move↵openescclose