d8370f3Lab: the double pendulum as an instrument (#/lab/edit)Jeremy Magland 1// Lab: the double pendulum as an instrument (audio-rate simulation, its motion is the sound).
2// Click the plot (or press S) to strike. Not part of the album; reachable at #/lab.
4import { dbToGain, type AudioEngine } from "../../core/audio.ts";
5import type { Piece } from "../../core/composition.ts";
6import type { Params } from "../../core/params.ts";
7import type { LabMsg, LabSettings, LabSnap, Signal } from "../../lab/protocol.ts";
8import workletUrl from "../../lab/pendulumWorklet.ts?worker&url";
9import { cssColor, fitCanvas } from "../shared/section.ts";
11const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
13export function createLabPiece(view: HTMLElement, params: () => Params): Piece {
14 const canvas = document.createElement("canvas");
15 canvas.title = "click (or press S) to strike";
16 canvas.style.cursor = "pointer";
17 view.append(canvas);
19 let audio: AudioEngine | null = null;
20 let node: AudioWorkletNode | null = null;
21 let out: GainNode | null = null;
22 let analyser: AnalyserNode | null = null;
23 let timer: number | undefined;
24 let playing = false;
25 let startedAt = 0;
26 let snap: LabSnap | null = null;
27 let lastSent = "";
28 let token = 0;
30 const settings = (P: Params): LabSettings => ({
31 mode: P.mode as LabSettings["mode"],
32 pitch: P.pitch as number,
33 energy: P.energy as number,
9c7f20bLab: strikes add energy to the current motion instead of restartingJeremy Magland 34 strikeEnergy: P.strikeEnergy as number,
d8370f3Lab: the double pendulum as an instrument (#/lab/edit)Jeremy Magland 35 ringTime: P.ringTime as number,
36 restrike: P.restrike as number,
37 swellTime: P.swellTime as number,
38 massRatio: P.massRatio as number,
39 lengthRatio: P.lengthRatio as number,
40 left: P.left as Signal,
41 right: P.right as Signal,
42 gain: dbToGain(P.gain as number),
43 dcCut: P.dcCut as number,
44 follow: P.follow as number,
45 });
47 const send = (m: LabMsg) => node?.port.postMessage(m);
48 const strike = () => send({ type: "strike" });
49 canvas.onclick = strike;
50 const onKey = (e: KeyboardEvent) => {
51 if ((e.key === "s" || e.key === "S") && !(e.target as HTMLElement).closest("input, select, textarea")) strike();
52 };
53 window.addEventListener("keydown", onKey);
55 function sync() {
56 if (!node || !audio || !out) return;
57 const P = params();
58 const s = settings(P);
59 const key = JSON.stringify(s);
60 if (key !== lastSent) {
61 lastSent = key;
62 send({ type: "settings", s });
63 }
64 out.gain.setTargetAtTime(dbToGain(P.level as number), audio.ctx.currentTime, 0.05);
65 }
67 async function start(a: AudioEngine) {
68 stop();
69 const my = ++token;
70 audio = a;
71 const ctx = a.ctx;
72 let p = loaded.get(ctx);
73 if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl)));
74 await p;
75 if (my !== token) return;
76 out = ctx.createGain();
77 out.gain.value = 0;
78 analyser = ctx.createAnalyser();
79 analyser.fftSize = 4096;
80 analyser.smoothingTimeConstant = 0.6;
81 node = new AudioWorkletNode(ctx, "pendulum-voice", { numberOfInputs: 0, outputChannelCount: [2] });
82 node.port.onmessage = (e: MessageEvent<LabSnap>) => (snap = e.data);
83 node.connect(out);
84 out.connect(a.input);
85 out.connect(analyser);
86 lastSent = "";
87 sync();
88 playing = true;
89 startedAt = ctx.currentTime;
90 timer = window.setInterval(sync, 50);
91 }
93 function stop() {
94 token++;
95 if (timer !== undefined) window.clearInterval(timer);
96 timer = undefined;
97 playing = false;
98 if (!audio) return;
99 const o = out, n = node, an = analyser;
100 if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03);
101 window.setTimeout(() => {
102 n?.disconnect();
103 o?.disconnect();
104 an?.disconnect();
105 }, 300);
106 node = out = analyser = null;
107 }
109 const wave = new Float32Array(2048);
110 let spec: Float32Array<ArrayBuffer> | null = null;
112 function draw() {
113 const P = params();
114 const g = fitCanvas(canvas);
115 const w = canvas.clientWidth, h = canvas.clientHeight;
116 g.clearRect(0, 0, w, h);
117 const fg = cssColor(view, "--fg"), dim = cssColor(view, "--dim"), muted = cssColor(view, "--muted");
118 const top = h * 0.62; // bob path above, waveform and spectrum below
119 // bob path over the last few ms
120 if (snap) {
121 const tr = snap.trail;
122 const pts = tr.length / 4;
123 const msPer = (2 / 48000) * 1000; // decimation 2 at ~48 kHz
124 const nShow = Math.min(pts, Math.round((P.trailMs as number) / msPer));
125 const L = 1 + (P.lengthRatio as number);
126 const sc = (0.46 * Math.min(w, top)) / L;
127 const cx = w / 2, cy = top / 2;
128 g.lineWidth = 1;
129 g.strokeStyle = fg;
130 g.beginPath();
131 for (let i = pts - nShow; i < pts; i++) {
132 const x = cx + sc * tr[4 * i + 2], y = cy + sc * tr[4 * i + 3];
133 if (i === pts - nShow) g.moveTo(x, y);
134 else g.lineTo(x, y);
135 }
136 g.globalAlpha = 0.8;
137 g.stroke();
138 // the current pose
139 const i = pts - 1;
140 g.globalAlpha = 1;
141 g.strokeStyle = muted;
142 g.beginPath();
143 g.moveTo(cx, cy);
144 g.lineTo(cx + sc * tr[4 * i], cy + sc * tr[4 * i + 1]);
145 g.lineTo(cx + sc * tr[4 * i + 2], cy + sc * tr[4 * i + 3]);
146 g.stroke();
147 }
148 // waveform and spectrum
149 if (analyser) {
150 const wh = (h - top) * 0.45, sy = top + 8;
151 analyser.getFloatTimeDomainData(wave);
152 g.strokeStyle = fg;
153 g.lineWidth = 1;
154 g.beginPath();
155 const N = 1024;
156 for (let i = 0; i < N; i++) {
157 const x = (i / (N - 1)) * w, y = sy + wh / 2 - (wave[i] * wh) / 2;
158 if (i) g.lineTo(x, y);
159 else g.moveTo(x, y);
160 }
161 g.stroke();
162 if (!spec || spec.length !== analyser.frequencyBinCount) spec = new Float32Array(analyser.frequencyBinCount);
163 analyser.getFloatFrequencyData(spec);
164 const sh = (h - top) * 0.45, sb = h - 4;
165 const sr = audio!.ctx.sampleRate;
166 const fx = (f: number) => (Math.log(f / 20) / Math.log(20000 / 20)) * w;
167 g.strokeStyle = dim;
168 g.beginPath();
169 for (const f of [100, 1000, 10000]) {
170 g.moveTo(fx(f), sb - sh);
171 g.lineTo(fx(f), sb);
172 }
173 g.stroke();
174 g.strokeStyle = fg;
175 g.beginPath();
176 let started = false;
177 for (let b = 1; b < spec.length; b++) {
178 const f = (b * sr) / (2 * spec.length);
179 if (f < 20 || f > 20000) continue;
180 const v = Math.max(0, Math.min(1, (spec[b] + 110) / 100));
181 const x = fx(f), y = sb - v * sh;
182 if (started) g.lineTo(x, y);
183 else g.moveTo(x, y), (started = true);
184 }
185 g.stroke();
186 }
187 if (!playing) {
188 g.fillStyle = muted;
189 g.font = "12px ui-monospace, monospace";
190 g.fillText("play, then click here (or press S) to strike", 8, 16);
191 }
192 }
194 function readouts(): Record<string, string> {
195 return {
196 mode: playing && snap ? snap.phase : "–",
197 energy: snap ? snap.energy.toFixed(4) : "–",
198 "time scale": snap ? `${snap.k.toFixed(0)} sim s per s` : "–",
199 strike: "click the plot or press S",
200 };
201 }
203 return {
204 get playing() {
205 return playing;
206 },
207 start: (a) => start(a),
208 stop,
209 draw,
210 now: () => (playing && audio ? audio.ctx.currentTime - startedAt : 0),
211 length: () => Infinity,
212 readouts,
213 dispose() {
214 stop();
215 window.removeEventListener("keydown", onKey);
216 view.replaceChildren();
217 },
218 };
219}