/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c05-ensemble / piece.ts
278 lines · 10.2 KBBlameHistoryRaw
1// Ensemble lab: six audio-rate pendulums sharing one time scale, so each one's pitch comes from its
2// size; their proportions are solved from musical ratios (see harmony.ts). A score pushes them in
3// chords (e.g. "36 25 … 1!4"); keys 1–6 also push that pendulum, R resets them all to rest.
5import { dbToGain, type AudioEngine } from "../../core/audio.ts";
6import type { Piece } from "../../core/composition.ts";
7import type { Params } from "../../core/params.ts";
8import workletUrl from "../../lab/ensembleWorklet.ts?worker&url";
9import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap, type Signal } from "../../lab/protocol.ts";
10import { randomSeed } from "../../core/rng.ts";
11import { cssColor, fitCanvas } from "../shared/section.ts";
12import { build, parseRatio, timeScale, type Built } from "./harmony.ts";
14const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
15const START_DELAY = 0.4; // s before the first step
17/** "36 25 1!4": one step per word, the pendulums pushed together; ! accents the digit before it. */
18export function parseScore(text: string, add: number, accent: number): { i: number; add: number }[][] {
19 return text
20 .trim()
21 .split(/\s+/)
22 .filter(Boolean)
23 .map((w) => {
24 const step: { i: number; add: number }[] = [];
25 for (let c = 0; c < w.length; c++) {
26 if (!/[1-6]/.test(w[c])) continue;
27 const loud = w[c + 1] === "!";
28 step.push({ i: Number(w[c]) - 1, add: add * (loud ? accent : 1) });
29 }
30 return step;
31 });
34export function createEnsemblePiece(view: HTMLElement, params: () => Params): Piece {
35 const canvas = document.createElement("canvas");
36 view.append(canvas);
38 let audio: AudioEngine | null = null;
39 let node: AudioWorkletNode | null = null;
40 let out: GainNode | null = null;
41 let timer: number | undefined;
42 let playing = false;
43 let startedAt = 0;
44 let snap: EnsembleSnap | null = null;
45 let lastSent = "";
46 let token = 0;
47 let ended = false;
48 let seedUsed = 0;
50 /** Physics for every pendulum from the musical ratios: one time scale, sizes and masses solved. */
51 function physics(P: Params): { k: number; built: Built[] } {
52 const base = P.basePitch as number;
53 const v = Array.from({ length: ENSEMBLE }, (_, i) => ({
54 ratio: parseRatio(P[`ratio${i + 1}`] as string),
55 partial: parseRatio(P[`partial${i + 1}`] as string),
56 shape: P[`shape${i + 1}`] as number,
57 }));
58 // the lowest-pitched pendulum is the biggest: give it l1 = 1
59 const low = v.reduce((a, b) => (b.ratio < a.ratio ? b : a));
60 const k = timeScale(base, low.ratio, low.partial, low.shape);
61 return { k, built: v.map((x) => build(base, x.ratio, x.partial, x.shape, k)) };
62 }
64 const settings = (P: Params): EnsembleSettings => {
65 const { k, built } = physics(P);
66 return {
67 voices: built.map((b, i) => ({
68 l1: b.l1,
69 l2: b.l2,
70 m2: b.m2,
71 upperHz: b.upper,
72 ringTime: P[`ring${i + 1}`] as number,
73 level: dbToGain(P[`level${i + 1}`] as number),
74 })),
75 k,
76 pulseAdds: P.pulseAdds as number,
77 score: parseScore(P.score as string, P.pulseAdds as number, P.accent as number),
78 stepSec: stepSec(P),
79 startDelay: START_DELAY,
80 seed: seedUsed,
81 signal: P.signal as Signal,
82 gain: dbToGain(P.gain as number),
83 dcCut: P.dcCut as number,
84 spread: P.spread as number,
85 };
86 };
88 const stepSec = (P: Params) => ((P.stepBeats as number) * 60) / Math.max(1, P.tempo as number);
89 const scoreEnd = (P: Params) => START_DELAY + parseScore(P.score as string, 0, 1).length * stepSec(P);
90 const total = (P: Params) => scoreEnd(P) + (P.tail as number);
92 const send = (m: EnsembleMsg) => node?.port.postMessage(m);
93 const onKey = (e: KeyboardEvent) => {
94 const el = e.target;
95 if (el instanceof Element && el.closest("input, select, textarea")) return;
96 if (/^[1-6]$/.test(e.key)) send({ type: "strike", i: Number(e.key) - 1 });
97 else if (e.key === "r" || e.key === "R") send({ type: "reset" });
98 };
99 window.addEventListener("keydown", onKey);
101 function sync() {
102 if (!node || !audio || !out) return;
103 const P = params();
104 const key = JSON.stringify(settings(P));
105 if (key !== lastSent) {
106 lastSent = key;
107 send({ type: "settings", s: settings(P) });
108 }
109 // the end: fade over the last `fade` s of the ring-out, then stop
110 const t = audio.ctx.currentTime - startedAt, T = total(P);
111 const fade = Math.min(P.fade as number, P.tail as number);
112 const k = Math.max(0, Math.min(1, (T - t) / fade));
113 out.gain.setTargetAtTime(dbToGain(P.level as number) * k * k, audio.ctx.currentTime, 0.05);
114 if (t >= T && !ended) {
115 ended = true;
116 stop();
117 piece.onEnded?.();
118 }
119 }
121 async function start(a: AudioEngine) {
122 stop();
123 const my = ++token;
124 audio = a;
125 const ctx = a.ctx;
126 let p = loaded.get(ctx);
127 if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl)));
128 await p;
129 if (my !== token) return;
130 ended = false;
131 snap = null;
132 const P0 = params();
133 seedUsed = (P0.seed as number) > 0 ? Math.round(P0.seed as number) : randomSeed();
134 out = ctx.createGain();
135 out.gain.value = 0;
136 node = new AudioWorkletNode(ctx, "pendulum-ensemble", { numberOfInputs: 0, outputChannelCount: [2] });
137 node.port.onmessage = (e: MessageEvent<EnsembleSnap>) => (snap = e.data);
138 node.connect(out).connect(a.input);
139 lastSent = "";
140 sync();
141 playing = true;
142 startedAt = ctx.currentTime;
143 timer = window.setInterval(sync, 50);
144 }
146 function stop() {
147 token++;
148 if (timer !== undefined) window.clearInterval(timer);
149 timer = undefined;
150 playing = false;
151 if (!audio) return;
152 const o = out, n = node;
153 if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03);
154 window.setTimeout(() => {
155 n?.disconnect();
156 o?.disconnect();
157 }, 300);
158 node = out = null;
159 }
161 // Layout: the pendulums hang from one line, left to right as listed, each given room in proportion
162 // to its size (most of its sideways reach: big swings may overlap a neighbour).
163 function layout(dr: number[], w: number, h: number) {
164 const ROOM = 1.5, GAP = 0.2; // drawn reaches of room per pendulum, and between pendulums
165 const fit = (rows: number[][]) => {
166 const rh = h / rows.length;
167 let unit = Infinity;
168 for (const r of rows) {
169 const span = r.reduce((a, i) => a + ROOM * dr[i], 0) + GAP * (r.length - 1);
170 unit = Math.min(unit, (0.92 * w) / span, (0.5 * rh) / Math.max(...r.map((i) => dr[i])));
171 }
172 return { rows, rh, unit };
173 };
174 const { rows, rh, unit } = fit([[0, 1, 2, 3, 4, 5]]);
175 const at: { x: number; y: number }[] = [];
176 rows.forEach((r, ri) => {
177 const span = (r.reduce((a, i) => a + ROOM * dr[i], 0) + GAP * (r.length - 1)) * unit;
178 // hang the row so its resting pendulums sit centred in the row
179 const y = ri * rh + rh / 2 - (Math.max(...r.map((i) => dr[i])) * unit) / 2;
180 let x = (w - span) / 2;
181 for (const i of r) {
182 at[i] = { x: x + (ROOM / 2) * dr[i] * unit, y };
183 x += (ROOM * dr[i] + GAP) * unit;
184 }
185 });
186 return { unit, at };
187 }
189 function draw() {
190 const P = params();
191 const g = fitCanvas(canvas);
192 const w = canvas.clientWidth, h = canvas.clientHeight;
193 g.clearRect(0, 0, w, h);
194 const fg = cssColor(view, "--fg"), muted = cssColor(view, "--muted");
195 const { built } = physics(P);
196 // compared sizes: length^sizeExp (true scale would make the highest a speck)
197 const ex = P.sizeExp as number;
198 const reach = built.map((b) => b.l1 + b.l2);
199 const dr = reach.map((r) => Math.pow(r, ex));
200 const { unit, at } = layout(dr, w, h);
201 const TR = snap ? snap.trails.length / (2 * ENSEMBLE) : 0;
202 const trailA = P.trail as number;
203 g.lineCap = "round";
204 g.lineJoin = "round";
205 for (let i = 0; i < ENSEMBLE; i++) {
206 const { x: cx, y: cy } = at[i];
207 const f = (unit * dr[i]) / reach[i]; // physical units → px for this pendulum
208 if (snap && trailA > 0) {
209 const o = i * 2 * TR;
210 g.strokeStyle = muted;
211 g.globalAlpha = trailA;
212 g.lineWidth = 1;
213 g.beginPath();
214 for (let j = 0; j < TR; j++) {
215 const x = cx + f * snap.trails[o + 2 * j], y = cy + f * snap.trails[o + 2 * j + 1];
216 if (j) g.lineTo(x, y);
217 else g.moveTo(x, y);
218 }
219 g.stroke();
220 }
221 const jt = snap ? snap.joints.subarray(4 * i, 4 * i + 4) : [0, built[i].l1, 0, reach[i]];
222 const x1 = cx + f * jt[0], y1 = cy + f * jt[1], x2 = cx + f * jt[2], y2 = cy + f * jt[3];
223 // a push brightens the pendulum, fading over a second
224 const age = snap ? snap.struck[i] : 1e9;
225 g.globalAlpha = 0.6 + 0.4 * Math.max(0, 1 - age);
226 g.strokeStyle = fg;
227 g.fillStyle = fg;
228 g.lineWidth = 1.5;
229 g.beginPath();
230 g.moveTo(cx, cy);
231 g.lineTo(x1, y1);
232 g.lineTo(x2, y2);
233 g.stroke();
234 const r2 = 2.2 * Math.cbrt(built[i].m2) + 1;
235 g.beginPath();
236 g.arc(x1, y1, 2, 0, 2 * Math.PI);
237 g.moveTo(x2 + r2, y2);
238 g.arc(x2, y2, r2, 0, 2 * Math.PI);
239 g.moveTo(cx + 1.5, cy);
240 g.arc(cx, cy, 1.5, 0, 2 * Math.PI);
241 g.fill();
242 }
243 g.globalAlpha = 1;
244 }
246 function readouts(): Record<string, string> {
247 const { k, built } = physics(params());
248 const r: Record<string, string> = {
249 keys: "1–6: push that pendulum · R: reset to rest",
250 score: snap ? `step ${snap.step} of ${parseScore(params().score as string, 0, 1).length}` : "–",
251 length: `${total(params()).toFixed(1)} s`,
252 "seed used": seedUsed ? String(seedUsed) : "–",
253 "time scale": `${k.toFixed(0)} sim s per s`,
254 };
255 built.forEach((b, i) => {
256 r[`pendulum ${i + 1}`] = `${b.lower.toFixed(1)} + ${b.upper.toFixed(1)} Hz; l1 ${b.l1.toFixed(3)}, l2 ${b.l2.toFixed(3)}, m2/m1 ${b.m2.toFixed(2)}${snap ? `; E ${snap.energy[i].toFixed(2)}` : ""}`;
257 });
258 return r;
259 }
261 const piece: Piece = {
262 get playing() {
263 return playing;
264 },
265 start: (a) => start(a),
266 stop,
267 draw,
268 now: () => (playing && audio ? audio.ctx.currentTime - startedAt : ended ? total(params()) : 0),
269 length: () => total(params()),
270 readouts,
271 dispose() {
272 stop();
273 window.removeEventListener("keydown", onKey);
274 view.replaceChildren();
275 },
276 };
277 return piece;
↑↓ move↵openescclose