/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / lab / pendulumWorklet.ts
184 lines · 7.1 KBCodeBlameHistory
d8370f3Lab: the double pendulum as an instrument (#/lab/edit)Jeremy Magland 1// The double pendulum as an instrument: simulated at audio rate inside the AudioWorklet, its
2// motion is the waveform. Time is scaled so the pendulum's lower small-swing mode lands at
3// `pitch` Hz. Modes: strike (start at an energy, ring down through damping, re-strike),
4// sustain (an energy controller holds the energy, like bowing), swell (energy rises, then rings
5// down). Any state quantity can be the left/right output.
7import { DoublePendulum } from "../physics/doublePendulum.ts";
8import { mulberry32 } from "../core/rng.ts";
9import type { LabMsg, LabSettings, LabSnap, Signal } from "./protocol.ts";
11declare const sampleRate: number;
12declare const currentTime: number;
13declare class AudioWorkletProcessor {
14 readonly port: MessagePort;
15 constructor();
17declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
19const TRAIL = 384; // samples of bob path sent per snapshot (decimated)
20const DECIM = 2;
22class PendulumVoice extends AudioWorkletProcessor {
23 private s: LabSettings | null = null;
24 private p = new DoublePendulum({ m1: 1, m2: 1, l1: 1, l2: 1, g: 1 });
25 private rand = mulberry32(12345);
26 private t = 0; // audio seconds since the last strike/swell
27 private phase = "silent";
28 private dcL = { x: 0, y: 0 };
29 private dcR = { x: 0, y: 0 };
30 private trail = new Float32Array(4 * TRAIL);
31 private trailW = 0;
32 private sinceSnap = 0;
33 private sampleCount = 0;
35 constructor() {
36 super();
37 this.p.controlled = false;
38 this.port.onmessage = (e: MessageEvent<LabMsg>) => {
39 if (e.data.type === "settings") {
40 const first = !this.s;
41 this.s = e.data.s;
42 this.p.cfg.m2 = this.s.massRatio;
43 this.p.cfg.l2 = this.s.lengthRatio;
44 if (first) this.strike();
45 } else if (e.data.type === "strike") this.strike();
46 };
47 }
49 /** ω of the lower small-swing mode (sim units), for the time scaling. */
50 private lowMode(): number {
51 const { m1, m2, l1, l2, g } = this.p.cfg;
52 // small oscillations: eigenvalues of M⁻¹K for the linearized double pendulum
53 const a = (m1 + m2) * l1 * l1, b = m2 * l1 * l2, c = m2 * l2 * l2;
54 const ka = (m1 + m2) * g * l1, kc = m2 * g * l2;
55 const det = a * c - b * b;
56 const tr = (ka * c + kc * a) / det, dt = (ka * kc) / det;
57 const lam = (tr - Math.sqrt(Math.max(0, tr * tr - 4 * dt))) / 2;
58 return Math.sqrt(Math.max(lam, 1e-9));
59 }
61 private strike() {
62 const s = this.s;
63 if (!s) return;
64 this.t = 0;
65 if (s.mode === "swell") {
66 this.p.randomize(Math.min(0.01, s.energy * 0.05), this.rand);
67 this.phase = "swelling";
68 } else {
69 this.p.randomize(s.energy, this.rand);
70 this.phase = s.mode === "sustain" ? "sustaining" : "ringing";
71 }
72 }
74 private signal(sig: Signal, w1: number, w2: number): number {
75 const { l1, l2, m2 } = this.p.cfg;
76 const y = this.p.y;
77 const L = l1 + l2;
78 const vmax = Math.sqrt((2 * this.p.vTop) / m2) + 1e-9;
79 const s1 = Math.sin(y[0]), c1 = Math.cos(y[0]), s2 = Math.sin(y[1]), c2 = Math.cos(y[1]);
80 switch (sig) {
81 case "x2": return (l1 * s1 + l2 * s2) / L;
82 case "y2": return -(l1 * c1 + l2 * c2) / L;
83 case "vx2": return (l1 * c1 * w1 + l2 * c2 * w2) / vmax;
84 case "vy2": return (l1 * s1 * w1 + l2 * s2 * w2) / vmax;
85 case "x1": return s1;
86 case "vx1": return (l1 * c1 * w1) / vmax;
87 case "θ1": return Math.atan2(s1, c1) / Math.PI;
88 case "θ2": return Math.atan2(s2, c2) / Math.PI;
89 case "θ2−θ1": return Math.atan2(Math.sin(y[1] - y[0]), Math.cos(y[1] - y[0])) / Math.PI;
90 case "ω1": return (w1 * l1) / vmax;
91 case "ω2": return (w2 * l2) / vmax;
92 case "p1": return y[2] / (vmax * (1 + m2) * l1 * l1 + 1e-9);
93 case "p2": return y[3] / (vmax * m2 * l2 * l2 + 1e-9);
94 case "speed2": return Math.hypot(l1 * c1 * w1 + l2 * c2 * w2, l1 * s1 * w1 + l2 * s2 * w2) / vmax;
95 }
96 }
98 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
99 const out = outputs[0];
100 const Lo = out[0], Ro = out[1] ?? out[0];
101 const s = this.s;
102 if (!s) return true;
103 const n = Lo.length;
104 const p = this.p;
105 const w0 = this.lowMode();
106 const k = (2 * Math.PI * s.pitch) / w0; // sim seconds per audio second
107 const dtSample = k / sampleRate;
108 const sub = Math.max(1, Math.ceil(dtSample / 0.004));
109 const h = dtSample / sub;
110 // ring time (amplitude −60 dB in s audio) → viscous damping rate (energy ∝ e^{−γ t_sim})
111 const gamma = s.ringTime > 0 ? (2 * 6.9078) / (s.ringTime * k) : 0;
112 const dcR = 1 - (2 * Math.PI * s.dcCut) / sampleRate;
113 const period = (2 * Math.PI) / w0; // sim seconds
114 p.tau = Math.max(0.05, s.follow * period);
115 for (let i = 0; i < n; i++) {
116 // mode logic (audio time since the last strike)
117 if (s.mode === "sustain") {
118 this.phase = "sustaining";
119 p.controlled = true;
120 p.eTarget = s.energy * p.vTop;
121 p.damping = 0;
122 } else if (s.mode === "swell") {
123 if (this.t < s.swellTime) {
124 p.controlled = true;
125 const u = this.t / Math.max(0.01, s.swellTime);
126 p.eTarget = s.energy * p.vTop * u * u;
127 p.damping = 0;
128 this.phase = "swelling";
129 } else {
130 p.controlled = false;
131 p.damping = gamma;
132 this.phase = "ringing";
133 }
134 } else {
135 p.controlled = false;
136 p.damping = gamma;
137 this.phase = "ringing";
138 }
139 for (let j = 0; j < sub; j++) p.step(h);
140 this.t += 1 / sampleRate;
141 if (s.restrike > 0 && this.t >= s.restrike) this.strike();
143 const d = p.derived();
144 let l = this.signal(s.left, d.w1, d.w2), r = s.right === s.left ? l : this.signal(s.right, d.w1, d.w2);
145 // remove constant offsets (angles and positions sit off zero), then gain and a soft limit
146 const yl = l - this.dcL.x + dcR * this.dcL.y;
147 this.dcL.x = l;
148 this.dcL.y = yl;
149 const yr = r - this.dcR.x + dcR * this.dcR.y;
150 this.dcR.x = r;
151 this.dcR.y = yr;
152 l = Math.tanh(s.gain * yl);
153 r = Math.tanh(s.gain * yr);
154 Lo[i] = Number.isFinite(l) ? l : 0;
155 Ro[i] = Number.isFinite(r) ? r : 0;
156 if (!Number.isFinite(p.y[0])) this.strike(); // never let a blow-up stick
158 // bob path for the display
159 if (++this.sampleCount % DECIM === 0) {
160 const y = p.y, cfg = p.cfg, o = 4 * this.trailW;
161 const x1 = cfg.l1 * Math.sin(y[0]), y1 = cfg.l1 * Math.cos(y[0]);
162 this.trail[o] = x1;
163 this.trail[o + 1] = y1;
164 this.trail[o + 2] = x1 + cfg.l2 * Math.sin(y[1]);
165 this.trail[o + 3] = y1 + cfg.l2 * Math.cos(y[1]);
166 this.trailW = (this.trailW + 1) % TRAIL;
167 }
168 }
169 this.sinceSnap += n;
170 if (this.sinceSnap >= sampleRate / 60) {
171 this.sinceSnap = 0;
172 // oldest → newest
173 const tr = new Float32Array(4 * TRAIL);
174 tr.set(this.trail.subarray(4 * this.trailW));
175 tr.set(this.trail.subarray(0, 4 * this.trailW), 4 * (TRAIL - this.trailW));
176 const snap: LabSnap = { type: "snap", energy: p.energyNorm(), phase: this.phase, trail: tr, k };
177 this.port.postMessage(snap, [tr.buffer]);
178 }
179 void currentTime;
180 return true;
181 }
184registerProcessor("pendulum-voice", PendulumVoice);
↑↓ move↵openescclose