import { DEFAULT_BLOCK, buildGrid, strikePatch, validateBlock } from './js/block.js';
import { runFDTD, timeStep } from './js/fdtd.js';
import { extractModes, modalStrike, residuesAt, spectrumDb, dominantFreq } from './js/modal.js';
import { exportSF2, noteName, freqToMidi, LAYERS, VARIANTS } from './js/export.js';
import { pitchScale } from './js/physics.js';
import { BlockView } from './js/view3d.js';
import { drawSpectrum, drawWave } from './js/plots.js';
const $ = (id) => document.getElementById(id);
// ---------- parameters ----------
const LIVE = [
{ key: 'pitch', label: 'Pitch', min: -12, max: 12, step: 0.1, value: 0, unit: 'st' },
{ key: 'eta', label: 'Damping (loss factor)', min: 0.002, max: 0.05, step: 0.001, value: 0.012, unit: '' },
{ key: 'hard', label: 'Mallet hardness log₁₀K', min: 6, max: 9.5, step: 0.05, value: 8, unit: '' },
{ key: 'mass', label: 'Mallet mass', min: 5, max: 100, step: 1, value: 20, unit: 'g' },
{ key: 'v0', label: 'Strike velocity', min: 0.2, max: 5, step: 0.1, value: 2, unit: 'm/s' },
];
const BLOCK = [
{ key: 'L', label: 'Length', min: 100, max: 300, step: 1, unit: 'mm' },
{ key: 'W', label: 'Depth', min: 40, max: 120, step: 1, unit: 'mm' },
{ key: 'H', label: 'Height', min: 35, max: 100, step: 1, unit: 'mm' },
{ key: 'wall', label: 'Wall thickness', min: 4, max: 15, step: 0.5, unit: 'mm' },
{ key: 'top', label: 'Top plate', min: 3, max: 15, step: 0.5, unit: 'mm' },
{ key: 'slotH', label: 'Slot height', min: 3, max: 15, step: 0.5, unit: 'mm' },
{ key: 'inset', label: 'Slot end inset', min: 8, max: 60, step: 1, unit: 'mm' },
{ key: 'rho', label: 'Density', min: 400, max: 1200, step: 5, unit: 'kg/m³' },
{ key: 'EL', label: 'Stiffness E_L', min: 6, max: 20, step: 0.1, unit: 'GPa' },
].map((p) => ({ ...p, value: DEFAULT_BLOCK[p.key] }));
const P = {};
function addSliders(container, defs, onChange) {
for (const d of defs) {
P[d.key] = d.value;
const row = document.createElement('label');
row.className = 'row';
row.innerHTML = `${d.label}`;
container.appendChild(row);
const inp = row.querySelector('input');
const show = () => ($(`v_${d.key}`).textContent = fmt(d, P[d.key]));
inp.addEventListener('input', () => { P[d.key] = parseFloat(inp.value); show(); onChange(d.key); });
show();
}
}
function fmt(d, v) {
if (d.key === 'hard') return v.toFixed(2);
if (d.key === 'pitch') return (v > 0 ? '+' : '') + v.toFixed(1) + ' st';
if (d.key === 'eta') return v.toFixed(3);
const dec = d.step < 0.1 ? 2 : d.step < 1 ? 1 : 0;
return v.toFixed(dec) + (d.unit ? ' ' + d.unit : '');
}
const block = () => Object.fromEntries(BLOCK.map((d) => [d.key, P[d.key]]));
const liveParams = () => ({ pitch: pitchScale(P.pitch), eta: P.eta, K: 10 ** P.hard, m: P.mass / 1000, v0: P.v0 });
// ---------- state ----------
let model = null; // modal model
let modelKey = ''; // block+dx the model was built for
let strike = [DEFAULT_BLOCK.L / 2, DEFAULT_BLOCK.W / 2];
let busy = false, cancel = false;
let actx = null, gain = 1;
let lastModal = null;
let throughput = 0; // cell-steps per second, measured
const ANALYSIS_DUR = 0.06; // s per analysis run
let lastRes = null; // last analysis run (for debugging)
const view = new BlockView($('view'), (x, y) => { strike = [x, y]; view.setStrike(x, y); updateInfo(); updateSfInfo(); playModal(); });
const keyOf = () => JSON.stringify([block(), $('dx').value]);
addSliders($('live'), LIVE, () => { updateInfo(); updateSfInfo(); });
addSliders($('blockp'), BLOCK, () => onBlockChange());
$('dx').addEventListener('change', () => { updateInfo(); });
function onBlockChange() {
const b = block();
const errs = validateBlock(b);
$('warn').textContent = errs.join('; ');
if (errs.length) return;
strike = [Math.min(strike[0], b.L), Math.min(strike[1], b.W)];
view.setBlock(b);
view.setStrike(...strike);
updateInfo();
}
function updateInfo() {
const b = block();
const dx = parseFloat($('dx').value);
const stale = model && modelKey !== keyOf();
$('stale').hidden = !stale;
$('strikepos').textContent = `${strike[0].toFixed(0)}, ${strike[1].toFixed(0)} mm`;
if (validateBlock(b).length) return;
const nx = Math.ceil(b.L / dx) + 2 * (10 + Math.ceil(20 / dx));
const ny = Math.ceil(b.W / dx) + 2 * (10 + Math.ceil(20 / dx));
const nz = Math.ceil(b.H / dx) + 2 * (10 + Math.ceil(20 / dx));
const dt = timeStep(b, dx);
const steps = 3 * Math.ceil(ANALYSIS_DUR / dt);
const cells = nx * ny * nz;
const est = throughput ? ` · est. ${Math.round((cells * steps) / throughput)} s` : '';
$('info').textContent = `analysis grid ${nx}×${ny}×${nz} = ${(cells / 1e6).toFixed(2)} M cells · ${steps.toLocaleString()} steps${est}`;
}
// ---------- audio ----------
function audio() {
if (!actx) actx = new AudioContext();
if (actx.state === 'suspended') actx.resume();
return actx;
}
function play(y, sr) {
const ctx = audio();
const buf = ctx.createBuffer(1, y.length, sr);
const ch = buf.getChannelData(0);
for (let i = 0; i < y.length; i++) ch[i] = Math.max(-1, Math.min(1, y[i] * gain));
const src = ctx.createBufferSource();
src.buffer = buf;
src.connect(ctx.destination);
src.start();
}
function playModal() {
if (!model) return;
const sr = audio().sampleRate;
const r = modalStrike(model, strike[0], strike[1], liveParams(), sr);
lastModal = { y: r.y, sr };
view.hit();
play(r.y, sr);
$('contact').textContent = `contact ${(r.T * 1000).toFixed(2)} ms, peak force ${r.Fm.toFixed(0)} N`;
drawPlots();
}
function drawPlots() {
const series = [], waves = [];
if (lastModal) {
series.push({ name: 'modal', ...spectrumDb(lastModal.y, lastModal.sr) });
waves.push({ name: 'modal', ...lastModal });
}
const marks = model ? model.modes.map((m) => m.f * pitchScale(P.pitch)) : [];
drawSpectrum($('spec'), series, marks);
drawWave($('wave'), waves, 0.2);
}
// ---------- simulations ----------
function setBusy(b, label = '') {
busy = b;
for (const id of ['analyze', 'export']) $(id).disabled = b;
$('cancel').hidden = !b;
$('status').textContent = label;
if (!b) $('bar').style.width = '0%';
}
const progress = (label) => (f, sec) => {
$('bar').style.width = (f * 100).toFixed(1) + '%';
const eta = f > 0.01 ? Math.round((sec / f) * (1 - f)) : '…';
$('status').textContent = `${label} ${(f * 100).toFixed(0)}% · ${eta} s left`;
};
async function analyze() {
if (busy) return;
const b = block();
if (validateBlock(b).length) return;
const dx = parseFloat($('dx').value);
setBusy(true, 'Analyzing…');
cancel = false;
try {
const grid = buildGrid(b, dx);
// run 1: source at the mic (sound); runs 2-3: force at two reference points (contact)
const refs = [[0.27, 0.38], [0.61, 0.77]].map(([fx, fy]) => {
const x = fx * b.L, y = fy * b.W;
const ib = Math.round(x / dx - 0.5), jb = Math.round(y / dx - 0.5);
return { x, y, surf: grid.surfIndex[ib + grid.nbx * jb], patch: strikePatch(grid, x, y) };
});
const jobs = [{ mode: 'analysis' }, ...refs.map((r) => ({ mode: 'impulse', patch: r.patch }))];
const runs = [];
let secs = 0;
for (let k = 0; k < jobs.length; k++) {
const res = await runFDTD({
block: b, grid, ...jobs[k], duration: ANALYSIS_DUR, stiffScale: 1, eta: 0, recRate: 48000,
onProgress: progress(`Analysis ${k + 1}/${jobs.length} (FDTD)`), isCancelled: () => cancel,
});
if (!res) { setBusy(false, 'Cancelled.'); return; }
throughput = (grid.N * res.nSteps) / res.seconds;
secs += res.seconds;
runs.push(res);
}
const res = { seconds: secs, nSteps: runs.reduce((a, r) => a + r.nSteps, 0) };
$('status').textContent = 'Extracting modes…';
await new Promise((r) => setTimeout(r, 20));
lastRes = { runs, grid, refs };
model = extractModes(runs, grid, refs);
modelKey = keyOf();
// loudness normalization from a reference modal strike
const ref = modalStrike(model, b.L / 2, b.W / 2, { pitch: 1, eta: 0.012, K: 1e8, m: 0.02, v0: 2 }, 48000);
gain = 0.35 / Math.max(1e-12, ...ref.y.map(Math.abs));
fillModeList();
updateSfInfo();
setBusy(false, `Found ${model.modes.length} modes in ${res.seconds.toFixed(1)} s (${res.nSteps.toLocaleString()} steps). Click the top face to strike.`);
updateInfo();
drawPlots();
} catch (e) {
console.error(e);
setBusy(false, 'Error: ' + e.message);
}
}
function fillModeList() {
const sel = $('overlay');
sel.innerHTML = '' +
model.modes.map((m, i) => ``).join('');
view.setOverlay(0, 0, null);
}
$('overlay').addEventListener('change', () => {
const i = parseInt($('overlay').value, 10);
if (!model || i < 0) { view.setOverlay(0, 0, null); return; }
const m = model.modes[i];
// rotate phase so the largest residue is real, then show the real part
let best = 0, br = 0, bi = 0;
for (let n = 0; n < m.re.length; n++) {
const a = m.re[n] ** 2 + m.im[n] ** 2;
if (a > best) { best = a; br = m.re[n]; bi = m.im[n]; }
}
const s = Math.sqrt(best) || 1;
const vals = new Float32Array(model.nbx * model.nby);
for (let k = 0; k < vals.length; k++) {
const n = model.surfIndex[k];
if (n >= 0) vals[k] = (m.re[n] * br + m.im[n] * bi) / (s * s);
}
view.setOverlay(model.nbx, model.nby, vals);
});
// ---------- SoundFont export ----------
function sfRange() {
let lo = parseInt($('sflo').value, 10), hi = parseInt($('sfhi').value, 10);
if (hi < lo) [lo, hi] = [hi, lo];
return { lo, hi, step: parseInt($('sfstep').value, 10) };
}
function updateSfInfo() {
const { lo, hi, step } = sfRange();
$('sflo_v').textContent = noteName(parseInt($('sflo').value, 10));
$('sfhi_v').textContent = noteName(parseInt($('sfhi').value, 10));
const nKeys = Math.floor((hi - lo) / step) + 1 + ((hi - lo) % step > step / 2 ? 1 : 0);
const n = nKeys * LAYERS * VARIANTS;
let pitch = '';
if (model) {
const f = dominantFreq(model, strike[0], strike[1], liveParams());
pitch = `Block rings at ${f.toFixed(0)} Hz (≈ ${noteName(Math.round(freqToMidi(f)))}); keys retune it. `;
}
$('sfinfo').textContent = `${pitch}${n} samples: ${nKeys} keys × ${LAYERS} velocity layers × ${VARIANTS} strike-point variations. ` +
'Uses the current damping, mallet and strike point; strike velocity sets the loudest layer.';
}
for (const id of ['sflo', 'sfhi', 'sfstep']) $(id).addEventListener('input', updateSfInfo);
async function doExport() {
if (busy || !model) return;
if (modelKey !== keyOf()) $('status').textContent = 'Note: block changed since analysis; exporting the analyzed block.';
setBusy(true, 'Rendering samples…');
try {
const { lo, hi, step } = sfRange();
const name = $('sfname').value.trim() || 'Woodblock';
const lp = liveParams();
const t0 = performance.now();
const r = await exportSF2({
model, block: block(), strike, live: lp, lo, hi, step, name, sampleRate: 44100,
onProgress: (f) => { $('bar').style.width = (f * 100).toFixed(1) + '%'; $('status').textContent = `Rendering samples ${(f * 100).toFixed(0)}%`; },
});
lastExport = r.bytes;
const blob = new Blob([r.bytes], { type: 'audio/x-soundfont' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = name.replace(/[^\w\- ]+/g, '_') + '.sf2';
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 10000);
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).`);
} catch (e) {
console.error(e);
setBusy(false, 'Export error: ' + e.message);
}
}
let lastExport = null;
$('export').onclick = doExport;
$('analyze').onclick = analyze;
$('cancel').onclick = () => (cancel = true);
$('strike').onclick = playModal;
window.addEventListener('keydown', (e) => {
if (e.code === 'Space' && e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT') { e.preventDefault(); playModal(); }
});
window.addEventListener('resize', drawPlots);
// for debugging in the console
window.wb = { get model() { return model; }, get lastRes() { return lastRes; }, get lastModal() { return lastModal; }, get lastExport() { return lastExport; }, residuesAt, extractModes, P };
onBlockChange();
drawPlots();
updateSfInfo();
if (!navigator.gpu) {
$('status').textContent = 'WebGPU is not available in this browser (try Chrome or Safari 26+).';
$('analyze').disabled = $('export').disabled = true;
} else {
analyze();
}