c8442c5Command-line renderer (Node WebGPU via Dawn) and gallery generatorJeremy Magland 1// Runs one simulation to completion in Node (Dawn WebGPU) and returns the pressure signal.
3import { create, globals } from "webgpu";
4import { defaultParams, type PhysParams } from "../params.ts";
5import { Simulation } from "../sim/simulation.ts";
7let devicePromise: Promise<GPUDevice> | null = null;
9export function getDevice(): Promise<GPUDevice> {
10 if (!devicePromise) {
11 Object.assign(globalThis, globals);
12 devicePromise = (async () => {
13 const gpu = create([]);
14 const adapter = await gpu.requestAdapter({ powerPreference: "high-performance" });
15 if (!adapter) throw new Error("No WebGPU adapter");
16 return adapter.requestDevice();
17 })();
18 }
19 return devicePromise;
20}
22export interface RunResult {
23 params: PhysParams;
24 audio: Float32Array;
25 fs: number;
26 steps: number;
27 seconds: number;
28 grid: { nx: number; ny: number };
29 dt: number;
30 maxContactForce: number;
31}
33export async function runSimulation(overrides: Partial<PhysParams>, log: (s: string) => void = () => {}): Promise<RunResult> {
34 const params: PhysParams = { ...defaultParams, ...overrides };
35 const device = await getDevice();
36 const sim = new Simulation(device, params);
37 const t0 = performance.now();
38 let lastLog = t0;
39 let maxContactForce = 0;
40 while (sim.phase !== "done") {
41 await sim.runBatch();
42 const st = sim.status();
43 if (st.stick) maxContactForce = Math.max(maxContactForce, st.stick.maxForce);
44 const now = performance.now();
45 if (now - lastLog > 5000) {
46 lastLog = now;
47 log(` ${st.phase} t=${st.t.toFixed(2)} s, ${(sim.totalSteps / ((now - t0) / 1000) / 1e3).toFixed(0)} k steps/s`);
48 }
49 }
50 const seconds = (performance.now() - t0) / 1000;
51 const result: RunResult = {
52 params,
53 audio: sim.processedAudio().slice(),
54 fs: sim.fs,
55 steps: sim.totalSteps,
56 seconds,
57 grid: { nx: sim.grid.nx, ny: sim.grid.ny },
58 dt: sim.dt,
59 maxContactForce,
60 };
61 sim.destroy();
62 return result;
63}