1// Render notes with the simulation to WAV files (and print diagnostics).
2// node scripts/render.ts [--params p.json] [--body bodies/fe_default.json] [--out renders] note:vel ...
3// e.g. node scripts/render.ts 28:100 43:60 55:120
4import fs from "node:fs";
5import path from "node:path";
6import { defaultParams, mergeParams } from "../src/core/params.ts";
7import { bodyFor } from "./fe_cache.ts";
8import { renderNote } from "../src/core/engine.ts";
9import { encodeWav, envelopeDecay, centroid } from "../src/core/dsp.ts";
10import type { BodyModel } from "../src/core/types.ts";
12const args = process.argv.slice(2);
13let params = defaultParams();
14let body: BodyModel | null = null;
15let outDir = path.join(import.meta.dirname, "..", "renders");
16const notes: [number, number][] = [];
17for (let i = 0; i < args.length; i++) {
18 const a = args[i];
19 if (a === "--params") params = mergeParams(JSON.parse(fs.readFileSync(args[++i], "utf8")));
20 else if (a === "--body") body = JSON.parse(fs.readFileSync(args[++i], "utf8"));
21 else if (a === "--out") outDir = args[++i];
22 else if (a.startsWith("--set")) { const [k, v] = args[++i].split("="); const ks = k.split("."); let o: any = params; for (const kk of ks.slice(0, -1)) o = o[kk]; o[ks[ks.length - 1]] = isNaN(Number(v)) ? (v === "true" ? true : v === "false" ? false : v) : Number(v); }
23 else { const [n, v] = a.split(":").map(Number); notes.push([n, v ?? 100]); }
24}
25if (!notes.length) notes.push([28, 100], [33, 100], [43, 100], [55, 100]);
26if (!body) body = bodyFor(params);
27fs.mkdirSync(outDir, { recursive: true });
28for (const [note, vel] of notes) {
29 const r = renderNote(params, body!, { note, velocity: vel });
30 let peak = 0; for (const v of r.audio) peak = Math.max(peak, Math.abs(v));
31 const ed = envelopeDecay(r.audio, r.sampleRate);
32 const f = path.join(outDir, `sim_${note}_${vel}.wav`);
33 fs.writeFileSync(f, encodeWav(r.audio, r.sampleRate, { scale: 0.5 / 1.0 }));
34 console.log(`note ${note} vel ${vel}: string ${"EADG"[r.fingering.string]} +${r.fingering.shift} L=${r.fingering.length.toFixed(3)} | F=${r.releaseForce.toFixed(2)} N slip ${(r.slipTime * 1e3).toFixed(2)} ms stick ${(r.stickTime * 1e3).toFixed(1)} ms | modes str ${r.modeCounts.strings.join(",")} body ${r.modeCounts.body} | peak ${peak.toExponential(2)} Pa, t20 ${ed.t20.toFixed(2)} s t40 ${ed.t40.toFixed(2)} s, centroid(0-0.3s) ${centroid(r.audio, r.sampleRate, 0, 0.3).toFixed(0)} Hz | ${r.elapsed.toFixed(2)} s cpu`);
35}