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;
39}
41interface Crash {
42 t: number;
43 x: number; // bob position (pendulum units)
44 y: number;
45 strength: number;
46}
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 p = pend;
239 while (simPieceT < target) {
240 const t0 = simPieceT;
241 simPieceT += DT / speed;
242 p.damping = damping(P, t0);
243 p.step(DT);
244 const [x, y] = bob(cfg, p.y);
245 // the outer bob crossing the vertical below the pivot
246 if (restAt === null && y > 0 && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
247 const f = prevX / (prevX - x);
248 const tc = t0 + f * (simPieceT - t0);
249 crashCount++;
250 if (sound) crash(tc, y, P);
251 else crashes.push({ t: tc, x: 0, y, strength: 0.5 });
252 }
253 prevX = x;
254 if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
255 restAt = simPieceT;
256 if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
257 }
258 if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
259 }
260 }
262 function crash(tc: number, y: number, P: Params) {
263 if (!audio || !inst || !pend) return;
264 const when = pieceStart + tc;
265 if (when < audio.ctx.currentTime - 0.02) return;
266 const L = cfg.l1 + cfg.l2;
267 // pitch: lowest with the bob straight down (y = L), highest at the pivot's height (y = 0)
268 const u = Math.max(0, Math.min(1, 1 - y / L));
269 const midi = (P.crashLow as number) + ((P.crashHigh as number) - (P.crashLow as number)) * Math.pow(u, P.crashCurve as number);
270 // strength: the first crash is the accent; later ones follow the bob's speed
271 let velocity: number;
272 if (crashCount === 1) velocity = P.firstVel as number;
273 else {
274 const w = pend.derived();
275 const yv = pend.y;
276 const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2;
277 const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2;
278 const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax));
279 const floor = P.loudFloor as number;
280 velocity = (P.maxVel as number) * (floor + (1 - floor) * Math.pow(xs, P.loudCurve as number));
281 }
282 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: 0.5 });
283 if (handle) lastNote = { handle, when };
284 crashes.push({ t: tc, x: 0, y, strength: velocity });
285 }
287 function endTime(P: Params): number {
288 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
289 return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring;
290 }
292 function tick() {
293 if (!audio || !playing || !pend) return;
294 const P = params();
295 ensureInstrument();
296 const ctx = audio.ctx;
297 const t = ctx.currentTime - pieceStart;
298 const total = endTime(P);
299 if (restAt !== null && t >= total) {
300 stop();
301 stoppedAt = total;
302 piece.onEnded?.();
303 return;
304 }
305 advanceTo(t + simAhead, true);
306 inst?.horizon?.(pieceStart + simPieceT);
308 // the height voice: pitch from the outer bob's height now (not ahead)
309 if (voice) {
310 const s = stateAt(t);
311 const L = cfg.l1 + cfg.l2;
312 const yb = cfg.l1 * Math.cos(s.th1) + cfg.l2 * Math.cos(s.th2); // +L at the bottom, −L at the top
313 const hn = (L - yb) / (2 * L); // 0 at the bottom, 1 at the top
314 const midi = (P.voiceLow as number) + ((P.voiceHigh as number) - (P.voiceLow as number)) * hn;
315 const e = Math.max(0, pend.energy()) / E0;
316 const fadeIn = Math.min(1, Math.max(0, t) / 2);
317 const fadeOut = restAt !== null ? Math.max(0, Math.min(1, (total - t) / Math.max(0.1, P.finalFade as number))) : 1;
318 const level = P.voice ? dbToGain(P.voiceLevel as number) * Math.pow(Math.min(1, e), P.voiceFollow as number) * fadeIn * fadeOut : 0;
319 voice.set(ctx.currentTime, midiToFreq(midi), level, P.voiceBright as number, P.voiceVibrato as number);
320 }
322 // keep the states drawing, blur, trail and voice still need
323 const keep = t - (P.trailLength as number) - 0.5;
324 let i = 0;
325 while (i < history.length - 2 && history[i + 1].t < keep) i++;
326 if (i > 0) history.splice(0, i);
327 while (crashes.length && crashes[0].t < t - RING_S - 1) crashes.shift();
328 }
330 // ── drawing ──
332 function stateAt(t: number): Snap {
333 const n = history.length;
334 if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI };
335 if (t <= history[0].t) return history[0];
336 if (t >= history[n - 1].t) return history[n - 1];
337 let lo = 0, hi = n - 1;
338 while (hi - lo > 1) {
339 const mid = (lo + hi) >> 1;
340 if (history[mid].t <= t) lo = mid;
341 else hi = mid;
342 }
343 const a = history[lo], b = history[hi];
344 const f = (t - a.t) / (b.t - a.t);
345 return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
346 }
348 let lastWall = 0;
349 let frameDt = 1 / 60;
351 function draw() {
352 const P = params();
353 if (!pend) makePendulum(P, null); // preview: balanced straight up
354 const t = now();
355 const wall = performance.now() / 1000;
356 const dtw = wall - lastWall;
357 lastWall = wall;
358 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
359 const g = fitCanvas(canvas);
360 const w = canvas.clientWidth, h = canvas.clientHeight;
361 g.clearRect(0, 0, w, h);
362 const fg = cssColor(view, "--fg");
363 const l1 = cfg.l1, l2 = cfg.l2;
364 const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
365 const x0 = w / 2, y0 = h / 2;
366 const pos = (s: { th1: number; th2: number }) => {
367 const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1);
368 return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)];
369 };
371 // trail of the outer bob, fading with age
372 if (P.trails && history.length > 1) {
373 const len = P.trailLength as number;
374 const BANDS = 6;
375 g.strokeStyle = fg;
376 g.lineWidth = 1;
377 g.lineJoin = g.lineCap = "round";
378 for (let band = 0; band < BANDS; band++) {
379 const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
380 g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
381 g.beginPath();
382 let started = false;
383 for (let i = 0; i < history.length; i += 2) {
384 const hs = history[i];
385 if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue;
386 if (hs.t > t) break;
387 const [, , bx, by] = pos(hs);
388 if (started) g.lineTo(bx, by);
389 else g.moveTo(bx, by), (started = true);
390 }
391 g.stroke();
392 }
393 g.globalAlpha = 1;
394 }
396 // crash rings, where each crash happened
397 if (P.crashRings) {
398 for (const c of crashes) {
399 const age = t - c.t;
400 if (age < 0 || age > RING_S) continue;
401 const s = stateAt(c.t);
402 const [, , bx, by] = pos(s);
403 g.strokeStyle = fg;
404 g.globalAlpha = (1 - age / RING_S) * (0.4 + 0.6 * c.strength);
405 g.lineWidth = 1.2;
406 g.beginPath();
407 g.arc(bx, by, 6 + 60 * Math.sqrt(age / RING_S) * (0.5 + c.strength), 0, 2 * Math.PI);
408 g.stroke();
409 }
410 g.globalAlpha = 1;
411 }
413 // the pendulum, with motion blur
414 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
415 let k = 1;
416 if (shutter > 0) {
417 let path = 0;
418 let a = stateAt(t);
419 for (let j = 1; j <= 8; j++) {
420 const b = stateAt(t - (shutter * j) / 8);
421 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
422 a = b;
423 }
424 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
425 }
426 const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
427 const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2);
428 g.strokeStyle = fg;
429 g.fillStyle = fg;
430 g.lineWidth = 1.5;
431 g.lineCap = "round";
432 g.globalAlpha = alpha;
433 for (let i = 0; i < k; i++) {
434 const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1)));
435 g.beginPath();
436 g.moveTo(x0, y0);
437 g.lineTo(x1, y1);
438 g.lineTo(x2, y2);
439 g.stroke();
440 g.beginPath();
441 g.arc(x1, y1, r1, 0, 2 * Math.PI);
442 g.moveTo(x2 + r2, y2);
443 g.arc(x2, y2, r2, 0, 2 * Math.PI);
444 g.fill();
445 }
446 g.globalAlpha = 1;
447 g.beginPath();
448 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
449 g.fill();
450 }
452 function notice(): string | null {
453 if (checking) return "checking what this device can play…";
454 const P = params();
455 if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
456 if (capacity.perVoice > CRASH_BUDGET) return "this device can't render the crashes in real time; expect glitches";
457 const want = Math.round(P.maxCrashes as number);
458 return voicesAllowed < want ? `${voicesAllowed} overlapping crash${voicesAllowed > 1 ? "es" : ""} (of ${want}): reduced to what this device can play` : null;
459 }
461 function readouts(): Record<string, string> {
462 const P = params();
463 const t = now();
464 const free = P.freeTime as number, damp = P.dampTime as number;
465 const phase = restAt !== null && simPieceT >= restAt ? "at rest" : crashCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
466 return {
467 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
468 phase,
469 energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
470 crashes: String(crashCount),
471 nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
472 friction: `${damping(P, t).toFixed(4)} /sim s`,
473 "seed used": seedUsed ? String(seedUsed) : "–",
474 "crash voices": capacity ? `${voicesAllowed} (one ringing crash: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
475 "audio load": stream ? `renderer ${Math.round(100 * (inst?.load?.() ?? 0))}%, ${inst?.underruns?.() ?? 0} underruns` : `${Math.round(100 * (inst?.load?.() ?? 0))}%`,
476 };
477 }
479 return piece;
480}