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 `