import { MATERIALS, LOW_NOTE, HIGH_NOTE, noteName, noteFreq, isBlack, nominalDesign, maxDepth, validateDesign, micPos } from './js/bar.js'; import { feBarModel } from './js/fe.js'; import { tuneDesign, partialErrors, DEFAULT_TARGETS } from './js/tune.js'; import { prepare, strike } from './js/synth.js'; import { MALLETS, graduatedMallet } from './js/physics.js'; import { analyzeBar, analysisCost, matchModes } from './js/analysis.js'; import { exportSF2, sampledKeys, LAYERS, VARIANTS } from './js/export.js'; import { spectrumDb } from './js/fft.js'; import { BarView } from './js/view3d.js'; import { drawSpectrum, drawWave } from './js/plots.js'; const $ = (id) => document.getElementById(id); // ---------- parameters ---------- const MALLET = [ { key: 'v0', label: 'Strike velocity', min: 0.2, max: 4, step: 0.05, value: 1.5, unit: 'm/s' }, { key: 'yarn', label: 'Yarn thickness', min: 0.3, max: 6, step: 0.1, value: MALLETS.medium.yarn, unit: 'mm' }, { key: 'Ky', label: 'Yarn stiffness log₁₀K', min: 8.5, max: 12.5, step: 0.05, value: MALLETS.medium.Ky, unit: '' }, { key: 'Kc', label: 'Core hardness log₁₀K', min: 6.5, max: 10, step: 0.05, value: MALLETS.medium.Kc, unit: '' }, { key: 'mass', label: 'Mallet mass', min: 10, max: 80, step: 1, value: MALLETS.medium.mass, unit: 'g' }, { key: 'lam', label: 'Yarn hysteresis', min: 0, max: 0.6, step: 0.01, value: MALLETS.medium.lam, unit: 's/m' }, ]; const RES = [ { key: 'diam', label: 'Tube diameter', min: 0.5, max: 1.3, step: 0.01, value: 0.9, unit: '× W' }, { key: 'gap', label: 'Gap below bar', min: 3, max: 60, step: 1, value: 20, unit: 'mm' }, { key: 'detune', label: 'Tube tuning', min: -100, max: 100, step: 1, value: 0, unit: 'cents' }, { key: 'loss', label: 'Tube wall loss', min: 0.25, max: 4, step: 0.05, value: 1, unit: '×' }, ]; const DAMP = [ { key: 'eta', label: 'Loss factor η (1 kHz)', min: 0.001, max: 0.03, step: 0.0005, value: MATERIALS.rosewood.eta, unit: '' }, { key: 'slope', label: 'η frequency slope', min: -0.5, max: 1, step: 0.05, value: 0, unit: '' }, ]; const DESIGN = [ { key: 'L', label: 'Length', min: 60, max: 1200, step: 0.5, unit: 'mm' }, { key: 'W', label: 'Width', min: 25, max: 100, step: 0.5, unit: 'mm' }, { key: 'h0', label: 'Thickness', min: 10, max: 32, step: 0.1, unit: 'mm' }, { key: 'd', label: 'Undercut depth', min: 0, max: 29, step: 0.05, unit: 'mm' }, { key: 'a', label: 'Undercut length', min: 0.2, max: 0.95, step: 0.005, unit: '× L' }, { key: 'p', label: 'Arch flatness', min: 1, max: 10, step: 0.1, unit: '' }, ].map((d) => ({ ...d, value: 0 })); const TARGET = [ { key: 'r2', label: 'Partial 2 ratio', min: 2, max: 6, step: 0.01, value: DEFAULT_TARGETS.r2, unit: '× f1' }, { key: 'r3', label: 'Partial 3 ratio', min: 5, max: 14, step: 0.01, value: DEFAULT_TARGETS.r3, unit: '× f1' }, { key: 'fCut', label: 'Tune partials up to', min: 2000, max: 20000, step: 100, value: DEFAULT_TARGETS.fCut, unit: 'Hz' }, ]; const MAT = [ { key: 'rho', label: 'Density', min: 500, max: 1300, step: 5, value: MATERIALS.rosewood.rho, unit: 'kg/m³' }, { key: 'EL', label: 'Stiffness E_L', min: 6, max: 30, step: 0.1, value: MATERIALS.rosewood.EL, unit: 'GPa' }, ]; const P = {}; const sliders = {}; 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'), val = row.querySelector('.val'); const show = () => (val.textContent = fmt(d, P[d.key])); inp.addEventListener('input', () => { P[d.key] = parseFloat(inp.value); show(); onChange(d.key); }); sliders[d.key] = { set: (v) => { P[d.key] = v; inp.value = v; show(); }, setMax: (m) => { inp.max = m; } }; show(); } } function fmt(d, v) { if (d.key === 'Ky' || d.key === 'Kc') return v.toFixed(2); if (d.key === 'detune') return (v > 0 ? '+' : '') + v.toFixed(0) + ' ¢'; if (d.key === 'eta') return v.toFixed(4); if (d.key === 'slope') return (v > 0 ? '+' : '') + v.toFixed(2); if (d.key === 'fCut') return (v / 1000).toFixed(1) + ' kHz'; if (d.key === 'a' || d.key === 'diam') return v.toFixed(2) + ' ' + d.unit; const dec = d.step < 0.1 ? 2 : d.step < 1 ? 1 : 0; return v.toFixed(dec) + (d.unit ? ' ' + d.unit : ''); } // ---------- state ---------- let note = 60; const designs = new Map(); // note -> { b, manual } let feModel = null; // FE bar model of the selected bar let fdModel = null; // FDTD bar model (with .key = design it was made for) let compareRows = []; let prep = null; let strikeF = [0.5, 0.4]; // strike point as fractions of L and W let busy = false, cancel = false; let actx = null, gain = 1; let lastStrike = null; let throughput = 0; // FDTD cell-steps per second, measured const mat = () => ({ rho: P.rho, EL: P.EL }); const targets = () => ({ r2: P.r2, r3: P.r3, fCut: P.fCut }); const res = () => ({ on: $('reson').checked, diam: P.diam, gap: P.gap, detune: P.detune, loss: P.loss }); const mallet = () => ({ v0: P.v0, yarn: P.yarn, Ky: P.Ky, Kc: P.Kc, mass: P.mass, lam: P.lam }); // the mallet actually used on a key (softer toward the bass when graduated) const malletFor = (n) => ($('grad').checked ? graduatedMallet(mallet(), n) : mallet()); function showGrad() { const m = malletFor(note), base = mallet(); const same = ['yarn', 'Ky', 'Kc', 'mass'].every((k) => Math.abs(m[k] - base[k]) < 1e-9); $('gradinfo').textContent = !$('grad').checked ? 'Same mallet on every key.' : same ? 'Below C4 the mallet gets softer and heavier, reaching a bass mallet at C2.' : `On ${noteName(note)}: yarn ${m.yarn.toFixed(1)} mm, log₁₀K ${m.Ky.toFixed(2)} / ${m.Kc.toFixed(2)}, ${m.mass.toFixed(0)} g.`; } const sound = () => ({ note, eta: P.eta, slope: P.slope, res: res() }); const bar = () => designs.get(note).b; const keyOf = (b) => JSON.stringify([b, mat()]); function designFor(n) { if (!designs.has(n)) designs.set(n, { b: tuneDesign(n, mat(), targets()), manual: false }); return designs.get(n).b; } // ---------- UI construction ---------- const view = new BarView($('view'), (x, y) => { const b = bar(); strikeF = [x / b.L, y / b.W]; view.setStrike(x, y); showStrike(); playStrike(); }); addSliders($('mallet'), MALLET, (k) => { if (k !== 'v0') $('mpreset').value = 'custom'; showGrad(); }); $('grad').addEventListener('change', showGrad); addSliders($('res'), RES, () => soundChanged()); addSliders($('damp'), DAMP, () => soundChanged()); addSliders($('design'), DESIGN, (k) => designEdited(k)); addSliders($('targets'), TARGET, () => retuneAll()); addSliders($('mat'), MAT, () => { $('matpreset').value = 'custom'; retuneAll(); }); $('reson').addEventListener('change', () => soundChanged()); $('mpreset').addEventListener('change', () => { const m = MALLETS[$('mpreset').value]; if (m) for (const k of ['yarn', 'Ky', 'Kc', 'mass', 'lam']) sliders[k].set(m[k]); showGrad(); }); $('matpreset').addEventListener('change', () => { const m = MATERIALS[$('matpreset').value]; if (!m) return; sliders.rho.set(m.rho); sliders.EL.set(m.EL); sliders.eta.set(m.eta); retuneAll(); }); // keyboard strip: naturals along the bottom, accidentals above, as on a marimba const keyEls = new Map(); (function buildKeys() { const box = $('keys'); const naturals = []; for (let n = LOW_NOTE; n <= HIGH_NOTE; n++) if (!isBlack(n)) naturals.push(n); const w = 100 / naturals.length; for (let n = LOW_NOTE; n <= HIGH_NOTE; n++) { const el = document.createElement('button'); el.className = 'key ' + (isBlack(n) ? 'acc' : 'nat'); const pos = naturals.filter((m) => m < n).length; el.style.left = (isBlack(n) ? pos * w - w * 0.42 : pos * w) + '%'; el.style.width = (isBlack(n) ? w * 0.84 : w) + '%'; el.title = `${noteName(n)} · ${noteFreq(n).toFixed(1)} Hz`; if (n % 12 === 0) el.textContent = noteName(n); el.addEventListener('click', () => { selectNote(n); playStrike(); }); box.appendChild(el); keyEls.set(n, el); } })(); function markKeys() { for (const [n, el] of keyEls) { el.classList.toggle('sel', n === note); el.classList.toggle('edited', !!designs.get(n)?.manual); } } // ---------- bar selection and editing ---------- function selectNote(n) { note = Math.max(LOW_NOTE, Math.min(HIGH_NOTE, n)); designFor(note); showDesign(); rebuild(); } function showDesign() { const b = bar(); for (const d of DESIGN) sliders[d.key].set(b[d.key]); sliders.d.setMax(maxDepth(b).toFixed(2)); $('notename').textContent = `· ${noteName(note)} ${noteFreq(note).toFixed(1)} Hz`; $('barnote').textContent = noteName(note); $('barstate').textContent = designs.get(note).manual ? 'edited' : 'auto-tuned'; showGrad(); } let pending = 0; function designEdited(k) { const b = { ...bar(), [k]: P[k] }; b.d = Math.min(b.d, maxDepth(b)); if (k !== 'd') sliders.d.set(b.d); sliders.d.setMax(maxDepth(b).toFixed(2)); designs.set(note, { b, manual: true }); $('barstate').textContent = 'edited'; if (!pending) pending = requestAnimationFrame(() => { pending = 0; rebuild(); }); } function retuneAll() { for (const [n, v] of [...designs]) if (!v.manual) designs.delete(n); selectNote(note); } $('autotune').onclick = () => { const b0 = bar(); const b = tuneDesign(note, mat(), targets(), b0); const nom = nominalDesign(note, mat()); 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; designs.set(note, { b, manual }); showDesign(); rebuild(); playStrike(); }; $('reset').onclick = () => { designs.delete(note); selectNote(note); playStrike(); }; // FE model of the selected bar, then the sound model function rebuild() { const b = bar(); const errs = validateDesign(b); $('warn').textContent = errs.join('; '); feModel = feBarModel(b, mat()); const fdOk = fdModel && fdModel.key === keyOf(b); $('source').querySelector('[value=FDTD]').disabled = !fdOk; if (!fdOk && $('source').value === 'FDTD') $('source').value = 'FE'; showCompare(fdOk); showPartials(); markKeys(); soundChanged(); updateInfo(); updateSfInfo(); } function soundModel() { const fdOk = fdModel && fdModel.key === keyOf(bar()); return $('source').value === 'FDTD' && fdOk ? fdModel : feModel; } function soundChanged() { prep = prepare(soundModel(), sound()); const b = bar(); const t = prep.tube; view.setScene(b, t ? { a: t.a * 1e3, L: t.L * 1e3, gap: P.gap } : null, micPos(b), feModel.nodes); view.setStrike(strikeF[0] * b.L, strikeF[1] * b.W); showStrike(); $('tubeinfo').textContent = t ? `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).` : 'No resonator: the bar radiates on its own.'; fillModeList(); drawPlots(); } $('source').addEventListener('change', () => soundChanged()); function showStrike() { const b = bar(); $('strikepos').textContent = `${(strikeF[0] * b.L).toFixed(0)}, ${(strikeF[1] * b.W).toFixed(0)} mm`; } function showPartials() { const f = ['B1', 'B2', 'B3'].map((l) => feModel.modes.find((m) => m.label === l)?.f ?? NaN); const e = partialErrors(f, note, targets()); const rows = e.map((x, i) => { const cls = !x.on ? 'muted' : Math.abs(x.cents) < 3 ? 'ok' : 'bad'; const err = x.on ? `${x.cents > 0 ? '+' : ''}${x.cents.toFixed(1)} ¢` : 'not tuned'; return `f${i + 1}${x.f.toFixed(1)} Hz${(x.f / f[0]).toFixed(2)}×${err}`; }); $('partials').innerHTML = `partialFEratiovs target${rows.join('')}`; } function fillModeList() { const sel = $('overlay'); const prev = sel.value; sel.innerHTML = '' + prep.modes.map((m, i) => ``).join(''); sel.value = prep.modes[prev] ? prev : '-1'; showOverlay(); } function showOverlay() { const i = parseInt($('overlay').value, 10); if (!prep || i < 0) { view.setOverlay(0, 0, null); return; } const m = prep.modes[i]; let mx = 0; for (const v of m.phi) mx = Math.max(mx, Math.abs(v)); view.setOverlay(prep.nx, prep.ny, Float32Array.from(m.phi, (v) => v / (mx || 1))); } $('overlay').addEventListener('change', showOverlay); // ---------- 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 playStrike() { if (!prep) return; const sr = audio().sampleRate; const b = bar(); const r = strike(prep, strikeF[0] * b.L, strikeF[1] * b.W, malletFor(note), sr); lastStrike = r; 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 (lastStrike) { series.push({ name: 'modal', ...spectrumDb(lastStrike.y, lastStrike.sr) }); waves.push({ name: 'modal', y: lastStrike.y, sr: lastStrike.sr }); } const marks = prep ? prep.modes.map((m) => m.f) : []; drawSpectrum($('spec'), series, marks, prep?.tube ? [prep.tube.fT, 3 * prep.tube.fT] : []); const full = $('wavespan').value === 'full'; drawWave($('wave'), waves, full ? null : 0.2); $('ringlen').textContent = lastStrike ? `${(lastStrike.y.length / lastStrike.sr).toFixed(2)} s rendered` : ''; } $('wavespan').addEventListener('change', () => { try { localStorage.setItem('mb-wavespan', $('wavespan').value); } catch {} drawPlots(); }); try { const v = localStorage.getItem('mb-wavespan'); if (v) $('wavespan').value = v; } catch {} // ---------- FDTD check ---------- function setBusy(b, label = '') { busy = b; for (const id of ['analyze', 'export', 'autotune']) $(id).disabled = b; $('cancel').hidden = !b; $('status').textContent = label; if (!b) $('bar').style.width = '0%'; } function updateInfo() { if (!navigator.gpu) return; const b = bar(); const dx = parseFloat($('dx').value); const f1 = feModel.modes.find((m) => m.label === 'B1')?.f ?? noteFreq(note); const { cells, steps } = analysisCost(b, mat(), dx, f1); const est = throughput ? `est. ${Math.round((cells * steps) / throughput)} s` : `roughly ${Math.max(1, Math.round((cells * steps) / 3e9))} s on a fast GPU`; const cen = b.h0 - b.d; $('info').textContent = `${(cells / 1e6).toFixed(2)} M cells · ${steps.toLocaleString()} steps · ${est}. ` + `Thinnest point ${cen.toFixed(1)} mm = ${(cen / dx).toFixed(1)} cells.`; } $('dx').addEventListener('change', updateInfo); function showCompare(ok) { if (!ok || !compareRows.length) { $('compare').innerHTML = fdModel && !ok ? 'Bar changed since the last FDTD analysis.' : ''; return; } const rows = compareRows.filter((r) => r.fe.f < 12000).map((r) => `${r.fe.label}${r.fe.f.toFixed(1)}${r.fd.f.toFixed(1)}${r.cents > 0 ? '+' : ''}${r.cents.toFixed(0)} ¢${r.fe.sigRad.toFixed(1)} / ${r.fd.sigRad.toFixed(1)}`); $('compare').innerHTML = `modeFE HzFDTD HzΔσ_rad FE/FDTD${rows.join('')}`; } async function analyze() { if (busy) return; const b = { ...bar() }; const dx = parseFloat($('dx').value); const f1 = feModel.modes.find((m) => m.label === 'B1')?.f ?? noteFreq(note); setBusy(true, 'Analyzing…'); cancel = false; try { const { cells, steps } = analysisCost(b, mat(), dx, f1); const t0 = performance.now(); const model = await analyzeBar(b, mat(), dx, f1, { isCancelled: () => cancel, onProgress: (label, frac, sec, fRun) => { $('bar').style.width = (frac * 100).toFixed(1) + '%'; const left = frac > 0.01 && frac < 1 ? ` · ${Math.round((sec / frac) * (1 - frac))} s left` : ''; $('status').textContent = `${label} ${frac < 1 ? (fRun * 100).toFixed(0) + '%' : ''}${left}`; }, }); if (!model) { setBusy(false, 'Cancelled.'); return; } throughput = (cells * steps) / model.seconds; model.key = keyOf(b); fdModel = model; compareRows = matchModes(feBarModel(b, mat()), model); const sec = ((performance.now() - t0) / 1000).toFixed(1); setBusy(false, `FDTD found ${model.modes.length} modes in ${sec} s. "Sound from" can now use them.`); rebuild(); } catch (e) { console.error(e); setBusy(false, 'Error: ' + e.message); } } $('analyze').onclick = analyze; $('cancel').onclick = () => (cancel = true); // ---------- 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 = sampledKeys(lo, hi, step).length; const edited = [...designs].filter(([n, v]) => v.manual && n >= lo && n <= hi).length; $('sfinfo').textContent = `${nKeys * LAYERS * VARIANTS} samples: ${nKeys} keys × ${LAYERS} velocity layers × ${VARIANTS} strike-point variations. ` + `Each sampled key is its own auto-tuned bar and tube${edited ? ` (${edited} edited bar${edited > 1 ? 's' : ''} in range are used as edited)` : ''}; ` + 'uses the current mallet (graduated if ticked), damping, resonator and strike point (as a fraction of the bar). FE modes.'; } for (const id of ['sflo', 'sfhi', 'sfstep']) $(id).addEventListener('input', updateSfInfo); async function doExport() { if (busy) return; setBusy(true, 'Rendering samples…'); try { const { lo, hi, step } = sfRange(); const name = $('sfname').value.trim() || 'Marimba'; const t0 = performance.now(); const r = await exportSF2({ lo, hi, step, name, sampleRate: 44100, mat: mat(), designFor, sound: { eta: P.eta, slope: P.slope, res: res() }, malletFor, strike: strikeF, onProgress: (f, k) => { $('bar').style.width = (f * 100).toFixed(1) + '%'; $('status').textContent = `Rendering ${noteName(k)} · ${(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); markKeys(); 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; $('strike').onclick = playStrike; window.addEventListener('keydown', (e) => { if (['INPUT', 'SELECT', 'TEXTAREA'].includes(e.target.tagName) && e.target.type !== 'range' && e.target.type !== 'checkbox') return; if (e.code === 'Space') { e.preventDefault(); playStrike(); } if (e.code === 'ArrowLeft' || e.code === 'ArrowRight') { if (e.target.type === 'range') return; e.preventDefault(); selectNote(note + (e.code === 'ArrowLeft' ? -1 : 1)); playStrike(); } }); window.addEventListener('resize', drawPlots); // for debugging in the console window.mb = { get prep() { return prep; }, get feModel() { return feModel; }, get fdModel() { return fdModel; }, get lastStrike() { return lastStrike; }, get lastExport() { return lastExport; }, designs, P }; // ---------- start ---------- // One fixed loudness scale (Pa -> full scale) so keys keep their relative loudness. { const b = designFor(60); const p0 = prepare(feBarModel(b, mat()), { note: 60, eta: P.eta, slope: P.slope, res: res() }); const r = strike(p0, b.L / 2, b.W / 2, { ...MALLETS.medium, v0: 1.5 }, 48000); let pk = 0; for (const v of r.y) pk = Math.max(pk, Math.abs(v)); gain = 0.3 / (pk || 1); } selectNote(60); if (!navigator.gpu) { $('analyze').disabled = true; $('info').textContent = 'WebGPU is not available in this browser (try Chrome or Safari 26+); the FE model still works.'; } $('status').textContent = 'Click the bar or a key to play. Each key is its own auto-tuned bar.';