Marimba lab: per-key tuned bars, coupled resonator tubes, SoundFont export
Each key from C2 to C7 has its own rosewood bar. A fast Timoshenko/torsion
FE model and a Levenberg-Marquardt tuner set length and undercut for
1:4:10 partials. A 1D resonator tube is coupled to the bar through the gap
over its mouth. Sound comes from a yarn-over-core mallet contact and an
exponentially windowed inverse FFT, kept causal and passive throughout.
Includes graduated mallets, an optional WebGPU FDTD check, and a
velocity-layered SoundFont export.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 changed files+2891−0
.gitignoreadded+3−0View file
@@ -0,0 +1,3 @@
1+.claude/
2+node_modules/
3+.DS_Store
README.mdadded+50−0View file
@@ -0,0 +1,50 @@
1+# Marimba
2+
3+Interactive marimba, C2–C7. Every key has its own rosewood bar, tuned by its undercut, with its own resonator tube underneath. Sound comes from modal synthesis of the bar coupled to the tube.
4+
5+```bash
6+npm run dev # http://127.0.0.1:8021
7+```
8+
9+The FE model, the tuner and the sound run in any modern browser. The optional 3D FDTD check needs WebGPU (Chrome, Safari 26+). three.js loads from jsDelivr (pinned 0.169.0).
10+
11+## Model
12+
13+- **Bars** (`js/bar.js`): width 72→40 mm and thickness 24→20 mm from C2 to C7. The top is flat. The bottom has an arch, `h(x) = h0 − d·(1 − |u|^p)` over the central fraction `a` of the length. Wood is orthotropic, with hardwood ratios scaled by E_L. Material presets are Honduras rosewood (default) and padauk.
14+- **FE modes** (`js/fe.js`): a Timoshenko beam with varying section models vertical bending, and Saint-Venant theory models torsion. Torsional stiffness uses the torsion constant of an orthotropic rectangle. Eigenvalues come from Sturm bisection on banded LDLᵀ factors, so tuning takes milliseconds. Radiation decay treats each top-face cell as a vertical dipole of bar volume plus added mass, and includes the mutual radiation between cells.
15+- **Tuner** (`js/tune.js`): adjusts length, undercut depth and undercut length (Levenberg–Marquardt) until f1 is the note and f2 : f3 = 4 : 10 × f1. Partials whose target is above the cutoff (9 kHz by default) are left free, so the top bars tune f1 and f2 only. A flat-bottomed arch (`p ≈ 4`) is needed to reach 1 : 4 : 10; a parabola cannot.
16+- **Resonator + sound** (`js/synth.js`): the tube is closed at the bottom and modelled as a 1D waveguide, with wall losses ∝ √f. Its end correction includes the bar acting as a partial lid. Flow pushed by the bar's underside over the mouth either enters the tube or escapes around the rim. The pressure in the gap pushes back on the bar. That coupling is rank one and is solved exactly at every frequency. The mic picks up the bar's dipole field plus the monopole of the flow the tube takes in. The tube length is set so the air column resonates at the note (adjustable in cents).
17+- **Mallet** (`js/physics.js`): yarn over a core. The yarn force is `K_y δ^2.5`. Once the yarn is compressed to 80 % of its thickness, the core adds `K_c δ^1.5`. Hunt–Crossley hysteresis applies to both. The contact is simulated against the bar modes. The mic signal is the contact force times the transfer function, transformed back to time with an exponentially windowed inverse FFT so long rings don't wrap around. Because that window amplifies anything that wraps to the end of the FFT (by up to ~10⁷), every part of the transfer function is kept causal and passive:
18+ - the force spectrum is computed exactly at every bin with a chirp-z (Bluestein) transform, not interpolated;
19+ - each mode's mic transfer is a magnitude plus a delay, not a constant complex factor;
20+ - the mouth's radiation load is the passive impedance of a small monopole;
21+ - the spectrum rolls off smoothly to zero at Nyquist;
22+ - the window is at least 0.6 s longer than the output, and grows when the note is still ringing at the cut.
23+
24+ Against an 8× longer reference, the error over random strikes is below −116 dB of the peak. Earlier versions had a rattle at the end of some notes; these measures removed it. At 1.5 m/s on mid bars, the presets give contacts of about 2 / 1 / 0.5 ms for soft / medium / hard. **Graduated mallets** (on by default) blend the chosen mallet toward a large, heavy bass mallet (about 4 ms contact) from C4 down to C2, as players do. With a 1 ms contact, a low bar's 10× partial is excited far more than its fundamental (16 dB more at C2), so the note sounds two octaves and a third too high.
25+- **Damping**: internal loss factor `η(f) = η₀ (f / 1 kHz)^slope`, plus the radiation decay and the tube's own losses.
26+
27+## FDTD check
28+
29+**Analyze bar (FDTD)** voxelizes the selected bar in air. It reuses woodblock2's WebGPU velocity–stress solver and runs two force-impulse simulations. Modes are fitted from the top-face velocities, matched to the FE modes by shape, and compared in a table. **Sound from → FDTD modes** plays them through the same tube and mic model.
30+
31+The grid makes thin wood too soft, so FDTD frequencies come out low and approach the FE values as the grid is refined. Example, C4 bar:
32+
33+| grid | bar | f1 FE | f1 FDTD |
34+|---|---|---|---|
35+| 3 mm | uniform (no undercut) | 698 Hz | 646 Hz (−135 ¢) |
36+| 3 mm | tuned (undercut 3 cells thick) | 262 Hz | 151 Hz (−951 ¢) |
37+| 2 mm | tuned | 262 Hz | 219 Hz (−312 ¢) |
38+
39+Higher torsion modes come out above the FE values even at 3 mm, which points to the FE torsion model (no warping) being too soft there.
40+
41+## Controls
42+
43+- **Keys**: the strip at the bottom selects and plays a bar; ← / → step through the keys. Edited bars get a dot.
44+- **Live**: mallet (preset or sliders, optionally graduated toward the bass), strike velocity, strike point (click the bar), resonator (on/off, diameter, gap, tuning, wall loss) and damping.
45+- **Bar**: length, width, thickness, undercut depth, length and flatness. **Auto-tune** retunes from the current shape. **Reset to auto** discards your edits.
46+- **All bars**: tuning targets and material. Changing them retunes every bar you haven't edited.
47+
48+## SoundFont export
49+
50+**Export .sf2** samples keys every 1–6 semitones. Each sampled key renders its own bar and tube (your edited design if there is one, otherwise the auto-tuned bar), so register changes are physical, not pitch-shifted. There are 4 velocity layers; softer layers use a slower strike and slightly softer yarn. SF2 has no round-robin, so each layer is split into 3 velocity bands struck at nearby points. One global gain keeps the physical loudness of keys and layers. The preset is GM program 13 (Marimba), bank 0. With the defaults (C2–C7, every 3 semitones) the file is about 23 MB and renders in about 11 s.
index.htmladded+99−0View file
@@ -0,0 +1,99 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>Marimba Lab</title>
7+ <link rel="stylesheet" href="style.css">
8+ <script type="importmap">
9+ {
10+ "imports": {
11+ "three": "https://cdn.jsdelivr.net/npm/three@0.169.0/build/three.module.js",
12+ "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.169.0/examples/jsm/"
13+ }
14+ }
15+ </script>
16+</head>
17+<body>
18+ <main>
19+ <section class="stage">
20+ <div id="view"></div>
21+ <div class="hint">Click the top of the bar to strike · Space repeats · ← → change key · drag to orbit</div>
22+ <div id="keys" class="keys"></div>
23+ <div class="plots">
24+ <div class="plot"><div class="ptitle">Spectrum <span class="muted">(ticks: modes · ▲ tube)</span></div><canvas id="spec"></canvas></div>
25+ <div class="plot"><div class="ptitle">Waveform <select id="wavespan" class="inline"><option value="0.2" selected>first 200 ms</option><option value="full">whole ring</option></select> <span id="ringlen" class="muted"></span></div><canvas id="wave"></canvas></div>
26+ </div>
27+ </section>
28+ <aside class="panel">
29+ <h1>Marimba <span id="notename" class="muted"></span></h1>
30+ <div class="actions">
31+ <button id="strike">Strike</button>
32+ </div>
33+ <div class="progress"><div id="bar"></div></div>
34+ <div class="status"><span id="status"></span> <button id="cancel" class="small" hidden>Cancel</button></div>
35+
36+ <h2>Mallet & strike <small>live</small></h2>
37+ <div class="kv"><span>Strike point</span><span id="strikepos"></span></div>
38+ <label class="row"><span class="lab">Mallet</span>
39+ <select id="mpreset"><option value="soft">soft</option><option value="medium" selected>medium</option><option value="hard">hard</option><option value="bass">bass</option><option value="custom">custom</option></select><span></span>
40+ </label>
41+ <label class="row"><span class="lab">Graduated mallets</span><input id="grad" type="checkbox" checked><span></span></label>
42+ <div class="info" id="gradinfo"></div>
43+ <div id="mallet"></div>
44+ <div class="kv muted"><span id="contact"></span></div>
45+
46+ <h2>Resonator <small>live</small></h2>
47+ <label class="row"><span class="lab">Tube under the bar</span><input id="reson" type="checkbox" checked><span></span></label>
48+ <div id="res"></div>
49+ <div class="info" id="tubeinfo"></div>
50+
51+ <h2>Damping <small>live</small></h2>
52+ <div id="damp"></div>
53+
54+ <h2>Bar <span id="barnote"></span> <small id="barstate"></small></h2>
55+ <div id="design"></div>
56+ <div id="warn" class="warn"></div>
57+ <table class="partials" id="partials"></table>
58+ <div class="actions">
59+ <button id="autotune">Auto-tune</button>
60+ <button id="reset" class="small">Reset to auto</button>
61+ </div>
62+ <div class="info">Auto-tune adjusts length, undercut depth and undercut length; width, thickness and arch shape stay as set.</div>
63+
64+ <h2>Tuning targets <small>all bars</small></h2>
65+ <div id="targets"></div>
66+
67+ <h2>Material <small>all bars</small></h2>
68+ <label class="row"><span class="lab">Wood</span>
69+ <select id="matpreset"><option value="rosewood" selected>Honduras rosewood</option><option value="padauk">Padauk</option><option value="custom">custom</option></select><span></span>
70+ </label>
71+ <div id="mat"></div>
72+
73+ <h2>Mode analysis <small>3D FDTD check</small></h2>
74+ <label class="row"><span class="lab">Grid spacing</span>
75+ <select id="dx"><option value="4">4 mm (fast)</option><option value="3" selected>3 mm</option><option value="2">2 mm (slow)</option><option value="1.5">1.5 mm (slowest)</option></select><span></span>
76+ </label>
77+ <div class="info" id="info"></div>
78+ <div class="info">The FDTD grid makes thin wood too soft, so FDTD frequencies come out low and approach the FE values as the grid is refined. Expect large gaps where the undercut is only 2–4 cells thick.</div>
79+ <div class="actions"><button id="analyze">Analyze bar (FDTD)</button></div>
80+ <table class="partials" id="compare"></table>
81+ <label class="row"><span class="lab">Sound from</span>
82+ <select id="source"><option value="FE" selected>FE modes</option><option value="FDTD" disabled>FDTD modes</option></select><span></span>
83+ </label>
84+ <label class="row"><span class="lab">Show mode on top</span><select id="overlay"><option value="-1">none</option></select><span></span></label>
85+
86+ <h2>Export instrument <small>SoundFont .sf2</small></h2>
87+ <label class="row"><span class="lab">Name</span><input id="sfname" type="text" value="Marimba"><span></span></label>
88+ <label class="row"><span class="lab">Lowest key</span><input id="sflo" type="range" min="36" max="96" step="1" value="36"><span class="val" id="sflo_v"></span></label>
89+ <label class="row"><span class="lab">Highest key</span><input id="sfhi" type="range" min="36" max="96" step="1" value="96"><span class="val" id="sfhi_v"></span></label>
90+ <label class="row"><span class="lab">Sample every</span>
91+ <select id="sfstep"><option value="1">1 semitone</option><option value="2">2 semitones</option><option value="3" selected>3 semitones</option><option value="4">4 semitones</option><option value="6">6 semitones</option></select><span></span>
92+ </label>
93+ <div class="info" id="sfinfo"></div>
94+ <div class="actions"><button id="export">Export .sf2</button></div>
95+ </aside>
96+ </main>
97+ <script type="module" src="main.js"></script>
98+</body>
99+</html>
js/analysis.jsadded+343−0View file
@@ -0,0 +1,343 @@
1+// 3D FDTD check of a bar: voxelize the bar in air, run two force-impulse simulations
2+// (js/fdtd.js), and turn the recorded top-face velocities into a bar model in the same form
3+// as the FE model: frequencies, radiation decay, and mass-normalized shapes on a grid.
4+
5+import { thickness } from './bar.js';
6+import { runFDTD, timeStep } from './fdtd.js';
7+import { fft, nextPow2, hann } from './fft.js';
8+
9+const MARGIN = 20, SPONGE = 10; // mm of air around the bar, sponge cells
10+
11+export function isWood(b, x, y, z) {
12+ if (x < 0 || x > b.L || y < 0 || y > b.W || z > b.h0) return false;
13+ return z >= b.h0 - thickness(b, x);
14+}
15+
16+/** Voxel grid (dx in mm). Top-face nodes are recorded on a coarser sampling (~6 mm). */
17+export function buildGrid(b, dx) {
18+ const pad = SPONGE + Math.ceil(MARGIN / dx);
19+ const nbx = Math.ceil(b.L / dx), nby = Math.ceil(b.W / dx), nbz = Math.ceil(b.h0 / dx);
20+ const nx = nbx + 2 * pad, ny = nby + 2 * pad, nz = nbz + 2 * pad;
21+ const o = pad * dx;
22+ const N = nx * ny * nz;
23+ const mat = new Uint32Array(N);
24+ const id = (i, j, k) => i + nx * (j + ny * k);
25+ for (let k = 0; k < nz; k++) {
26+ const z = (k + 0.5) * dx - o;
27+ for (let j = 0; j < ny; j++) {
28+ const y = (j + 0.5) * dx - o;
29+ for (let i = 0; i < nx; i++) {
30+ if (isWood(b, (i + 0.5) * dx - o, y, z)) mat[id(i, j, k)] = 1;
31+ }
32+ }
33+ }
34+ // top-face vz nodes (node above the topmost wood cell of each column)
35+ const kTop = new Int32Array(nbx * nby).fill(-1);
36+ for (let jb = 0; jb < nby; jb++) {
37+ for (let ib = 0; ib < nbx; ib++) {
38+ for (let k = nz - 2; k > 0; k--) if (mat[id(ib + pad, jb + pad, k)] === 1) { kTop[ib + nbx * jb] = k; break; }
39+ }
40+ }
41+ const st = Math.max(1, Math.round(6 / dx));
42+ const sIdx = [], sPos = [];
43+ const colSurf = new Int32Array(nbx * nby).fill(-1);
44+ for (let jb = Math.floor(st / 2); jb < nby; jb += st) {
45+ for (let ib = Math.floor(st / 2); ib < nbx; ib += st) {
46+ const k = kTop[ib + nbx * jb];
47+ if (k < 0) continue;
48+ colSurf[ib + nbx * jb] = sIdx.length;
49+ sIdx.push(id(ib + pad, jb + pad, k));
50+ sPos.push([(ib + 0.5) * dx, (jb + 0.5) * dx]);
51+ }
52+ }
53+ let nWood = 0;
54+ for (let n = 0; n < N; n++) nWood += mat[n];
55+ return { nx, ny, nz, N, dx, ns: SPONGE, pad, o, nbx, nby, mat, kTop, surf: Uint32Array.from(sIdx), sPos, colSurf, micIdx: 0, nWood, id };
56+}
57+
58+// Gaussian force patch around a top-face point (mm), on all top-face columns.
59+export function strikePatch(grid, sx, sy) {
60+ const ib0 = Math.round(sx / grid.dx - 0.5), jb0 = Math.round(sy / grid.dx - 0.5);
61+ const idx = [], w = [];
62+ for (let dj = -2; dj <= 2; dj++) {
63+ for (let di = -2; di <= 2; di++) {
64+ const ib = ib0 + di, jb = jb0 + dj;
65+ if (ib < 0 || jb < 0 || ib >= grid.nbx || jb >= grid.nby) continue;
66+ const k = grid.kTop[ib + grid.nbx * jb];
67+ if (k < 0) continue;
68+ idx.push(grid.id(ib + grid.pad, jb + grid.pad, k));
69+ w.push(Math.exp(-(di * di + dj * dj) / 2));
70+ }
71+ }
72+ const sum = w.reduce((a, c) => a + c, 0);
73+ return { idx: Uint32Array.from(idx), w: Float32Array.from(w.map((v) => v / sum)) };
74+}
75+
76+// Two reference points away from the nodes of most bending and torsion modes.
77+export function refPoints(b) {
78+ return [[0.06, 0.2], [0.37, 0.88]].map(([fx, fy]) => [fx * b.L, fy * b.W]);
79+}
80+
81+export const analysisDuration = (f1) => Math.min(0.1, Math.max(0.03, 6 / f1));
82+
83+// Estimated cost, for the UI.
84+export function analysisCost(b, mat, dx, f1) {
85+ const pad = SPONGE + Math.ceil(MARGIN / dx);
86+ const cells = (Math.ceil(b.L / dx) + 2 * pad) * (Math.ceil(b.W / dx) + 2 * pad) * (Math.ceil(b.h0 / dx) + 2 * pad);
87+ const steps = 2 * Math.ceil(analysisDuration(f1) / timeStep(mat, dx));
88+ return { cells, steps };
89+}
90+
91+/**
92+ * Run the analysis. Returns a bar model { source: 'FDTD', design, nx, ny, modes } or null
93+ * if cancelled. onProgress(label, frac, sec), isCancelled().
94+ */
95+export async function analyzeBar(b, mat, dx, f1, { onProgress, isCancelled, nx = 120, ny = 8 } = {}) {
96+ const grid = buildGrid(b, dx);
97+ const runs = [];
98+ const refs = refPoints(b).map(([x, y]) => {
99+ const ib = Math.round(x / dx - 0.5), jb = Math.round(y / dx - 0.5);
100+ // nearest recorded sample to the reference point
101+ let best = 0, bd = Infinity;
102+ grid.sPos.forEach((p, s) => { const d = Math.hypot(p[0] - x, p[1] - y); if (d < bd) { bd = d; best = s; } });
103+ return { x, y, ib, jb, surf: best, patch: strikePatch(grid, x, y) };
104+ });
105+ let seconds = 0;
106+ for (let k = 0; k < refs.length; k++) {
107+ const res = await runFDTD({
108+ mat, grid, mode: 'impulse', patch: refs[k].patch, duration: analysisDuration(f1), stiffScale: 1, recRate: 48000,
109+ onProgress: (f, sec) => onProgress?.(`FDTD run ${k + 1}/${refs.length}`, (k + f) / refs.length, seconds + sec, f), isCancelled,
110+ });
111+ if (!res) return null;
112+ seconds += res.seconds;
113+ runs.push(res);
114+ }
115+ onProgress?.('Extracting modes…', 1, seconds, 1);
116+ await new Promise((r) => setTimeout(r, 20));
117+ const modes = extractModes(runs, refs, { fmin: 0.3 * f1 });
118+ // resample each mode onto the regular top-face grid used by the FE model
119+ const st = Math.max(1, Math.round(6 / dx));
120+ const sx = st * dx, x0 = (Math.floor(st / 2) + 0.5) * dx;
121+ const cols = Math.ceil((grid.nbx - Math.floor(st / 2)) / st), rows = Math.ceil((grid.nby - Math.floor(st / 2)) / st);
122+ const at = (i, j) => grid.colSurf[(Math.floor(st / 2) + i * st) + grid.nbx * (Math.floor(st / 2) + j * st)];
123+ const out = modes.map((m) => {
124+ const phi = new Float32Array(nx * ny);
125+ for (let j = 0; j < ny; j++) {
126+ const v = Math.min(rows - 1.0001, Math.max(0, (((j + 0.5) / ny) * b.W - x0) / sx));
127+ const j0 = Math.floor(v), fv = v - j0, j1 = Math.min(rows - 1, j0 + 1);
128+ for (let i = 0; i < nx; i++) {
129+ const u = Math.min(cols - 1.0001, Math.max(0, (((i + 0.5) / nx) * b.L - x0) / sx));
130+ const i0 = Math.floor(u), fu = u - i0, i1 = Math.min(cols - 1, i0 + 1);
131+ const g = (ii, jj) => { const s = at(ii, jj); return s >= 0 ? m.phi[s] : 0; };
132+ phi[j * nx + i] = g(i0, j0) * (1 - fu) * (1 - fv) + g(i1, j0) * fu * (1 - fv) + g(i0, j1) * (1 - fu) * fv + g(i1, j1) * fu * fv;
133+ }
134+ }
135+ return { f: m.f, sigRad: m.sigRad, phi, label: '' };
136+ });
137+ return { source: 'FDTD', design: { ...b }, nx, ny, modes: out, seconds, grid: { nx: grid.nx, ny: grid.ny, nz: grid.nz } };
138+}
139+
140+/**
141+ * Poles from the combined spectrum, radiation decay from two half windows, then a
142+ * least-squares fit of complex amplitudes with those poles. The mobility V(ref → P) of a
143+ * mass-normalized mode is -φ(ref)φ(P) (force down, velocity up), which gives φ(P).
144+ */
145+export function extractModes(runs, refs, { maxModes = 60, fmin = 50, fmax = 16000 } = {}) {
146+ const { nRec, nSurf, recRate } = runs[0];
147+ const t = Float64Array.from({ length: nRec }, (_, r) => (r + 0.5) / recRate);
148+ const win = hann(nRec);
149+
150+ const nfft = nextPow2(nRec) * 4;
151+ const Ptot = new Float64Array(nfft / 2);
152+ const stride = Math.max(1, Math.floor(nSurf / 300));
153+ const re = new Float64Array(nfft), im = new Float64Array(nfft);
154+ for (const run of runs) {
155+ const P = new Float64Array(nfft / 2);
156+ for (let n = 0; n < nSurf; n += stride) {
157+ re.fill(0); im.fill(0);
158+ for (let r = 0; r < nRec; r++) re[r] = run.data[r * nSurf + n] * win[r];
159+ fft(re, im);
160+ for (let k = 0; k < nfft / 2; k++) P[k] += re[k] * re[k] + im[k] * im[k];
161+ }
162+ let m = 0;
163+ for (let k = 0; k < nfft / 2; k++) m = Math.max(m, P[k]);
164+ for (let k = 0; k < nfft / 2; k++) Ptot[k] += P[k] / m;
165+ }
166+ const df = recRate / nfft;
167+ const k0 = Math.max(2, Math.floor(fmin / df));
168+ const k1 = Math.min(nfft / 2 - 2, Math.floor(Math.min(fmax, 0.45 * recRate) / df));
169+ let pmax = 0;
170+ for (let k = k0; k <= k1; k++) pmax = Math.max(pmax, Ptot[k]);
171+ const span = Math.round(3 * (nfft / nRec));
172+ const peaks = [];
173+ for (let k = k0; k <= k1; k++) {
174+ if (Ptot[k] < pmax * 1e-7) continue;
175+ let ok = true;
176+ for (let q = Math.max(0, k - span); q <= Math.min(nfft / 2 - 1, k + span); q++) {
177+ if (q !== k && Ptot[q] > Ptot[k]) { ok = false; break; }
178+ }
179+ if (!ok) continue;
180+ const a = Math.log(Ptot[k - 1]), bb = Math.log(Ptot[k]), c = Math.log(Ptot[k + 1]);
181+ const d = (0.5 * (a - c)) / (a - 2 * bb + c);
182+ peaks.push({ f: (k + (Number.isFinite(d) ? d : 0)) * df, p: Ptot[k] });
183+ }
184+ peaks.sort((x, y) => y.p - x.p);
185+ const poles = peaks.slice(0, maxModes).sort((x, y) => x.f - y.f).map((pk) => ({ f: pk.f, w: 2 * Math.PI * pk.f }));
186+
187+ // radiation decay from two half-window DFTs
188+ const half = Math.floor(nRec / 2);
189+ const w1 = hann(half);
190+ const Dt = half / recRate;
191+ const sstride = Math.max(1, Math.floor(nSurf / 150));
192+ for (const pole of poles) {
193+ let P1 = 0, P2 = 0;
194+ for (const run of runs) {
195+ for (let n = 0; n < nSurf; n += sstride) {
196+ let ar = 0, ai = 0, br = 0, bi = 0;
197+ for (let r = 0; r < 2 * half; r++) {
198+ const c = Math.cos(pole.w * t[r]), s = Math.sin(pole.w * t[r]);
199+ const v = run.data[r * nSurf + n] * (r < half ? w1[r] : w1[r - half]);
200+ if (r < half) { ar += v * c; ai += v * s; } else { br += v * c; bi += v * s; }
201+ }
202+ P1 += ar * ar + ai * ai; P2 += br * br + bi * bi;
203+ }
204+ }
205+ const sig = P2 > 0 ? (0.5 * Math.log(P1 / P2)) / Dt : 0;
206+ pole.sig = Math.min(300, Math.max(0, Number.isFinite(sig) ? sig : 0));
207+ }
208+
209+ const r0 = Math.ceil(2 * runs[0].pulseT * recRate);
210+ const fits = runs.map((run) => lsFit(run.data, nRec, nSurf, t, r0, poles, recRate));
211+
212+ return poles.map((pole, n) => {
213+ let best = null;
214+ for (let k = 0; k < runs.length; k++) {
215+ const [fr, fi] = halfSineFT(runs[k].pulseA, runs[k].pulseT, pole.w);
216+ const f2 = fr * fr + fi * fi;
217+ const Vre = new Float64Array(nSurf), Vim = new Float64Array(nSurf);
218+ let vmax = 0;
219+ for (let s = 0; s < nSurf; s++) {
220+ const ar = fits[k].re[n * nSurf + s], ai = fits[k].im[n * nSurf + s];
221+ Vre[s] = (ar * fr + ai * fi) / f2;
222+ Vim[s] = (ai * fr - ar * fi) / f2;
223+ vmax = Math.max(vmax, Math.hypot(Vre[s], Vim[s]));
224+ }
225+ const sr = refs[k].surf;
226+ const vr = Math.hypot(Vre[sr], Vim[sr]);
227+ const ratio = vr / (vmax || 1);
228+ if (!best || ratio > best.ratio) best = { ratio, Vre, Vim, sr, vr };
229+ }
230+ // φ(P) = Re(V(P) e^{-i arg V(ref)}) / sqrt|V(ref)|
231+ const { Vre, Vim, sr, vr } = best;
232+ const cr = Vre[sr] / vr, ci = -Vim[sr] / vr, sc = 1 / Math.sqrt(vr || 1e-30);
233+ const phi = new Float64Array(nSurf);
234+ for (let s = 0; s < nSurf; s++) phi[s] = (Vre[s] * cr - Vim[s] * ci) * sc;
235+ return { f: pole.f, sigRad: pole.sig, phi, quality: best.ratio };
236+ }).filter((m) => m.quality > 0.05);
237+}
238+
239+// Fourier transform of a half-sine pulse A sin(πt/T), 0<t<T, at angular frequency w.
240+function halfSineFT(A, T, w) {
241+ const a = Math.PI / T;
242+ const den = a * a - w * w;
243+ if (Math.abs(den) < 1e-6 * a * a) return [0, (-A * T) / 2];
244+ return [(A * a * (1 + Math.cos(w * T))) / den, (-A * a * Math.sin(w * T)) / den];
245+}
246+
247+// Fit h(t) = Σ Re(Aₙ e^{(iωₙ - σₙ)t}) for every surface point (columns of data).
248+function lsFit(data, nRec, nSurf, t, r0, poles, recRate) {
249+ const M = poles.length, K = 2 * M, nT = nRec - r0;
250+ const B = new Float64Array(nT * K);
251+ for (let r = 0; r < nT; r++) {
252+ const tt = t[r + r0];
253+ for (let n = 0; n < M; n++) {
254+ const e = Math.exp(-poles[n].sig * tt);
255+ const x = poles[n].w / (2 * recRate), bc = Math.sin(x) / x; // boxcar decimation response
256+ B[r * K + 2 * n] = bc * e * Math.cos(poles[n].w * tt);
257+ B[r * K + 2 * n + 1] = -bc * e * Math.sin(poles[n].w * tt);
258+ }
259+ }
260+ const G = new Float64Array(K * K);
261+ for (let r = 0; r < nT; r++) {
262+ const o = r * K;
263+ for (let i = 0; i < K; i++) {
264+ const bi = B[o + i];
265+ for (let j = i; j < K; j++) G[i * K + j] += bi * B[o + j];
266+ }
267+ }
268+ let tr = 0;
269+ for (let i = 0; i < K; i++) tr += G[i * K + i];
270+ for (let i = 0; i < K; i++) {
271+ G[i * K + i] += (1e-9 * tr) / K;
272+ for (let j = 0; j < i; j++) G[i * K + j] = G[j * K + i];
273+ }
274+ const L = cholesky(G, K);
275+ const C = new Float64Array(K * nSurf);
276+ for (let r = 0; r < nT; r++) {
277+ const o = (r + r0) * nSurf;
278+ for (let i = 0; i < K; i++) {
279+ const b = B[r * K + i];
280+ const ci = i * nSurf;
281+ for (let s = 0; s < nSurf; s++) C[ci + s] += b * data[o + s];
282+ }
283+ }
284+ const col = new Float64Array(K);
285+ const out = { re: new Float32Array(M * nSurf), im: new Float32Array(M * nSurf) };
286+ for (let s = 0; s < nSurf; s++) {
287+ for (let i = 0; i < K; i++) col[i] = C[i * nSurf + s];
288+ for (let i = 0; i < K; i++) {
289+ let v = col[i];
290+ for (let j = 0; j < i; j++) v -= L[i * K + j] * col[j];
291+ col[i] = v / L[i * K + i];
292+ }
293+ for (let i = K - 1; i >= 0; i--) {
294+ let v = col[i];
295+ for (let j = i + 1; j < K; j++) v -= L[j * K + i] * col[j];
296+ col[i] = v / L[i * K + i];
297+ }
298+ for (let n = 0; n < M; n++) {
299+ out.re[n * nSurf + s] = col[2 * n];
300+ out.im[n * nSurf + s] = col[2 * n + 1];
301+ }
302+ }
303+ return out;
304+}
305+
306+function cholesky(A, n) {
307+ const L = new Float64Array(n * n);
308+ for (let i = 0; i < n; i++) {
309+ for (let j = 0; j <= i; j++) {
310+ let s = A[i * n + j];
311+ for (let k = 0; k < j; k++) s -= L[i * n + k] * L[j * n + k];
312+ L[i * n + j] = i === j ? Math.sqrt(Math.max(s, 1e-300)) : s / L[j * n + j];
313+ }
314+ }
315+ return L;
316+}
317+
318+/**
319+ * Label FDTD modes by the FE mode they resemble most (shape correlation on the grid).
320+ * Returns rows [{ fe, fd, corr, cents }] for the FE modes that found a partner.
321+ */
322+export function matchModes(fe, fd) {
323+ const norm = (p) => Math.sqrt(p.reduce((a, v) => a + v * v, 0)) || 1;
324+ const rows = [];
325+ for (const m of fd.modes) {
326+ let best = null;
327+ for (const q of fe.modes) {
328+ let s = 0;
329+ for (let i = 0; i < m.phi.length; i++) s += m.phi[i] * q.phi[i];
330+ const c = Math.abs(s) / (norm(m.phi) * norm(q.phi));
331+ if (!best || c > best.c) best = { q, c };
332+ }
333+ if (best && best.c > 0.7) {
334+ m.label = best.q.label;
335+ rows.push({ fe: best.q, fd: m, corr: best.c, cents: 1200 * Math.log2(m.f / best.q.f) });
336+ } else m.label = '?';
337+ }
338+ // keep the best match per FE mode; number the rest
339+ const seen = new Map();
340+ for (const r of rows) if (!seen.has(r.fe.label) || seen.get(r.fe.label).corr < r.corr) seen.set(r.fe.label, r);
341+ for (const m of fd.modes) if (m.label !== '?' && seen.get(m.label)?.fd !== m) m.label += "'";
342+ return [...seen.values()].sort((a, b) => a.fe.f - b.fe.f);
343+}
js/bar.jsadded+105−0View file
@@ -0,0 +1,105 @@
1+// Bar geometry, wood materials, the nominal size of each key's bar, and the resonator
2+// and mic placement. Lengths in mm unless a name says otherwise.
3+// Axes: x = length (grain, L), y = width (front edge at y = 0, T), z = thickness (up, R).
4+// The top face is flat at z = h0; the undercut arch is cut into the bottom face.
5+
6+export const AIR = { rho: 1.2, c: 343 };
7+
8+export const MATERIALS = {
9+ rosewood: { label: 'Honduras rosewood', rho: 1025, EL: 22.0, eta: 0.006 },
10+ padauk: { label: 'Padauk', rho: 745, EL: 11.7, eta: 0.01 },
11+};
12+
13+export const LOW_NOTE = 36; // C2
14+export const HIGH_NOTE = 96; // C7
15+
16+const NOTE = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
17+export const noteName = (k) => NOTE[k % 12] + (Math.floor(k / 12) - 1);
18+export const noteFreq = (k) => 440 * 2 ** ((k - 69) / 12);
19+export const freqToMidi = (f) => 69 + 12 * Math.log2(f / 440);
20+export const isBlack = (k) => [1, 3, 6, 8, 10].includes(k % 12);
21+
22+// Orthotropic hardwood stiffness (ratios as for dense hardwoods), scaled by E_L (Pa).
23+export function woodStiffness(EL, scale = 1) {
24+ const E = EL * scale;
25+ const Ex = E, Ey = 0.065 * E, Ez = 0.132 * E; // L, T, R
26+ const nuLT = 0.476, nuLR = 0.424, nuRT = 0.774;
27+ const S = [
28+ [1 / Ex, -nuLT / Ex, -nuLR / Ex],
29+ [-nuLT / Ex, 1 / Ey, -nuRT / Ez],
30+ [-nuLR / Ex, -nuRT / Ez, 1 / Ez],
31+ ];
32+ const C = inv3(S);
33+ return {
34+ E: Ex,
35+ c11: C[0][0], c22: C[1][1], c33: C[2][2],
36+ c12: C[0][1], c13: C[0][2], c23: C[1][2],
37+ gxy: 0.063 * E, gxz: 0.111 * E, gyz: 0.02 * E,
38+ };
39+}
40+
41+function inv3(m) {
42+ const [a, b, c] = m[0], [d, e, f] = m[1], [g, h, i] = m[2];
43+ const A = e * i - f * h, B = -(d * i - f * g), Cc = d * h - e * g;
44+ const det = a * A + b * B + c * Cc;
45+ return [
46+ [A / det, -(b * i - c * h) / det, (b * f - c * e) / det],
47+ [B / det, (a * i - c * g) / det, -(a * f - c * d) / det],
48+ [Cc / det, -(a * h - b * g) / det, (a * e - b * d) / det],
49+ ];
50+}
51+
52+/**
53+ * A bar design: { L, W, h0 (mm), d: undercut depth (mm), a: undercut length as a
54+ * fraction of L, p: arch shape exponent (2 = parabola, larger = flatter bottom) }.
55+ */
56+export function thickness(b, x) {
57+ const u = Math.abs(x - b.L / 2) / ((b.a * b.L) / 2);
58+ return u < 1 ? b.h0 - b.d * (1 - u ** b.p) : b.h0;
59+}
60+
61+export const MIN_THICK = 3; // mm left at the deepest point of the arch
62+export const maxDepth = (b) => b.h0 - Math.max(MIN_THICK, 0.1 * b.h0);
63+
64+// Width and thickness change smoothly from C2 to C7; the tuner sets length and undercut.
65+export function nominalDesign(note, mat) {
66+ const t = (note - LOW_NOTE) / (HIGH_NOTE - LOW_NOTE);
67+ const W = 72 - 32 * t, h0 = 24 - 4 * t; // typical 5-octave concert ranges
68+ // length guess: uniform-bar formula, with the arch lowering f1 more in the bass
69+ const c = Math.sqrt((mat.EL * 1e9) / mat.rho);
70+ const lower = 1.2 * 2 ** ((HIGH_NOTE - note) / 24);
71+ const L = 1000 * Math.sqrt((1.028 * c * h0 * 1e-3) / (noteFreq(note) * lower));
72+ const b = { L, W, h0, d: 0, a: 0.45, p: 4 };
73+ b.d = 0.65 * maxDepth(b);
74+ return b;
75+}
76+
77+export function validateDesign(b) {
78+ const e = [];
79+ if (b.d > maxDepth(b) + 1e-9) e.push(`undercut deeper than ${maxDepth(b).toFixed(1)} mm`);
80+ if (b.L < 2 * b.W) e.push('bar shorter than twice its width');
81+ return e;
82+}
83+
84+// ---------- resonator and mic ----------
85+
86+/**
87+ * Resonator: closed-bottom round tube centred under the bar.
88+ * res = { on, diam (fraction of W), gap (mm from the bar's bottom plane to the tube top),
89+ * detune (cents), loss (× wall loss) }
90+ */
91+export function tubeGeom(b, res) {
92+ const a = (res.diam * b.W) / 2; // radius, mm
93+ // end correction: unflanged pipe plus the bar acting as a partial lid over the mouth
94+ const delta = 0.61 * a + (0.15 * a * a) / Math.max(2, res.gap);
95+ return { a, delta, x: b.L / 2, y: b.W / 2, zTop: -res.gap };
96+}
97+
98+// Tube length (mm) whose air column, with the end correction, resonates at f (Hz).
99+export function tubeLength(f, delta) {
100+ const k = (2 * Math.PI * f) / (AIR.c * 1000); // 1/mm
101+ return (Math.PI / 2 - Math.atan(k * delta)) / k;
102+}
103+
104+export const MIC = { front: 300, up: 450 }; // mm in front of and above the bar centre
105+export const micPos = (b) => [b.L / 2, b.W / 2 - MIC.front, b.h0 + MIC.up];
js/export.jsadded+82−0View file
@@ -0,0 +1,82 @@
1+// Render a velocity-layered marimba SoundFont. Every sampled key is its own bar (the key's
2+// edited design, or the auto-tuned one) over its own tuned tube, so the low end really is
3+// longer, darker and slower to decay than the top.
4+
5+import { feBarModel } from './fe.js';
6+import { prepare, strike } from './synth.js';
7+import { buildSF2 } from './sf2.js';
8+
9+export const LAYERS = 4; // velocity layers
10+export const VARIANTS = 3; // strike-point variations, interleaved in velocity
11+const RR_OFFSETS = [[0, 0], [0.012, -0.06], [-0.01, 0.07]]; // fractions of L and W
12+
13+export function sampledKeys(lo, hi, step) {
14+ const keys = [];
15+ for (let k = lo; k <= hi; k += step) keys.push(k);
16+ if (keys[keys.length - 1] !== hi && hi - keys[keys.length - 1] > step / 2) keys.push(hi);
17+ return keys;
18+}
19+
20+/**
21+ * opts: { lo, hi, step, name, sampleRate, designFor(note) -> design, mat,
22+ * sound: { eta, slope, res }, malletFor(note) -> mallet (with v0), strike: [fx, fy], onProgress(frac, label) }
23+ */
24+export async function exportSF2(opts) {
25+ const { lo, hi, step, name, mat, sound } = opts;
26+ const sr = opts.sampleRate ?? 44100;
27+ const keys = sampledKeys(lo, hi, step);
28+ const ranges = keys.map((k, i) => [
29+ i === 0 ? lo : Math.floor((keys[i - 1] + k) / 2) + 1,
30+ i === keys.length - 1 ? hi : Math.floor((k + keys[i + 1]) / 2),
31+ ]);
32+ const nBands = LAYERS * VARIANTS;
33+ const band = (b) => [1 + Math.floor((b * 127) / nBands), Math.floor(((b + 1) * 127) / nBands)];
34+
35+ const raw = [], zones = [];
36+ const total = keys.length * nBands;
37+ let done = 0, peak = 0;
38+ for (let ki = 0; ki < keys.length; ki++) {
39+ const k = keys[ki];
40+ const design = opts.designFor(k);
41+ const model = feBarModel(design, mat);
42+ const prep = prepare(model, { note: k, eta: sound.eta, slope: sound.slope, res: sound.res });
43+ for (let b = 0; b < nBands; b++) {
44+ const layer = Math.floor(b / VARIANTS), rr = b % VARIANTS;
45+ const x = (layer + 1) / LAYERS;
46+ const m0 = opts.malletFor(k);
47+ const ml = { ...m0, v0: m0.v0 * (0.12 + 0.88 * x), Ky: m0.Ky + 0.3 * (x - 1) };
48+ const fx = Math.min(0.97, Math.max(0.03, opts.strike[0] + RR_OFFSETS[rr][0]));
49+ const fy = Math.min(0.95, Math.max(0.05, opts.strike[1] + RR_OFFSETS[rr][1]));
50+ const { y } = strike(prep, fx * design.L, fy * design.W, ml, sr, 3);
51+ for (let i = 0; i < y.length; i++) peak = Math.max(peak, Math.abs(y[i]));
52+ const [vlo, vhi] = band(b);
53+ zones.push({ keyLo: ranges[ki][0], keyHi: ranges[ki][1], velLo: vlo, velHi: vhi, sample: raw.length });
54+ raw.push({ y, root: k, name: `mb${k}v${layer + 1}r${rr + 1}` });
55+ done++;
56+ opts.onProgress?.(done / total, k);
57+ await new Promise((r) => setTimeout(r, 0));
58+ }
59+ }
60+
61+ // one global gain so keys and layers keep their physical loudness; trim tails at -66 dB
62+ const g = (0.89 * 32767) / (peak || 1);
63+ const floor = peak * 10 ** (-66 / 20);
64+ const fade = Math.round(0.01 * sr);
65+ const samples = raw.map((s) => {
66+ let end = s.y.length - 1;
67+ while (end > 0 && Math.abs(s.y[end]) < floor) end--;
68+ const n = Math.min(s.y.length, end + fade);
69+ const d = new Int16Array(n);
70+ for (let i = 0; i < n; i++) {
71+ const fo = i > n - fade ? (n - i) / fade : 1;
72+ d[i] = Math.max(-32768, Math.min(32767, Math.round(s.y[i] * g * fo)));
73+ }
74+ return { name: s.name, data: d, root: s.root };
75+ });
76+
77+ const bytes = buildSF2({
78+ name, bank: 0, program: 12, sampleRate: sr, samples, zones, // GM 13: Marimba
79+ releaseSec: 1.5, disableVelocityAttenuation: true,
80+ });
81+ return { bytes, keys, nSamples: samples.length };
82+}
js/fdtd.jsadded+308−0View file
@@ -0,0 +1,308 @@
1+// 3D staggered-grid (velocity-stress) FDTD on WebGPU for orthotropic wood + air, used
2+// only to find the bar's modes (undamped; the modal model adds damping itself).
3+// Air cells use mu = 0, lambda = rho c^2, so one kernel handles both media.
4+// mode 1 = 'analysis': volume-velocity pulse at the mic, record vz at every top-surface
5+// node (by reciprocity this gives mic pressure per unit force at every strike point).
6+// mode 2 = 'impulse': half-sine force pulse on a patch, record vz at every top-surface node
7+// (surface mobility, used for the modal model's contact dynamics).
8+
9+import { AIR, woodStiffness } from './bar.js';
10+
11+const WGSL = /* wgsl */ `
12+struct P {
13+ nx:u32, ny:u32, nz:u32, N:u32,
14+ dx:f32, dt:f32, rhoW:f32, rhoA:f32,
15+ c11:f32, c22:f32, c33:f32, c12:f32,
16+ c13:f32, c23:f32, gxy:f32, gxz:f32,
17+ gyz:f32, lamA:f32, ns:f32, dmax:f32,
18+ mode:u32, pulseT:f32, pulseA:f32, nPatch:u32,
19+ micIdx:u32, nRec:u32, decim:u32, nSurf:u32,
20+};
21+@group(0) @binding(0) var<uniform> p: P;
22+@group(0) @binding(1) var<storage, read_write> fld: array<f32>;
23+@group(0) @binding(2) var<storage, read> mat: array<u32>;
24+@group(0) @binding(3) var<storage, read_write> state: array<f32>;
25+@group(0) @binding(4) var<storage, read> idxs: array<u32>;
26+@group(0) @binding(5) var<storage, read> patchW: array<f32>;
27+@group(0) @binding(6) var<storage, read_write> outb: array<f32>;
28+@group(0) @binding(7) var<storage, read_write> acc: array<f32>;
29+
30+const VX = 0u; const VY = 1u; const VZ = 2u;
31+const SXX = 3u; const SYY = 4u; const SZZ = 5u;
32+const SXY = 6u; const SXZ = 7u; const SYZ = 8u;
33+
34+fn id(i:u32, j:u32, k:u32) -> u32 { return i + p.nx * (j + p.ny * k); }
35+fn fv(c:u32, n:u32) -> f32 { return fld[c * p.N + n]; }
36+fn isW(n:u32) -> bool { return mat[n] == 1u; }
37+fn rho(n:u32) -> f32 { return select(p.rhoA, p.rhoW, isW(n)); }
38+
39+fn sponge(i:u32, j:u32, k:u32) -> f32 {
40+ let x = f32(i); let y = f32(j); let z = f32(k);
41+ let dxs = max(max(p.ns - x, x - (f32(p.nx) - 1.0 - p.ns)), 0.0);
42+ let dys = max(max(p.ns - y, y - (f32(p.ny) - 1.0 - p.ns)), 0.0);
43+ let dzs = max(max(p.ns - z, z - (f32(p.nz) - 1.0 - p.ns)), 0.0);
44+ let r2 = (dxs * dxs + dys * dys + dzs * dzs) / (p.ns * p.ns);
45+ return exp(-p.dmax * r2 * p.dt);
46+}
47+
48+fn inside(g:vec3u) -> bool {
49+ return g.x >= 1u && g.y >= 1u && g.z >= 1u && g.x < p.nx - 1u && g.y < p.ny - 1u && g.z < p.nz - 1u;
50+}
51+
52+@compute @workgroup_size(8, 8, 4)
53+fn vel(@builtin(global_invocation_id) g: vec3u) {
54+ if (!inside(g)) { return; }
55+ let c = id(g.x, g.y, g.z);
56+ let sx = 1u; let sy = p.nx; let sz = p.nx * p.ny;
57+ let h = p.dt / p.dx;
58+ let sp = sponge(g.x, g.y, g.z);
59+ {
60+ let n = c + sx;
61+ let d = fv(SXX, n) - fv(SXX, c) + fv(SXY, c) - fv(SXY, c - sy) + fv(SXZ, c) - fv(SXZ, c - sz);
62+ fld[VX * p.N + c] = sp * (fv(VX, c) + 2.0 * h * d / (rho(c) + rho(n)));
63+ }
64+ {
65+ let n = c + sy;
66+ let d = fv(SXY, c) - fv(SXY, c - sx) + fv(SYY, n) - fv(SYY, c) + fv(SYZ, c) - fv(SYZ, c - sz);
67+ fld[VY * p.N + c] = sp * (fv(VY, c) + 2.0 * h * d / (rho(c) + rho(n)));
68+ }
69+ {
70+ let n = c + sz;
71+ let d = fv(SXZ, c) - fv(SXZ, c - sx) + fv(SYZ, c) - fv(SYZ, c - sy) + fv(SZZ, n) - fv(SZZ, c);
72+ fld[VZ * p.N + c] = sp * (fv(VZ, c) + 2.0 * h * d / (rho(c) + rho(n)));
73+ }
74+}
75+
76+fn upd(comp:u32, n:u32, t:f32, sp:f32) {
77+ let i = comp * p.N + n;
78+ fld[i] = sp * (fld[i] + p.dt * t);
79+}
80+
81+@compute @workgroup_size(8, 8, 4)
82+fn str(@builtin(global_invocation_id) g: vec3u) {
83+ if (!inside(g)) { return; }
84+ let c = id(g.x, g.y, g.z);
85+ let sx = 1u; let sy = p.nx; let sz = p.nx * p.ny;
86+ let sp = sponge(g.x, g.y, g.z);
87+ let idx = 1.0 / p.dx;
88+ let wc = isW(c);
89+ let exx = (fv(VX, c) - fv(VX, c - sx)) * idx;
90+ let eyy = (fv(VY, c) - fv(VY, c - sy)) * idx;
91+ let ezz = (fv(VZ, c) - fv(VZ, c - sz)) * idx;
92+ var c11 = p.lamA; var c22 = p.lamA; var c33 = p.lamA;
93+ var c12 = p.lamA; var c13 = p.lamA; var c23 = p.lamA;
94+ if (wc) { c11 = p.c11; c22 = p.c22; c33 = p.c33; c12 = p.c12; c13 = p.c13; c23 = p.c23; }
95+ upd(SXX, c, c11 * exx + c12 * eyy + c13 * ezz, sp);
96+ upd(SYY, c, c12 * exx + c22 * eyy + c23 * ezz, sp);
97+ upd(SZZ, c, c13 * exx + c23 * eyy + c33 * ezz, sp);
98+ // shear moduli at edges: harmonic mean of the 4 cells, i.e. 0 unless all are wood
99+ {
100+ let all = wc && isW(c + sx) && isW(c + sy) && isW(c + sx + sy);
101+ let e = (fv(VX, c + sy) - fv(VX, c) + fv(VY, c + sx) - fv(VY, c)) * idx;
102+ upd(SXY, c, select(0.0, p.gxy, all) * e, sp);
103+ }
104+ {
105+ let all = wc && isW(c + sx) && isW(c + sz) && isW(c + sx + sz);
106+ let e = (fv(VX, c + sz) - fv(VX, c) + fv(VZ, c + sx) - fv(VZ, c)) * idx;
107+ upd(SXZ, c, select(0.0, p.gxz, all) * e, sp);
108+ }
109+ {
110+ let all = wc && isW(c + sy) && isW(c + sz) && isW(c + sy + sz);
111+ let e = (fv(VY, c + sz) - fv(VY, c) + fv(VZ, c + sy) - fv(VZ, c)) * idx;
112+ upd(SYZ, c, select(0.0, p.gyz, all) * e, sp);
113+ }
114+}
115+
116+// Single-thread step: the source pulse (at the mic, or a force on the patch).
117+@compute @workgroup_size(1)
118+fn aux() {
119+ let s = state[0];
120+ let t = s * p.dt;
121+ let dx3 = p.dx * p.dx * p.dx;
122+ var A = 0.0;
123+ if (t < p.pulseT) { A = p.pulseA * sin(3.14159265 * t / p.pulseT); }
124+ if (p.mode == 2u) {
125+ // downward force A (N) spread over the patch's surface nodes
126+ let rs = 0.5 * (p.rhoW + p.rhoA);
127+ for (var n = 0u; n < p.nPatch; n++) {
128+ let q = VZ * p.N + idxs[n];
129+ fld[q] = fld[q] - p.dt * A * patchW[n] / (rs * dx3);
130+ }
131+ } else {
132+ // volume velocity A (m^3/s) at the mic cell
133+ let m = p.micIdx;
134+ let dS = p.dt * p.lamA * A / dx3;
135+ fld[SXX * p.N + m] -= dS;
136+ fld[SYY * p.N + m] -= dS;
137+ fld[SZZ * p.N + m] -= dS;
138+ }
139+ state[0] = s + 1.0;
140+}
141+
142+// Boxcar-decimated recording of vz at every top-surface node.
143+@compute @workgroup_size(64)
144+fn rec(@builtin(global_invocation_id) g: vec3u) {
145+ let n = g.x;
146+ if (n >= p.nSurf) { return; }
147+ let s = u32(state[0]); // steps completed
148+ var a = acc[n] + fld[VZ * p.N + idxs[p.nPatch + n]];
149+ if (s % p.decim == 0u) {
150+ let r = s / p.decim - 1u;
151+ if (r < p.nRec) { outb[r * p.nSurf + n] = a / f32(p.decim); }
152+ a = 0.0;
153+ }
154+ acc[n] = a;
155+}
156+`;
157+
158+let devicePromise = null;
159+export function getDevice() {
160+ if (!devicePromise) {
161+ devicePromise = (async () => {
162+ if (!navigator.gpu) throw new Error('WebGPU is not available in this browser.');
163+ const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
164+ if (!adapter) throw new Error('No WebGPU adapter found.');
165+ return adapter.requestDevice({
166+ requiredLimits: {
167+ maxStorageBufferBindingSize: adapter.limits.maxStorageBufferBindingSize,
168+ maxBufferSize: adapter.limits.maxBufferSize,
169+ },
170+ });
171+ })();
172+ }
173+ return devicePromise;
174+}
175+
176+// Time step (CFL) for a grid spacing dx (mm) and stiffness scale.
177+export function timeStep(mat, dx, stiffScale = 1) {
178+ const C = woodStiffness(mat.EL * 1e9, stiffScale);
179+ const cmax = Math.sqrt(Math.max(C.c11, C.c22, C.c33) / mat.rho);
180+ return (0.9 * dx * 1e-3) / (cmax * Math.sqrt(3));
181+}
182+
183+/**
184+ * Run one analysis simulation, recording vz at every top-surface node.
185+ * opts: { mat, grid, mode: 'analysis'|'impulse', duration (s), stiffScale,
186+ * patch: {idx, w} (impulse), recRate, onProgress(frac, sec), isCancelled() }
187+ * Returns { dt, nSteps, data: Float32Array [nRec x nSurf], recRate, pulseT, pulseA, ... }.
188+ */
189+export async function runFDTD(opts) {
190+ const device = await getDevice();
191+ const { mat, grid, mode } = opts;
192+ const modeId = { analysis: 1, impulse: 2 }[mode];
193+ if (!modeId) throw new Error(`unknown FDTD mode ${mode}`);
194+ const dt = timeStep(mat, grid.dx, opts.stiffScale ?? 1);
195+ const nSteps = Math.ceil(opts.duration / dt);
196+ const C = woodStiffness(mat.EL * 1e9, opts.stiffScale ?? 1);
197+ const lamA = AIR.rho * AIR.c * AIR.c;
198+ const dxm = grid.dx * 1e-3;
199+ const dmax = (3 * AIR.c * Math.log(1e3)) / (2 * grid.ns * dxm);
200+
201+ const decim = Math.max(1, Math.round(1 / (opts.recRate * dt)));
202+ const nRec = Math.floor(nSteps / decim);
203+ const nSurf = grid.surf.length;
204+ const patch = modeId === 2 ? opts.patch : { idx: new Uint32Array(0), w: new Float32Array(0) };
205+ const pulseT = 6e-5, pulseA = modeId === 1 ? 1e-6 : 1; // m^3/s (mic source) or N (force)
206+
207+ // Uniforms (order must match struct P)
208+ const U = new ArrayBuffer(112);
209+ const dv = new DataView(U);
210+ let off = 0;
211+ const u = (v) => { dv.setUint32(off, v, true); off += 4; };
212+ const f = (v) => { dv.setFloat32(off, v, true); off += 4; };
213+ u(grid.nx); u(grid.ny); u(grid.nz); u(grid.N);
214+ f(dxm); f(dt); f(mat.rho); f(AIR.rho);
215+ f(C.c11); f(C.c22); f(C.c33); f(C.c12);
216+ f(C.c13); f(C.c23); f(C.gxy); f(C.gxz);
217+ f(C.gyz); f(lamA); f(grid.ns); f(dmax);
218+ u(modeId); f(pulseT); f(pulseA); u(patch.idx.length);
219+ u(grid.micIdx); u(nRec); u(decim); u(nSurf);
220+
221+ const usage = GPUBufferUsage;
222+ const mk = (size, use, data) => {
223+ const b = device.createBuffer({ size: Math.max(16, Math.ceil(size / 4) * 4), usage: use, mappedAtCreation: !!data });
224+ if (data) {
225+ new data.constructor(b.getMappedRange()).set(data);
226+ b.unmap();
227+ }
228+ return b;
229+ };
230+ const S = usage.STORAGE | usage.COPY_DST | usage.COPY_SRC;
231+ const uni = mk(U.byteLength, usage.UNIFORM | usage.COPY_DST);
232+ device.queue.writeBuffer(uni, 0, U);
233+ const fldB = mk(9 * grid.N * 4, S);
234+ const matB = mk(grid.N * 4, S, grid.mat);
235+ const stateB = mk(16, S, new Float32Array(4));
236+ const idxArr = new Uint32Array(Math.max(1, patch.idx.length + nSurf));
237+ idxArr.set(patch.idx, 0);
238+ idxArr.set(grid.surf, patch.idx.length);
239+ const idxB = mk(idxArr.byteLength, S, idxArr);
240+ const pw = new Float32Array(Math.max(1, patch.w.length));
241+ pw.set(patch.w);
242+ const pwB = mk(pw.byteLength, S, pw);
243+ const outLen = nRec * nSurf;
244+ const outB = mk(outLen * 4, S);
245+ const accB = mk(Math.max(1, nSurf) * 4, S);
246+
247+ const layout = device.createBindGroupLayout({
248+ entries: ['uniform', 'storage', 'read-only-storage', 'storage', 'read-only-storage', 'read-only-storage', 'storage', 'storage']
249+ .map((type, binding) => ({ binding, visibility: GPUShaderStage.COMPUTE, buffer: { type } })),
250+ });
251+ const bg = device.createBindGroup({
252+ layout,
253+ entries: [uni, fldB, matB, stateB, idxB, pwB, outB, accB].map((buffer, binding) => ({ binding, resource: { buffer } })),
254+ });
255+ const module = device.createShaderModule({ code: WGSL });
256+ const info = await module.getCompilationInfo();
257+ const errs = info.messages.filter((m) => m.type === 'error');
258+ if (errs.length) throw new Error('WGSL: ' + errs.map((m) => `${m.lineNum}: ${m.message}`).join('\n'));
259+ const plLayout = device.createPipelineLayout({ bindGroupLayouts: [layout] });
260+ const [pVel, pStr, pAux, pRec] = await Promise.all(
261+ ['vel', 'str', 'aux', 'rec'].map((e) =>
262+ device.createComputePipelineAsync({ layout: plLayout, compute: { module, entryPoint: e } })),
263+ );
264+
265+ const wg = [Math.ceil(grid.nx / 8), Math.ceil(grid.ny / 8), Math.ceil(grid.nz / 4)];
266+ const wgRec = Math.ceil(Math.max(1, nSurf) / 64);
267+ const chunk = 200;
268+ const t0 = performance.now();
269+ let cancelled = false;
270+ for (let s = 0; s < nSteps; s += chunk) {
271+ const enc = device.createCommandEncoder();
272+ const pass = enc.beginComputePass();
273+ pass.setBindGroup(0, bg);
274+ const n = Math.min(chunk, nSteps - s);
275+ for (let q = 0; q < n; q++) {
276+ pass.setPipeline(pVel); pass.dispatchWorkgroups(wg[0], wg[1], wg[2]);
277+ pass.setPipeline(pAux); pass.dispatchWorkgroups(1);
278+ pass.setPipeline(pStr); pass.dispatchWorkgroups(wg[0], wg[1], wg[2]);
279+ pass.setPipeline(pRec); pass.dispatchWorkgroups(wgRec);
280+ }
281+ pass.end();
282+ device.queue.submit([enc.finish()]);
283+ if ((s / chunk) % 10 === 9 || s + chunk >= nSteps) {
284+ await device.queue.onSubmittedWorkDone();
285+ const frac = Math.min(1, (s + n) / nSteps);
286+ opts.onProgress?.(frac, (performance.now() - t0) / 1000);
287+ if (opts.isCancelled?.()) { cancelled = true; break; }
288+ }
289+ }
290+
291+ let data = null;
292+ if (!cancelled) {
293+ const read = device.createBuffer({ size: outLen * 4, usage: usage.MAP_READ | usage.COPY_DST });
294+ const enc = device.createCommandEncoder();
295+ enc.copyBufferToBuffer(outB, 0, read, 0, outLen * 4);
296+ device.queue.submit([enc.finish()]);
297+ await read.mapAsync(GPUMapMode.READ);
298+ data = new Float32Array(read.getMappedRange().slice(0));
299+ read.unmap();
300+ read.destroy();
301+ }
302+ for (const b of [uni, fldB, matB, stateB, idxB, pwB, outB, accB]) b.destroy();
303+ if (cancelled) return null;
304+ return {
305+ dt, nSteps, data, decim, nRec, nSurf, pulseT, pulseA,
306+ recRate: 1 / (decim * dt), seconds: (performance.now() - t0) / 1000,
307+ };
308+}
js/fe.jsadded+274−0View file
@@ -0,0 +1,274 @@
1+// Fast finite-element model of a free bar with a varying thickness profile:
2+// - vertical bending: Timoshenko beam (2-node elements, w and rotation ψ, reduced shear
3+// integration), shear modulus G_LR, rotary inertia included;
4+// - torsion: Saint-Venant, with the torsion constant of an orthotropic rectangle.
5+// Eigenvalues come from Sturm-sequence bisection on banded LDLᵀ factors and eigenvectors
6+// from inverse iteration, so asking for a few modes costs well under a millisecond.
7+
8+import { thickness, woodStiffness, AIR } from './bar.js';
9+
10+const KAPPA = 5 / 6;
11+export const NE = 160; // elements along the length
12+
13+// ---------- banded symmetric matrices (upper band, row-major, width b+1) ----------
14+
15+function band(n, b) { return { n, b, A: new Float64Array(n * (b + 1)) }; }
16+function addSym(m, i, j, v) { // add v to (i,j) and (j,i)
17+ if (j < i) [i, j] = [j, i];
18+ m.A[i * (m.b + 1) + (j - i)] += v;
19+}
20+
21+// LDLᵀ of K - lam M. Fills L (band by column) and d; returns the number of negative pivots.
22+function ldl(K, M, lam, L, d) {
23+ const { n, b } = K, w = b + 1;
24+ let neg = 0;
25+ for (let j = 0; j < n; j++) {
26+ let s = K.A[j * w] - lam * M.A[j * w];
27+ for (let k = Math.max(0, j - b); k < j; k++) { const l = L[k * w + (j - k)]; s -= l * l * d[k]; }
28+ if (s === 0) s = 1e-300;
29+ d[j] = s;
30+ if (s < 0) neg++;
31+ const iMax = Math.min(n - 1, j + b);
32+ for (let i = j + 1; i <= iMax; i++) {
33+ let t = K.A[j * w + (i - j)] - lam * M.A[j * w + (i - j)];
34+ for (let k = Math.max(0, i - b); k < j; k++) t -= L[k * w + (i - k)] * L[k * w + (j - k)] * d[k];
35+ L[j * w + (i - j)] = t / s;
36+ }
37+ }
38+ return neg;
39+}
40+
41+function ldlSolve(L, d, n, b, r) {
42+ const w = b + 1, x = Float64Array.from(r);
43+ for (let i = 0; i < n; i++) for (let k = Math.max(0, i - b); k < i; k++) x[i] -= L[k * w + (i - k)] * x[k];
44+ for (let i = 0; i < n; i++) x[i] /= d[i];
45+ for (let i = n - 1; i >= 0; i--) for (let k = i + 1; k <= Math.min(n - 1, i + b); k++) x[i] -= L[i * w + (k - i)] * x[k];
46+ return x;
47+}
48+
49+function bandMul(m, x) {
50+ const { n, b } = m, w = b + 1, y = new Float64Array(n);
51+ for (let i = 0; i < n; i++) {
52+ y[i] += m.A[i * w] * x[i];
53+ for (let k = 1; k <= b && i + k < n; k++) {
54+ const v = m.A[i * w + k];
55+ y[i] += v * x[i + k];
56+ y[i + k] += v * x[i];
57+ }
58+ }
59+ return y;
60+}
61+
62+class Eig {
63+ constructor(K, M, nRigid) {
64+ this.K = K; this.M = M; this.nRigid = nRigid;
65+ this.L = new Float64Array(K.n * (K.b + 1));
66+ this.d = new Float64Array(K.n);
67+ }
68+ count(lam) { return ldl(this.K, this.M, lam, this.L, this.d); }
69+ // m-th flexible eigenvalue (m = 1, 2, ...), by bisection
70+ value(m, guess) {
71+ const want = m + this.nRigid;
72+ let lo = 1, hi = guess > 0 ? guess * 1.5 : 1e6;
73+ while (this.count(hi) < want) { lo = hi; hi *= 4; }
74+ let cLo = this.count(lo);
75+ while (cLo >= want) { hi = lo; lo /= 4; cLo = this.count(lo); }
76+ for (let it = 0; it < 80 && hi / lo - 1 > 1e-11; it++) {
77+ const mid = Math.sqrt(lo * hi);
78+ if (this.count(mid) >= want) hi = mid; else lo = mid;
79+ }
80+ return Math.sqrt(lo * hi);
81+ }
82+ // mass-normalized eigenvector by inverse iteration
83+ vector(lam) {
84+ const { K, M } = this, n = K.n;
85+ let x = Float64Array.from({ length: n }, (_, i) => Math.sin(1.3 + 0.37 * i) + 0.5 * Math.cos(0.11 * i));
86+ this.count(lam * (1 - 1e-9));
87+ for (let it = 0; it < 4; it++) {
88+ x = ldlSolve(this.L, this.d, n, K.b, bandMul(M, x));
89+ const mx = bandMul(M, x);
90+ let s = 0;
91+ for (let i = 0; i < n; i++) s += x[i] * mx[i];
92+ s = 1 / Math.sqrt(s);
93+ for (let i = 0; i < n; i++) x[i] *= s;
94+ }
95+ return x;
96+ }
97+}
98+
99+// ---------- assembly ----------
100+
101+function sections(b, ne) {
102+ const le = (b.L * 1e-3) / ne, W = b.W * 1e-3;
103+ const out = [];
104+ for (let e = 0; e < ne; e++) {
105+ const h = thickness(b, ((e + 0.5) * b.L) / ne) * 1e-3;
106+ out.push({ le, A: W * h, I: (W * h ** 3) / 12, h, W });
107+ }
108+ return out;
109+}
110+
111+function bendingSystem(b, mat, ne) {
112+ const C = woodStiffness(mat.EL * 1e9);
113+ const n = 2 * (ne + 1);
114+ const K = band(n, 3), M = band(n, 3);
115+ for (const [e, s] of sections(b, ne).entries()) {
116+ const o = 2 * e, { le, A, I } = s;
117+ // bending on ψ
118+ const kb = (C.E * I) / le;
119+ addSym(K, o + 1, o + 1, kb); addSym(K, o + 3, o + 3, kb); addSym(K, o + 1, o + 3, -kb);
120+ // shear, one-point integration: γ = (w2-w1)/le - (ψ1+ψ2)/2
121+ const B = [-1 / le, -0.5, 1 / le, -0.5], ks = KAPPA * C.gxz * A * le;
122+ for (let i = 0; i < 4; i++) for (let j = i; j < 4; j++) addSym(K, o + i, o + j, ks * B[i] * B[j]);
123+ // consistent mass: translation and rotary inertia
124+ const mt = (mat.rho * A * le) / 6, mr = (mat.rho * I * le) / 6;
125+ addSym(M, o, o, 2 * mt); addSym(M, o + 2, o + 2, 2 * mt); addSym(M, o, o + 2, mt);
126+ addSym(M, o + 1, o + 1, 2 * mr); addSym(M, o + 3, o + 3, 2 * mr); addSym(M, o + 1, o + 3, mr);
127+ }
128+ return new Eig(K, M, 2);
129+}
130+
131+// Torsion constant of a b × t rectangle (isotropic), b ≥ t not required.
132+function rectJ(b, t) {
133+ if (b < t) [b, t] = [t, b];
134+ const r = t / b;
135+ return b * t ** 3 * (1 / 3 - 0.21 * r * (1 - r ** 4 / 12));
136+}
137+
138+function torsionSystem(b, mat, ne) {
139+ const C = woodStiffness(mat.EL * 1e9);
140+ const n = ne + 1;
141+ const K = band(n, 1), M = band(n, 1);
142+ // orthotropic: stretch the width by alpha = sqrt(G_LT / G_LR), isotropic with G_LT
143+ const alpha = Math.sqrt(C.gxy / C.gxz);
144+ for (const [e, s] of sections(b, ne).entries()) {
145+ const { le, h, W } = s;
146+ const GJ = alpha * C.gxy * rectJ(W / alpha, h);
147+ const Ip = (W * h * (W * W + h * h)) / 12;
148+ const k = GJ / le, m = (mat.rho * Ip * le) / 6;
149+ addSym(K, e, e, k); addSym(K, e + 1, e + 1, k); addSym(K, e, e + 1, -k);
150+ addSym(M, e, e, 2 * m); addSym(M, e + 1, e + 1, 2 * m); addSym(M, e, e + 1, m);
151+ }
152+ return new Eig(K, M, 1);
153+}
154+
155+// First `count` vertical bending frequencies (Hz). Used by the tuner.
156+export function bendFreqs(b, mat, count = 3, ne = NE) {
157+ const eig = bendingSystem(b, mat, ne);
158+ const out = [];
159+ let guess = 0;
160+ for (let m = 1; m <= count; m++) {
161+ const lam = eig.value(m, guess);
162+ out.push(Math.sqrt(lam) / (2 * Math.PI));
163+ guess = lam * 4;
164+ }
165+ return out;
166+}
167+
168+/**
169+ * All bending and torsion modes below fmax (Hz).
170+ * Returns [{ kind: 'B'|'T', idx, f, shape: Float64Array (nodal w (m/√kg) or twist (rad/√(kg·m²))) }]
171+ */
172+export function feModes(b, mat, { fmax = 24000, ne = NE } = {}) {
173+ const modes = [];
174+ for (const [kind, sys, stride] of [['B', bendingSystem(b, mat, ne), 2], ['T', torsionSystem(b, mat, ne), 1]]) {
175+ const lamMax = (2 * Math.PI * fmax) ** 2;
176+ const nFlex = sys.count(lamMax) - sys.nRigid;
177+ let guess = 0;
178+ for (let m = 1; m <= nFlex; m++) {
179+ const lam = sys.value(m, guess);
180+ guess = lam * 1.2;
181+ const v = sys.vector(lam);
182+ const shape = new Float64Array(ne + 1);
183+ for (let i = 0; i <= ne; i++) shape[i] = v[i * stride];
184+ // sign: positive at the left end
185+ if (shape[0] < 0) for (let i = 0; i <= ne; i++) shape[i] = -shape[i];
186+ modes.push({ kind, idx: m, f: Math.sqrt(lam) / (2 * Math.PI), shape });
187+ }
188+ }
189+ modes.sort((p, q) => p.f - q.f);
190+ return modes;
191+}
192+
193+// ---------- top-surface grid model, shared with the FDTD analysis ----------
194+
195+/**
196+ * Sample FE modes on a grid of cells over the top face. Vertical displacement per unit
197+ * modal coordinate: bending w(x); torsion θ(x)·(y - W/2).
198+ * Returns a bar model: { source, design, nx, ny, modes: [{ f, label, sigRad, phi }] }.
199+ */
200+export function feBarModel(b, mat, opts = {}) {
201+ const ne = opts.ne ?? NE;
202+ const fe = feModes(b, mat, { fmax: opts.fmax ?? 24000, ne });
203+ const nx = opts.nx ?? 120, ny = opts.ny ?? 8;
204+ const modes = fe.map((m) => {
205+ const phi = new Float32Array(nx * ny);
206+ for (let i = 0; i < nx; i++) {
207+ const u = ((i + 0.5) / nx) * ne, i0 = Math.min(ne - 1, Math.floor(u)), fu = u - i0;
208+ const s = m.shape[i0] * (1 - fu) + m.shape[i0 + 1] * fu;
209+ for (let j = 0; j < ny; j++) {
210+ const y = ((j + 0.5) / ny - 0.5) * b.W * 1e-3;
211+ phi[j * nx + i] = m.kind === 'B' ? s : s * y;
212+ }
213+ }
214+ return { f: m.f, label: `${m.kind}${m.idx}`, kind: m.kind, phi, sigRad: 0 };
215+ });
216+ const model = { source: 'FE', design: { ...b }, nx, ny, modes };
217+ for (const m of model.modes) m.sigRad = dipoleRadDecay(model, m);
218+ // the f1 nodal lines (where the support cords go)
219+ const s = fe.find((m) => m.kind === 'B')?.shape;
220+ model.nodes = [];
221+ if (s) for (let i = 0; i < ne; i++) if (s[i] * s[i + 1] < 0) model.nodes.push(((i + s[i] / (s[i] - s[i + 1])) / ne) * b.L);
222+ return model;
223+}
224+
225+// Cell geometry of a grid model (m).
226+export function cellGeom(model) {
227+ const b = model.design;
228+ const dx = (b.L * 1e-3) / model.nx, dy = (b.W * 1e-3) / model.ny;
229+ return { dx, dy, dA: dx * dy, x: (i) => (i + 0.5) * dx, y: (j) => (j + 0.5) * dy };
230+}
231+
232+// Effective dipole volume per unit top area (m): added mass of a strip of width W plus the
233+// bar's own volume. A bar slice moving with velocity v acts as a dipole of moment v·V.
234+export const dipoleDepth = (b) => ((Math.PI * b.W) / 4 + b.h0) * 1e-3;
235+
236+/**
237+ * Radiation decay rate (1/s, amplitude) of one mode, treating every top-face cell as a
238+ * vertical point dipole in free space. Power of a set of z-dipoles in a plane:
239+ * P = ρω⁴/(24πc³) ΣΣ DᵢDⱼ C(k rᵢⱼ), C(u) = 1.5 (j0(u) - j1(u)/u).
240+ */
241+export function dipoleRadDecay(model, m) {
242+ const b = model.design;
243+ const { dx, dy } = cellGeom(model);
244+ // coarse cells (about 40 x 4) for the double sum
245+ const sx = Math.max(1, Math.round(model.nx / 40)), sy = Math.max(1, Math.round(model.ny / 4));
246+ const V = dipoleDepth(b) * dx * dy;
247+ const pts = [];
248+ for (let i0 = 0; i0 < model.nx; i0 += sx) {
249+ for (let j0 = 0; j0 < model.ny; j0 += sy) {
250+ let D = 0, cx = 0, cy = 0, n = 0;
251+ for (let i = i0; i < Math.min(model.nx, i0 + sx); i++) {
252+ for (let j = j0; j < Math.min(model.ny, j0 + sy); j++) {
253+ D += m.phi[j * model.nx + i] * V; cx += (i + 0.5) * dx; cy += (j + 0.5) * dy; n++;
254+ }
255+ }
256+ pts.push([cx / n, cy / n, D]);
257+ }
258+ }
259+ const w = 2 * Math.PI * m.f, k = w / AIR.c;
260+ let S = 0;
261+ for (let p = 0; p < pts.length; p++) {
262+ for (let q = 0; q < pts.length; q++) {
263+ const u = k * Math.hypot(pts[p][0] - pts[q][0], pts[p][1] - pts[q][1]);
264+ let C = 1;
265+ if (u > 1e-4) {
266+ const j0 = Math.sin(u) / u, j1 = Math.sin(u) / (u * u) - Math.cos(u) / u;
267+ C = 1.5 * (j0 - j1 / u);
268+ }
269+ S += pts[p][2] * pts[q][2] * C;
270+ }
271+ }
272+ // energy of a unit-amplitude mass-normalized mode is ω²/2; σ = P / (2E)
273+ return (AIR.rho * w ** 4 * Math.max(0, S)) / (24 * Math.PI * AIR.c ** 3);
274+}
js/fft.jsadded+46−0View file
@@ -0,0 +1,46 @@
1+// Radix-2 FFT and a dB spectrum helper.
2+
3+// ---------- FFT (radix-2, in place) ----------
4+export function fft(re, im) {
5+ const n = re.length;
6+ for (let i = 1, j = 0; i < n; i++) {
7+ let bit = n >> 1;
8+ for (; j & bit; bit >>= 1) j ^= bit;
9+ j ^= bit;
10+ if (i < j) {
11+ [re[i], re[j]] = [re[j], re[i]];
12+ [im[i], im[j]] = [im[j], im[i]];
13+ }
14+ }
15+ for (let len = 2; len <= n; len <<= 1) {
16+ const ang = (-2 * Math.PI) / len;
17+ const wr = Math.cos(ang), wi = Math.sin(ang);
18+ for (let i = 0; i < n; i += len) {
19+ let cr = 1, ci = 0;
20+ for (let k = 0; k < len / 2; k++) {
21+ const a = i + k, b = a + len / 2;
22+ const tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;
23+ re[b] = re[a] - tr; im[b] = im[a] - ti;
24+ re[a] += tr; im[a] += ti;
25+ const t = cr * wr - ci * wi;
26+ ci = cr * wi + ci * wr;
27+ cr = t;
28+ }
29+ }
30+ }
31+}
32+
33+export const nextPow2 = (n) => 1 << Math.ceil(Math.log2(n));
34+export const hann = (n) => Float64Array.from({ length: n }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * (i + 0.5)) / n));
35+
36+// Magnitude spectrum in dB (Hann window), returns {df, db}.
37+export function spectrumDb(y, sr, nfft = 32768) {
38+ const n = Math.min(y.length, nfft);
39+ const re = new Float64Array(nfft), im = new Float64Array(nfft);
40+ const w = hann(n);
41+ for (let i = 0; i < n; i++) re[i] = y[i] * w[i];
42+ fft(re, im);
43+ const db = new Float32Array(nfft / 2);
44+ for (let k = 0; k < nfft / 2; k++) db[k] = 10 * Math.log10(re[k] * re[k] + im[k] * im[k] + 1e-30);
45+ return { df: sr / nfft, db };
46+}
js/physics.jsadded+51−0View file
@@ -0,0 +1,51 @@
1+// Damping law and the mallet model.
2+
3+// Internal damping: loss factor η(f) = η₀ (f / 1 kHz)^slope; amplitude decay σ = π f η.
4+export function internalDecay(f, eta, slope) {
5+ return Math.PI * f * eta * Math.pow(Math.max(f, 1) / 1000, slope);
6+}
7+
8+/**
9+ * Yarn-wound mallet: a soft yarn layer over a harder core.
10+ * F = K_y δ^P_YARN · (1 + λ δ̇) (yarn, Hunt–Crossley hysteresis)
11+ * + K_c (δ - 0.8 t)^1.5 · (1 + λ δ̇) when δ > 0.8 t (core reached through the yarn)
12+ * mallet = { yarn: t (mm), Ky: log10 K_y (SI), Kc: log10 K_c (SI), mass (g), v0 (m/s), lam (s/m) }
13+ */
14+export const P_YARN = 2.5;
15+
16+export const MALLETS = {
17+ soft: { yarn: 4, Ky: 9.4, Kc: 8.0, mass: 30, lam: 0.25 }, // ~2 ms contact at 1.5 m/s
18+ medium: { yarn: 2.5, Ky: 10.6, Kc: 8.6, mass: 30, lam: 0.2 }, // ~1 ms
19+ hard: { yarn: 0.6, Ky: 11.6, Kc: 9.5, mass: 28, lam: 0.12 }, // ~0.5 ms
20+ bass: { yarn: 6, Ky: 8.6, Kc: 7.6, mass: 45, lam: 0.25 }, // ~4 ms: large, heavy bass mallet
21+};
22+
23+// Graduated mallets, as players use: below C4 the mallet blends toward the bass mallet,
24+// reaching it at C2. Without this, a 1 ms contact on a low bar excites the 10× partial
25+// far more than the fundamental, and the note sounds two octaves and a third too high.
26+export const GRAD_TOP = 60, GRAD_BOTTOM = 36;
27+export function graduatedMallet(ml, note) {
28+ const s = Math.min(1, Math.max(0, (GRAD_TOP - note) / (GRAD_TOP - GRAD_BOTTOM)));
29+ if (s === 0) return { ...ml };
30+ const out = { ...ml };
31+ for (const k of ['yarn', 'Ky', 'Kc', 'mass', 'lam']) out[k] = ml[k] + s * (MALLETS.bass[k] - ml[k]);
32+ // only ever softer than the chosen mallet
33+ out.Ky = Math.min(out.Ky, ml.Ky); out.Kc = Math.min(out.Kc, ml.Kc); out.yarn = Math.max(out.yarn, ml.yarn);
34+ return out;
35+}
36+
37+export function malletForce(ml, delta, ddot) {
38+ if (delta <= 0) return 0;
39+ const t = ml.yarn * 1e-3 * 0.8;
40+ let F = 10 ** ml.Ky * Math.pow(delta, P_YARN);
41+ if (delta > t) F += 10 ** ml.Kc * Math.pow(delta - t, 1.5);
42+ return Math.max(0, F * (1 + ml.lam * ddot));
43+}
44+
45+// Rough contact duration against a rigid surface (s), to pick the simulation step.
46+export function contactTimeGuess(ml) {
47+ const m = ml.mass * 1e-3, v = Math.max(0.05, ml.v0);
48+ const K = 10 ** ml.Ky;
49+ const d = Math.pow(((P_YARN + 1) * m * v * v) / (2 * K), 1 / (P_YARN + 1));
50+ return Math.max(1e-4, (3 * Math.min(d, ml.yarn * 1e-3 + 1e-3)) / v);
51+}
js/plots.jsadded+105−0View file
@@ -0,0 +1,105 @@
1+// Small canvas plots: spectrum (log f, dB) and waveform overlay.
2+
3+function setup(canvas) {
4+ const dpr = window.devicePixelRatio || 1;
5+ const w = canvas.clientWidth, h = canvas.clientHeight;
6+ canvas.width = w * dpr; canvas.height = h * dpr;
7+ const g = canvas.getContext('2d');
8+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
9+ const cs = getComputedStyle(document.documentElement);
10+ const col = (n) => cs.getPropertyValue(n).trim();
11+ g.clearRect(0, 0, w, h);
12+ g.font = '11px system-ui, sans-serif';
13+ return { g, w, h, col };
14+}
15+
16+const SERIES = { modal: '--c-modal' };
17+
18+// series: [{name:'modal', df, db}], marks: frequencies (Hz), tri: frequencies drawn as ▲
19+export function drawSpectrum(canvas, series, marks = [], tri = []) {
20+ const { g, w, h, col } = setup(canvas);
21+ const L = 34, R = 8, T = 8, B = 20;
22+ const f0 = 40, f1 = 16000;
23+ const X = (f) => L + ((Math.log(f) - Math.log(f0)) / (Math.log(f1) - Math.log(f0))) * (w - L - R);
24+ let top = -Infinity;
25+ for (const s of series) for (let k = 1; k < s.db.length; k++) if (k * s.df > f0 && k * s.df < f1) top = Math.max(top, s.db[k]);
26+ if (!Number.isFinite(top)) top = 0;
27+ top = Math.ceil(top / 10) * 10;
28+ const range = 70;
29+ const Y = (d) => T + ((top - d) / range) * (h - T - B);
30+ g.strokeStyle = col('--grid'); g.fillStyle = col('--muted'); g.lineWidth = 1;
31+ for (const f of [50, 100, 200, 500, 1000, 2000, 5000, 10000]) {
32+ g.beginPath(); g.moveTo(X(f), T); g.lineTo(X(f), h - B); g.stroke();
33+ g.fillText(f >= 1000 ? f / 1000 + 'k' : String(f), X(f) - 8, h - 6);
34+ }
35+ for (let d = 0; d <= range; d += 20) {
36+ g.beginPath(); g.moveTo(L, Y(top - d)); g.lineTo(w - R, Y(top - d)); g.stroke();
37+ g.fillText(String(-d), 4, Y(top - d) + 4);
38+ }
39+ g.strokeStyle = col('--mark');
40+ for (const f of marks) { if (f > f0 && f < f1) { g.beginPath(); g.moveTo(X(f), h - B); g.lineTo(X(f), h - B - 6); g.stroke(); } }
41+ g.fillStyle = col('--tube');
42+ for (const f of tri) {
43+ if (f > f0 && f < f1) { g.beginPath(); g.moveTo(X(f), h - B - 9); g.lineTo(X(f) - 4, h - B); g.lineTo(X(f) + 4, h - B); g.fill(); }
44+ }
45+ for (const s of series) {
46+ g.strokeStyle = col(SERIES[s.name]); g.lineWidth = 1.4;
47+ g.beginPath();
48+ let first = true;
49+ for (let k = 1; k < s.db.length; k++) {
50+ const f = k * s.df;
51+ if (f < f0 || f > f1) continue;
52+ const x = X(f), y = Math.min(h - B, Math.max(T, Y(s.db[k])));
53+ if (first) { g.moveTo(x, y); first = false; } else g.lineTo(x, y);
54+ }
55+ g.stroke();
56+ }
57+ g.fillStyle = col('--muted');
58+ g.fillText('dB / Hz', w - 60, T + 10);
59+}
60+
61+// series: [{name, y, sr}] shown over the first `dur` seconds (null = the whole signal)
62+export function drawWave(canvas, series, dur = 0.25) {
63+ const { g, w, h, col } = setup(canvas);
64+ const L = 8, R = 8, T = 6, B = 18;
65+ if (dur == null) dur = Math.max(0.05, ...series.map((s) => s.y.length / s.sr));
66+ let amax = 1e-12;
67+ for (const s of series) for (let i = 0; i < Math.min(s.y.length, dur * s.sr); i++) amax = Math.max(amax, Math.abs(s.y[i]));
68+ g.strokeStyle = col('--grid');
69+ g.beginPath(); g.moveTo(L, (T + h - B) / 2); g.lineTo(w - R, (T + h - B) / 2); g.stroke();
70+ // time ticks: a 1-2-5 step giving about 4-8 labels; ms below half a second, s above
71+ const step = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2].find((v) => dur / v <= 8) ?? 5;
72+ const ms = dur <= 0.5;
73+ g.fillStyle = col('--muted');
74+ for (let t = 0; t <= dur + 1e-9; t += step) {
75+ const lab = ms ? (t * 1000).toFixed(0) : t.toFixed(step < 1 ? 1 : 0);
76+ const x = L + (t / dur) * (w - L - R) - 6;
77+ if (x < w - R - 26) g.fillText(lab, x, h - 5);
78+ }
79+ g.fillText(ms ? 'ms' : 's', w - 14, h - 5);
80+ const mid = (T + h - B) / 2, half = (h - T - B) / 2;
81+ for (const s of series) {
82+ g.strokeStyle = col(SERIES[s.name]); g.lineWidth = 1;
83+ g.beginPath();
84+ const n = Math.min(s.y.length, Math.floor(dur * s.sr));
85+ const px = w - L - R, perPx = (dur * s.sr) / px;
86+ if (perPx > 2) {
87+ // many samples per pixel: draw the min..max range of each column
88+ for (let c = 0; c < px; c++) {
89+ const i0 = Math.floor(c * perPx), i1 = Math.min(n, Math.floor((c + 1) * perPx));
90+ if (i0 >= n) break;
91+ let lo = Infinity, hi = -Infinity;
92+ for (let i = i0; i < Math.max(i1, i0 + 1); i++) { lo = Math.min(lo, s.y[i]); hi = Math.max(hi, s.y[i]); }
93+ g.moveTo(L + c + 0.5, mid - (hi / amax) * half);
94+ g.lineTo(L + c + 0.5, mid - (lo / amax) * half + 0.5);
95+ }
96+ } else {
97+ for (let i = 0; i < n; i++) {
98+ const x = L + (i / (dur * s.sr)) * px;
99+ const y = mid - (s.y[i] / amax) * half;
100+ i ? g.lineTo(x, y) : g.moveTo(x, y);
101+ }
102+ }
103+ g.stroke();
104+ }
105+}
js/sf2.jsadded+150−0View file
@@ -0,0 +1,150 @@
1+// Minimal SoundFont 2.01 writer: one preset -> one instrument -> many sample zones.
2+
3+const enc = new TextEncoder();
4+
5+function str(s, len) { // fixed-length, zero-padded ASCII
6+ const b = new Uint8Array(len);
7+ b.set(enc.encode(s.replace(/[^\x20-\x7e]/g, '_')).slice(0, len - 1));
8+ return b;
9+}
10+function zstr(s) { // zero-terminated, even length
11+ const t = enc.encode(s.replace(/[^\x20-\x7e]/g, '_'));
12+ const b = new Uint8Array(t.length + 1 + ((t.length + 1) % 2));
13+ b.set(t);
14+ return b;
15+}
16+function concat(parts) {
17+ const n = parts.reduce((a, p) => a + p.length, 0);
18+ const out = new Uint8Array(n);
19+ let o = 0;
20+ for (const p of parts) { out.set(p, o); o += p.length; }
21+ return out;
22+}
23+function chunk(id, data) {
24+ const h = new Uint8Array(8);
25+ h.set(enc.encode(id));
26+ new DataView(h.buffer).setUint32(4, data.length, true);
27+ return concat(data.length % 2 ? [h, data, new Uint8Array(1)] : [h, data]);
28+}
29+function list(type, chunks) { return chunk('LIST', concat([enc.encode(type), ...chunks])); }
30+
31+// Fixed-size record builder
32+function records(size, items, fill) {
33+ const b = new Uint8Array(size * items.length);
34+ const dv = new DataView(b.buffer);
35+ items.forEach((it, i) => fill(dv, i * size, it, b));
36+ return b;
37+}
38+
39+export const GEN = { releaseVolEnv: 38, instrument: 41, keyRange: 43, velRange: 44, sampleModes: 54, sampleID: 53, overridingRootKey: 58 };
40+
41+/**
42+ * opts: {
43+ * name, bank, program, sampleRate,
44+ * samples: [{ name, data: Int16Array, root, correction? }],
45+ * zones: [{ keyLo, keyHi, velLo, velHi, sample }],
46+ * releaseSec, disableVelocityAttenuation
47+ * }
48+ */
49+export function buildSF2(opts) {
50+ const { name, samples, zones } = opts;
51+ const PAD = 46;
52+
53+ // ---- sdta ----
54+ const total = samples.reduce((a, s) => a + s.data.length + PAD, 0);
55+ const smpl = new Int16Array(total);
56+ const offsets = [];
57+ let o = 0;
58+ for (const s of samples) {
59+ offsets.push(o);
60+ smpl.set(s.data, o);
61+ o += s.data.length + PAD;
62+ }
63+ const sdta = list('sdta', [chunk('smpl', new Uint8Array(smpl.buffer))]);
64+
65+ // ---- INFO ----
66+ const ifil = new Uint8Array(4);
67+ new DataView(ifil.buffer).setUint16(0, 2, true);
68+ new DataView(ifil.buffer).setUint16(2, 1, true);
69+ const info = list('INFO', [
70+ chunk('ifil', ifil), chunk('isng', zstr('EMU8000')), chunk('INAM', zstr(name)), chunk('ISFT', zstr('Marimba Lab')),
71+ ]);
72+
73+ // ---- pdta ----
74+ // instrument zones: global zone (release + velocity modulator override), then sample zones
75+ const igen = [], ibag = [], imod = [];
76+ ibag.push([igen.length, imod.length]);
77+ igen.push([GEN.releaseVolEnv, Math.round(1200 * Math.log2(opts.releaseSec ?? 2)), 's']);
78+ if (opts.disableVelocityAttenuation) {
79+ // same source/dest as the default "velocity -> initial attenuation" modulator, amount 0
80+ imod.push([0x0502, 48, 0, 0, 0]);
81+ }
82+ for (const z of zones) {
83+ ibag.push([igen.length, imod.length]);
84+ igen.push([GEN.keyRange, [z.keyLo, z.keyHi], 'r']);
85+ igen.push([GEN.velRange, [z.velLo, z.velHi], 'r']);
86+ igen.push([GEN.sampleModes, 0, 'u']);
87+ igen.push([GEN.sampleID, z.sample, 'u']);
88+ }
89+ const nIbag = ibag.length;
90+ ibag.push([igen.length, imod.length]); // terminal
91+ igen.push([0, 0, 'u']);
92+ imod.push([0, 0, 0, 0, 0]);
93+
94+ const genRec = (dv, off, [op, amt, kind]) => {
95+ dv.setUint16(off, op, true);
96+ if (kind === 'r') { dv.setUint8(off + 2, amt[0]); dv.setUint8(off + 3, amt[1]); }
97+ else if (kind === 's') dv.setInt16(off + 2, amt, true);
98+ else dv.setUint16(off + 2, amt, true);
99+ };
100+ const bagRec = (dv, off, [g, m]) => { dv.setUint16(off, g, true); dv.setUint16(off + 2, m, true); };
101+ const modRec = (dv, off, [src, dst, amt, asrc, tr]) => {
102+ dv.setUint16(off, src, true); dv.setUint16(off + 2, dst, true); dv.setInt16(off + 4, amt, true);
103+ dv.setUint16(off + 6, asrc, true); dv.setUint16(off + 8, tr, true);
104+ };
105+
106+ const inst = records(22, [[name, 0], ['EOI', nIbag]], (dv, off, [n, bag], b) => {
107+ b.set(str(n, 20), off); dv.setUint16(off + 20, bag, true);
108+ });
109+
110+ // preset: one zone pointing at instrument 0
111+ const pgen = [[GEN.instrument, 0, 'u'], [0, 0, 'u']];
112+ const pbag = [[0, 0], [1, 0]];
113+ const pmod = [[0, 0, 0, 0, 0]];
114+ const phdr = records(38, [[name, opts.program ?? 0, opts.bank ?? 0, 0], ['EOP', 0, 0, 1]], (dv, off, [n, prog, bank, bag], b) => {
115+ b.set(str(n, 20), off);
116+ dv.setUint16(off + 20, prog, true); dv.setUint16(off + 22, bank, true); dv.setUint16(off + 24, bag, true);
117+ });
118+
119+ const sr = opts.sampleRate;
120+ const shdrItems = samples.map((s, i) => ({ ...s, start: offsets[i], end: offsets[i] + s.data.length }));
121+ shdrItems.push({ name: 'EOS', start: 0, end: 0, root: 0, terminal: true });
122+ const shdr = records(46, shdrItems, (dv, off, s, b) => {
123+ b.set(str(s.name, 20), off);
124+ dv.setUint32(off + 20, s.start, true);
125+ dv.setUint32(off + 24, s.end, true);
126+ const ls = s.terminal ? 0 : Math.min(s.start + 8, s.end);
127+ const le = s.terminal ? 0 : Math.max(ls, s.end - 8);
128+ dv.setUint32(off + 28, ls, true);
129+ dv.setUint32(off + 32, le, true);
130+ dv.setUint32(off + 36, s.terminal ? 0 : sr, true);
131+ dv.setUint8(off + 40, s.root);
132+ dv.setInt8(off + 41, s.correction ?? 0);
133+ dv.setUint16(off + 42, 0, true);
134+ dv.setUint16(off + 44, s.terminal ? 0 : 1, true); // 1 = mono sample
135+ });
136+
137+ const pdta = list('pdta', [
138+ chunk('phdr', phdr),
139+ chunk('pbag', records(4, pbag, bagRec)),
140+ chunk('pmod', records(10, pmod, modRec)),
141+ chunk('pgen', records(4, pgen, genRec)),
142+ chunk('inst', inst),
143+ chunk('ibag', records(4, ibag, bagRec)),
144+ chunk('imod', records(10, imod, modRec)),
145+ chunk('igen', records(4, igen, genRec)),
146+ chunk('shdr', shdr),
147+ ]);
148+
149+ return chunk('RIFF', concat([enc.encode('sfbk'), info, sdta, pdta]));
150+}
js/synth.jsadded+352−0View file
@@ -0,0 +1,352 @@
1+// Sound of a mallet strike: bar modes coupled to the resonator tube, radiated to the mic.
2+//
3+// Bar: mass-normalized modes φₙ (vertical displacement on the top face), so a downward force
4+// F at P drives q̈ₙ + 2σₙq̇ₙ + ωₙ²qₙ = φₙ(P)·F (+ the gap pressure, below).
5+// Tube: closed at the bottom; seen from its mouth it has input impedance
6+// Z_t = Z₀ coth(Γ L_t), Γ = s/c + β√s (wall losses ∝ √f).
7+// The bar's underside pushes volume flow U = -s Σ aₙ q̇ₙ... into the gap over the mouth
8+// (aₙ = ∫ φₙ over the mouth). That flow either enters the tube (Z_t) or escapes around the
9+// rim (Z_e = s M + radiation resistance), so the gap pressure is p_m = Z_t‖Z_e · U and it
10+// pushes back on the bar with generalized force aₙ p_m. The coupling is rank one, so the
11+// coupled response is solved in closed form at each frequency (Sherman–Morrison).
12+// Mic: each top-face cell is a vertical dipole of moment v·V (bar volume + added mass), and
13+// the flow swallowed by the tube removes a monopole at the mouth.
14+// Time signal: contact force from a Hertz-type mallet simulation against the bar modes,
15+// then multiplication by the transfer function and an inverse FFT, with an exponential
16+// window (evaluate at s = γ + iω) so long ringing does not wrap around.
17+// The FFT window is TAIL seconds longer than the output and the force spectrum is sampled
18+// every 2 Hz: interpolating it makes faint copies of the strike every 1/df seconds, and the
19+// copy at negative time would otherwise wrap to the end of the output, where the
20+// exponential window amplifies it enormously (heard as a rattle at the end of some notes).
21+
22+import { AIR, tubeGeom, tubeLength, micPos, noteFreq } from './bar.js';
23+import { cellGeom, dipoleDepth } from './fe.js';
24+import { internalDecay, malletForce, contactTimeGuess } from './physics.js';
25+import { fft, nextPow2 } from './fft.js';
26+
27+/**
28+ * opts: { note, eta, slope, res: { on, diam, gap, detune, loss } }
29+ */
30+export function prepare(model, opts) {
31+ const b = model.design;
32+ const { nx, ny } = model;
33+ const { dx, dy, dA } = cellGeom(model);
34+ const mic = micPos(b).map((v) => v * 1e-3);
35+ const zTop = b.h0 * 1e-3;
36+ const r0 = Math.hypot(mic[0] - (b.L / 2) * 1e-3, mic[1] - (b.W / 2) * 1e-3, mic[2] - zTop);
37+ const tg = tubeGeom(b, opts.res);
38+ const at = tg.a * 1e-3;
39+
40+ // fraction of each cell over the tube mouth (3 x 3 subsamples)
41+ const cover = new Float32Array(nx * ny);
42+ for (let j = 0; j < ny; j++) {
43+ for (let i = 0; i < nx; i++) {
44+ let c = 0;
45+ for (let u = 0; u < 3; u++) for (let v = 0; v < 3; v++) {
46+ const x = (i + (u + 0.5) / 3) * dx - tg.x * 1e-3, y = (j + (v + 0.5) / 3) * dy - tg.y * 1e-3;
47+ if (x * x + y * y < at * at) c++;
48+ }
49+ cover[j * nx + i] = c / 9;
50+ }
51+ }
52+ // per-cell geometry toward the mic
53+ const geo = [];
54+ for (let j = 0; j < ny; j++) {
55+ for (let i = 0; i < nx; i++) {
56+ const ex = mic[0] - (i + 0.5) * dx, ey = mic[1] - (j + 0.5) * dy, ez = mic[2] - zTop;
57+ const r = Math.hypot(ex, ey, ez);
58+ geo.push({ r, cos: ez / r });
59+ }
60+ }
61+ const V = dipoleDepth(b) * dA;
62+ const c = AIR.c, rho = AIR.rho;
63+ const modes = model.modes.map((m) => {
64+ const w = 2 * Math.PI * m.f;
65+ const sig = m.sigRad + internalDecay(m.f, opts.eta, opts.slope);
66+ let a = 0, Br = 0, Bi = 0;
67+ for (let q = 0; q < nx * ny; q++) {
68+ const ph = m.phi[q];
69+ a += ph * cover[q] * dA;
70+ // ρ s cosθ (1/r² + s/(c r)) e^{-s (r - r0)/c} / 4π at s = iω, per unit q̇
71+ const { r, cos } = geo[q];
72+ const k = (ph * V * rho * cos) / (4 * Math.PI);
73+ const tr = -(w * w) / (c * r), ti = w / (r * r);
74+ const ang = (-w * (r - r0)) / c, cr = Math.cos(ang), ci = Math.sin(ang);
75+ Br += k * (tr * cr - ti * ci);
76+ Bi += k * (tr * ci + ti * cr);
77+ }
78+ // Causal form for synthesis: |B| e^{-sτ}, with 0 ≤ τ < one period chosen so it matches B at
79+ // s = iω. (A constant complex B at all frequencies is non-causal and leaks before t = 0.)
80+ const Bmag = Math.hypot(Br, Bi);
81+ let ph = -Math.atan2(Bi, Br);
82+ if (ph < 0) ph += 2 * Math.PI;
83+ return { f: m.f, w, sig, a, Br, Bi, Bmag, Btau: ph / w, phi: m.phi, label: m.label };
84+ });
85+
86+ let tube = null;
87+ if (opts.res.on) {
88+ const fT = noteFreq(opts.note) * 2 ** ((opts.res.detune || 0) / 1200);
89+ const Lt = tubeLength(fT, tg.delta) * 1e-3;
90+ const S = Math.PI * at * at;
91+ const mouth = [tg.x * 1e-3, tg.y * 1e-3, tg.zTop * 1e-3];
92+ tube = {
93+ L: Lt, S, a: at, fT, delta: tg.delta * 1e-3,
94+ Z0: (rho * c) / S,
95+ // escape path: inertance of the end correction, minus the part the radiation
96+ // impedance below already carries (ρ/4πa)
97+ M: (rho * (tg.delta * 1e-3 - at / 4)) / S,
98+ // passive radiation impedance of a small monopole of radius a:
99+ // (ρc/4πa²)·(sa/c)/(1 + sa/c) ≈ sρ/4πa + ρω²/4πc at low ka
100+ Rr: (rho * c) / (4 * Math.PI * at * at), ta: at / c,
101+ beta: ((opts.res.loss ?? 1) * 3e-5) / (Math.sqrt(Math.PI) * at),
102+ rt: Math.hypot(mic[0] - mouth[0], mic[1] - mouth[1], mic[2] - mouth[2]),
103+ };
104+ }
105+ return { model, modes, tube, r0, nx, ny, dx, dy };
106+}
107+
108+// Bilinear interpolation of every mode's φ at a top-face point (mm).
109+export function phiAt(prep, sx, sy) {
110+ const { nx, ny, dx, dy } = prep;
111+ const u = Math.min(nx - 1.0001, Math.max(0, (sx * 1e-3) / dx - 0.5));
112+ const v = Math.min(ny - 1.0001, Math.max(0, (sy * 1e-3) / dy - 0.5));
113+ const i0 = Math.floor(u), j0 = Math.floor(v), fu = u - i0, fv = v - j0;
114+ const i1 = Math.min(nx - 1, i0 + 1), j1 = Math.min(ny - 1, j0 + 1);
115+ return prep.modes.map((m) =>
116+ m.phi[j0 * nx + i0] * (1 - fu) * (1 - fv) + m.phi[j0 * nx + i1] * fu * (1 - fv) +
117+ m.phi[j1 * nx + i0] * (1 - fu) * fv + m.phi[j1 * nx + i1] * fu * fv);
118+}
119+
120+/**
121+ * Mallet against the bar modes (tube ignored over the few ms of contact).
122+ * Returns { F (N, downward on the bar), h (s) }.
123+ */
124+export function simulateContact(modes, phiP, ml, hStep = 0) {
125+ const T0 = contactTimeGuess(ml);
126+ const h = hStep || T0 / 300;
127+ const nMax = Math.ceil(Math.max(0.02, 10 * T0) / h);
128+ const M = modes.length;
129+ const Er = new Float64Array(M), Ei = new Float64Array(M), Gr = new Float64Array(M), Gi = new Float64Array(M);
130+ const Pr = new Float64Array(M), Pi = new Float64Array(M), ph = new Float64Array(M);
131+ const zr = new Float64Array(M), zi = new Float64Array(M);
132+ for (let n = 0; n < M; n++) {
133+ const { w, sig } = modes[n];
134+ const wd = Math.sqrt(Math.max(1e-6, w * w - sig * sig));
135+ const pr = -sig, pi = wd; // pole
136+ const e = Math.exp(pr * h);
137+ Er[n] = e * Math.cos(pi * h); Ei[n] = e * Math.sin(pi * h);
138+ // G = r (E - 1)/p, r = 1 + iσ/ω_d
139+ const nr = Er[n] - 1, ni = Ei[n], d = pr * pr + pi * pi;
140+ const qr = (nr * pr + ni * pi) / d, qi = (ni * pr - nr * pi) / d;
141+ const rr = 1, ri = sig / wd;
142+ Gr[n] = qr * rr - qi * ri; Gi[n] = qr * ri + qi * rr;
143+ Pr[n] = pr / d; Pi[n] = -pi / d; // 1/p
144+ ph[n] = phiP[n];
145+ }
146+ const m = ml.mass * 1e-3;
147+ let xm = 0, vm = ml.v0, wb = 0, vb = 0, apart = 0;
148+ const F = [];
149+ for (let k = 0; k < nMax; k++) {
150+ const f = malletForce(ml, xm - wb, vm - vb);
151+ F.push(f);
152+ wb = 0; vb = 0;
153+ for (let n = 0; n < M; n++) {
154+ const g = ph[n] * f;
155+ const a = Er[n] * zr[n] - Ei[n] * zi[n] + Gr[n] * g;
156+ zi[n] = Er[n] * zi[n] + Ei[n] * zr[n] + Gi[n] * g;
157+ zr[n] = a;
158+ vb += ph[n] * zr[n];
159+ wb += ph[n] * (zr[n] * Pr[n] - zi[n] * Pi[n]);
160+ }
161+ vm -= (f * h) / m;
162+ xm += vm * h;
163+ apart = f > 0 ? 0 : apart + 1;
164+ if (k > 20 && apart * h > 3e-4 && vm < vb) break;
165+ }
166+ return { F: Float64Array.from(F), h };
167+}
168+
169+/**
170+ * X_k = Σ_n F_n h e^{-s_k t_n}, s_k = γ + i k Δω, t_n = (n + ½) h, for k = 0..K-1 (Δω = 2π/(Mh·h)), by the
171+ * chirp-z transform (Bluestein): nk = (n² + k² - (k-n)²)/2 turns the sum into a convolution.
172+ * Exact, unlike interpolating a coarse spectrum, whose errors become ghost strikes that the
173+ * exponential window amplifies.
174+ */
175+function forceSpectrum(F, h, gam, Mh, K) {
176+ // Δω = 2π/T and h = T/Mh, so α = Δω·h = 2π/Mh and α m²/2 = π (m² mod 2Mh)/Mh exactly
177+ const nF = F.length, dw = (2 * Math.PI) / (Mh * h);
178+ const L = nextPow2(nF + K);
179+ const ar = new Float64Array(L), ai = new Float64Array(L), br = new Float64Array(L), bi = new Float64Array(L);
180+ const chirp = (m) => (Math.PI * ((m * m) % (2 * Mh))) / Mh;
181+ for (let n = 0; n < nF; n++) {
182+ const x = F[n] * h * Math.exp(-gam * (n + 0.5) * h), c = chirp(n);
183+ ar[n] = x * Math.cos(c); ai[n] = -x * Math.sin(c);
184+ }
185+ for (let m = 0; m < K; m++) { const c = chirp(m); br[m] = Math.cos(c); bi[m] = Math.sin(c); }
186+ for (let m = 1; m < nF; m++) { const c = chirp(m); br[L - m] = Math.cos(c); bi[L - m] = Math.sin(c); }
187+ fft(ar, ai); fft(br, bi);
188+ // product, then inverse FFT via conjugation
189+ for (let j = 0; j < L; j++) {
190+ const r = ar[j] * br[j] - ai[j] * bi[j], i = ar[j] * bi[j] + ai[j] * br[j];
191+ ar[j] = r; ai[j] = -i;
192+ }
193+ fft(ar, ai);
194+ const Xr = new Float64Array(K), Xi = new Float64Array(K);
195+ for (let k = 0; k < K; k++) {
196+ const cr = ar[k] / L, ci = -ai[k] / L;
197+ const ph = -chirp(k) - (k * dw * h) / 2; // e^{-iα k²/2} and the half-step offset
198+ const er = Math.cos(ph), ei = Math.sin(ph);
199+ Xr[k] = cr * er - ci * ei; Xi[k] = cr * ei + ci * er;
200+ }
201+ return [Xr, Xi];
202+}
203+
204+// complex helpers on [re, im] pairs (kept inline in the hot loop below)
205+function cdiv(ar, ai, br, bi) { const d = br * br + bi * bi; return [(ar * br + ai * bi) / d, (ai * br - ar * bi) / d]; }
206+function csqrt(r, i) {
207+ const m = Math.hypot(r, i);
208+ const sr = Math.sqrt((m + r) / 2), si = Math.sign(i || 1) * Math.sqrt(Math.max(0, (m - r) / 2));
209+ return [sr, si];
210+}
211+function ccoth(r, i) {
212+ // coth(z) = (sinh 2x - i sin 2y) / (cosh 2x - cos 2y)
213+ const den = Math.cosh(2 * r) - Math.cos(2 * i);
214+ return [Math.sinh(2 * r) / den, -Math.sin(2 * i) / den];
215+}
216+
217+/**
218+ * Mic pressure (Pa) for a strike at (sx, sy) mm.
219+ * ml: mallet (see physics.js) with v0; returns { y: Float32Array, sr, F, h, T, Fm, dur }.
220+ */
221+export function strike(prep, sx, sy, ml, sr, maxDur = 4) {
222+ const phiAll = phiAt(prep, sx, sy);
223+
224+ // modes below Nyquist take part in the sound
225+ const idx = [];
226+ prep.modes.forEach((m, n) => { if (m.f < 0.48 * sr) idx.push(n); });
227+ const M = idx.length;
228+ const w2 = new Float64Array(M), s2 = new Float64Array(M), aC = new Float64Array(M), phi = new Float64Array(M);
229+ const Bm = new Float64Array(M), Bt = new Float64Array(M);
230+ let sigMin = Infinity;
231+ idx.forEach((n, q) => {
232+ const m = prep.modes[n];
233+ w2[q] = m.w * m.w; s2[q] = 2 * m.sig; aC[q] = m.a; phi[q] = phiAll[n]; Bm[q] = m.Bmag; Bt[q] = m.Btau;
234+ if (Math.abs(phi[q]) > 1e-9 || (prep.tube && Math.abs(m.a) > 1e-12)) sigMin = Math.min(sigMin, m.sig);
235+ });
236+ if (prep.tube) {
237+ // the tube's own (wall-loss) decay can be slower than the bar's
238+ const t = prep.tube, w = 2 * Math.PI * t.fT;
239+ sigMin = Math.min(sigMin, t.beta * Math.sqrt(w / 2) * AIR.c);
240+ }
241+ const dur = Math.min(maxDur, Math.max(0.4, 7 / (Number.isFinite(sigMin) ? sigMin : 10)));
242+ // Exponential window: the part of the ring beyond T wraps to the start, scaled by
243+ // e^{-σT}·e^{-γ(T - t)}. Keep that 120 dB down at the end of the output even when the
244+ // output is cut while the note still rings (the maxDur cap, light damping). γ is capped
245+ // so e^{γ·dur} cannot blow up rounding errors; if the cap binds, the window grows instead.
246+ // The window is also at least TAIL longer than the output, so nothing from just before
247+ // t = 0 can wrap into it.
248+ const TAIL = 0.6, GMAX = 16 / dur, NEED = Math.log(1e6);
249+ const sMin = Number.isFinite(sigMin) ? sigMin : 10;
250+ let N = nextPow2(Math.ceil((dur + TAIL) * sr));
251+ while (N < 1 << 22 && sMin * (N / sr) + GMAX * (N / sr - dur) < NEED) N *= 2;
252+ const T = N / sr;
253+ const gam = Math.min(GMAX, Math.max(Math.log(1e4) / T, (NEED - sMin * T) / (T - dur)));
254+ // per-mode delay phasors e^{-sτ}: e^{-γτ} fixed, e^{-iωτ} rotated bin by bin
255+ const bpR = new Float64Array(M), bpI = new Float64Array(M), brR = new Float64Array(M), brI = new Float64Array(M);
256+ for (let q = 0; q < M; q++) {
257+ bpR[q] = Bm[q] * Math.exp(-gam * Bt[q]); bpI[q] = 0;
258+ const a = (-2 * Math.PI * Bt[q]) / T;
259+ brR[q] = Math.cos(a); brI[q] = Math.sin(a);
260+ }
261+
262+ // force spectrum at s = γ + iω_k on every bin, exactly (chirp-z / Bluestein)
263+ // contact step h = T / Mh with Mh an integer, so the chirp phases reduce exactly
264+ const Mh = Math.max(1, Math.round(T / (contactTimeGuess(ml) / 300)));
265+ const { F, h } = simulateContact(prep.modes, phiAll, ml, T / Mh);
266+ let Fm = 0, nC = 0;
267+ for (const f of F) { Fm = Math.max(Fm, f); if (f > 0) nC++; }
268+ const [Fcr, Fci] = forceSpectrum(F, h, gam, Mh, N / 2 + 1);
269+
270+ const tube = prep.tube;
271+ const c = AIR.c, rho = AIR.rho;
272+ const re = new Float64Array(N), im = new Float64Array(N);
273+ const Dr = new Float64Array(M), Di = new Float64Array(M);
274+ for (let k = 0; k <= N / 2; k++) {
275+ const w = (2 * Math.PI * k) / T;
276+ const sR = gam, sI = w;
277+ const ssR = sR * sR - sI * sI, ssI = 2 * sR * sI;
278+ // bar modes
279+ let gR = 0, gI = 0, hR = 0, hI = 0;
280+ for (let q = 0; q < M; q++) {
281+ const dR = ssR + s2[q] * sR + w2[q], dI = ssI + s2[q] * sI;
282+ const dd = dR * dR + dI * dI;
283+ const r = dR / dd, i = -dI / dd;
284+ Dr[q] = r; Di[q] = i;
285+ const ta = aC[q];
286+ gR += ta * phi[q] * r; gI += ta * phi[q] * i;
287+ hR += ta * ta * r; hI += ta * ta * i;
288+ }
289+ // gap pressure per unit force, and the tube's swallowed flow
290+ let PmR = 0, PmI = 0, UtR = 0, UtI = 0;
291+ if (tube) {
292+ const [qR, qI] = csqrt(sR, sI);
293+ const GR = sR / c + tube.beta * qR, GI = sI / c + tube.beta * qI;
294+ const [cR, cI] = ccoth(GR * tube.L, GI * tube.L);
295+ const ZtR = tube.Z0 * cR, ZtI = tube.Z0 * cI;
296+ const [radR, radI] = cdiv(tube.Rr * tube.ta * sR, tube.Rr * tube.ta * sI, 1 + tube.ta * sR, tube.ta * sI);
297+ const ZeR = tube.M * sR + radR, ZeI = tube.M * sI + radI;
298+ const nR = ZtR * ZeR - ZtI * ZeI, nI = ZtR * ZeI + ZtI * ZeR;
299+ const [ZpR, ZpI] = cdiv(nR, nI, ZtR + ZeR, ZtI + ZeI);
300+ const sZR = sR * ZpR - sI * ZpI, sZI = sR * ZpI + sI * ZpR; // s Z_par
301+ const numR = -(sZR * gR - sZI * gI), numI = -(sZR * gI + sZI * gR);
302+ const denR = 1 + sZR * hR - sZI * hI, denI = sZR * hI + sZI * hR;
303+ [PmR, PmI] = cdiv(numR, numI, denR, denI);
304+ [UtR, UtI] = cdiv(PmR, PmI, ZtR, ZtI); // into the tube
305+ }
306+ // bar dipole radiation: Σ s qₙ Bₙ
307+ let aR = 0, aI = 0;
308+ for (let q = 0; q < M; q++) {
309+ const fR = phi[q] + aC[q] * PmR, fI = aC[q] * PmI;
310+ const qR = Dr[q] * fR - Di[q] * fI, qI = Dr[q] * fI + Di[q] * fR;
311+ aR += qR * bpR[q] - qI * bpI[q];
312+ aI += qR * bpI[q] + qI * bpR[q];
313+ const t = bpR[q] * brR[q] - bpI[q] * brI[q];
314+ bpI[q] = bpR[q] * brI[q] + bpI[q] * brR[q];
315+ bpR[q] = t;
316+ }
317+ // times s, times e^{-s r0/c}
318+ let pR = sR * aR - sI * aI, pI = sR * aI + sI * aR;
319+ {
320+ const e = Math.exp((-sR * prep.r0) / c), ang = (-sI * prep.r0) / c;
321+ const cR = e * Math.cos(ang), cI = e * Math.sin(ang);
322+ [pR, pI] = [pR * cR - pI * cI, pR * cI + pI * cR];
323+ }
324+ if (tube) {
325+ // monopole -U_t at the mouth: ρ s (-U_t) e^{-s r/c} / (4π r)
326+ const e = Math.exp((-sR * tube.rt) / c) / (4 * Math.PI * tube.rt), ang = (-sI * tube.rt) / c;
327+ const cR = e * Math.cos(ang), cI = e * Math.sin(ang);
328+ const uR = -rho * (sR * UtR - sI * UtI), uI = -rho * (sR * UtI + sI * UtR);
329+ pR += uR * cR - uI * cI;
330+ pI += uR * cI + uI * cR;
331+ }
332+ // force on the bar is downward, φ is up
333+ const FR = -Fcr[k], FI = -Fci[k];
334+ // smooth roll-off to zero at Nyquist: a hard cut there smears in time and the
335+ // exponential window would amplify the smear near the end of the output
336+ const fr = k / N, tap = fr < 0.44 ? 1 : Math.cos(((fr - 0.44) / 0.06) * (Math.PI / 2)) ** 2;
337+ const YR = tap * (FR * pR - FI * pI), YI = tap * (FR * pI + FI * pR);
338+ // inverse transform via a forward FFT of the conjugate
339+ re[k] = YR; im[k] = -YI;
340+ if (k > 0 && k < N / 2) { re[N - k] = YR; im[N - k] = YI; }
341+ if (k === N / 2) im[k] = 0;
342+ }
343+ fft(re, im);
344+ const nOut = Math.min(N, Math.ceil(dur * sr));
345+ const y = new Float32Array(nOut);
346+ for (let n = 0; n < nOut; n++) y[n] = (re[n] / T) * Math.exp((gam * n) / sr);
347+ // fade out: short if the note has died away, longer if maxDur cut it while still ringing
348+ const cut = 7 / (Number.isFinite(sigMin) ? sigMin : 10) > dur + 1e-9;
349+ const fade = Math.min(nOut, Math.round((cut ? 0.5 : 0.02) * sr));
350+ for (let n = 0; n < fade; n++) y[nOut - 1 - n] *= 0.5 - 0.5 * Math.cos((Math.PI * n) / fade);
351+ return { y, sr, F, h, T: nC * h, Fm, dur };
352+}
js/tune.jsadded+121−0View file
@@ -0,0 +1,121 @@
1+// Undercut tuner: adjusts bar length L, undercut depth d and undercut length a so the first
2+// three bending partials land on f1 = note, f2 = r2·f1, f3 = r3·f1. Partials whose target
3+// lies above the cutoff are left free (as makers do on the top bars); a tiny pull toward
4+// the nominal arch then keeps the problem well posed. Levenberg–Marquardt on log errors.
5+
6+import { bendFreqs } from './fe.js';
7+import { maxDepth, noteFreq, nominalDesign } from './bar.js';
8+
9+export const DEFAULT_TARGETS = { r2: 4, r3: 10, fCut: 9000 };
10+
11+const A_LO = 0.2, A_HI = 0.95;
12+const logit = (u) => Math.log(u / (1 - u));
13+const sigm = (t) => 1 / (1 + Math.exp(-t));
14+const clampU = (u) => Math.min(1 - 1e-6, Math.max(1e-6, u));
15+
16+function toParams(b) {
17+ return [Math.log(b.L), logit(clampU(b.d / maxDepth(b))), logit(clampU((b.a - A_LO) / (A_HI - A_LO)))];
18+}
19+function fromParams(base, t) {
20+ const b = { ...base, L: Math.exp(t[0]) };
21+ b.d = sigm(t[1]) * maxDepth(b);
22+ b.a = A_LO + (A_HI - A_LO) * sigm(t[2]);
23+ return b;
24+}
25+
26+export function partialTargets(note, targets) {
27+ const f1 = noteFreq(note);
28+ return { f: [f1, f1 * targets.r2, f1 * targets.r3], on: [true, f1 * targets.r2 <= targets.fCut, f1 * targets.r3 <= targets.fCut] };
29+}
30+
31+// cents error of each partial against its target
32+export function partialErrors(f, note, targets) {
33+ const t = partialTargets(note, targets);
34+ return f.map((fi, i) => ({ f: fi, target: t.f[i], on: t.on[i], cents: 1200 * Math.log2(fi / t.f[i]) }));
35+}
36+
37+function residuals(t, base, mat, tg, nominal, ne) {
38+ const b = fromParams(base, t);
39+ const f = bendFreqs(b, mat, 3, ne);
40+ const r = [Math.log(f[0] / tg.f[0])];
41+ r.push(tg.on[1] ? Math.log(f[1] / tg.f[1]) : 0);
42+ r.push(tg.on[2] ? Math.log(f[2] / tg.f[2]) : 0);
43+ const w = 3e-3;
44+ r.push(w * (t[1] - nominal[1]), w * (t[2] - nominal[2]));
45+ return r;
46+}
47+
48+function solve3(A, g) {
49+ const M = A.map((row, i) => [...row, g[i]]);
50+ for (let c = 0; c < 3; c++) {
51+ let p = c;
52+ for (let r = c + 1; r < 3; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
53+ [M[c], M[p]] = [M[p], M[c]];
54+ for (let r = c + 1; r < 3; r++) {
55+ const f = M[r][c] / M[c][c];
56+ for (let k = c; k < 4; k++) M[r][k] -= f * M[c][k];
57+ }
58+ }
59+ const x = [0, 0, 0];
60+ for (let r = 2; r >= 0; r--) {
61+ let s = M[r][3];
62+ for (let k = r + 1; k < 3; k++) s -= M[r][k] * x[k];
63+ x[r] = s / M[r][r];
64+ }
65+ return x;
66+}
67+
68+const cost = (r) => r.reduce((a, v) => a + v * v, 0);
69+
70+function lm(start, mat, note, targets, ne) {
71+ const tg = partialTargets(note, targets);
72+ const nominal = toParams(nominalDesign(note, mat));
73+ let t = toParams(start);
74+ let r = residuals(t, start, mat, tg, nominal, ne), c = cost(r);
75+ let lam = 1e-3;
76+ for (let it = 0; it < 60 && c > 1e-14; it++) {
77+ const J = [];
78+ for (let k = 0; k < 3; k++) {
79+ const tt = [...t];
80+ tt[k] += 1e-6;
81+ const rk = residuals(tt, start, mat, tg, nominal, ne);
82+ J.push(rk.map((v, i) => (v - r[i]) / 1e-6));
83+ }
84+ const A = [0, 1, 2].map((i) => [0, 1, 2].map((j) => J[i].reduce((a, v, q) => a + v * J[j][q], 0)));
85+ const g = [0, 1, 2].map((i) => -J[i].reduce((a, v, q) => a + v * r[q], 0));
86+ let improved = false;
87+ for (let tries = 0; tries < 12; tries++) {
88+ const Ad = A.map((row, i) => row.map((v, j) => v + (i === j ? lam * (A[i][i] + 1e-9) : 0)));
89+ const dt = solve3(Ad, g);
90+ const step = Math.max(...dt.map(Math.abs));
91+ const s = step > 1.5 ? 1.5 / step : 1; // limit wild steps
92+ const tn = t.map((v, i) => v + s * dt[i]);
93+ const rn = residuals(tn, start, mat, tg, nominal, ne), cn = cost(rn);
94+ if (cn < c) { t = tn; r = rn; c = cn; lam = Math.max(1e-9, lam / 4); improved = true; break; }
95+ lam *= 5;
96+ }
97+ if (!improved) break;
98+ }
99+ return { design: fromParams(start, t), cost: c };
100+}
101+
102+/**
103+ * Tune a design for a note. Starts from `start` (or the nominal bar) and also from the
104+ * nominal bar, keeping the better result. Width, thickness and arch shape are kept.
105+ */
106+export function tuneDesign(note, mat, targets = DEFAULT_TARGETS, start = null, ne = 120) {
107+ const nominal = nominalDesign(note, mat);
108+ const base = start ? { ...start } : nominal;
109+ let best = lm(base, mat, note, targets, ne);
110+ if (start && best.cost > 1e-8) {
111+ const alt = lm({ ...nominal, W: base.W, h0: base.h0, p: base.p }, mat, note, targets, ne);
112+ if (alt.cost < best.cost) best = alt;
113+ }
114+ // final polish of f1 at full resolution (length only)
115+ let b = best.design;
116+ for (let k = 0; k < 3; k++) {
117+ const f1 = bendFreqs(b, mat, 1)[0];
118+ b = { ...b, L: b.L * Math.sqrt(f1 / noteFreq(note)) };
119+ }
120+ return b;
121+}
js/view3d.jsadded+246−0View file
@@ -0,0 +1,246 @@
1+// three.js view of one bar with its resonator tube: click the top face to strike.
2+
3+import * as THREE from 'three';
4+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
5+import { thickness } from './bar.js';
6+
7+const S = 0.004; // scene units per mm
8+
9+function rosewoodTexture() {
10+ const c = document.createElement('canvas');
11+ c.width = 1024; c.height = 256;
12+ const g = c.getContext('2d');
13+ g.fillStyle = '#6a2c1c';
14+ g.fillRect(0, 0, c.width, c.height);
15+ for (let y = 0; y < c.height; y++) {
16+ const v = Math.sin(y * 0.21 + Math.sin(y * 0.031) * 4) * 0.5 + 0.5;
17+ g.fillStyle = `rgba(35,10,5,${0.06 + 0.3 * v * v * v})`;
18+ g.fillRect(0, y, c.width, 1);
19+ }
20+ for (let i = 0; i < 90; i++) {
21+ g.strokeStyle = `rgba(${i % 3 ? '25,8,4' : '150,80,50'},${0.05 + Math.random() * 0.12})`;
22+ g.lineWidth = 1 + Math.random() * 1.5;
23+ g.beginPath();
24+ const y = Math.random() * c.height;
25+ g.moveTo(0, y);
26+ for (let x = 0; x <= c.width; x += 32) g.lineTo(x, y + Math.sin(x * 0.006 + i) * 5);
27+ g.stroke();
28+ }
29+ const t = new THREE.CanvasTexture(c);
30+ t.colorSpace = THREE.SRGBColorSpace;
31+ t.wrapS = t.wrapT = THREE.RepeatWrapping;
32+ return t;
33+}
34+
35+export class BarView {
36+ constructor(container, onPick) {
37+ this.container = container;
38+ this.onPick = onPick;
39+ const r = (this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }));
40+ r.setPixelRatio(Math.min(2, window.devicePixelRatio));
41+ container.appendChild(r.domElement);
42+ this.scene = new THREE.Scene();
43+ this.camera = new THREE.PerspectiveCamera(35, 1, 0.01, 100);
44+ this.camera.position.set(0.9, 1.1, 2.4);
45+ this.controls = new OrbitControls(this.camera, r.domElement);
46+ this.controls.enableDamping = true;
47+ this.scene.add(new THREE.HemisphereLight(0xffffff, 0x404050, 1.3));
48+ const sun = new THREE.DirectionalLight(0xffffff, 2.4);
49+ sun.position.set(2, 4, 3);
50+ this.scene.add(sun);
51+ const fill = new THREE.DirectionalLight(0xffffff, 0.6);
52+ fill.position.set(-3, -1, -2);
53+ this.scene.add(fill);
54+ this.tex = rosewoodTexture();
55+ this.group = new THREE.Group();
56+ this.scene.add(this.group);
57+
58+ // mallet: yarn head on a rattan stick
59+ this.mallet = new THREE.Group();
60+ const R = 17 * S;
61+ const head = new THREE.Mesh(new THREE.SphereGeometry(R, 24, 16), new THREE.MeshStandardMaterial({ color: 0x5b6f8f, roughness: 0.95 }));
62+ head.position.y = R;
63+ const stick = new THREE.Mesh(new THREE.CylinderGeometry(4 * S, 4 * S, 380 * S, 12), new THREE.MeshStandardMaterial({ color: 0xd8c39a }));
64+ stick.position.set(0, R + 80 * S, -175 * S);
65+ stick.rotation.x = -Math.PI / 2.6;
66+ this.mallet.add(head, stick);
67+ this.scene.add(this.mallet);
68+ this.mic = new THREE.Mesh(new THREE.SphereGeometry(9 * S, 16, 12), new THREE.MeshStandardMaterial({ color: 0x3d8bfd, emissive: 0x112244 }));
69+ this.scene.add(this.mic);
70+ this.hitT = -1;
71+
72+ const ray = new THREE.Raycaster();
73+ let down = null;
74+ r.domElement.addEventListener('pointerdown', (e) => (down = [e.clientX, e.clientY]));
75+ r.domElement.addEventListener('pointerup', (e) => {
76+ if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4 || !this.topPick) return;
77+ const rect = r.domElement.getBoundingClientRect();
78+ const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
79+ ray.setFromCamera(ndc, this.camera);
80+ const hit = ray.intersectObject(this.topPick)[0];
81+ if (hit) {
82+ const p = this.toBar(hit.point);
83+ this.onPick(p[0], p[1]);
84+ }
85+ });
86+ new ResizeObserver(() => this.resize()).observe(container);
87+ this.resize();
88+ const loop = () => {
89+ requestAnimationFrame(loop);
90+ this.animate();
91+ this.controls.update();
92+ r.render(this.scene, this.camera);
93+ };
94+ loop();
95+ }
96+
97+ // bar mm -> scene (bar centre at the origin)
98+ toScene(x, y, z) {
99+ const b = this.bar;
100+ return new THREE.Vector3((x - b.L / 2) * S, (z - b.h0 / 2) * S, (b.W / 2 - y) * S);
101+ }
102+ toBar(v) {
103+ const b = this.bar;
104+ return [v.x / S + b.L / 2, b.W / 2 - v.z / S, v.y / S + b.h0 / 2];
105+ }
106+
107+ /**
108+ * bar: design; tube: { a, L (mm), gap } or null; mic: [x,y,z] mm; nodes: x positions (mm)
109+ */
110+ setScene(bar, tube, mic, nodes = []) {
111+ const first = !this.bar;
112+ const resized = !this.bar || Math.abs(this.bar.L - bar.L) > 1;
113+ this.bar = bar;
114+ this.group.clear();
115+ // side profile in the x-z plane, extruded across the width
116+ const sh = new THREE.Shape();
117+ const P = (x, z) => [(x - bar.L / 2) * S, (z - bar.h0 / 2) * S];
118+ sh.moveTo(...P(0, bar.h0));
119+ sh.lineTo(...P(bar.L, bar.h0));
120+ const n = 160;
121+ for (let i = n; i >= 0; i--) {
122+ const x = (i / n) * bar.L;
123+ sh.lineTo(...P(x, bar.h0 - thickness(bar, x)));
124+ }
125+ sh.closePath();
126+ const geo = new THREE.ExtrudeGeometry(sh, { depth: bar.W * S, bevelEnabled: false, curveSegments: 1 });
127+ geo.translate(0, 0, (-bar.W * S) / 2);
128+ const tex = this.tex.clone();
129+ tex.repeat.set(1.2, 4);
130+ tex.needsUpdate = true;
131+ const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ map: tex, roughness: 0.45 }));
132+ this.group.add(mesh);
133+
134+ // support cords at the f1 nodes
135+ const cordMat = new THREE.MeshStandardMaterial({ color: 0x222222, roughness: 0.9 });
136+ for (const x of nodes) {
137+ const c = new THREE.Mesh(new THREE.CylinderGeometry(1.6 * S, 1.6 * S, (bar.W + 60) * S, 8), cordMat);
138+ c.rotation.x = Math.PI / 2;
139+ c.position.copy(this.toScene(x, bar.W / 2, -1.6));
140+ this.group.add(c);
141+ }
142+
143+ // resonator
144+ if (tube) {
145+ const metal = new THREE.MeshStandardMaterial({ color: 0xc9a75a, metalness: 0.85, roughness: 0.32, side: THREE.DoubleSide });
146+ const pipe = new THREE.Mesh(new THREE.CylinderGeometry(tube.a * S, tube.a * S, tube.L * S, 48, 1, true), metal);
147+ pipe.position.copy(this.toScene(bar.L / 2, bar.W / 2, -tube.gap - tube.L / 2));
148+ const inner = new THREE.Mesh(
149+ new THREE.CylinderGeometry(tube.a * S * 0.985, tube.a * S * 0.985, tube.L * S, 48, 1, true),
150+ new THREE.MeshStandardMaterial({ color: 0x1b140c, roughness: 1, side: THREE.BackSide }),
151+ );
152+ inner.position.copy(pipe.position);
153+ const cap = new THREE.Mesh(new THREE.CircleGeometry(tube.a * S, 48), metal);
154+ cap.rotation.x = Math.PI / 2;
155+ cap.position.copy(this.toScene(bar.L / 2, bar.W / 2, -tube.gap - tube.L));
156+ this.group.add(pipe, inner, cap);
157+ }
158+
159+ // invisible pick plane + mode overlay on the top face
160+ this.topPick = new THREE.Mesh(new THREE.PlaneGeometry(bar.L * S, bar.W * S), new THREE.MeshBasicMaterial({ visible: false }));
161+ this.topPick.rotation.x = -Math.PI / 2;
162+ this.topPick.position.copy(this.toScene(bar.L / 2, bar.W / 2, bar.h0 + 0.2));
163+ this.group.add(this.topPick);
164+ this.overlay = new THREE.Mesh(
165+ new THREE.PlaneGeometry(bar.L * S, bar.W * S),
166+ new THREE.MeshBasicMaterial({ transparent: true, opacity: 0.85, depthWrite: false }),
167+ );
168+ this.overlay.rotation.x = -Math.PI / 2;
169+ this.overlay.position.copy(this.toScene(bar.L / 2, bar.W / 2, bar.h0 + 0.3));
170+ this.overlay.visible = false;
171+ this.group.add(this.overlay);
172+ this.mic.position.copy(this.toScene(...mic));
173+ if (this.strike) this.setStrike(...this.strike);
174+ if (resized) this.frame(first);
175+ }
176+
177+ // keep the camera direction, set the distance so the bar fills the view
178+ frame(first) {
179+ const target = new THREE.Vector3(0, -40 * S, 0);
180+ const d = Math.max(0.8, this.bar.L * S * 2.0) * Math.max(1, 1.3 / this.camera.aspect);
181+ const dir = first ? new THREE.Vector3(0.3, 0.85, 1).normalize() : this.camera.position.clone().sub(this.controls.target).normalize();
182+ this.controls.target.copy(target);
183+ this.camera.position.copy(target).addScaledVector(dir, d);
184+ }
185+
186+ setStrike(x, y) {
187+ this.strike = [x, y];
188+ if (!this.bar) return;
189+ this.malletRest = this.toScene(x, y, this.bar.h0);
190+ this.mallet.position.copy(this.malletRest).add(new THREE.Vector3(0, 60 * S, 0));
191+ }
192+
193+ hit() { this.hitT = performance.now(); }
194+
195+ animate() {
196+ if (!this.malletRest) return;
197+ const lift = 60 * S;
198+ let h = lift;
199+ if (this.hitT > 0) {
200+ const t = (performance.now() - this.hitT) / 1000;
201+ h = t < 0.03 ? lift * (1 - t / 0.03) : t < 0.25 ? lift * Math.sin(((t - 0.03) / 0.22) * Math.PI / 2) : lift;
202+ }
203+ this.mallet.position.copy(this.malletRest).add(new THREE.Vector3(0, h, 0));
204+ }
205+
206+ // values[ny][nx] in [-1,1] (row j = y from the front edge), or null to hide
207+ setOverlay(nx, ny, values) {
208+ if (!values) { this.overlay.visible = false; return; }
209+ const c = document.createElement('canvas');
210+ c.width = nx; c.height = ny;
211+ const g = c.getContext('2d');
212+ const img = g.createImageData(nx, ny);
213+ for (let j = 0; j < ny; j++) {
214+ for (let i = 0; i < nx; i++) {
215+ const v = values[j * nx + i];
216+ // canvas row 0 is the plane's far (back) edge, i.e. y = W
217+ const o = ((ny - 1 - j) * nx + i) * 4;
218+ const [r, gg, b] = colormap(v);
219+ img.data[o] = r; img.data[o + 1] = gg; img.data[o + 2] = b; img.data[o + 3] = 255;
220+ }
221+ }
222+ g.putImageData(img, 0, 0);
223+ const t = new THREE.CanvasTexture(c);
224+ t.colorSpace = THREE.SRGBColorSpace;
225+ t.magFilter = THREE.LinearFilter;
226+ this.overlay.material.map?.dispose();
227+ this.overlay.material.map = t;
228+ this.overlay.material.needsUpdate = true;
229+ this.overlay.visible = true;
230+ }
231+
232+ resize() {
233+ const w = this.container.clientWidth, h = this.container.clientHeight;
234+ if (!w || !h) return;
235+ this.renderer.setSize(w, h);
236+ this.camera.aspect = w / h;
237+ this.camera.updateProjectionMatrix();
238+ if (this.bar) this.frame(false);
239+ }
240+}
241+
242+// signed value in [-1,1] -> blue / white / red
243+function colormap(v) {
244+ const a = Math.min(1, Math.abs(v));
245+ return v >= 0 ? [255, 255 * (1 - a), 255 * (1 - a)] : [255 * (1 - a), 255 * (1 - a), 255];
246+}
main.jsadded+480−0View file
@@ -0,0 +1,480 @@
1+import { MATERIALS, LOW_NOTE, HIGH_NOTE, noteName, noteFreq, isBlack, nominalDesign, maxDepth, validateDesign, micPos } from './js/bar.js';
2+import { feBarModel } from './js/fe.js';
3+import { tuneDesign, partialErrors, DEFAULT_TARGETS } from './js/tune.js';
4+import { prepare, strike } from './js/synth.js';
5+import { MALLETS, graduatedMallet } from './js/physics.js';
6+import { analyzeBar, analysisCost, matchModes } from './js/analysis.js';
7+import { exportSF2, sampledKeys, LAYERS, VARIANTS } from './js/export.js';
8+import { spectrumDb } from './js/fft.js';
9+import { BarView } from './js/view3d.js';
10+import { drawSpectrum, drawWave } from './js/plots.js';
11+
12+const $ = (id) => document.getElementById(id);
13+
14+// ---------- parameters ----------
15+const MALLET = [
16+ { key: 'v0', label: 'Strike velocity', min: 0.2, max: 4, step: 0.05, value: 1.5, unit: 'm/s' },
17+ { key: 'yarn', label: 'Yarn thickness', min: 0.3, max: 6, step: 0.1, value: MALLETS.medium.yarn, unit: 'mm' },
18+ { key: 'Ky', label: 'Yarn stiffness log₁₀K', min: 8.5, max: 12.5, step: 0.05, value: MALLETS.medium.Ky, unit: '' },
19+ { key: 'Kc', label: 'Core hardness log₁₀K', min: 6.5, max: 10, step: 0.05, value: MALLETS.medium.Kc, unit: '' },
20+ { key: 'mass', label: 'Mallet mass', min: 10, max: 80, step: 1, value: MALLETS.medium.mass, unit: 'g' },
21+ { key: 'lam', label: 'Yarn hysteresis', min: 0, max: 0.6, step: 0.01, value: MALLETS.medium.lam, unit: 's/m' },
22+];
23+const RES = [
24+ { key: 'diam', label: 'Tube diameter', min: 0.5, max: 1.3, step: 0.01, value: 0.9, unit: '× W' },
25+ { key: 'gap', label: 'Gap below bar', min: 3, max: 60, step: 1, value: 20, unit: 'mm' },
26+ { key: 'detune', label: 'Tube tuning', min: -100, max: 100, step: 1, value: 0, unit: 'cents' },
27+ { key: 'loss', label: 'Tube wall loss', min: 0.25, max: 4, step: 0.05, value: 1, unit: '×' },
28+];
29+const DAMP = [
30+ { key: 'eta', label: 'Loss factor η (1 kHz)', min: 0.001, max: 0.03, step: 0.0005, value: MATERIALS.rosewood.eta, unit: '' },
31+ { key: 'slope', label: 'η frequency slope', min: -0.5, max: 1, step: 0.05, value: 0, unit: '' },
32+];
33+const DESIGN = [
34+ { key: 'L', label: 'Length', min: 60, max: 1200, step: 0.5, unit: 'mm' },
35+ { key: 'W', label: 'Width', min: 25, max: 100, step: 0.5, unit: 'mm' },
36+ { key: 'h0', label: 'Thickness', min: 10, max: 32, step: 0.1, unit: 'mm' },
37+ { key: 'd', label: 'Undercut depth', min: 0, max: 29, step: 0.05, unit: 'mm' },
38+ { key: 'a', label: 'Undercut length', min: 0.2, max: 0.95, step: 0.005, unit: '× L' },
39+ { key: 'p', label: 'Arch flatness', min: 1, max: 10, step: 0.1, unit: '' },
40+].map((d) => ({ ...d, value: 0 }));
41+const TARGET = [
42+ { key: 'r2', label: 'Partial 2 ratio', min: 2, max: 6, step: 0.01, value: DEFAULT_TARGETS.r2, unit: '× f1' },
43+ { key: 'r3', label: 'Partial 3 ratio', min: 5, max: 14, step: 0.01, value: DEFAULT_TARGETS.r3, unit: '× f1' },
44+ { key: 'fCut', label: 'Tune partials up to', min: 2000, max: 20000, step: 100, value: DEFAULT_TARGETS.fCut, unit: 'Hz' },
45+];
46+const MAT = [
47+ { key: 'rho', label: 'Density', min: 500, max: 1300, step: 5, value: MATERIALS.rosewood.rho, unit: 'kg/m³' },
48+ { key: 'EL', label: 'Stiffness E_L', min: 6, max: 30, step: 0.1, value: MATERIALS.rosewood.EL, unit: 'GPa' },
49+];
50+
51+const P = {};
52+const sliders = {};
53+function addSliders(container, defs, onChange) {
54+ for (const d of defs) {
55+ P[d.key] = d.value;
56+ const row = document.createElement('label');
57+ row.className = 'row';
58+ row.innerHTML = `<span class="lab">${d.label}</span><input type="range" min="${d.min}" max="${d.max}" step="${d.step}" value="${d.value}"><span class="val"></span>`;
59+ container.appendChild(row);
60+ const inp = row.querySelector('input'), val = row.querySelector('.val');
61+ const show = () => (val.textContent = fmt(d, P[d.key]));
62+ inp.addEventListener('input', () => { P[d.key] = parseFloat(inp.value); show(); onChange(d.key); });
63+ sliders[d.key] = { set: (v) => { P[d.key] = v; inp.value = v; show(); }, setMax: (m) => { inp.max = m; } };
64+ show();
65+ }
66+}
67+function fmt(d, v) {
68+ if (d.key === 'Ky' || d.key === 'Kc') return v.toFixed(2);
69+ if (d.key === 'detune') return (v > 0 ? '+' : '') + v.toFixed(0) + ' ¢';
70+ if (d.key === 'eta') return v.toFixed(4);
71+ if (d.key === 'slope') return (v > 0 ? '+' : '') + v.toFixed(2);
72+ if (d.key === 'fCut') return (v / 1000).toFixed(1) + ' kHz';
73+ if (d.key === 'a' || d.key === 'diam') return v.toFixed(2) + ' ' + d.unit;
74+ const dec = d.step < 0.1 ? 2 : d.step < 1 ? 1 : 0;
75+ return v.toFixed(dec) + (d.unit ? ' ' + d.unit : '');
76+}
77+
78+// ---------- state ----------
79+let note = 60;
80+const designs = new Map(); // note -> { b, manual }
81+let feModel = null; // FE bar model of the selected bar
82+let fdModel = null; // FDTD bar model (with .key = design it was made for)
83+let compareRows = [];
84+let prep = null;
85+let strikeF = [0.5, 0.4]; // strike point as fractions of L and W
86+let busy = false, cancel = false;
87+let actx = null, gain = 1;
88+let lastStrike = null;
89+let throughput = 0; // FDTD cell-steps per second, measured
90+
91+const mat = () => ({ rho: P.rho, EL: P.EL });
92+const targets = () => ({ r2: P.r2, r3: P.r3, fCut: P.fCut });
93+const res = () => ({ on: $('reson').checked, diam: P.diam, gap: P.gap, detune: P.detune, loss: P.loss });
94+const mallet = () => ({ v0: P.v0, yarn: P.yarn, Ky: P.Ky, Kc: P.Kc, mass: P.mass, lam: P.lam });
95+// the mallet actually used on a key (softer toward the bass when graduated)
96+const malletFor = (n) => ($('grad').checked ? graduatedMallet(mallet(), n) : mallet());
97+function showGrad() {
98+ const m = malletFor(note), base = mallet();
99+ const same = ['yarn', 'Ky', 'Kc', 'mass'].every((k) => Math.abs(m[k] - base[k]) < 1e-9);
100+ $('gradinfo').textContent = !$('grad').checked
101+ ? 'Same mallet on every key.'
102+ : same ? 'Below C4 the mallet gets softer and heavier, reaching a bass mallet at C2.'
103+ : `On ${noteName(note)}: yarn ${m.yarn.toFixed(1)} mm, log₁₀K ${m.Ky.toFixed(2)} / ${m.Kc.toFixed(2)}, ${m.mass.toFixed(0)} g.`;
104+}
105+const sound = () => ({ note, eta: P.eta, slope: P.slope, res: res() });
106+const bar = () => designs.get(note).b;
107+const keyOf = (b) => JSON.stringify([b, mat()]);
108+
109+function designFor(n) {
110+ if (!designs.has(n)) designs.set(n, { b: tuneDesign(n, mat(), targets()), manual: false });
111+ return designs.get(n).b;
112+}
113+
114+// ---------- UI construction ----------
115+const view = new BarView($('view'), (x, y) => {
116+ const b = bar();
117+ strikeF = [x / b.L, y / b.W];
118+ view.setStrike(x, y);
119+ showStrike();
120+ playStrike();
121+});
122+
123+addSliders($('mallet'), MALLET, (k) => { if (k !== 'v0') $('mpreset').value = 'custom'; showGrad(); });
124+$('grad').addEventListener('change', showGrad);
125+addSliders($('res'), RES, () => soundChanged());
126+addSliders($('damp'), DAMP, () => soundChanged());
127+addSliders($('design'), DESIGN, (k) => designEdited(k));
128+addSliders($('targets'), TARGET, () => retuneAll());
129+addSliders($('mat'), MAT, () => { $('matpreset').value = 'custom'; retuneAll(); });
130+$('reson').addEventListener('change', () => soundChanged());
131+
132+$('mpreset').addEventListener('change', () => {
133+ const m = MALLETS[$('mpreset').value];
134+ if (m) for (const k of ['yarn', 'Ky', 'Kc', 'mass', 'lam']) sliders[k].set(m[k]);
135+ showGrad();
136+});
137+$('matpreset').addEventListener('change', () => {
138+ const m = MATERIALS[$('matpreset').value];
139+ if (!m) return;
140+ sliders.rho.set(m.rho); sliders.EL.set(m.EL); sliders.eta.set(m.eta);
141+ retuneAll();
142+});
143+
144+// keyboard strip: naturals along the bottom, accidentals above, as on a marimba
145+const keyEls = new Map();
146+(function buildKeys() {
147+ const box = $('keys');
148+ const naturals = [];
149+ for (let n = LOW_NOTE; n <= HIGH_NOTE; n++) if (!isBlack(n)) naturals.push(n);
150+ const w = 100 / naturals.length;
151+ for (let n = LOW_NOTE; n <= HIGH_NOTE; n++) {
152+ const el = document.createElement('button');
153+ el.className = 'key ' + (isBlack(n) ? 'acc' : 'nat');
154+ const pos = naturals.filter((m) => m < n).length;
155+ el.style.left = (isBlack(n) ? pos * w - w * 0.42 : pos * w) + '%';
156+ el.style.width = (isBlack(n) ? w * 0.84 : w) + '%';
157+ el.title = `${noteName(n)} · ${noteFreq(n).toFixed(1)} Hz`;
158+ if (n % 12 === 0) el.textContent = noteName(n);
159+ el.addEventListener('click', () => { selectNote(n); playStrike(); });
160+ box.appendChild(el);
161+ keyEls.set(n, el);
162+ }
163+})();
164+
165+function markKeys() {
166+ for (const [n, el] of keyEls) {
167+ el.classList.toggle('sel', n === note);
168+ el.classList.toggle('edited', !!designs.get(n)?.manual);
169+ }
170+}
171+
172+// ---------- bar selection and editing ----------
173+function selectNote(n) {
174+ note = Math.max(LOW_NOTE, Math.min(HIGH_NOTE, n));
175+ designFor(note);
176+ showDesign();
177+ rebuild();
178+}
179+
180+function showDesign() {
181+ const b = bar();
182+ for (const d of DESIGN) sliders[d.key].set(b[d.key]);
183+ sliders.d.setMax(maxDepth(b).toFixed(2));
184+ $('notename').textContent = `· ${noteName(note)} ${noteFreq(note).toFixed(1)} Hz`;
185+ $('barnote').textContent = noteName(note);
186+ $('barstate').textContent = designs.get(note).manual ? 'edited' : 'auto-tuned';
187+ showGrad();
188+}
189+
190+let pending = 0;
191+function designEdited(k) {
192+ const b = { ...bar(), [k]: P[k] };
193+ b.d = Math.min(b.d, maxDepth(b));
194+ if (k !== 'd') sliders.d.set(b.d);
195+ sliders.d.setMax(maxDepth(b).toFixed(2));
196+ designs.set(note, { b, manual: true });
197+ $('barstate').textContent = 'edited';
198+ if (!pending) pending = requestAnimationFrame(() => { pending = 0; rebuild(); });
199+}
200+
201+function retuneAll() {
202+ for (const [n, v] of [...designs]) if (!v.manual) designs.delete(n);
203+ selectNote(note);
204+}
205+
206+$('autotune').onclick = () => {
207+ const b0 = bar();
208+ const b = tuneDesign(note, mat(), targets(), b0);
209+ const nom = nominalDesign(note, mat());
210+ const manual = Math.abs(b.W - nom.W) > 1e-6 || Math.abs(b.h0 - nom.h0) > 1e-6 || Math.abs(b.p - nom.p) > 1e-6;
211+ designs.set(note, { b, manual });
212+ showDesign();
213+ rebuild();
214+ playStrike();
215+};
216+$('reset').onclick = () => { designs.delete(note); selectNote(note); playStrike(); };
217+
218+// FE model of the selected bar, then the sound model
219+function rebuild() {
220+ const b = bar();
221+ const errs = validateDesign(b);
222+ $('warn').textContent = errs.join('; ');
223+ feModel = feBarModel(b, mat());
224+ const fdOk = fdModel && fdModel.key === keyOf(b);
225+ $('source').querySelector('[value=FDTD]').disabled = !fdOk;
226+ if (!fdOk && $('source').value === 'FDTD') $('source').value = 'FE';
227+ showCompare(fdOk);
228+ showPartials();
229+ markKeys();
230+ soundChanged();
231+ updateInfo();
232+ updateSfInfo();
233+}
234+
235+function soundModel() {
236+ const fdOk = fdModel && fdModel.key === keyOf(bar());
237+ return $('source').value === 'FDTD' && fdOk ? fdModel : feModel;
238+}
239+
240+function soundChanged() {
241+ prep = prepare(soundModel(), sound());
242+ const b = bar();
243+ const t = prep.tube;
244+ view.setScene(b, t ? { a: t.a * 1e3, L: t.L * 1e3, gap: P.gap } : null, micPos(b), feModel.nodes);
245+ view.setStrike(strikeF[0] * b.L, strikeF[1] * b.W);
246+ showStrike();
247+ $('tubeinfo').textContent = t
248+ ? `Tube ${(t.L * 1000).toFixed(0)} mm long, ${(t.a * 2000).toFixed(0)} mm across, tuned to ${t.fT.toFixed(1)} Hz (end correction ${(t.delta * 1000).toFixed(1)} mm).`
249+ : 'No resonator: the bar radiates on its own.';
250+ fillModeList();
251+ drawPlots();
252+}
253+$('source').addEventListener('change', () => soundChanged());
254+
255+function showStrike() {
256+ const b = bar();
257+ $('strikepos').textContent = `${(strikeF[0] * b.L).toFixed(0)}, ${(strikeF[1] * b.W).toFixed(0)} mm`;
258+}
259+
260+function showPartials() {
261+ const f = ['B1', 'B2', 'B3'].map((l) => feModel.modes.find((m) => m.label === l)?.f ?? NaN);
262+ const e = partialErrors(f, note, targets());
263+ const rows = e.map((x, i) => {
264+ const cls = !x.on ? 'muted' : Math.abs(x.cents) < 3 ? 'ok' : 'bad';
265+ const err = x.on ? `${x.cents > 0 ? '+' : ''}${x.cents.toFixed(1)} ¢` : 'not tuned';
266+ return `<tr><td>f${i + 1}</td><td>${x.f.toFixed(1)} Hz</td><td class="muted">${(x.f / f[0]).toFixed(2)}×</td><td class="${cls}">${err}</td></tr>`;
267+ });
268+ $('partials').innerHTML = `<tr><th>partial</th><th>FE</th><th>ratio</th><th>vs target</th></tr>${rows.join('')}`;
269+}
270+
271+function fillModeList() {
272+ const sel = $('overlay');
273+ const prev = sel.value;
274+ sel.innerHTML = '<option value="-1">none</option>' +
275+ prep.modes.map((m, i) => `<option value="${i}">${m.label || i + 1}: ${m.f.toFixed(0)} Hz</option>`).join('');
276+ sel.value = prep.modes[prev] ? prev : '-1';
277+ showOverlay();
278+}
279+function showOverlay() {
280+ const i = parseInt($('overlay').value, 10);
281+ if (!prep || i < 0) { view.setOverlay(0, 0, null); return; }
282+ const m = prep.modes[i];
283+ let mx = 0;
284+ for (const v of m.phi) mx = Math.max(mx, Math.abs(v));
285+ view.setOverlay(prep.nx, prep.ny, Float32Array.from(m.phi, (v) => v / (mx || 1)));
286+}
287+$('overlay').addEventListener('change', showOverlay);
288+
289+// ---------- audio ----------
290+function audio() {
291+ if (!actx) actx = new AudioContext();
292+ if (actx.state === 'suspended') actx.resume();
293+ return actx;
294+}
295+function play(y, sr) {
296+ const ctx = audio();
297+ const buf = ctx.createBuffer(1, y.length, sr);
298+ const ch = buf.getChannelData(0);
299+ for (let i = 0; i < y.length; i++) ch[i] = Math.max(-1, Math.min(1, y[i] * gain));
300+ const src = ctx.createBufferSource();
301+ src.buffer = buf;
302+ src.connect(ctx.destination);
303+ src.start();
304+}
305+
306+function playStrike() {
307+ if (!prep) return;
308+ const sr = audio().sampleRate;
309+ const b = bar();
310+ const r = strike(prep, strikeF[0] * b.L, strikeF[1] * b.W, malletFor(note), sr);
311+ lastStrike = r;
312+ view.hit();
313+ play(r.y, sr);
314+ $('contact').textContent = `contact ${(r.T * 1000).toFixed(2)} ms, peak force ${r.Fm.toFixed(0)} N`;
315+ drawPlots();
316+}
317+
318+function drawPlots() {
319+ const series = [], waves = [];
320+ if (lastStrike) {
321+ series.push({ name: 'modal', ...spectrumDb(lastStrike.y, lastStrike.sr) });
322+ waves.push({ name: 'modal', y: lastStrike.y, sr: lastStrike.sr });
323+ }
324+ const marks = prep ? prep.modes.map((m) => m.f) : [];
325+ drawSpectrum($('spec'), series, marks, prep?.tube ? [prep.tube.fT, 3 * prep.tube.fT] : []);
326+ const full = $('wavespan').value === 'full';
327+ drawWave($('wave'), waves, full ? null : 0.2);
328+ $('ringlen').textContent = lastStrike ? `${(lastStrike.y.length / lastStrike.sr).toFixed(2)} s rendered` : '';
329+}
330+$('wavespan').addEventListener('change', () => {
331+ try { localStorage.setItem('mb-wavespan', $('wavespan').value); } catch {}
332+ drawPlots();
333+});
334+try { const v = localStorage.getItem('mb-wavespan'); if (v) $('wavespan').value = v; } catch {}
335+
336+// ---------- FDTD check ----------
337+function setBusy(b, label = '') {
338+ busy = b;
339+ for (const id of ['analyze', 'export', 'autotune']) $(id).disabled = b;
340+ $('cancel').hidden = !b;
341+ $('status').textContent = label;
342+ if (!b) $('bar').style.width = '0%';
343+}
344+
345+function updateInfo() {
346+ if (!navigator.gpu) return;
347+ const b = bar();
348+ const dx = parseFloat($('dx').value);
349+ const f1 = feModel.modes.find((m) => m.label === 'B1')?.f ?? noteFreq(note);
350+ const { cells, steps } = analysisCost(b, mat(), dx, f1);
351+ const est = throughput ? `est. ${Math.round((cells * steps) / throughput)} s` : `roughly ${Math.max(1, Math.round((cells * steps) / 3e9))} s on a fast GPU`;
352+ const cen = b.h0 - b.d;
353+ $('info').textContent = `${(cells / 1e6).toFixed(2)} M cells · ${steps.toLocaleString()} steps · ${est}. ` +
354+ `Thinnest point ${cen.toFixed(1)} mm = ${(cen / dx).toFixed(1)} cells.`;
355+}
356+$('dx').addEventListener('change', updateInfo);
357+
358+function showCompare(ok) {
359+ if (!ok || !compareRows.length) {
360+ $('compare').innerHTML = fdModel && !ok ? '<tr><td class="muted">Bar changed since the last FDTD analysis.</td></tr>' : '';
361+ return;
362+ }
363+ const rows = compareRows.filter((r) => r.fe.f < 12000).map((r) =>
364+ `<tr><td>${r.fe.label}</td><td>${r.fe.f.toFixed(1)}</td><td>${r.fd.f.toFixed(1)}</td><td class="${Math.abs(r.cents) < 20 ? 'ok' : 'bad'}">${r.cents > 0 ? '+' : ''}${r.cents.toFixed(0)} ¢</td><td class="muted">${r.fe.sigRad.toFixed(1)} / ${r.fd.sigRad.toFixed(1)}</td></tr>`);
365+ $('compare').innerHTML = `<tr><th>mode</th><th>FE Hz</th><th>FDTD Hz</th><th>Δ</th><th>σ_rad FE/FDTD</th></tr>${rows.join('')}`;
366+}
367+
368+async function analyze() {
369+ if (busy) return;
370+ const b = { ...bar() };
371+ const dx = parseFloat($('dx').value);
372+ const f1 = feModel.modes.find((m) => m.label === 'B1')?.f ?? noteFreq(note);
373+ setBusy(true, 'Analyzing…');
374+ cancel = false;
375+ try {
376+ const { cells, steps } = analysisCost(b, mat(), dx, f1);
377+ const t0 = performance.now();
378+ const model = await analyzeBar(b, mat(), dx, f1, {
379+ isCancelled: () => cancel,
380+ onProgress: (label, frac, sec, fRun) => {
381+ $('bar').style.width = (frac * 100).toFixed(1) + '%';
382+ const left = frac > 0.01 && frac < 1 ? ` · ${Math.round((sec / frac) * (1 - frac))} s left` : '';
383+ $('status').textContent = `${label} ${frac < 1 ? (fRun * 100).toFixed(0) + '%' : ''}${left}`;
384+ },
385+ });
386+ if (!model) { setBusy(false, 'Cancelled.'); return; }
387+ throughput = (cells * steps) / model.seconds;
388+ model.key = keyOf(b);
389+ fdModel = model;
390+ compareRows = matchModes(feBarModel(b, mat()), model);
391+ const sec = ((performance.now() - t0) / 1000).toFixed(1);
392+ setBusy(false, `FDTD found ${model.modes.length} modes in ${sec} s. "Sound from" can now use them.`);
393+ rebuild();
394+ } catch (e) {
395+ console.error(e);
396+ setBusy(false, 'Error: ' + e.message);
397+ }
398+}
399+$('analyze').onclick = analyze;
400+$('cancel').onclick = () => (cancel = true);
401+
402+// ---------- SoundFont export ----------
403+function sfRange() {
404+ let lo = parseInt($('sflo').value, 10), hi = parseInt($('sfhi').value, 10);
405+ if (hi < lo) [lo, hi] = [hi, lo];
406+ return { lo, hi, step: parseInt($('sfstep').value, 10) };
407+}
408+function updateSfInfo() {
409+ const { lo, hi, step } = sfRange();
410+ $('sflo_v').textContent = noteName(parseInt($('sflo').value, 10));
411+ $('sfhi_v').textContent = noteName(parseInt($('sfhi').value, 10));
412+ const nKeys = sampledKeys(lo, hi, step).length;
413+ const edited = [...designs].filter(([n, v]) => v.manual && n >= lo && n <= hi).length;
414+ $('sfinfo').textContent = `${nKeys * LAYERS * VARIANTS} samples: ${nKeys} keys × ${LAYERS} velocity layers × ${VARIANTS} strike-point variations. ` +
415+ `Each sampled key is its own auto-tuned bar and tube${edited ? ` (${edited} edited bar${edited > 1 ? 's' : ''} in range are used as edited)` : ''}; ` +
416+ 'uses the current mallet (graduated if ticked), damping, resonator and strike point (as a fraction of the bar). FE modes.';
417+}
418+for (const id of ['sflo', 'sfhi', 'sfstep']) $(id).addEventListener('input', updateSfInfo);
419+
420+async function doExport() {
421+ if (busy) return;
422+ setBusy(true, 'Rendering samples…');
423+ try {
424+ const { lo, hi, step } = sfRange();
425+ const name = $('sfname').value.trim() || 'Marimba';
426+ const t0 = performance.now();
427+ const r = await exportSF2({
428+ lo, hi, step, name, sampleRate: 44100, mat: mat(), designFor,
429+ sound: { eta: P.eta, slope: P.slope, res: res() }, malletFor, strike: strikeF,
430+ onProgress: (f, k) => { $('bar').style.width = (f * 100).toFixed(1) + '%'; $('status').textContent = `Rendering ${noteName(k)} · ${(f * 100).toFixed(0)}%`; },
431+ });
432+ lastExport = r.bytes;
433+ const blob = new Blob([r.bytes], { type: 'audio/x-soundfont' });
434+ const a = document.createElement('a');
435+ a.href = URL.createObjectURL(blob);
436+ a.download = name.replace(/[^\w\- ]+/g, '_') + '.sf2';
437+ a.click();
438+ setTimeout(() => URL.revokeObjectURL(a.href), 10000);
439+ markKeys();
440+ setBusy(false, `Exported ${a.download}: ${r.nSamples} samples, ${(r.bytes.length / 1e6).toFixed(1)} MB, ${noteName(lo)}–${noteName(hi)} (${((performance.now() - t0) / 1000).toFixed(1)} s).`);
441+ } catch (e) {
442+ console.error(e);
443+ setBusy(false, 'Export error: ' + e.message);
444+ }
445+}
446+let lastExport = null;
447+$('export').onclick = doExport;
448+
449+$('strike').onclick = playStrike;
450+window.addEventListener('keydown', (e) => {
451+ if (['INPUT', 'SELECT', 'TEXTAREA'].includes(e.target.tagName) && e.target.type !== 'range' && e.target.type !== 'checkbox') return;
452+ if (e.code === 'Space') { e.preventDefault(); playStrike(); }
453+ if (e.code === 'ArrowLeft' || e.code === 'ArrowRight') {
454+ if (e.target.type === 'range') return;
455+ e.preventDefault();
456+ selectNote(note + (e.code === 'ArrowLeft' ? -1 : 1));
457+ playStrike();
458+ }
459+});
460+window.addEventListener('resize', drawPlots);
461+
462+// for debugging in the console
463+window.mb = { get prep() { return prep; }, get feModel() { return feModel; }, get fdModel() { return fdModel; }, get lastStrike() { return lastStrike; }, get lastExport() { return lastExport; }, designs, P };
464+
465+// ---------- start ----------
466+// One fixed loudness scale (Pa -> full scale) so keys keep their relative loudness.
467+{
468+ const b = designFor(60);
469+ const p0 = prepare(feBarModel(b, mat()), { note: 60, eta: P.eta, slope: P.slope, res: res() });
470+ const r = strike(p0, b.L / 2, b.W / 2, { ...MALLETS.medium, v0: 1.5 }, 48000);
471+ let pk = 0;
472+ for (const v of r.y) pk = Math.max(pk, Math.abs(v));
473+ gain = 0.3 / (pk || 1);
474+}
475+selectNote(60);
476+if (!navigator.gpu) {
477+ $('analyze').disabled = true;
478+ $('info').textContent = 'WebGPU is not available in this browser (try Chrome or Safari 26+); the FE model still works.';
479+}
480+$('status').textContent = 'Click the bar or a key to play. Each key is its own auto-tuned bar.';
package.jsonadded+8−0View file
@@ -0,0 +1,8 @@
1+{
2+ "name": "marimba",
3+ "private": true,
4+ "type": "module",
5+ "scripts": {
6+ "dev": "python3 -m http.server 8021 --bind 127.0.0.1"
7+ }
8+}
style.cssadded+68−0View file
@@ -0,0 +1,68 @@
1+:root {
2+ --bg: #f6f4f0; --panel: #ffffff; --fg: #1d1b18; --muted: #6f6a62; --line: #e2ddd4;
3+ --accent: #a0522d; --grid: #ebe6dd; --mark: #b8b0a2;
4+ --c-modal: #c2410c; --warn: #b45309; --tube: #b08d2e; --ok: #15803d;
5+ color-scheme: light dark;
6+}
7+@media (prefers-color-scheme: dark) {
8+ :root {
9+ --bg: #151412; --panel: #1e1c19; --fg: #ece8e1; --muted: #9a948a; --line: #34302b;
10+ --accent: #e0915c; --grid: #2a2723; --mark: #5c564e;
11+ --c-modal: #fb923c; --warn: #fbbf24; --tube: #d6b35a; --ok: #4ade80;
12+ }
13+}
14+* { box-sizing: border-box; }
15+html, body { margin: 0; height: 100%; background: var(--bg); color: var(--fg); font: 13px/1.4 system-ui, -apple-system, sans-serif; }
16+main { display: grid; grid-template-columns: 1fr 340px; height: 100vh; }
17+.stage { display: grid; grid-template-rows: 1fr auto auto; grid-template-columns: minmax(0, 1fr); min-width: 0; position: relative; }
18+#view { min-height: 300px; position: relative; overflow: hidden; }
19+#view canvas { position: absolute; inset: 0; }
20+.hint { position: absolute; top: 10px; left: 14px; color: var(--muted); font-size: 12px; pointer-events: none; }
21+.plots { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding: 10px; border-top: 1px solid var(--line); }
22+.plot { min-width: 0; }
23+.plot canvas { width: 100%; height: 170px; display: block; }
24+.ptitle { color: var(--muted); font-size: 12px; margin-bottom: 4px; }
25+select.inline { font-size: 11px; padding: 0 2px; }
26+.panel { background: var(--panel); border-left: 1px solid var(--line); padding: 14px 16px; overflow-y: auto; }
27+h1 { font-size: 17px; margin: 0 0 10px; }
28+h2 { font-size: 13px; margin: 18px 0 6px; padding-top: 10px; border-top: 1px solid var(--line); }
29+h2 small { color: var(--muted); font-weight: 400; margin-left: 6px; }
30+.row { display: grid; grid-template-columns: 130px 1fr 64px; align-items: center; gap: 8px; margin: 3px 0; }
31+.row .lab { color: var(--muted); font-size: 12px; }
32+.row .val { text-align: right; font-variant-numeric: tabular-nums; font-size: 12px; }
33+input[type=range] { width: 100%; accent-color: var(--accent); }
34+input[type=text] { width: 100%; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 3px 6px; font: inherit; }
35+select { background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 6px; padding: 3px 4px; }
36+.actions { display: flex; gap: 6px; flex-wrap: wrap; margin: 6px 0; }
37+button { background: var(--accent); color: #fff; border: 0; border-radius: 7px; padding: 7px 11px; font: inherit; font-weight: 600; cursor: pointer; }
38+button:disabled { opacity: 0.45; cursor: default; }
39+button.small { padding: 2px 8px; font-size: 12px; background: var(--muted); }
40+.progress { height: 4px; background: var(--grid); border-radius: 2px; overflow: hidden; margin-top: 8px; }
41+#bar { height: 100%; width: 0; background: var(--accent); transition: width 0.2s; }
42+.status { min-height: 36px; margin-top: 6px; font-size: 12px; color: var(--muted); }
43+.kv { display: flex; justify-content: space-between; font-size: 12px; margin: 2px 0 4px; }
44+.muted { color: var(--muted); }
45+.info { font-size: 11px; color: var(--muted); margin: 6px 0; font-variant-numeric: tabular-nums; }
46+.warn { color: var(--warn); font-size: 12px; margin: 4px 0; }
47+.warn:empty { display: none; }
48+h1 .muted { font-weight: 400; font-size: 14px; }
49+.keys { position: relative; height: 62px; margin: 0 10px 8px; }
50+.key { position: absolute; padding: 0; border-radius: 3px; font-size: 9px; font-weight: 500; color: #f3e6dc;
51+ display: flex; align-items: flex-end; justify-content: center; padding-bottom: 2px; border: 1px solid rgba(0,0,0,0.25); }
52+.key.nat { top: 26px; height: 36px; background: #7a3522; }
53+.key.acc { top: 0; height: 24px; background: #5a2416; z-index: 1; }
54+.key:hover { filter: brightness(1.25); }
55+.key.sel { background: var(--accent); outline: 2px solid var(--fg); z-index: 2; }
56+.key.edited::before { content: ''; position: absolute; top: 3px; left: 50%; width: 5px; height: 5px; margin-left: -2.5px; border-radius: 50%; background: #fbbf24; }
57+input[type=checkbox] { accent-color: var(--accent); justify-self: start; }
58+table.partials { width: 100%; border-collapse: collapse; font-size: 12px; font-variant-numeric: tabular-nums; margin: 6px 0; }
59+table.partials th { text-align: left; color: var(--muted); font-weight: 500; font-size: 11px; }
60+table.partials td, table.partials th { padding: 1px 4px 1px 0; }
61+.ok { color: var(--ok); }
62+.bad { color: var(--warn); }
63+@media (max-width: 800px) {
64+ main { grid-template-columns: 1fr; height: auto; }
65+ .stage { grid-template-rows: 55vh auto auto; }
66+ .plots { grid-template-columns: 1fr; padding: 10px 16px; }
67+ .panel { border-left: 0; border-top: 1px solid var(--line); padding: 14px 16px; }
68+}