/ proof-of-concept / bead-percussion
Sign in
proof-of-concept / bead-percussion
bead-percussion / src / sim / solver.ts
728 lines · 25.9 KBBlameHistoryRaw
1// Time integration of the bead system.
2//
3// The conservative part (springs, external force pulses) is integrated with
4// velocity Verlet, optionally composed into Yoshida's fourth-order scheme.
5// Damping (friction and dashpots) is linear in the velocities, dv/dt = -A v,
6// and is applied as a separate exact step v <- exp(-tau A) v, once per audio
7// sample (Strang splitting over the sample interval Delta = 1/fs). The
8// splitting error is second order in Delta and scales with the damping rate,
9// which is small compared with the oscillation frequencies; the conservative
10// part is second order (Verlet) or fourth order (Yoshida) in the step h.
12import { angleDiff, hingeAngle } from "./hinge";
13import { prepare } from "./prepare";
14import type { BeadSystem, Method, Modes, SimResult } from "./types";
16const YOSHIDA_W1 = 1 / (2 - Math.cbrt(2));
17const YOSHIDA_W0 = -Math.cbrt(2) * YOSHIDA_W1;
19export function stepCoefficients(method: Method): number[] {
20 return method === "yoshida4" ? [YOSHIDA_W1, YOSHIDA_W0, YOSHIDA_W1] : [1];
23// Largest h*omega for which the method is stable on x'' = -omega^2 x.
24export function stabilityLimit(method: Method): number {
25 if (method === "verlet") return 2;
26 const cs = stepCoefficients(method);
27 const stable = (h: number) => {
28 // transfer matrix of one full step for omega = 1
29 let m = [1, 0, 0, 1]; // [x<-x, x<-v, v<-x, v<-v]
30 const mul = (a: number[], b: number[]) => [
31 a[0] * b[0] + a[1] * b[2],
32 a[0] * b[1] + a[1] * b[3],
33 a[2] * b[0] + a[3] * b[2],
34 a[2] * b[1] + a[3] * b[3],
35 ];
36 for (const c of cs) {
37 const kick = [1, 0, (-c * h) / 2, 1];
38 const drift = [1, c * h, 0, 1];
39 m = mul(kick, mul(drift, mul(kick, m)));
40 }
41 return Math.abs(m[0] + m[3]) < 2;
42 };
43 let h = 1e-3;
44 while (stable(h + 1e-3)) h += 1e-3;
45 return h;
48// Error of the numerical oscillation frequency for x'' = -omega^2 x, in cents
49// (positive: the simulated tone is sharp).
50export function frequencyErrorCents(method: Method, omega: number, h: number): number {
51 let m = [1, 0, 0, 1];
52 const mul = (a: number[], b: number[]) => [
53 a[0] * b[0] + a[1] * b[2],
54 a[0] * b[1] + a[1] * b[3],
55 a[2] * b[0] + a[3] * b[2],
56 a[2] * b[1] + a[3] * b[3],
57 ];
58 for (const c of stepCoefficients(method)) {
59 const kick = [1, 0, (-c * h * omega * omega) / 2, 1];
60 const drift = [1, c * h, 0, 1];
61 m = mul(kick, mul(drift, mul(kick, m)));
62 }
63 const half = (m[0] + m[3]) / 2;
64 if (Math.abs(half) >= 1) return NaN;
65 const omegaNum = Math.acos(half) / h;
66 return 1200 * Math.log2(omegaNum / omega);
69export interface SimOptions {
70 modes?: Modes | null;
71 onProgress?: (t: number) => void;
72 // called at every frame record with the full-precision state (do not keep the arrays)
73 onFrame?: (frame: number, t: number, x: Float64Array, v: Float64Array) => void;
74 maxAnimBytes?: number;
77export function simulate(sys: BeadSystem, opts: SimOptions = {}): SimResult {
78 const t0 = performance.now();
79 const warnings: string[] = [];
80 const { n, mass, pinned } = sys;
81 const N3 = 3 * n;
82 const x = new Float64Array(sys.pos0);
83 const v = new Float64Array(N3);
84 const F = new Float64Array(N3);
85 const invm = new Float64Array(n);
86 for (let i = 0; i < n; i++) invm[i] = pinned[i] ? 0 : 1 / mass[i];
88 // ---- forces ------------------------------------------------------------
89 const { si, sj, sk, sL0, sk3, bi, bj, bk, bkb, bcb, hi, hj, hk, hl, hkh, hch, hth0 } = sys;
90 const nhg = hi.length;
91 const hg = new Float64Array(12 * nhg); // hinge gradients, refreshed where needed
92 const hb = (h: number) => [hi[h], hj[h], hk[h], hl[h]]; // the hinge's beads, in gradient order
93 const ns = si.length;
94 const nb = bi.length;
95 const internalForces = (): number => {
96 F.fill(0);
97 let pe = 0;
98 for (let s = 0; s < ns; s++) {
99 const i3 = 3 * si[s];
100 const j3 = 3 * sj[s];
101 const dx = x[j3] - x[i3];
102 const dy = x[j3 + 1] - x[i3 + 1];
103 const dz = x[j3 + 2] - x[i3 + 2];
104 const L = Math.sqrt(dx * dx + dy * dy + dz * dz);
105 const e = L - sL0[s];
106 const k = sk[s];
107 const k3 = sk3[s];
108 const e2 = e * e;
109 pe += 0.5 * k * e2 + 0.25 * k3 * e2 * e2;
110 const g = (k * e + k3 * e2 * e) / L;
111 F[i3] += g * dx;
112 F[i3 + 1] += g * dy;
113 F[i3 + 2] += g * dz;
114 F[j3] -= g * dx;
115 F[j3 + 1] -= g * dy;
116 F[j3 + 2] -= g * dz;
117 }
118 for (let b = 0; b < nb; b++) {
119 const i3 = 3 * bi[b];
120 const j3 = 3 * bj[b];
121 const k3 = 3 * bk[b];
122 const kb = bkb[b];
123 const d0 = x[i3] - 2 * x[j3] + x[k3];
124 const d1 = x[i3 + 1] - 2 * x[j3 + 1] + x[k3 + 1];
125 const d2 = x[i3 + 2] - 2 * x[j3 + 2] + x[k3 + 2];
126 pe += 0.5 * kb * (d0 * d0 + d1 * d1 + d2 * d2);
127 F[i3] -= kb * d0;
128 F[i3 + 1] -= kb * d1;
129 F[i3 + 2] -= kb * d2;
130 F[j3] += 2 * kb * d0;
131 F[j3 + 1] += 2 * kb * d1;
132 F[j3 + 2] += 2 * kb * d2;
133 F[k3] -= kb * d0;
134 F[k3 + 1] -= kb * d1;
135 F[k3 + 2] -= kb * d2;
136 }
137 for (let h = 0; h < nhg; h++) {
138 const o = 12 * h;
139 const d = angleDiff(hingeAngle(x, hi[h], hj[h], hk[h], hl[h], hg, o), hth0[h]);
140 pe += 0.5 * hkh[h] * d * d;
141 const s = hkh[h] * d;
142 const i3 = 3 * hi[h], j3 = 3 * hj[h], k3 = 3 * hk[h], l3 = 3 * hl[h];
143 F[i3] -= s * hg[o];
144 F[i3 + 1] -= s * hg[o + 1];
145 F[i3 + 2] -= s * hg[o + 2];
146 F[j3] -= s * hg[o + 3];
147 F[j3 + 1] -= s * hg[o + 4];
148 F[j3 + 2] -= s * hg[o + 5];
149 F[k3] -= s * hg[o + 6];
150 F[k3 + 1] -= s * hg[o + 7];
151 F[k3 + 2] -= s * hg[o + 8];
152 F[l3] -= s * hg[o + 9];
153 F[l3 + 1] -= s * hg[o + 10];
154 F[l3 + 2] -= s * hg[o + 11];
155 }
156 return pe;
157 };
158 const pulses = sys.hits.filter(h => h.duration > 0);
159 const externalForces = (t: number) => {
160 for (const p of pulses) {
161 const u = (t - p.t) / p.duration;
162 if (u <= 0 || u >= 1) continue;
163 const w = 0.5 * (1 - Math.cos(2 * Math.PI * u));
164 for (const b of p.beads) {
165 F[3 * b] += w * p.force[0];
166 F[3 * b + 1] += w * p.force[1];
167 F[3 * b + 2] += w * p.force[2];
168 }
169 }
170 };
172 // ---- rest state checks and time step (shared with the GPU solver) ----------
173 let pe = internalForces();
174 const prep = prepare(sys);
175 const { peRest, residualForce, maxTension, omegaMax, substeps, h, nSamples } = prep;
176 warnings.push(...prep.warnings);
177 const fs = sys.sampleRate;
178 const nSteps = nSamples * substeps;
179 const cs = stepCoefficients(sys.method);
181 // ---- damping: v <- exp(-tau A) v ------------------------------------------
182 // dashpots with c = ca = 0 are dropped
183 const keepD = Array.from(sys.dc.keys()).filter(d => sys.dc[d] !== 0 || sys.dca[d] !== 0);
184 const di = Int32Array.from(keepD, d => sys.di[d]);
185 const dj = Int32Array.from(keepD, d => sys.dj[d]);
186 const dc = Float64Array.from(keepD, d => sys.dc[d]);
187 const dca = Float64Array.from(keepD, d => sys.dca[d]);
188 const axialDamped = dca.some(c => c > 0);
189 const dd = new Float64Array(3 * dca.length); // dashpot directions, refreshed where needed
190 const { friction } = sys;
191 const nd = di.length;
192 let normA = 0; // infinity-norm bound of A
193 {
194 const row = new Float64Array(n);
195 for (let i = 0; i < n; i++) row[i] = friction[i];
196 for (let d = 0; d < nd; d++) {
197 row[di[d]] += 2 * dc[d];
198 row[dj[d]] += 2 * dc[d];
199 row[di[d]] += 2 * dca[d];
200 row[dj[d]] += 2 * dca[d];
201 }
202 for (let b = 0; b < nb; b++) {
203 row[bi[b]] += 4 * bcb[b];
204 row[bj[b]] += 8 * bcb[b];
205 row[bk[b]] += 4 * bcb[b];
206 }
207 for (let i = 0; i < n; i++) normA = Math.max(normA, row[i] * invm[i]);
208 }
209 const hingeDamped = hch.some(c => c > 0);
210 const hasDamping = normA > 0 || hingeDamped;
211 const frictionOnly = dc.every(c => c === 0) && !axialDamped && bcb.every(c => c === 0) && !hingeDamped; // then exp(-tau A) is diagonal
212 // Hinge damping depends on the configuration through grad theta, so its
213 // gradients (and its part of the norm bound) are refreshed at the current
214 // positions before each damping step; positions do not change during it.
215 let normAh = 0;
216 const hingeRow = new Float64Array(n);
217 const refreshHinges = () => {
218 if (axialDamped) {
219 for (let d = 0; d < dca.length; d++) {
220 const i3 = 3 * di[d];
221 const j3 = 3 * dj[d];
222 const e0 = x[j3] - x[i3];
223 const e1 = x[j3 + 1] - x[i3 + 1];
224 const e2 = x[j3 + 2] - x[i3 + 2];
225 const L = Math.sqrt(e0 * e0 + e1 * e1 + e2 * e2) || 1;
226 dd[3 * d] = e0 / L;
227 dd[3 * d + 1] = e1 / L;
228 dd[3 * d + 2] = e2 / L;
229 }
230 }
231 if (!hingeDamped) return;
232 hingeRow.fill(0);
233 const row = hingeRow;
234 for (let h = 0; h < nhg; h++) {
235 const o = 12 * h;
236 hingeAngle(x, hi[h], hj[h], hk[h], hl[h], hg, o);
237 let total = 0;
238 for (let q = 0; q < 12; q++) total += Math.abs(hg[o + q]);
239 const c = hch[h] * total;
240 row[hi[h]] += c * (Math.abs(hg[o]) + Math.abs(hg[o + 1]) + Math.abs(hg[o + 2]));
241 row[hj[h]] += c * (Math.abs(hg[o + 3]) + Math.abs(hg[o + 4]) + Math.abs(hg[o + 5]));
242 row[hk[h]] += c * (Math.abs(hg[o + 6]) + Math.abs(hg[o + 7]) + Math.abs(hg[o + 8]));
243 row[hl[h]] += c * (Math.abs(hg[o + 9]) + Math.abs(hg[o + 10]) + Math.abs(hg[o + 11]));
244 }
245 normAh = 0;
246 for (let i = 0; i < n; i++) normAh = Math.max(normAh, row[i] * invm[i]);
247 };
248 const term = new Float64Array(N3);
249 const tmp = new Float64Array(N3);
250 const fa = new Float64Array(n);
251 for (let i = 0; i < n; i++) fa[i] = friction[i] * invm[i];
252 const applyA = (w: Float64Array, out: Float64Array) => {
253 for (let i = 0; i < n; i++) {
254 const a = fa[i];
255 out[3 * i] = a * w[3 * i];
256 out[3 * i + 1] = a * w[3 * i + 1];
257 out[3 * i + 2] = a * w[3 * i + 2];
258 }
259 for (let d = 0; d < nd; d++) {
260 const i3 = 3 * di[d];
261 const j3 = 3 * dj[d];
262 const r0 = w[i3] - w[j3];
263 const r1 = w[i3 + 1] - w[j3 + 1];
264 const r2 = w[i3 + 2] - w[j3 + 2];
265 // force on i: -c r - ca (d . r) d, with r = w_i - w_j
266 let f0 = dc[d] * r0;
267 let f1 = dc[d] * r1;
268 let f2 = dc[d] * r2;
269 if (dca[d] !== 0) {
270 const u0 = dd[3 * d], u1 = dd[3 * d + 1], u2 = dd[3 * d + 2];
271 const s = dca[d] * (u0 * r0 + u1 * r1 + u2 * r2);
272 f0 += s * u0;
273 f1 += s * u1;
274 f2 += s * u2;
275 }
276 const mi = invm[di[d]];
277 const mj = invm[dj[d]];
278 out[i3] += mi * f0;
279 out[i3 + 1] += mi * f1;
280 out[i3 + 2] += mi * f2;
281 out[j3] -= mj * f0;
282 out[j3 + 1] -= mj * f1;
283 out[j3 + 2] -= mj * f2;
284 }
285 for (let b = 0; b < nb; b++) {
286 const cb = bcb[b];
287 if (cb === 0) continue;
288 const i3 = 3 * bi[b];
289 const j3 = 3 * bj[b];
290 const k3 = 3 * bk[b];
291 const ci = cb * invm[bi[b]];
292 const cj = -2 * cb * invm[bj[b]];
293 const ck = cb * invm[bk[b]];
294 const r0 = w[i3] - 2 * w[j3] + w[k3];
295 const r1 = w[i3 + 1] - 2 * w[j3 + 1] + w[k3 + 1];
296 const r2 = w[i3 + 2] - 2 * w[j3 + 2] + w[k3 + 2];
297 out[i3] += ci * r0;
298 out[i3 + 1] += ci * r1;
299 out[i3 + 2] += ci * r2;
300 out[j3] += cj * r0;
301 out[j3 + 1] += cj * r1;
302 out[j3 + 2] += cj * r2;
303 out[k3] += ck * r0;
304 out[k3 + 1] += ck * r1;
305 out[k3 + 2] += ck * r2;
306 }
307 if (hingeDamped) {
308 for (let h = 0; h < nhg; h++) {
309 const ch = hch[h];
310 if (ch === 0) continue;
311 const o = 12 * h;
312 const i3 = 3 * hi[h], j3 = 3 * hj[h], k3 = 3 * hk[h], l3 = 3 * hl[h];
313 let s =
314 hg[o] * w[i3] + hg[o + 1] * w[i3 + 1] + hg[o + 2] * w[i3 + 2] +
315 hg[o + 3] * w[j3] + hg[o + 4] * w[j3 + 1] + hg[o + 5] * w[j3 + 2] +
316 hg[o + 6] * w[k3] + hg[o + 7] * w[k3 + 1] + hg[o + 8] * w[k3 + 2] +
317 hg[o + 9] * w[l3] + hg[o + 10] * w[l3 + 1] + hg[o + 11] * w[l3 + 2];
318 s *= ch;
319 const ai = s * invm[hi[h]], aj = s * invm[hj[h]], ak = s * invm[hk[h]], al = s * invm[hl[h]];
320 out[i3] += ai * hg[o];
321 out[i3 + 1] += ai * hg[o + 1];
322 out[i3 + 2] += ai * hg[o + 2];
323 out[j3] += aj * hg[o + 3];
324 out[j3 + 1] += aj * hg[o + 4];
325 out[j3 + 2] += aj * hg[o + 5];
326 out[k3] += ak * hg[o + 6];
327 out[k3 + 1] += ak * hg[o + 7];
328 out[k3 + 2] += ak * hg[o + 8];
329 out[l3] += al * hg[o + 9];
330 out[l3 + 1] += al * hg[o + 10];
331 out[l3 + 2] += al * hg[o + 11];
332 }
333 }
334 };
335 const kinetic = () => {
336 let ke = 0;
337 for (let i = 0; i < n; i++) {
338 ke += 0.5 * mass[i] * (v[3 * i] ** 2 + v[3 * i + 1] ** 2 + v[3 * i + 2] ** 2);
339 }
340 return ke;
341 };
342 let dissipated = 0;
343 const applyDamping = (tau: number) => {
344 if (!hasDamping || tau === 0) return;
345 const keBefore = kinetic();
346 if (frictionOnly) {
347 for (let i = 0; i < n; i++) {
348 const f = Math.exp(-tau * friction[i] * invm[i]);
349 v[3 * i] *= f;
350 v[3 * i + 1] *= f;
351 v[3 * i + 2] *= f;
352 }
353 } else {
354 // Taylor series with scaling; |tau_s| * normA <= 0.5 so terms shrink fast.
355 refreshHinges();
356 const nsub = Math.max(1, Math.ceil((Math.abs(tau) * (normA + normAh)) / 0.5));
357 const ts = tau / nsub;
358 for (let r = 0; r < nsub; r++) {
359 let vmax = 0;
360 for (let q = 0; q < N3; q++) {
361 term[q] = v[q];
362 vmax = Math.max(vmax, Math.abs(v[q]));
363 }
364 if (vmax === 0) break;
365 for (let k = 1; k < 40; k++) {
366 applyA(term, tmp);
367 const c = -ts / k;
368 let tmax = 0;
369 for (let q = 0; q < N3; q++) {
370 const val = c * tmp[q];
371 term[q] = val;
372 v[q] += val;
373 const a = Math.abs(val);
374 if (a > tmax) tmax = a;
375 }
376 if (tmax <= 1e-17 * vmax) break;
377 }
378 }
379 }
380 dissipated += keBefore - kinetic();
381 };
383 // ---- recording -------------------------------------------------------------
384 const audio = new Float32Array(nSamples);
385 const lb = sys.listenBeads;
386 const [ldx, ldy, ldz] = sys.listenDir;
387 const pos0 = sys.pos0;
388 // Acceleration is (F - damping force) / m on each listener bead, with F the
389 // spring, bending and pulse forces at the current positions and time (the
390 // force array is current at every sample boundary). The damping force uses
391 // the dashpots and bending triplets that touch each listener bead.
392 const touchD = Array.from(lb, b => Array.from(di.keys()).filter(d => di[d] === b || dj[d] === b));
393 const touchB = Array.from(lb, b => Array.from(bi.keys()).filter(t => (bcb[t] !== 0 && (bi[t] === b || bj[t] === b || bk[t] === b))));
394 const touchH = Array.from(lb, b => Array.from(hi.keys()).filter(h => hch[h] !== 0 && hb(h).includes(b)));
395 const dampForce = (v: Float64Array, q: number, b: number, c: number) => {
396 let f = -friction[b] * v[3 * b + c];
397 for (const d of touchD[q]) {
398 const other = di[d] === b ? dj[d] : di[d];
399 f -= dc[d] * (v[3 * b + c] - v[3 * other + c]);
400 if (dca[d] !== 0) {
401 const rel = [0, 1, 2].reduce((acc, q) => acc + dd[3 * d + q] * (v[3 * b + q] - v[3 * other + q]), 0);
402 f -= dca[d] * rel * dd[3 * d + c];
403 }
404 }
405 for (const t of touchB[q]) {
406 const r = v[3 * bi[t] + c] - 2 * v[3 * bj[t] + c] + v[3 * bk[t] + c];
407 const w = bj[t] === b ? -2 : 1;
408 f -= bcb[t] * w * r;
409 }
410 for (const h of touchH[q]) {
411 const o = 12 * h;
412 const beads = hb(h);
413 let s = 0;
414 for (let p = 0; p < 4; p++) {
415 const b3 = 3 * beads[p];
416 s += hg[o + 3 * p] * v[b3] + hg[o + 3 * p + 1] * v[b3 + 1] + hg[o + 3 * p + 2] * v[b3 + 2];
417 }
418 f -= hch[h] * s * hg[o + 3 * beads.indexOf(b) + c];
419 }
420 return f;
421 };
422 // At a sample boundary the damping for the time pendingD has not been
423 // applied yet; vb = v - pendingD A v brings the velocities to the boundary
424 // (to second order) for the listener's velocity and damping force.
425 const vb = new Float64Array(N3);
426 const Av = new Float64Array(N3);
427 const listen = (pendingD: number) => {
428 let s = 0;
429 if (sys.listenQuantity !== "displacement") {
430 refreshHinges(); // hinge damping gradients at the current positions
431 if (pendingD !== 0 && hasDamping) {
432 applyA(v, Av);
433 for (let q = 0; q < N3; q++) vb[q] = v[q] - pendingD * Av[q];
434 } else vb.set(v);
435 }
436 lb.forEach((b, q) => {
437 const dir = [ldx, ldy, ldz];
438 for (let c = 0; c < 3; c++) {
439 if (dir[c] === 0) continue;
440 let val: number;
441 if (sys.listenQuantity === "displacement") val = x[3 * b + c] - pos0[3 * b + c];
442 else {
443 if (sys.listenQuantity === "velocity") val = vb[3 * b + c];
444 else val = (F[3 * b + c] + dampForce(vb, q, b, c)) * invm[b];
445 }
446 s += val * dir[c];
447 }
448 });
449 return s / lb.length;
450 };
451 const frameStride = Math.max(1, Math.round(fs / sys.frameRate));
452 const nFrames = Math.floor((nSamples - 1) / frameStride) + 1;
453 const maxAnimBytes = opts.maxAnimBytes ?? 150e6;
454 const animStride = frameStride * Math.max(1, Math.ceil((nFrames * N3 * 4) / maxAnimBytes));
455 const frameTimes = new Float64Array(nFrames);
456 const energy = new Float64Array(nFrames);
457 const dissipatedRec = new Float64Array(nFrames);
458 const animTimes: number[] = [];
459 const animFrames: Float32Array[] = [];
461 const modes = opts.modes ?? null;
462 const nModes = modes ? modes.freqs.length : 0;
463 const modeEnergy = modes ? new Float32Array(nFrames * nModes) : null;
464 let bz: Float64Array | null = null;
465 let bv: Float64Array | null = null;
466 let om2: Float64Array | null = null;
467 if (modes) {
468 bz = new Float64Array(modes.dof.length);
469 bv = new Float64Array(modes.dof.length);
470 om2 = new Float64Array(nModes);
471 for (let k = 0; k < nModes; k++) om2[k] = (2 * Math.PI * modes.freqs[k]) ** 2;
472 }
473 const recordModes = (f: number) => {
474 if (!modes || !modeEnergy || !bz || !bv || !om2) return;
475 const dof = modes.dof;
476 const nf = dof.length;
477 for (let r = 0; r < nf; r++) {
478 const q = dof[r];
479 const sm = Math.sqrt(mass[(q / 3) | 0]);
480 bz[r] = sm * (x[q] - pos0[q]);
481 bv[r] = sm * v[q];
482 }
483 const psi = modes.psi;
484 for (let k = 0; k < nModes; k++) {
485 let q = 0;
486 let qd = 0;
487 const off = k * nf;
488 for (let r = 0; r < nf; r++) {
489 q += psi[off + r] * bz[r];
490 qd += psi[off + r] * bv[r];
491 }
492 modeEnergy[f * nModes + k] = 0.5 * (qd * qd + om2[k] * q * q);
493 }
494 };
496 // ---- impulses, by audio sample ----------------------------------------------
497 const impulsesAt = new Map<number, typeof sys.hits>();
498 for (const hit of sys.hits) {
499 if (hit.duration > 0) continue;
500 const s = Math.round(hit.t * fs);
501 if (s >= nSamples) continue;
502 if (!impulsesAt.has(s)) impulsesAt.set(s, []);
503 impulsesAt.get(s)!.push(hit);
504 }
505 const tExcitationEnd = Math.max(0, ...sys.hits.map(hh => hh.t + hh.duration));
507 // ---- main loop ---------------------------------------------------------------
508 // Each audio sample interval Delta = substeps * h is one macro step:
509 // D(Delta/2) [substeps conservative steps] D(Delta/2). The damping halves of
510 // neighboring macro steps are merged unless something needs the velocities
511 // at the boundary (a frame record or an impulse).
512 const Delta = 1 / fs;
513 pe = internalForces();
514 externalForces(0);
515 let pendingD = 0;
516 let aborted: string | null = null;
517 let frame = 0;
518 let lastProgress = performance.now();
519 for (let s = 0; s <= nSteps; s++) {
520 const t = s * h;
521 const sample = s % substeps === 0 ? s / substeps : -1;
522 const isFrame = sample >= 0 && sample % frameStride === 0 && frame < nFrames;
523 const imps = sample >= 0 ? impulsesAt.get(sample) : undefined;
524 if ((isFrame || imps) && pendingD !== 0) {
525 applyDamping(pendingD);
526 pendingD = 0;
527 }
528 if (imps) {
529 for (const hit of imps) {
530 for (const b of hit.beads) {
531 if (pinned[b]) continue;
532 v[3 * b] += hit.velocity[0];
533 v[3 * b + 1] += hit.velocity[1];
534 v[3 * b + 2] += hit.velocity[2];
535 }
536 }
537 }
538 if (sample >= 0 && sample < nSamples) audio[sample] = listen(pendingD);
539 if (isFrame) {
540 frameTimes[frame] = t;
541 energy[frame] = kinetic() + pe - peRest;
542 dissipatedRec[frame] = dissipated;
543 recordModes(frame);
544 opts.onFrame?.(frame, t, x, v);
545 if (sample % animStride === 0) {
546 const d = new Float32Array(N3);
547 for (let q = 0; q < N3; q++) d[q] = x[q] - pos0[q];
548 animTimes.push(t);
549 animFrames.push(d);
550 }
551 frame++;
552 }
553 if (s === nSteps) break;
554 if (sample >= 0) {
555 pendingD += Delta / 2;
556 applyDamping(pendingD);
557 pendingD = 0;
558 }
560 let tj = t;
561 for (const c of cs) {
562 const kh = (c * h) / 2;
563 for (let i = 0; i < n; i++) {
564 const im = invm[i] * kh;
565 v[3 * i] += im * F[3 * i];
566 v[3 * i + 1] += im * F[3 * i + 1];
567 v[3 * i + 2] += im * F[3 * i + 2];
568 }
569 const dh = c * h;
570 for (let q = 0; q < N3; q++) x[q] += dh * v[q];
571 tj += c * h;
572 pe = internalForces();
573 externalForces(tj);
574 for (let i = 0; i < n; i++) {
575 const im = invm[i] * kh;
576 v[3 * i] += im * F[3 * i];
577 v[3 * i + 1] += im * F[3 * i + 1];
578 v[3 * i + 2] += im * F[3 * i + 2];
579 }
580 }
581 if ((s + 1) % substeps === 0) pendingD = Delta / 2;
583 if ((s & 1023) === 0) {
584 if (!Number.isFinite(pe)) {
585 aborted = `The solution blew up at t = ${t.toFixed(4)} s. Reduce dt (or safety) or the strike strength.`;
586 break;
587 }
588 const now = performance.now();
589 if (opts.onProgress && now - lastProgress > 200) {
590 opts.onProgress(t);
591 lastProgress = now;
592 }
593 }
594 }
596 // energy drift after the last excitation
597 let energyDrift = 0;
598 let ref = -1;
599 for (let f = 0; f < frame; f++) {
600 if (frameTimes[f] < tExcitationEnd) continue;
601 const total = energy[f] + dissipatedRec[f];
602 if (ref < 0) ref = total;
603 else if (ref > 0) energyDrift = Math.max(energyDrift, Math.abs(total - ref) / ref);
604 }
606 return {
607 audio,
608 sampleRate: fs,
609 dt: h,
610 substeps,
611 omegaMax,
612 frameTimes: frameTimes.slice(0, frame),
613 energy: energy.slice(0, frame),
614 dissipated: dissipatedRec.slice(0, frame),
615 animTimes: Float64Array.from(animTimes),
616 animFrames,
617 modeEnergy: modeEnergy ? modeEnergy.slice(0, frame * nModes) : null,
618 residualForce,
619 maxTension,
620 energyDrift,
621 freqErrors: [1000, 2000, 5000, 10000, 20000]
622 .filter(hz => hz < fs / 2)
623 .map(hz => ({ hz, cents: frequencyErrorCents(sys.method, 2 * Math.PI * hz, h) })),
624 elapsedMs: performance.now() - t0,
625 aborted,
626 warnings,
627 };
630// Highest frequency (rad/s) of the system linearized about the rest positions,
631// by power iteration on M^{-1/2} H M^{-1/2}, with a small margin.
632export function estimateOmegaMax(sys: BeadSystem): number {
633 const { n, si, sj, sk, sL0, sk3, pos0, mass, pinned } = sys;
634 const ns = si.length;
635 // per-spring 3x3 blocks B = keff d d^T + (f/L)(I - d d^T)
636 const B = new Float64Array(ns * 6);
637 for (let s = 0; s < ns; s++) {
638 const i3 = 3 * si[s];
639 const j3 = 3 * sj[s];
640 const dx = pos0[j3] - pos0[i3];
641 const dy = pos0[j3 + 1] - pos0[i3 + 1];
642 const dz = pos0[j3 + 2] - pos0[i3 + 2];
643 const L = Math.sqrt(dx * dx + dy * dy + dz * dz);
644 const e = L - sL0[s];
645 const keff = sk[s] + 3 * sk3[s] * e * e;
646 const g = (sk[s] * e + sk3[s] * e * e * e) / L;
647 const u = [dx / L, dy / L, dz / L];
648 const a = keff - g;
649 B[6 * s] = a * u[0] * u[0] + g;
650 B[6 * s + 1] = a * u[1] * u[1] + g;
651 B[6 * s + 2] = a * u[2] * u[2] + g;
652 B[6 * s + 3] = a * u[0] * u[1];
653 B[6 * s + 4] = a * u[0] * u[2];
654 B[6 * s + 5] = a * u[1] * u[2];
655 }
656 const ism = new Float64Array(n);
657 for (let i = 0; i < n; i++) ism[i] = pinned[i] ? 0 : 1 / Math.sqrt(mass[i]);
658 // hinges at rest: stiffness kh grad(theta) grad(theta)^T (theta = theta0 there)
659 const hg0 = new Float64Array(12 * sys.hi.length);
660 for (let h = 0; h < sys.hi.length; h++) hingeAngle(pos0, sys.hi[h], sys.hj[h], sys.hk[h], sys.hl[h], hg0.subarray(12 * h, 12 * h + 12));
661 let w = new Float64Array(3 * n);
662 let seed = 12345;
663 for (let q = 0; q < 3 * n; q++) {
664 seed = (seed * 1103515245 + 12345) & 0x7fffffff;
665 w[q] = ism[Math.floor(q / 3)] * (seed / 0x7fffffff - 0.5);
666 }
667 const u = new Float64Array(3 * n);
668 const y = new Float64Array(3 * n);
669 let lambda = 0;
670 for (let it = 0; it < 500; it++) {
671 let norm = 0;
672 for (let q = 0; q < 3 * n; q++) norm += w[q] * w[q];
673 norm = Math.sqrt(norm);
674 if (norm === 0) return 1;
675 for (let q = 0; q < 3 * n; q++) u[q] = (w[q] / norm) * ism[Math.floor(q / 3)];
676 y.fill(0);
677 for (let s = 0; s < ns; s++) {
678 const i3 = 3 * si[s];
679 const j3 = 3 * sj[s];
680 const r0 = u[i3] - u[j3];
681 const r1 = u[i3 + 1] - u[j3 + 1];
682 const r2 = u[i3 + 2] - u[j3 + 2];
683 const b = 6 * s;
684 const f0 = B[b] * r0 + B[b + 3] * r1 + B[b + 4] * r2;
685 const f1 = B[b + 3] * r0 + B[b + 1] * r1 + B[b + 5] * r2;
686 const f2 = B[b + 4] * r0 + B[b + 5] * r1 + B[b + 2] * r2;
687 y[i3] += f0;
688 y[i3 + 1] += f1;
689 y[i3 + 2] += f2;
690 y[j3] -= f0;
691 y[j3 + 1] -= f1;
692 y[j3 + 2] -= f2;
693 }
694 for (let h = 0; h < sys.hi.length; h++) {
695 const o = 12 * h;
696 const beads = [sys.hi[h], sys.hj[h], sys.hk[h], sys.hl[h]];
697 let s = 0;
698 for (let p = 0; p < 4; p++) for (let c = 0; c < 3; c++) s += hg0[o + 3 * p + c] * u[3 * beads[p] + c];
699 s *= sys.hkh[h];
700 for (let p = 0; p < 4; p++) for (let c = 0; c < 3; c++) y[3 * beads[p] + c] += s * hg0[o + 3 * p + c];
701 }
702 for (let b = 0; b < sys.bi.length; b++) {
703 const i3 = 3 * sys.bi[b];
704 const j3 = 3 * sys.bj[b];
705 const k3 = 3 * sys.bk[b];
706 const kb = sys.bkb[b];
707 for (let q = 0; q < 3; q++) {
708 const r = kb * (u[i3 + q] - 2 * u[j3 + q] + u[k3 + q]);
709 y[i3 + q] += r;
710 y[j3 + q] -= 2 * r;
711 y[k3 + q] += r;
712 }
713 }
714 let rq = 0;
715 const wNext = new Float64Array(3 * n);
716 for (let q = 0; q < 3 * n; q++) {
717 wNext[q] = y[q] * ism[Math.floor(q / 3)];
718 rq += (w[q] / norm) * wNext[q];
719 }
720 w = wNext;
721 if (it > 20 && Math.abs(rq - lambda) < 1e-8 * Math.abs(rq)) {
722 lambda = rq;
723 break;
724 }
725 lambda = rq;
726 }
727 return Math.sqrt(Math.max(lambda, 1e-300)) * 1.02;
↑↓ move↵openescclose