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
34const CLICK_RING_S = 0.35; // click ring lifetime
36interface Snap {
37 t: number;
38 th1: number;
39 th2: number;
40}
42interface Crash {
43 t: number;
44 x: number; // bob position (pendulum units)
45 y: number;
46 strength: number;
47 click?: boolean; // a pass by the pivot, not a crash
48}
50export function createCrashPiece(view: HTMLElement, params: () => Params): Piece {
51 view.classList.add("c04");
52 const canvas = document.createElement("canvas");
53 view.append(canvas);
55 let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
56 let pend: DoublePendulum | null = null;
57 let prevX = 0;
58 let E0 = 1;
59 let vmax = 1;
60 let history: Snap[] = [];
61 let lastHistT = -Infinity;
62 let crashes: Crash[] = [];
63 let crashCount = 0;
64 let clickCount = 0;
65 let lastNote: { handle: NoteHandle; when: number } | null = null;
66 let restAt: number | null = null;
67 let audio: AudioEngine | null = null;
68 let out: GainNode | null = null;
69 let noteBus: GainNode | null = null;
70 let inst: NoteInstrument | null = null;
71 let instKey = "";
72 let clickBus: GainNode | null = null;
73 let clickInst: NoteInstrument | null = null;
74 let clickKey = "";
75 let voice: GlideVoice | null = null;
76 let timer: number | undefined;
77 let playing = false;
78 let startToken = 0;
79 let pieceStart = 0;
80 let simPieceT = 0;
81 let seedUsed = 0;
82 let stoppedAt = 0;
83 let stream = false;
84 let simAhead = LOOKAHEAD;
85 let nudge = { d: 0, ratio: 1, side: 1, tipsAt: 0 };
86 let capacity: VoiceCapacity | null = null;
87 let checking = false;
88 let voicesAllowed = 4;
90 const piece: Piece = {
91 get playing() {
92 return playing;
93 },
94 start,
95 stop,
96 draw,
97 now,
98 length: () => endTime(params()),
99 readouts,
100 notice,
101 dispose() {
102 stop();
103 view.classList.remove("c04");
104 view.replaceChildren();
105 },
106 };
108 function now(): number {
109 if (!audio || !playing) return stoppedAt;
110 return audio.ctx.currentTime - pieceStart;
111 }
113 // ── setup ──
115 function makePendulum(P: Params, rand: (() => number) | null) {
116 cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
117 const side = rand ? (rand() < 0.5 ? -1 : 1) : 1;
118 const ratio = rand ? 0.6 + 0.8 * rand() : 1;
119 const speed = P.speed as number;
120 const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
121 nudge = { d: cal.nudge, ratio, side, tipsAt: cal.tipsAt / speed };
122 pend = inverted(cfg, cal.nudge, ratio, side);
123 prevX = bob(cfg, pend.y)[0];
124 E0 = pend.energy();
125 vmax = Math.sqrt((2 * E0) / cfg.m2);
126 history = [];
127 crashes = [];
128 crashCount = 0;
129 clickCount = 0;
130 lastNote = null;
131 restAt = null;
132 pushHistory(0);
133 }
135 function ensureInstrument() {
136 if (!audio || !out) return;
137 const P = params();
138 const ctx = audio.ctx;
139 if (!noteBus) {
140 noteBus = ctx.createGain();
141 noteBus.connect(out);
142 }
143 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
144 const name = P.crashInstrument as string;
145 const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`;
146 if (inst && instKey === key) return;
147 inst?.dispose();
148 instKey = key;
149 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
150 inst = factory(ctx, noteBus, { custom: P.modalCustom as string, overrides: { voices: voicesAllowed } });
151 }
153 /** The click for passes by the pivot: its own (cheap) instrument and level. */
154 function ensureClick() {
155 if (!audio || !out) return;
156 const P = params();
157 const ctx = audio.ctx;
158 if (!clickBus) {
159 clickBus = ctx.createGain();
160 clickBus.connect(out);
161 }
162 clickBus.gain.setTargetAtTime(dbToGain(P.clickLevel as number), ctx.currentTime, 0.05);
163 const name = P.clickInstrument as string;
164 const key = P.click ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
165 if (clickKey === key && (clickInst || !key)) return;
166 clickInst?.dispose();
167 clickInst = null;
168 clickKey = key;
169 if (!key) return;
170 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
171 clickInst = factory(ctx, clickBus, { custom: P.modalCustom as string });
172 }
174 // ── transport ──
176 async function start(a: AudioEngine, offset: number) {
177 stop();
178 const token = ++startToken;
179 audio = a;
180 const P = params();
181 const ctx = a.ctx;
182 stream = !!P.streamAudio;
183 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
184 const wanted = Math.round(P.maxCrashes as number);
185 voicesAllowed = wanted;
186 if (P.deviceLimit) {
187 checking = true;
188 try {
189 capacity = await crashCapacity(P, ctx.sampleRate, wanted);
190 voicesAllowed = capacity.cap;
191 } finally {
192 checking = false;
193 }
194 if (token !== startToken) return;
195 }
196 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
197 const rng = mulberry32(seedUsed);
198 makePendulum(P, () => rng());
199 simPieceT = 0;
200 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
202 out = ctx.createGain();
203 out.connect(a.input);
204 ensureInstrument();
205 ensureClick();
206 await Promise.all([inst?.ready, clickInst?.ready]);
207 if (token !== startToken) return;
208 pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
209 if (P.voice) {
210 voice = new GlideVoice(ctx, out);
211 voice.start(ctx.currentTime + 0.05, midiToFreq(P.voiceHigh as number));
212 }
213 playing = true;
214 tick();
215 timer = window.setInterval(tick, TICK_MS);
216 }
218 function stop() {
219 startToken++;
220 if (timer !== undefined) window.clearInterval(timer);
221 timer = undefined;
222 const wasPlaying = playing;
223 if (playing) {
224 stoppedAt = now();
225 playing = false;
226 }
227 if (!audio) return;
228 const t = audio.ctx.currentTime;
229 if (voice) {
230 if (wasPlaying) voice.stop(t + 0.3, 0.3);
231 voice.dispose();
232 voice = null;
233 }
234 const o = out;
235 if (o) {
236 o.gain.setTargetAtTime(0, t, 0.05);
237 window.setTimeout(() => o.disconnect(), 600);
238 }
239 inst?.dispose();
240 inst = null;
241 instKey = "";
242 clickInst?.dispose();
243 clickInst = null;
244 clickKey = "";
245 clickBus = null;
246 noteBus = null;
247 out = null;
248 }
250 // ── simulation ──
252 function pushHistory(t: number) {
253 if (!pend) return;
254 history.push({ t, th1: pend.y[0], th2: pend.y[1] });
255 lastHistT = t;
256 }
258 /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
259 function damping(P: Params, t: number): number {
260 const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
261 const s = u * u * (3 - 2 * u);
262 return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
263 }
265 function advanceTo(target: number, sound: boolean) {
266 if (!pend) return;
267 const P = params();
268 const speed = P.speed as number;
269 const end = (P.freeTime as number) + (P.dampTime as number);
270 const restE = P.restEnergy as number;
271 const minY = (P.minDepth as number) * (cfg.l1 + cfg.l2);
272 const p = pend;
273 while (simPieceT < target) {
274 const t0 = simPieceT;
275 simPieceT += DT / speed;
276 p.damping = damping(P, t0);
277 p.step(DT);
278 const [x, y] = bob(cfg, p.y);
279 // the outer bob crossing the vertical below the pivot (not near the pivot itself: a folded
280 // pendulum sweeping its bob through the middle doesn't count)
281 if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
282 // sweeping past the pivot: a click
283 const f = prevX / (prevX - x);
284 const tc = t0 + f * (simPieceT - t0);
285 clickCount++;
286 if (sound) click(tc, y, P);
287 } else if (restAt === null && y > minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
288 const f = prevX / (prevX - x);
289 const tc = t0 + f * (simPieceT - t0);
290 crashCount++;
291 if (sound) crash(tc, y, P);
292 else crashes.push({ t: tc, x: 0, y, strength: 0.5 });
293 }
294 prevX = x;
295 if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
296 restAt = simPieceT;
297 if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
298 }
299 if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
300 }
301 }
303 function crash(tc: number, y: number, P: Params) {
304 if (!audio || !inst || !pend) return;
305 const when = pieceStart + tc;
306 if (when < audio.ctx.currentTime - 0.02) return;
307 const L = cfg.l1 + cfg.l2;
308 // pitch: lowest with the bob straight down (y = L), highest at the shallowest crossing that counts
309 const yMin = (P.minDepth as number) * L;
310 const u = Math.max(0, Math.min(1, (L - y) / Math.max(1e-9, L - yMin)));
311 const midi = (P.crashLow as number) + ((P.crashHigh as number) - (P.crashLow as number)) * Math.pow(u, P.crashCurve as number);
312 // strength: the first crash is the accent; later ones follow the bob's speed
313 const velocity = crashCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P);
314 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: 0.5 });
315 if (handle) lastNote = { handle, when };
316 crashes.push({ t: tc, x: 0, y, strength: velocity });
317 }
319 /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
320 function speedStrength(P: Params): number {
321 if (!pend) return 0;
322 const w = pend.derived();
323 const yv = pend.y;
324 const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2;
325 const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2;
326 const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax));
327 const floor = P.loudFloor as number;
328 return floor + (1 - floor) * Math.pow(xs, P.loudCurve as number);
329 }
331 function click(tc: number, y: number, P: Params) {
332 if (!audio || !clickInst) return;
333 const when = pieceStart + tc;
334 if (when < audio.ctx.currentTime - 0.02) return;
335 const velocity = (P.clickMaxVel as number) * speedStrength(P);
336 clickInst.play({ when, freq: midiToFreq(P.clickPitch as number), velocity, pan: 0, duration: P.clickLength as number });
337 crashes.push({ t: tc, x: 0, y, strength: velocity, click: true });
338 }
340 function endTime(P: Params): number {
341 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
342 return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring;
343 }
345 function tick() {
346 if (!audio || !playing || !pend) return;
347 const P = params();
348 ensureInstrument();
349 const ctx = audio.ctx;
350 const t = ctx.currentTime - pieceStart;
351 const total = endTime(P);
352 if (restAt !== null && t >= total) {
353 stop();
354 stoppedAt = total;
355 piece.onEnded?.();
356 return;
357 }
358 ensureClick();
359 advanceTo(t + simAhead, true);
360 inst?.horizon?.(pieceStart + simPieceT);
361 clickInst?.horizon?.(pieceStart + simPieceT);
363 // the height voice: pitch from the outer bob's height now (not ahead)
364 if (voice) {
365 const s = stateAt(t);
366 const L = cfg.l1 + cfg.l2;
367 const yb = cfg.l1 * Math.cos(s.th1) + cfg.l2 * Math.cos(s.th2); // +L at the bottom, −L at the top
368 const hn = (L - yb) / (2 * L); // 0 at the bottom, 1 at the top
369 const midi = (P.voiceLow as number) + ((P.voiceHigh as number) - (P.voiceLow as number)) * hn;
370 const e = Math.max(0, pend.energy()) / E0;
371 const fadeIn = Math.min(1, Math.max(0, t) / 2);
372 const fadeOut = restAt !== null ? Math.max(0, Math.min(1, (total - t) / Math.max(0.1, P.finalFade as number))) : 1;
373 const level = P.voice ? dbToGain(P.voiceLevel as number) * Math.pow(Math.min(1, e), P.voiceFollow as number) * fadeIn * fadeOut : 0;
374 voice.set(ctx.currentTime, midiToFreq(midi), level, P.voiceBright as number, P.voiceVibrato as number);
375 }
377 // keep the states drawing, blur, trail and voice still need
378 const keep = t - (P.trailLength as number) - 0.5;
379 let i = 0;
380 while (i < history.length - 2 && history[i + 1].t < keep) i++;
381 if (i > 0) history.splice(0, i);
382 while (crashes.length && crashes[0].t < t - RING_S - 1) crashes.shift();
383 }
385 // ── drawing ──
387 function stateAt(t: number): Snap {
388 const n = history.length;
389 if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI };
390 if (t <= history[0].t) return history[0];
391 if (t >= history[n - 1].t) return history[n - 1];
392 let lo = 0, hi = n - 1;
393 while (hi - lo > 1) {
394 const mid = (lo + hi) >> 1;
395 if (history[mid].t <= t) lo = mid;
396 else hi = mid;
397 }
398 const a = history[lo], b = history[hi];
399 const f = (t - a.t) / (b.t - a.t);
400 return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
401 }
403 let lastWall = 0;
404 let frameDt = 1 / 60;
406 function draw() {
407 const P = params();
408 if (!pend) makePendulum(P, null); // preview: balanced straight up
409 const t = now();
410 const wall = performance.now() / 1000;
411 const dtw = wall - lastWall;
412 lastWall = wall;
413 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
414 const g = fitCanvas(canvas);
415 const w = canvas.clientWidth, h = canvas.clientHeight;
416 g.clearRect(0, 0, w, h);
417 const fg = cssColor(view, "--fg");
418 const l1 = cfg.l1, l2 = cfg.l2;
419 const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
420 const x0 = w / 2, y0 = h / 2;
421 const pos = (s: { th1: number; th2: number }) => {
422 const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1);
423 return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)];
424 };
426 // trail of the outer bob, fading with age
427 if (P.trails && history.length > 1) {
428 const len = P.trailLength as number;
429 const BANDS = 6;
430 g.strokeStyle = fg;
431 g.lineWidth = 1;
432 g.lineJoin = g.lineCap = "round";
433 for (let band = 0; band < BANDS; band++) {
434 const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
435 g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
436 g.beginPath();
437 let started = false;
438 for (let i = 0; i < history.length; i += 2) {
439 const hs = history[i];
440 if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue;
441 if (hs.t > t) break;
442 const [, , bx, by] = pos(hs);
443 if (started) g.lineTo(bx, by);
444 else g.moveTo(bx, by), (started = true);
445 }
446 g.stroke();
447 }
448 g.globalAlpha = 1;
449 }
451 // crash rings, where each crash happened
452 if (P.crashRings) {
453 for (const c of crashes) {
454 const age = t - c.t;
455 const life = c.click ? CLICK_RING_S : RING_S;
456 if (age < 0 || age > life) continue;
457 const s = stateAt(c.t);
458 const [, , bx, by] = pos(s);
459 g.strokeStyle = fg;
460 g.globalAlpha = (1 - age / life) * (0.4 + 0.6 * c.strength);
461 g.lineWidth = c.click ? 1 : 1.2;
462 g.beginPath();
463 const grow = c.click ? 14 : 60 * (0.5 + c.strength);
464 g.arc(bx, by, (c.click ? 3 : 6) + grow * Math.sqrt(age / life), 0, 2 * Math.PI);
465 g.stroke();
466 }
467 g.globalAlpha = 1;
468 }
470 // the pendulum, with motion blur
471 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
472 let k = 1;
473 if (shutter > 0) {
474 let path = 0;
475 let a = stateAt(t);
476 for (let j = 1; j <= 8; j++) {
477 const b = stateAt(t - (shutter * j) / 8);
478 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
479 a = b;
480 }
481 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
482 }
483 const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
484 const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2);
485 g.strokeStyle = fg;
486 g.fillStyle = fg;
487 g.lineWidth = 1.5;
488 g.lineCap = "round";
489 g.globalAlpha = alpha;
490 for (let i = 0; i < k; i++) {
491 const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1)));
492 g.beginPath();
493 g.moveTo(x0, y0);
494 g.lineTo(x1, y1);
495 g.lineTo(x2, y2);
496 g.stroke();
497 g.beginPath();
498 g.arc(x1, y1, r1, 0, 2 * Math.PI);
499 g.moveTo(x2 + r2, y2);
500 g.arc(x2, y2, r2, 0, 2 * Math.PI);
501 g.fill();
502 }
503 g.globalAlpha = 1;
504 g.beginPath();
505 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
506 g.fill();
507 }
509 function notice(): string | null {
510 if (checking) return "checking what this device can play…";
511 const P = params();
512 if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
513 if (capacity.perVoice > CRASH_BUDGET) return "this device can't render the crashes in real time; expect glitches";
514 const want = Math.round(P.maxCrashes as number);
515 return voicesAllowed < want ? `${voicesAllowed} overlapping crash${voicesAllowed > 1 ? "es" : ""} (of ${want}): reduced to what this device can play` : null;
516 }
518 function readouts(): Record<string, string> {
519 const P = params();
520 const t = now();
521 const free = P.freeTime as number, damp = P.dampTime as number;
522 const phase = restAt !== null && simPieceT >= restAt ? "at rest" : crashCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
523 return {
524 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
525 phase,
526 energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
527 crashes: String(crashCount),
528 clicks: String(clickCount),
529 nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
530 friction: `${damping(P, t).toFixed(4)} /sim s`,
531 "seed used": seedUsed ? String(seedUsed) : "–",
532 "crash voices": capacity ? `${voicesAllowed} (one ringing crash: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
533 "audio load": stream ? `renderer ${Math.round(100 * (inst?.load?.() ?? 0))}%, ${inst?.underruns?.() ?? 0} underruns` : `${Math.round(100 * (inst?.load?.() ?? 0))}%`,
534 };
535 }
537 return piece;
538}