/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c04-crash / piece.ts
483 lines · 17.6 KBBlameHistoryRaw
1// Composition 4: crash.
2//
3// One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about
4// `fallAfter` seconds. A soft high voice follows the outer bob's height, so you hear it come down;
5// when the bob first swings through the bottom, a big low crash. From then on, every time the outer
6// bob crosses the vertical below the pivot there is a crash whose pitch rises with the height of
7// the crossing (continuous). Slight friction throughout, growing toward the end until it comes to
8// rest; the last crash rings out and the piece ends with the fade.
10import type { AudioEngine } from "../../core/audio.ts";
11import { dbToGain } from "../../core/audio.ts";
12import type { Piece } from "../../core/composition.ts";
13import type { Params } from "../../core/params.ts";
14import { mulberry32, randomSeed } from "../../core/rng.ts";
15import { GlideVoice } from "../../instruments/glide.ts";
16import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
17import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
18import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
19import { midiToFreq } from "../../music/scales.ts";
20import type { DoublePendulum, PendulumConfig } from "../../physics/doublePendulum.ts";
21import { cssColor, fitCanvas } from "../shared/section.ts";
22import { CRASH_BUDGET, crashCapacity, type VoiceCapacity } from "./capacity.ts";
23import { DT, bob, inverted, nudgeForTip } from "./fall.ts";
25const STREAMED = streamedModalInstruments();
26const LOOKAHEAD = 0.15;
27const STREAM_PREBUFFER = 0.4;
28const TICK_MS = 25;
29const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest regardless
30const HISTORY_DT = 1 / 480; // piece-time spacing of stored states (drawing, blur, trail, voice)
31const BLUR_MAX_SAMPLES = 48;
32const BLUR_SPACING_PX = 2;
33const RING_S = 0.9; // crash ring lifetime
35interface Snap {
36 t: number;
37 th1: number;
38 th2: number;
41interface Crash {
42 t: number;
43 x: number; // bob position (pendulum units)
44 y: number;
45 strength: number;
48export function createCrashPiece(view: HTMLElement, params: () => Params): Piece {
49 view.classList.add("c04");
50 const canvas = document.createElement("canvas");
51 view.append(canvas);
53 let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
54 let pend: DoublePendulum | null = null;
55 let prevX = 0;
56 let E0 = 1;
57 let vmax = 1;
58 let history: Snap[] = [];
59 let lastHistT = -Infinity;
60 let crashes: Crash[] = [];
61 let crashCount = 0;
62 let lastNote: { handle: NoteHandle; when: number } | null = null;
63 let restAt: number | null = null;
64 let audio: AudioEngine | null = null;
65 let out: GainNode | null = null;
66 let noteBus: GainNode | null = null;
67 let inst: NoteInstrument | null = null;
68 let instKey = "";
69 let voice: GlideVoice | null = null;
70 let timer: number | undefined;
71 let playing = false;
72 let startToken = 0;
73 let pieceStart = 0;
74 let simPieceT = 0;
75 let seedUsed = 0;
76 let stoppedAt = 0;
77 let stream = false;
78 let simAhead = LOOKAHEAD;
79 let nudge = { d: 0, ratio: 1, side: 1, tipsAt: 0 };
80 let capacity: VoiceCapacity | null = null;
81 let checking = false;
82 let voicesAllowed = 4;
84 const piece: Piece = {
85 get playing() {
86 return playing;
87 },
88 start,
89 stop,
90 draw,
91 now,
92 length: () => endTime(params()),
93 readouts,
94 notice,
95 dispose() {
96 stop();
97 view.classList.remove("c04");
98 view.replaceChildren();
99 },
100 };
102 function now(): number {
103 if (!audio || !playing) return stoppedAt;
104 return audio.ctx.currentTime - pieceStart;
105 }
107 // ── setup ──
109 function makePendulum(P: Params, rand: (() => number) | null) {
110 cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
111 const side = rand ? (rand() < 0.5 ? -1 : 1) : 1;
112 const ratio = rand ? 0.6 + 0.8 * rand() : 1;
113 const speed = P.speed as number;
114 const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
115 nudge = { d: cal.nudge, ratio, side, tipsAt: cal.tipsAt / speed };
116 pend = inverted(cfg, cal.nudge, ratio, side);
117 prevX = bob(cfg, pend.y)[0];
118 E0 = pend.energy();
119 vmax = Math.sqrt((2 * E0) / cfg.m2);
120 history = [];
121 crashes = [];
122 crashCount = 0;
123 lastNote = null;
124 restAt = null;
125 pushHistory(0);
126 }
128 function ensureInstrument() {
129 if (!audio || !out) return;
130 const P = params();
131 const ctx = audio.ctx;
132 if (!noteBus) {
133 noteBus = ctx.createGain();
134 noteBus.connect(out);
135 }
136 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
137 const name = P.crashInstrument as string;
138 const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`;
139 if (inst && instKey === key) return;
140 inst?.dispose();
141 instKey = key;
142 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
143 inst = factory(ctx, noteBus, { custom: P.modalCustom as string, overrides: { voices: voicesAllowed } });
144 }
146 // ── transport ──
148 async function start(a: AudioEngine, offset: number) {
149 stop();
150 const token = ++startToken;
151 audio = a;
152 const P = params();
153 const ctx = a.ctx;
154 stream = !!P.streamAudio;
155 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
156 const wanted = Math.round(P.maxCrashes as number);
157 voicesAllowed = wanted;
158 if (P.deviceLimit) {
159 checking = true;
160 try {
161 capacity = await crashCapacity(P, ctx.sampleRate, wanted);
162 voicesAllowed = capacity.cap;
163 } finally {
164 checking = false;
165 }
166 if (token !== startToken) return;
167 }
168 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
169 const rng = mulberry32(seedUsed);
170 makePendulum(P, () => rng());
171 simPieceT = 0;
172 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
174 out = ctx.createGain();
175 out.connect(a.input);
176 ensureInstrument();
177 await inst?.ready;
178 if (token !== startToken) return;
179 pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
180 if (P.voice) {
181 voice = new GlideVoice(ctx, out);
182 voice.start(ctx.currentTime + 0.05, midiToFreq(P.voiceHigh as number));
183 }
184 playing = true;
185 tick();
186 timer = window.setInterval(tick, TICK_MS);
187 }
189 function stop() {
190 startToken++;
191 if (timer !== undefined) window.clearInterval(timer);
192 timer = undefined;
193 const wasPlaying = playing;
194 if (playing) {
195 stoppedAt = now();
196 playing = false;
197 }
198 if (!audio) return;
199 const t = audio.ctx.currentTime;
200 if (voice) {
201 if (wasPlaying) voice.stop(t + 0.3, 0.3);
202 voice.dispose();
203 voice = null;
204 }
205 const o = out;
206 if (o) {
207 o.gain.setTargetAtTime(0, t, 0.05);
208 window.setTimeout(() => o.disconnect(), 600);
209 }
210 inst?.dispose();
211 inst = null;
212 instKey = "";
213 noteBus = null;
214 out = null;
215 }
217 // ── simulation ──
219 function pushHistory(t: number) {
220 if (!pend) return;
221 history.push({ t, th1: pend.y[0], th2: pend.y[1] });
222 lastHistT = t;
223 }
225 /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
226 function damping(P: Params, t: number): number {
227 const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
228 const s = u * u * (3 - 2 * u);
229 return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
230 }
232 function advanceTo(target: number, sound: boolean) {
233 if (!pend) return;
234 const P = params();
235 const speed = P.speed as number;
236 const end = (P.freeTime as number) + (P.dampTime as number);
237 const restE = P.restEnergy as number;
238 const minY = (P.minDepth as number) * (cfg.l1 + cfg.l2);
239 const p = pend;
240 while (simPieceT < target) {
241 const t0 = simPieceT;
242 simPieceT += DT / speed;
243 p.damping = damping(P, t0);
244 p.step(DT);
245 const [x, y] = bob(cfg, p.y);
246 // the outer bob crossing the vertical below the pivot (not near the pivot itself: a folded
247 // pendulum sweeping its bob through the middle doesn't count)
248 if (restAt === null && y > minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
249 const f = prevX / (prevX - x);
250 const tc = t0 + f * (simPieceT - t0);
251 crashCount++;
252 if (sound) crash(tc, y, P);
253 else crashes.push({ t: tc, x: 0, y, strength: 0.5 });
254 }
255 prevX = x;
256 if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
257 restAt = simPieceT;
258 if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
259 }
260 if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
261 }
262 }
264 function crash(tc: number, y: number, P: Params) {
265 if (!audio || !inst || !pend) return;
266 const when = pieceStart + tc;
267 if (when < audio.ctx.currentTime - 0.02) return;
268 const L = cfg.l1 + cfg.l2;
269 // pitch: lowest with the bob straight down (y = L), highest at the shallowest crossing that counts
270 const yMin = (P.minDepth as number) * L;
271 const u = Math.max(0, Math.min(1, (L - y) / Math.max(1e-9, L - yMin)));
272 const midi = (P.crashLow as number) + ((P.crashHigh as number) - (P.crashLow as number)) * Math.pow(u, P.crashCurve as number);
273 // strength: the first crash is the accent; later ones follow the bob's speed
274 let velocity: number;
275 if (crashCount === 1) velocity = P.firstVel as number;
276 else {
277 const w = pend.derived();
278 const yv = pend.y;
279 const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2;
280 const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2;
281 const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax));
282 const floor = P.loudFloor as number;
283 velocity = (P.maxVel as number) * (floor + (1 - floor) * Math.pow(xs, P.loudCurve as number));
284 }
285 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: 0.5 });
286 if (handle) lastNote = { handle, when };
287 crashes.push({ t: tc, x: 0, y, strength: velocity });
288 }
290 function endTime(P: Params): number {
291 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
292 return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring;
293 }
295 function tick() {
296 if (!audio || !playing || !pend) return;
297 const P = params();
298 ensureInstrument();
299 const ctx = audio.ctx;
300 const t = ctx.currentTime - pieceStart;
301 const total = endTime(P);
302 if (restAt !== null && t >= total) {
303 stop();
304 stoppedAt = total;
305 piece.onEnded?.();
306 return;
307 }
308 advanceTo(t + simAhead, true);
309 inst?.horizon?.(pieceStart + simPieceT);
311 // the height voice: pitch from the outer bob's height now (not ahead)
312 if (voice) {
313 const s = stateAt(t);
314 const L = cfg.l1 + cfg.l2;
315 const yb = cfg.l1 * Math.cos(s.th1) + cfg.l2 * Math.cos(s.th2); // +L at the bottom, −L at the top
316 const hn = (L - yb) / (2 * L); // 0 at the bottom, 1 at the top
317 const midi = (P.voiceLow as number) + ((P.voiceHigh as number) - (P.voiceLow as number)) * hn;
318 const e = Math.max(0, pend.energy()) / E0;
319 const fadeIn = Math.min(1, Math.max(0, t) / 2);
320 const fadeOut = restAt !== null ? Math.max(0, Math.min(1, (total - t) / Math.max(0.1, P.finalFade as number))) : 1;
321 const level = P.voice ? dbToGain(P.voiceLevel as number) * Math.pow(Math.min(1, e), P.voiceFollow as number) * fadeIn * fadeOut : 0;
322 voice.set(ctx.currentTime, midiToFreq(midi), level, P.voiceBright as number, P.voiceVibrato as number);
323 }
325 // keep the states drawing, blur, trail and voice still need
326 const keep = t - (P.trailLength as number) - 0.5;
327 let i = 0;
328 while (i < history.length - 2 && history[i + 1].t < keep) i++;
329 if (i > 0) history.splice(0, i);
330 while (crashes.length && crashes[0].t < t - RING_S - 1) crashes.shift();
331 }
333 // ── drawing ──
335 function stateAt(t: number): Snap {
336 const n = history.length;
337 if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI };
338 if (t <= history[0].t) return history[0];
339 if (t >= history[n - 1].t) return history[n - 1];
340 let lo = 0, hi = n - 1;
341 while (hi - lo > 1) {
342 const mid = (lo + hi) >> 1;
343 if (history[mid].t <= t) lo = mid;
344 else hi = mid;
345 }
346 const a = history[lo], b = history[hi];
347 const f = (t - a.t) / (b.t - a.t);
348 return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
349 }
351 let lastWall = 0;
352 let frameDt = 1 / 60;
354 function draw() {
355 const P = params();
356 if (!pend) makePendulum(P, null); // preview: balanced straight up
357 const t = now();
358 const wall = performance.now() / 1000;
359 const dtw = wall - lastWall;
360 lastWall = wall;
361 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
362 const g = fitCanvas(canvas);
363 const w = canvas.clientWidth, h = canvas.clientHeight;
364 g.clearRect(0, 0, w, h);
365 const fg = cssColor(view, "--fg");
366 const l1 = cfg.l1, l2 = cfg.l2;
367 const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
368 const x0 = w / 2, y0 = h / 2;
369 const pos = (s: { th1: number; th2: number }) => {
370 const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1);
371 return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)];
372 };
374 // trail of the outer bob, fading with age
375 if (P.trails && history.length > 1) {
376 const len = P.trailLength as number;
377 const BANDS = 6;
378 g.strokeStyle = fg;
379 g.lineWidth = 1;
380 g.lineJoin = g.lineCap = "round";
381 for (let band = 0; band < BANDS; band++) {
382 const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
383 g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
384 g.beginPath();
385 let started = false;
386 for (let i = 0; i < history.length; i += 2) {
387 const hs = history[i];
388 if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue;
389 if (hs.t > t) break;
390 const [, , bx, by] = pos(hs);
391 if (started) g.lineTo(bx, by);
392 else g.moveTo(bx, by), (started = true);
393 }
394 g.stroke();
395 }
396 g.globalAlpha = 1;
397 }
399 // crash rings, where each crash happened
400 if (P.crashRings) {
401 for (const c of crashes) {
402 const age = t - c.t;
403 if (age < 0 || age > RING_S) continue;
404 const s = stateAt(c.t);
405 const [, , bx, by] = pos(s);
406 g.strokeStyle = fg;
407 g.globalAlpha = (1 - age / RING_S) * (0.4 + 0.6 * c.strength);
408 g.lineWidth = 1.2;
409 g.beginPath();
410 g.arc(bx, by, 6 + 60 * Math.sqrt(age / RING_S) * (0.5 + c.strength), 0, 2 * Math.PI);
411 g.stroke();
412 }
413 g.globalAlpha = 1;
414 }
416 // the pendulum, with motion blur
417 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
418 let k = 1;
419 if (shutter > 0) {
420 let path = 0;
421 let a = stateAt(t);
422 for (let j = 1; j <= 8; j++) {
423 const b = stateAt(t - (shutter * j) / 8);
424 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
425 a = b;
426 }
427 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
428 }
429 const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
430 const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2);
431 g.strokeStyle = fg;
432 g.fillStyle = fg;
433 g.lineWidth = 1.5;
434 g.lineCap = "round";
435 g.globalAlpha = alpha;
436 for (let i = 0; i < k; i++) {
437 const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1)));
438 g.beginPath();
439 g.moveTo(x0, y0);
440 g.lineTo(x1, y1);
441 g.lineTo(x2, y2);
442 g.stroke();
443 g.beginPath();
444 g.arc(x1, y1, r1, 0, 2 * Math.PI);
445 g.moveTo(x2 + r2, y2);
446 g.arc(x2, y2, r2, 0, 2 * Math.PI);
447 g.fill();
448 }
449 g.globalAlpha = 1;
450 g.beginPath();
451 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
452 g.fill();
453 }
455 function notice(): string | null {
456 if (checking) return "checking what this device can play…";
457 const P = params();
458 if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
459 if (capacity.perVoice > CRASH_BUDGET) return "this device can't render the crashes in real time; expect glitches";
460 const want = Math.round(P.maxCrashes as number);
461 return voicesAllowed < want ? `${voicesAllowed} overlapping crash${voicesAllowed > 1 ? "es" : ""} (of ${want}): reduced to what this device can play` : null;
462 }
464 function readouts(): Record<string, string> {
465 const P = params();
466 const t = now();
467 const free = P.freeTime as number, damp = P.dampTime as number;
468 const phase = restAt !== null && simPieceT >= restAt ? "at rest" : crashCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
469 return {
470 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
471 phase,
472 energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
473 crashes: String(crashCount),
474 nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
475 friction: `${damping(P, t).toFixed(4)} /sim s`,
476 "seed used": seedUsed ? String(seedUsed) : "–",
477 "crash voices": capacity ? `${voicesAllowed} (one ringing crash: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
478 "audio load": stream ? `renderer ${Math.round(100 * (inst?.load?.() ?? 0))}%, ${inst?.underruns?.() ?? 0} underruns` : `${Math.round(100 * (inst?.load?.() ?? 0))}%`,
479 };
480 }
482 return piece;
↑↓ move↵openescclose