// The time-domain engine: strings (two polarisations each) coupled at the bridge to the body modes, // plucked by a finger, stopped by a finger, heard through the body's radiation. // // String, modal form. A string of vibrating length L (stop/nut at x = 0, bridge at x = L) whose // bridge end moves with the bridge notch, w(t), in each polarisation: // u(x,t) = w(t) x/L + sum_n q_n(t) sin(n pi x / L) // From the Lagrangian (kinetic energy of string and body, tension + bending + body potential): // q_n'' + 2 s_n q_n' + w_n^2 q_n = (2 / mu L) G_n - g_n w'' g_n = 2 (-1)^(n+1) / (n pi) // eta_m'' + 2 z_m W_m eta_m' + W_m^2 eta_m = - sum_c B_cm [ T w_c/L + (mu L/2) sum_n g_n q_n'' + (mu L/3) w_c'' - F_dir,c ] // with w_c = sum_m B_cm eta_m (c = string x polarisation, B = the body's notch mode shapes by/bz). // The w'' mass coupling is solved exactly each step: everything is linear in the unknown notch // displacements w+ (one per string-polarisation, at most 8), and the matrix of that small system is // constant, so it is inverted once. Each oscillator uses a central-difference update with its // stiffness replaced by (2/k sin(w k/2))^2, which makes the discrete frequency exact and the scheme // stable for every mode below Nyquist. Per-mode damping s_n is Valette's (air + viscoelastic + floor). // // Geometric nonlinearity (Kirchhoff-Carrier): the tension rises by EA/(2L) int u_x^2 dx, summed // over both polarisations, explicit in time. // // Plucking finger: during the stick phase a pad (spring padK + dashpot padR, spread over padWidth) // is dragged at pullSpeed in the pull direction; when the contact force reaches the release force // for the velocity, the string slides off the pad and the force falls to zero as cos^2 over the // slip time. Stopping finger: a dashpot near the stop, implicit (it is very stiff in modal terms). // // String, FD form (engine.stringModel = "fd"): the same string as a finite-difference stiff string // with Bilbao's frequency-dependent loss (sigma0 + sigma1 beta^2, fitted to the Valette damping at // the fundamental and at 2 kHz), the bridge end node moving with the notch; its force on the bridge // (tension and bending shear at the end, plus half a cell of mass) enters the same notch solve. // // Output: p(t) = sum_m radRe_m eta_m'' - radIm_m W_m eta_m' (complex radiation at each mode's // frequency), computed at the internal rate and decimated. import type { Params } from "./params.ts"; import type { BodyMode, BodyModel } from "./types.ts"; import { N_STRINGS, STRING_OPEN_MIDI } from "./types.ts"; import { fingering, midiToHz, pluckForVelocity, stringConst, stringModes, valetteQinv, type Fingering, type StringConst } from "./strings.ts"; import { bandFrequency, decimate } from "./dsp.ts"; export interface RenderOpts { note: number; velocity: number; /** seconds of sound after the release (default p.engine.duration) */ duration?: number; /** seconds kept before the release (default 0.004) */ preRoll?: number; onProgress?: (frac: number) => void; /** explicit tuning (open-string tension factors, stopped-length factor); default: tuneByEar */ tuning?: Tuning; } export interface Tuning { tensionScale: number[]; lengthScale: number } export interface RenderResult { /** the output mix (mixOutput of mic and pickup), at p.engine.sampleRate */ audio: Float32Array; /** radiated pressure at the listener, Pa */ mic: Float32Array; /** bridge pickup, Pa-equivalent (pickupPaPerN per N of string force on the bridge) */ pickup: Float32Array; sampleRate: number; fingering: Fingering; releaseForce: number; slipTime: number; /** time from the start of the pull to the release, s */ stickTime: number; /** cpu time, s */ elapsed: number; modeCounts: { strings: number[]; body: number }; } /** One string-polarisation's contribution to the notch solve, common to modal and FD strings. */ interface StringPol { /** before the solve: given the finger force on this polarisation and the tension increase, compute P (k^2-scaled bracket, known part) */ pre(fingerF: number, dT: number): number; /** residual mass at the notch (constant), kg */ readonly m: number; /** after the solve: advance to n+1 given w+ */ post(wNext: number): void; /** displacement at the finger (weighted over the pad), current step and previous step */ uFinger(): number; uFingerPrev(): number; /** int u_x^2 dx (for the tension modulation) */ e2(): number; /** the notch displacement now and one step ago */ w: number; wPrev: number; } const HANN_PTS = 9; /** Pad weights: raised cosine over the pad width, normalised to sum 1. */ function padPoints(center: number, width: number, L: number): { x: number[]; wt: number[] } { const x: number[] = [], wt: number[] = []; let s = 0; for (let j = 0; j < HANN_PTS; j++) { const t = (j + 0.5) / HANN_PTS - 0.5; // -0.5..0.5 const v = 0.5 + 0.5 * Math.cos(2 * Math.PI * t); const xx = Math.min(L * 0.999, Math.max(L * 0.001, center + t * width)); x.push(xx); wt.push(v); s += v; } return { x, wt: wt.map((v) => v / s) }; } class ModalPol implements StringPol { N: number; q: Float64Array; qp: Float64Array; qn: Float64Array; a: Float64Array; om: Float64Array; inv: Float64Array; g: Float64Array; G2: Float64Array; fw: Float64Array; e: Float64Array; kn2: Float64Array; Ap: Float64Array; m: number; w = 0; wPrev = 0; private kappa: number; private k2: number; private muL2: number; private muL3: number; private L: number; private mu: number; private T: number; private xfOverL: number; private rho: number; private damp: boolean; private aD = 0; private bD = 0; private sEE: number; constructor(sc: StringConst, L: number, modes: { w: Float64Array; sigma: Float64Array }, k: number, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) { const N = modes.w.length; this.N = N; this.L = L; this.mu = sc.mu; this.T = sc.T; this.q = new Float64Array(N); this.qp = new Float64Array(N); this.qn = new Float64Array(N); this.a = new Float64Array(N); this.om = new Float64Array(N); this.inv = new Float64Array(N); this.g = new Float64Array(N); this.G2 = new Float64Array(N); this.fw = new Float64Array(N); this.e = new Float64Array(N); this.kn2 = new Float64Array(N); this.Ap = new Float64Array(N); this.k2 = k * k; this.kappa = (k * k * 2) / (sc.mu * L); this.muL2 = (sc.mu * L) / 2; this.muL3 = (sc.mu * L) / 3; this.xfOverL = finger ? finger.x.reduce((s, x, j) => s + x * finger.wt[j], 0) / L : 0; this.damp = !!stop && stop.r > 0; this.rho = stop ? stop.r / (2 * k) : 0; for (let n = 0; n < N; n++) { const nn = n + 1; const s = Math.sin((modes.w[n] * k) / 2); this.a[n] = 4 * s * s; // k^2 * wtilde^2 this.om[n] = 1 - modes.sigma[n] * k; this.inv[n] = 1 / (1 + modes.sigma[n] * k); this.g[n] = (2 * (nn % 2 === 1 ? 1 : -1)) / (nn * Math.PI); this.kn2[n] = (nn * Math.PI / L) ** 2; if (finger) { let v = 0; for (let j = 0; j < finger.x.length; j++) v += finger.wt[j] * Math.sin((nn * Math.PI * finger.x[j]) / L); this.fw[n] = v; } if (stop) this.e[n] = Math.sin((nn * Math.PI * stop.x) / L); } // stop damper elimination constants: F_d = aD + bD w+ let sEE = 0, sEG = 0; for (let n = 0; n < N; n++) { sEE += this.e[n] * this.e[n] * this.inv[n]; sEG += this.e[n] * this.g[n] * this.inv[n]; } this.sEE = sEE; const den = 1 + this.rho * this.kappa * sEE; this.bD = this.damp ? (this.rho * sEG) / den : 0; // Gamma_n = g_n - kappa e_n bD; beta = sum g inv Gamma let beta = 0; for (let n = 0; n < N; n++) { this.G2[n] = this.g[n] - this.kappa * this.e[n] * this.bD; beta += this.g[n] * this.inv[n] * this.G2[n]; } this.m = sc.mu * L * (1 / 3 - beta / 2); } pre(fingerF: number, dT: number): number { const { N, q, qp, a, om, g, kn2, fw, Ap, inv } = this; const k2 = this.k2, kap = this.kappa; const wTerm = -2 * this.w + this.wPrev; const nl = (k2 * dT) / this.mu; let alpha = 0, sGq = 0, sEA = 0, usPrev = 0; for (let n = 0; n < N; n++) { const qn = q[n]; const A = 2 * qn - om[n] * qp[n] - a[n] * qn - g[n] * wTerm + kap * fingerF * fw[n] - nl * kn2[n] * qn; Ap[n] = A; sGq += g[n] * (2 * qn - qp[n]); } if (this.damp) { const e = this.e; for (let n = 0; n < N; n++) { sEA += e[n] * Ap[n] * inv[n]; usPrev += e[n] * qp[n]; } this.aD = (-this.rho * (sEA - usPrev)) / (1 + this.rho * kap * this.sEE); const ka = kap * this.aD; for (let n = 0; n < N; n++) Ap[n] += ka * e[n]; } for (let n = 0; n < N; n++) alpha += g[n] * inv[n] * Ap[n]; const fDir = fingerF * this.xfOverL; return this.muL2 * (alpha - sGq) + this.muL3 * wTerm + k2 * (((this.T + dT) * this.w) / this.L - fDir); } post(wNext: number): void { const { N, Ap, G2, inv, qn } = this; for (let n = 0; n < N; n++) qn[n] = (Ap[n] - G2[n] * wNext) * inv[n]; const t = this.qp; this.qp = this.q; this.q = this.qn; this.qn = t; this.wPrev = this.w; this.w = wNext; } uFinger(): number { let s = 0; for (let n = 0; n < this.N; n++) s += this.fw[n] * this.q[n]; return s + this.w * this.xfOverL; } uFingerPrev(): number { let s = 0; for (let n = 0; n < this.N; n++) s += this.fw[n] * this.qp[n]; return s + this.wPrev * this.xfOverL; } e2(): number { let s = 0; for (let n = 0; n < this.N; n++) s += this.kn2[n] * this.q[n] * this.q[n]; return (s * this.L) / 2 + (this.w * this.w) / this.L; } } class FDPol implements StringPol { N: number; h: number; u: Float64Array; up: Float64Array; un: Float64Array; m: number; w = 0; wPrev = 0; private c2: number; private kap2: number; private s1: number; private k: number; private mu: number; private T: number; private EI: number; private den: Float64Array; private pc: Float64Array; private fwt: Float64Array; private fIdx: Int32Array; private fIdxN: number; constructor(sc: StringConst, L: number, k: number, courant: number, sig: { s0: number; s1: number }, finger: { x: number[]; wt: number[] } | null, stop: { x: number; r: number } | null) { this.k = k; this.mu = sc.mu; this.T = sc.T; this.EI = sc.EI; const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu; const a = c2 * k * k + 4 * sig.s1 * k; const hmin = Math.sqrt((a + Math.sqrt(a * a + 16 * kap2 * k * k)) / 2); const N = Math.max(8, Math.floor((L * courant) / hmin)); const h = L / N; this.N = N; this.h = h; this.c2 = c2; this.kap2 = kap2; this.s1 = sig.s1; this.u = new Float64Array(N + 1); this.up = new Float64Array(N + 1); this.un = new Float64Array(N + 1); this.den = new Float64Array(N + 1); this.pc = new Float64Array(N + 1); for (let l = 0; l <= N; l++) { this.den[l] = 1 + sig.s0 * k; this.pc[l] = 1 - sig.s0 * k; } if (stop && stop.r > 0) { const l = Math.max(1, Math.min(N - 1, Math.round(stop.x / h))); const extra = (stop.r * k) / (2 * sc.mu * h); this.den[l] += extra; this.pc[l] -= extra; } // finger weights onto nodes (linear interpolation of each pad point) const wt = new Float64Array(N + 1); if (finger) { for (let j = 0; j < finger.x.length; j++) { const xl = finger.x[j] / h, l0 = Math.floor(xl), fr = xl - l0; if (l0 >= 1 && l0 <= N - 1) wt[l0] += finger.wt[j] * (1 - fr); if (l0 + 1 >= 1 && l0 + 1 <= N - 1) wt[l0 + 1] += finger.wt[j] * fr; } } const idx: number[] = []; for (let l = 0; l <= N; l++) if (wt[l] !== 0) idx.push(l); this.fIdx = Int32Array.from(idx); this.fIdxN = idx.length; this.fwt = wt; this.m = (sc.mu * h) / 2; } private fF = 0; private dT = 0; pre(fingerF: number, dT: number): number { this.fF = fingerF; this.dT = dT; const { u, h, N } = this; const k2 = this.k * this.k; const uxxx = (-u[N - 2] + 2 * u[N - 1] - this.w) / (h * h * h); return k2 * (((this.T + dT) * (this.w - u[N - 1])) / h - this.EI * uxxx) + this.m * (-2 * this.w + this.wPrev); } post(wNext: number): void { const { u, up, un, N, h, den, pc } = this; const k = this.k, k2 = k * k; const lam2 = ((this.c2 + this.dT / this.mu) * k2) / (h * h); const mu2 = (this.kap2 * k2) / (h * h * h * h); const sx = (2 * this.s1 * k) / (h * h); const fsc = (k2 * this.fF) / (this.mu * h); const w = this.w; // ghost values: u[-1] = -u[1], u[N+1] = 2 w - u[N-1]; same for the previous step const at = (arr: Float64Array, l: number, wv: number) => (l < 0 ? -arr[-l] : l > N ? 2 * wv - arr[2 * N - l] : arr[l]); for (let l = 1; l < N; l++) { const ul = u[l]; const dxx = u[l + 1] - 2 * ul + u[l - 1]; const dxxp = up[l + 1] - 2 * up[l] + up[l - 1]; let d4: number; if (l >= 2 && l <= N - 2) d4 = u[l + 2] - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + u[l - 2]; else d4 = at(u, l + 2, w) - 4 * u[l + 1] + 6 * ul - 4 * u[l - 1] + at(u, l - 2, w); un[l] = (2 * ul - pc[l] * up[l] + lam2 * dxx - mu2 * d4 + sx * (dxx - dxxp) + fsc * this.fwt[l]) / den[l]; } un[0] = 0; un[N] = wNext; this.up = u; this.u = un; this.un = up; this.wPrev = this.w; this.w = wNext; } uFinger(): number { let s = 0; for (let j = 0; j < this.fIdxN; j++) { const l = this.fIdx[j]; s += this.fwt[l] * this.u[l]; } return s; } uFingerPrev(): number { let s = 0; for (let j = 0; j < this.fIdxN; j++) { const l = this.fIdx[j]; s += this.fwt[l] * this.up[l]; } return s; } e2(): number { let s = 0; for (let l = 0; l < this.N; l++) { const d = this.u[l + 1] - this.u[l]; s += d * d; } return s / this.h; } } /** * Bilbao loss parameters sigma0, sigma1 (decay sigma0 + sigma1 beta^2) fitted to the Valette * damping of the string's partials from f1 up to fTop, minimising the relative error. The FD loss * grows as f^2 at high frequency while Valette's floor makes it ~ f, so this is a compromise; the * modal string reproduces Valette exactly. */ function fitFDLoss(p: Params, sc: StringConst, f1: number, fTop: number): { s0: number; s1: number } { const c2 = sc.T / sc.mu, kap2 = sc.EI / sc.mu; const beta2 = (f: number) => { const w = 2 * Math.PI * f; return (-c2 + Math.sqrt(c2 * c2 + 4 * kap2 * w * w)) / (2 * kap2); }; // minimise sum_n w_n ((s0 + s1 b_n) / sig_n - 1)^2, b_n = beta^2, w_n = 1/n (the low partials carry the sustain) let a11 = 0, a12 = 0, a22 = 0, r1 = 0, r2 = 0; for (let n = 1; n * f1 <= fTop; n++) { const f = n * f1, sg = Math.PI * f * valetteQinv(p, sc, f), b = beta2(f), wn = 1 / n; const u = 1 / sg, v = b / sg; a11 += wn * u * u; a12 += wn * u * v; a22 += wn * v * v; r1 += wn * u; r2 += wn * v; } const det = a11 * a22 - a12 * a12; let s0 = (r1 * a22 - r2 * a12) / det, s1 = (a11 * r2 - a12 * r1) / det; if (s1 < 0) { s1 = 0; s0 = r1 / a11; } if (s0 < 0) { s0 = 0; s1 = r2 / a22; } return { s0, s1 }; } export function renderNote(p: Params, body: BodyModel, o: RenderOpts): RenderResult { const t0 = performance.now(); const fs = p.engine.sampleRate; const os = Math.max(1, Math.round(p.engine.oversample)); const fsi = fs * os, k = 1 / fsi; const fmaxStr = Math.min(p.engine.stringFmax, 0.3 * fsi); const fing = fingering(p, o.note); const { force: fRel, slip } = pluckForVelocity(p, o.velocity); const duration = o.duration ?? p.engine.duration; const preRoll = o.preRoll ?? 0.004; // ---- body const bm = thinModes(body.modes.filter((m) => m.f > 0 && m.f < 0.45 * fsi), p.engine.bodyOverlap); const M = bm.length; const bA = new Float64Array(M), bOm = new Float64Array(M), bInv = new Float64Array(M); const rr = new Float64Array(M), ri = new Float64Array(M); for (let m = 0; m < M; m++) { const wm = 2 * Math.PI * bm[m].f; const s = Math.sin((wm * k) / 2); const sk = bm[m].zeta * wm * k; bA[m] = 4 * s * s; bOm[m] = 1 - sk; bInv[m] = 1 / (1 + sk); rr[m] = bm[m].radRe / (k * k); ri[m] = (bm[m].radIm * wm) / (2 * k); } // ---- tuning by ear (see tuneByEar): tension of the open strings, length of the stopped note const L0 = p.strings.scaleLength; const tuning = o.tuning ?? (p.engine.intonate ? tuneByEar(p, body, fing) : null); const tensionScale = tuning ? tuning.tensionScale : [1, 1, 1, 1]; if (tuning && fing.stopped) fing.length *= tuning.lengthScale; // ---- strings: the played one, and the other open strings if sympathetic const finger = padPoints(fing.length - p.pluck.position, p.pluck.padWidth, fing.length); // keep the pluck point on the string for short (high) notes: at most 40 % of the length from the bridge if (p.pluck.position > 0.4 * fing.length) { const pp = padPoints(0.6 * fing.length, Math.min(p.pluck.padWidth, 0.1 * fing.length), fing.length); finger.x = pp.x; finger.wt = pp.wt; } const pols: StringPol[] = []; const polString: number[] = []; const polDir: number[] = []; // 0 = y (vertical), 1 = z (lateral) const active: number[] = [fing.string]; if (p.engine.sympathetic) for (let i = 0; i < N_STRINGS; i++) if (i !== fing.string) active.push(i); const strModeCounts: number[] = []; const muteSigma = 25 * p.engine.sympatheticMute; const scs: StringConst[] = []; const Ls: number[] = []; for (const si of active) { const sc0 = stringConst(p, si); const sc: StringConst = { ...sc0, T: sc0.T * tensionScale[si] }; const played = si === fing.string; const L = played ? fing.length : L0; const stop = played && fing.stopped && p.stop.damping > 0 ? { x: p.stop.offset, r: p.stop.damping } : null; const extra = played ? 0 : muteSigma; scs[si] = sc; Ls[si] = L; for (let dir = 0; dir < 2; dir++) { if (p.engine.stringModel === "fd") { const f1 = Math.sqrt(sc.T / sc.mu) / (2 * L); const sig = fitFDLoss(p, sc, f1, 1500); sig.s0 += extra; pols.push(new FDPol(sc, L, k, p.engine.fdCourant, sig, played ? finger : null, stop)); if (dir === 0) strModeCounts.push((pols[pols.length - 1] as FDPol).N); } else { const modes = stringModes(p, sc, L, played ? fmaxStr : Math.min(fmaxStr, 5000), extra); pols.push(new ModalPol(sc, L, modes, k, played ? finger : null, stop)); if (dir === 0) strModeCounts.push(modes.w.length); } polString.push(si); polDir.push(dir); } } const C = pols.length; // notch mode shapes per string-polarisation, stored mode-major: BT[m*C + c] const BT = new Float64Array(C * M); for (let c = 0; c < C; c++) for (let m = 0; m < M; m++) BT[m * C + c] = polDir[c] === 0 ? bm[m].by[polString[c]] : bm[m].bz[polString[c]]; // Phi_dc = sum_m B_dm B_cm inv_m ; system (I + Phi diag(m)) w+ = SB - Phi P const Phi = new Float64Array(C * C); for (let m = 0; m < M; m++) for (let d = 0; d < C; d++) for (let c = 0; c < C; c++) Phi[d * C + c] += BT[m * C + d] * BT[m * C + c] * bInv[m]; const Ms = new Float64Array(C * C); for (let d = 0; d < C; d++) for (let c = 0; c < C; c++) Ms[d * C + c] = (d === c ? 1 : 0) + Phi[d * C + c] * pols[c].m; const Minv = invert(Ms, C); // ---- finger const ang = (p.pluck.angleDeg * Math.PI) / 180; const dirY = -Math.sin(ang), dirZ = Math.cos(ang); // pull: sideways, slightly into the board (-y) const iy = 0, iz = 1; // the played string is first in `active`, so its pols are 0 (y) and 1 (z) let phase: 0 | 1 | 2 = 0; // 0 stick, 1 slip, 2 free let tRel = -1, relFy = 0, relFz = 0; const maxStick = 0.25; const eta = new Float64Array(M), etaP = new Float64Array(M), etaN = new Float64Array(M); const Bm = new Float64Array(M); const P = new Float64Array(C), SB = new Float64Array(C), rhs = new Float64Array(C), wN = new Float64Array(C), fc = new Float64Array(C); // pickup: a bridge piezo reading the strings' force on the bridge (vertical + a share of lateral), // in Pa-equivalent (pickupPaPerN per newton) so it mixes with the microphone at comparable level const pickY = 1, pickZ = p.output.pickupLateral; const pickScale = p.output.pickupPaPerN / (k * k); const preSteps = Math.round(preRoll * fsi); const postSteps = Math.round(duration * fsi); const maxSteps = Math.round(maxStick * fsi) + postSteps + 1; const ring = new Float64Array(preSteps + 1), ring2 = new Float64Array(preSteps + 1); let ringPos = 0; const out = new Float64Array(preSteps + postSteps), out2 = new Float64Array(preSteps + postSteps); let outN = 0; let relStep = -1; const nonlinear = p.engine.nonlinear; const dTs = new Float64Array(N_STRINGS); let cur = eta, prev = etaP, next = etaN; let lastProg = 0; for (let step = 0; step < maxSteps; step++) { const t = step * k; // tension modulation per active string if (nonlinear) { for (let c = 0; c < C; c += 2) { const si = polString[c]; dTs[si] = (scs[si].EA / (2 * Ls[si])) * (pols[c].e2() + pols[c + 1].e2()); } } // finger force let Fy = 0, Fz = 0; if (phase === 0) { const X = p.pluck.pullSpeed * t; const uy = pols[iy].uFinger(), uz = pols[iz].uFinger(); const vy = (uy - pols[iy].uFingerPrev()) / k, vz = (uz - pols[iz].uFingerPrev()) / k; Fy = p.pluck.padK * (X * dirY - uy) + p.pluck.padR * (p.pluck.pullSpeed * dirY - vy); Fz = p.pluck.padK * (X * dirZ - uz) + p.pluck.padR * (p.pluck.pullSpeed * dirZ - vz); const F = Math.hypot(Fy, Fz); if (F >= fRel || t >= maxStick) { phase = 1; tRel = t; relStep = step; const s = fRel / Math.max(F, 1e-12); relFy = Fy * s; relFz = Fz * s; Fy = relFy; Fz = relFz; } } else if (phase === 1) { const x = (t - tRel) / slip; if (x >= 1) { phase = 2; } else { const cc = Math.cos((Math.PI / 2) * x); Fy = relFy * cc * cc; Fz = relFz * cc * cc; } } // strings: known parts for (let c = 0; c < C; c++) { const ff = c === iy ? Fy : c === iz ? Fz : 0; P[c] = pols[c].pre(ff, nonlinear ? dTs[polString[c]] : 0); } // body: known parts, and SB_d = sum_m B_dm Bm_m inv_m SB.fill(0); for (let m = 0; m < M; m++) { const b = 2 * cur[m] - bOm[m] * prev[m] - bA[m] * cur[m]; Bm[m] = b; const bi = b * bInv[m], o = m * C; for (let d = 0; d < C; d++) SB[d] += BT[o + d] * bi; } for (let d = 0; d < C; d++) { let s = SB[d]; for (let c = 0; c < C; c++) s -= Phi[d * C + c] * P[c]; rhs[d] = s; } for (let d = 0; d < C; d++) { let s = 0; for (let c = 0; c < C; c++) s += Minv[d * C + c] * rhs[c]; wN[d] = s; } // string forces on the bridge (k^2-scaled, sign: bracket = -k^2 F), body update, output let pick = 0; for (let c = 0; c < C; c++) { fc[c] = P[c] + pols[c].m * wN[c]; pick += fc[c] * (polDir[c] === 0 ? pickY : pickZ); } let pr = 0; for (let m = 0; m < M; m++) { let v = Bm[m]; const o = m * C; for (let c = 0; c < C; c++) v -= BT[o + c] * fc[c]; const en = v * bInv[m]; next[m] = en; pr += rr[m] * (en - 2 * cur[m] + prev[m]) - ri[m] * (en - prev[m]); } const pk = -pick * pickScale; for (let c = 0; c < C; c++) pols[c].post(wN[c]); const tmp = prev; prev = cur; cur = next; next = tmp; // output: keep a ring of the last preSteps samples until the release, then record if (relStep < 0) { ring[ringPos] = pr; ring2[ringPos] = pk; ringPos = (ringPos + 1) % (preSteps + 1); } else { if (outN === 0) { // flush the pre-roll (oldest first) for (let j = 0; j < preSteps; j++) { const q = (ringPos + 1 + j) % (preSteps + 1); out[outN] = ring[q]; out2[outN++] = ring2[q]; } } out[outN] = pr; out2[outN++] = pk; if (outN >= out.length) break; } if (o.onProgress && relStep >= 0) { const fr = outN / out.length; if (fr - lastProg > 0.02) { lastProg = fr; o.onProgress(fr); } } } const mic = Float32Array.from(decimate(out.subarray(0, outN), os)); const pickup = Float32Array.from(decimate(out2.subarray(0, outN), os)); return { audio: mixOutput(p, mic, pickup), mic, pickup, sampleRate: fs, fingering: fing, releaseForce: fRel, slipTime: slip, stickTime: tRel, elapsed: (performance.now() - t0) / 1000, modeCounts: { strings: strModeCounts, body: M }, }; } /** * Tuning by ear. The bridge gives under the string (spring-like below the body resonances, so the * pitch goes flat; strongly near them), so a player tunes the open strings and places the stopping * finger by ear. Here: short quiet calibration renders (linear, otherwise as the real render, * including the sympathetic strings, which load the bridge too) measure the first partial; the open * strings' tensions (all four, two passes) and then the stopped length are corrected. Cached per body * and string set-up. */ const tuneCache = new Map(); export function tuneByEar(p: Params, body: BodyModel, fing: Fingering): Tuning { const bodyKey = `${body.modes.length}:${body.modes.slice(0, 40).reduce((s, m) => s + m.f * 1.7 + m.by[0] * 3.1 + m.bz[3] * 0.7, 0)}`; const q = cloneForTuning(p); const base = JSON.stringify([bodyKey, q.engine, q.strings, q.pluck.angleDeg, q.pluck.position, q.stop, q.fe.stringSpacing]); const measure = (note: number, tuning: Tuning) => { const r = renderNote(q, body, { note, velocity: 40, duration: 1.1, tuning }); return bandFrequency(r.audio, r.sampleRate, midiToHz(note), 0.25, 0.85); }; // open strings: all four together (they load the bridge for each other), two passes const openKey = `${base}|open`; let tensionScale = tuneCache.get(openKey) as number[] | undefined; if (!tensionScale) { tensionScale = [1, 1, 1, 1]; for (let it = 0; it < 2; it++) { for (let si = 0; si < N_STRINGS; si++) { const note = STRING_OPEN_MIDI[si]; const f = measure(note, { tensionScale: [...tensionScale], lengthScale: 1 }); if (f > 0) tensionScale[si] *= Math.pow(midiToHz(note) / f, 2); } } tuneCache.set(openKey, tensionScale); } let lengthScale = 1; if (fing.stopped) { const note = STRING_OPEN_MIDI[fing.string] + fing.shift; const key = `${base}|note${note}`; const cached = tuneCache.get(key) as number | undefined; if (cached !== undefined) lengthScale = cached; else { for (let it = 0; it < 2; it++) { const f = measure(note, { tensionScale, lengthScale }); if (!(f > 0)) break; lengthScale *= f / midiToHz(note); } tuneCache.set(key, lengthScale); } } return { tensionScale, lengthScale }; } function cloneForTuning(p: Params): Params { const q = JSON.parse(JSON.stringify(p)) as Params; q.engine.nonlinear = false; q.engine.oversample = 1; q.engine.intonate = false; // only the first partial matters here: fewer string modes and body modes q.engine.stringFmax = 2500; q.engine.bodyOverlap = Math.max(1, q.engine.bodyOverlap / 2); return q; } /** * Where the body's modal overlap (half-power bandwidth x modal density) is high, individual modes * cannot be told apart, so the engine can use fewer of them: in 1/6-octave bands, keep every k-th * mode with k = floor(overlap / target), and scale its notch coupling by sqrt(k). That keeps the * band's mean bridge admittance (sum of b^2) and radiated power (sum of b^2 rad^2), and leaves the * overlap at about `target`, so the response stays smooth. target <= 0 keeps every mode. */ export function thinModes(modes: BodyMode[], target: number): BodyMode[] { if (!(target > 0)) return modes; const sorted = [...modes].sort((a, b) => a.f - b.f); const out: BodyMode[] = []; let i = 0; while (i < sorted.length) { const f0 = sorted[i].f, f1 = f0 * Math.pow(2, 1 / 6); let j = i; while (j < sorted.length && sorted[j].f < f1) j++; const band = sorted.slice(i, j); const fc = Math.sqrt(f0 * f1), dens = band.length / (f1 - f0); const meanZeta = band.reduce((s, m) => s + m.zeta, 0) / band.length; const overlap = dens * 2 * meanZeta * fc; const k = Math.max(1, Math.floor(overlap / target)); if (k === 1 || band.length < 2 * k) out.push(...band); else { const g = Math.sqrt(k); for (let q = Math.floor(k / 2); q < band.length; q += k) { const m = band[q]; out.push({ ...m, by: m.by.map((v) => v * g), bz: m.bz.map((v) => v * g) }); } } i = j; } return out; } /** The output: micMix * mic + pickupMix * pickup (with its trim), times the output gain. */ export function mixOutput(p: Params, mic: Float32Array, pickup: Float32Array): Float32Array { const g = Math.pow(10, p.output.gainDb / 20); const a = p.output.micMix * g, b = p.output.pickupMix * Math.pow(10, p.output.pickupGainDb / 20) * g; const y = new Float32Array(mic.length); for (let i = 0; i < y.length; i++) y[i] = a * mic[i] + b * pickup[i]; return y; } /** Small dense matrix inverse (Gauss-Jordan with partial pivoting). */ function invert(A: Float64Array, n: number): Float64Array { const a = Float64Array.from(A); const inv = new Float64Array(n * n); for (let i = 0; i < n; i++) inv[i * n + i] = 1; for (let col = 0; col < n; col++) { let piv = col; for (let r = col + 1; r < n; r++) if (Math.abs(a[r * n + col]) > Math.abs(a[piv * n + col])) piv = r; if (piv !== col) for (let j = 0; j < n; j++) { [a[col * n + j], a[piv * n + j]] = [a[piv * n + j], a[col * n + j]]; [inv[col * n + j], inv[piv * n + j]] = [inv[piv * n + j], inv[col * n + j]]; } const d = a[col * n + col]; for (let j = 0; j < n; j++) { a[col * n + j] /= d; inv[col * n + j] /= d; } for (let r = 0; r < n; r++) if (r !== col) { const f = a[r * n + col]; if (f === 0) continue; for (let j = 0; j < n; j++) { a[r * n + j] -= f * a[col * n + j]; inv[r * n + j] -= f * inv[col * n + j]; } } } return inv; }