/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / lab / pendulumWorklet.ts
167 lines · 6.2 KBBlameHistoryRaw
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";
10import { kick, lowMode, signal } from "./voice.ts";
12declare const sampleRate: number;
13declare const currentTime: number;
14declare class AudioWorkletProcessor {
15 readonly port: MessagePort;
16 constructor();
18declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
20const TRAIL = 384; // samples of bob path sent per snapshot (decimated)
21const DECIM = 2;
23class PendulumVoice extends AudioWorkletProcessor {
24 private s: LabSettings | null = null;
25 private p = new DoublePendulum({ m1: 1, m2: 1, l1: 1, l2: 1, g: 1 });
26 private rand = mulberry32(12345);
27 private t = 0; // audio seconds since the last strike/swell
28 private swellFrom = 0; // energy (normalized) when the current swell began
29 private phase = "silent";
30 private dcL = { x: 0, y: 0 };
31 private dcR = { x: 0, y: 0 };
32 private trail = new Float32Array(4 * TRAIL);
33 private trailW = 0;
34 private sinceSnap = 0;
35 private sampleCount = 0;
37 constructor() {
38 super();
39 this.p.controlled = false;
40 this.port.onmessage = (e: MessageEvent<LabMsg>) => {
41 if (e.data.type === "settings") {
42 const first = !this.s;
43 this.s = e.data.s;
44 this.p.cfg.m2 = this.s.massRatio;
45 this.p.cfg.l2 = this.s.lengthRatio;
46 if (first) {
47 // start hanging at rest; the first strike sets it going
48 this.p.y.fill(0);
49 this.strike();
50 }
51 } else if (e.data.type === "strike") this.strike();
52 };
53 }
55 /**
56 * A strike adds energy to the current motion (it never restarts): a momentum kick along the
57 * current momentum (like pushing a swing in time, so it always adds), or in a random direction
58 * if the pendulum is still, sized so the energy rises by exactly `strikeEnergy`.
59 */
60 private strike() {
61 const s = this.s;
62 if (!s) return;
63 this.t = 0;
64 if (s.mode === "swell") {
65 this.swellFrom = this.p.energyNorm();
66 this.phase = "swelling";
67 if (this.swellFrom < 1e-6) this.kick(1e-4 * this.p.vTop); // something to swell from
68 return;
69 }
70 this.kick(s.strikeEnergy * this.p.vTop);
71 }
73 private kick(add: number) {
74 kick(this.p, add, this.rand);
75 }
77 private signal(sig: Signal, w1: number, w2: number): number {
78 return signal(this.p, sig, w1, w2);
79 }
81 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
82 const out = outputs[0];
83 const Lo = out[0], Ro = out[1] ?? out[0];
84 const s = this.s;
85 if (!s) return true;
86 const n = Lo.length;
87 const p = this.p;
88 const w0 = lowMode(p);
89 const k = (2 * Math.PI * s.pitch) / w0; // sim seconds per audio second
90 const dtSample = k / sampleRate;
91 const sub = Math.max(1, Math.ceil(dtSample / 0.004));
92 const h = dtSample / sub;
93 // ring time (amplitude −60 dB in s audio) → viscous damping rate (energy ∝ e^{−γ t_sim})
94 const gamma = s.ringTime > 0 ? (2 * 6.9078) / (s.ringTime * k) : 0;
95 const dcR = 1 - (2 * Math.PI * s.dcCut) / sampleRate;
96 const period = (2 * Math.PI) / w0; // sim seconds
97 p.tau = Math.max(0.05, s.follow * period);
98 for (let i = 0; i < n; i++) {
99 // mode logic (audio time since the last strike)
100 if (s.mode === "sustain") {
101 this.phase = "sustaining";
102 p.controlled = true;
103 p.eTarget = s.energy * p.vTop;
104 p.damping = 0;
105 } else if (s.mode === "swell") {
106 if (this.t < s.swellTime) {
107 p.controlled = true;
108 const u = this.t / Math.max(0.01, s.swellTime);
109 p.eTarget = (this.swellFrom + (s.energy - this.swellFrom) * u * u) * p.vTop;
110 p.damping = 0;
111 this.phase = "swelling";
112 } else {
113 p.controlled = false;
114 p.damping = gamma;
115 this.phase = "ringing";
116 }
117 } else {
118 p.controlled = false;
119 p.damping = gamma;
120 this.phase = "ringing";
121 }
122 for (let j = 0; j < sub; j++) p.step(h);
123 this.t += 1 / sampleRate;
124 if (s.restrike > 0 && this.t >= s.restrike) this.strike();
126 const d = p.derived();
127 let l = this.signal(s.left, d.w1, d.w2), r = s.right === s.left ? l : this.signal(s.right, d.w1, d.w2);
128 // remove constant offsets (angles and positions sit off zero), then gain and a soft limit
129 const yl = l - this.dcL.x + dcR * this.dcL.y;
130 this.dcL.x = l;
131 this.dcL.y = yl;
132 const yr = r - this.dcR.x + dcR * this.dcR.y;
133 this.dcR.x = r;
134 this.dcR.y = yr;
135 l = Math.tanh(s.gain * yl);
136 r = Math.tanh(s.gain * yr);
137 Lo[i] = Number.isFinite(l) ? l : 0;
138 Ro[i] = Number.isFinite(r) ? r : 0;
139 if (!Number.isFinite(p.y[0])) this.strike(); // never let a blow-up stick
141 // bob path for the display
142 if (++this.sampleCount % DECIM === 0) {
143 const y = p.y, cfg = p.cfg, o = 4 * this.trailW;
144 const x1 = cfg.l1 * Math.sin(y[0]), y1 = cfg.l1 * Math.cos(y[0]);
145 this.trail[o] = x1;
146 this.trail[o + 1] = y1;
147 this.trail[o + 2] = x1 + cfg.l2 * Math.sin(y[1]);
148 this.trail[o + 3] = y1 + cfg.l2 * Math.cos(y[1]);
149 this.trailW = (this.trailW + 1) % TRAIL;
150 }
151 }
152 this.sinceSnap += n;
153 if (this.sinceSnap >= sampleRate / 60) {
154 this.sinceSnap = 0;
155 // oldest → newest
156 const tr = new Float32Array(4 * TRAIL);
157 tr.set(this.trail.subarray(4 * this.trailW));
158 tr.set(this.trail.subarray(0, 4 * this.trailW), 4 * (TRAIL - this.trailW));
159 const snap: LabSnap = { type: "snap", energy: p.energyNorm(), phase: this.phase, trail: tr, k };
160 this.port.postMessage(snap, [tr.buffer]);
161 }
162 void currentTime;
163 return true;
164 }
167registerProcessor("pendulum-voice", PendulumVoice);
↑↓ move↵openescclose