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. Short piano notes mark the outer bob's height as it passes a ladder of
5// levels (higher level, higher note), so you hear it come down;
6// when the bob first swings through the bottom, a big low crash. From then on, every time the outer
7// bob crosses the vertical below the pivot there is a crash whose pitch rises with the height of
8// the crossing (continuous). Slight friction throughout, growing toward the end until it comes to
9// rest; the last crash rings out and the piece ends with the fade.
11import type { AudioEngine } from "../../core/audio.ts";
12import { dbToGain } from "../../core/audio.ts";
13import type { Piece } from "../../core/composition.ts";
14import type { Params } from "../../core/params.ts";
15import { mulberry32, randomSeed } from "../../core/rng.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 { NOTE_NAMES, midiToFreq, quantize } 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)
31const BLUR_MAX_SAMPLES = 48;
32const BLUR_SPACING_PX = 2;
33const RING_S = 0.9; // crash ring lifetime
34const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it
35const CLICK_RING_S = 0.35; // click ring lifetime
37interface Snap {
38 t: number;
39 th1: number;
40 th2: number;
41}
43interface Crash {
44 t: number;
45 x: number; // bob position (pendulum units)
46 y: number;
47 strength: number;
48 click?: boolean; // a pass by the pivot, not a crash
49}
51export function createCrashPiece(view: HTMLElement, params: () => Params): Piece {
52 view.classList.add("c04");
53 const canvas = document.createElement("canvas");
54 view.append(canvas);
56 let cfg: PendulumConfig = { m1: 1, l1: 1, g: 1, m2: 1, l2: 1 };
57 let pend: DoublePendulum | null = null;
58 let prevX = 0;
59 let E0 = 1;
60 let vmax = 1;
61 let history: Snap[] = [];
62 let lastHistT = -Infinity;
63 let crashes: Crash[] = [];
64 let crashCount = 0;
65 let clickCount = 0;
66 let lastNote: { handle: NoteHandle; when: number } | null = null;
67 let restAt: number | null = null;
68 let audio: AudioEngine | null = null;
69 let out: GainNode | null = null;
70 let noteBus: GainNode | null = null;
71 let inst: NoteInstrument | null = null;
72 let instKey = "";
73 let clickBus: GainNode | null = null;
74 let clickInst: NoteInstrument | null = null;
75 let clickKey = "";
76 // height notes: levels (MIDI pitches, ascending) and where the bob is among them
77 let heightBus: GainNode | null = null;
78 let heightInst: NoteInstrument | null = null;
79 let heightKey = "";
80 let levels: number[] = [];
81 let levelIdx = 0; // number of levels below the bob's current pitch position
82 let heightCount = 0;
83 let timer: number | undefined;
84 let playing = false;
85 let startToken = 0;
86 let pieceStart = 0;
87 let simPieceT = 0;
88 let seedUsed = 0;
89 let stoppedAt = 0;
90 let stream = false;
91 let simAhead = LOOKAHEAD;
92 let nudge = { d: 0, ratio: 1, side: 1, tipsAt: 0 };
93 let capacity: VoiceCapacity | null = null;
94 let checking = false;
95 let voicesAllowed = 4;
97 const piece: Piece = {
98 get playing() {
99 return playing;
100 },
101 start,
102 stop,
103 draw,
104 now,
105 length: () => endTime(params()),
106 readouts,
107 notice,
108 dispose() {
109 stop();
110 view.classList.remove("c04");
111 view.replaceChildren();
112 },
113 };
115 function now(): number {
116 if (!audio || !playing) return stoppedAt;
117 return audio.ctx.currentTime - pieceStart;
118 }
120 // ── setup ──
122 function makePendulum(P: Params, rand: (() => number) | null) {
123 cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
124 const side = rand ? (rand() < 0.5 ? -1 : 1) : 1;
125 const ratio = rand ? 0.6 + 0.8 * rand() : 1;
126 const speed = P.speed as number;
127 const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
128 nudge = { d: cal.nudge, ratio, side, tipsAt: cal.tipsAt / speed };
129 pend = inverted(cfg, cal.nudge, ratio, side);
130 prevX = bob(cfg, pend.y)[0];
131 E0 = pend.energy();
132 vmax = Math.sqrt((2 * E0) / cfg.m2);
133 history = [];
134 crashes = [];
135 crashCount = 0;
136 clickCount = 0;
137 lastNote = null;
138 restAt = null;
139 pushHistory(0);
140 }
142 function ensureInstrument() {
143 if (!audio || !out) return;
144 const P = params();
145 const ctx = audio.ctx;
146 if (!noteBus) {
147 noteBus = ctx.createGain();
148 noteBus.connect(out);
149 }
150 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), ctx.currentTime, 0.05);
151 const name = P.crashInstrument as string;
152 const key = `${name}\n${name === "modal: custom" ? P.modalCustom : ""}\n${voicesAllowed}`;
153 if (inst && instKey === key) return;
154 inst?.dispose();
155 instKey = key;
156 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
157 inst = factory(ctx, noteBus, { custom: P.modalCustom as string, overrides: { voices: voicesAllowed } });
158 }
160 /** The click for passes by the pivot: its own (cheap) instrument and level. */
161 function ensureClick() {
162 if (!audio || !out) return;
163 const P = params();
164 const ctx = audio.ctx;
165 if (!clickBus) {
166 clickBus = ctx.createGain();
167 clickBus.connect(out);
168 }
169 clickBus.gain.setTargetAtTime(dbToGain(P.clickLevel as number), ctx.currentTime, 0.05);
170 const name = P.clickInstrument as string;
171 const key = P.click ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
172 if (clickKey === key && (clickInst || !key)) return;
173 clickInst?.dispose();
174 clickInst = null;
175 clickKey = key;
176 if (!key) return;
177 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
178 clickInst = factory(ctx, clickBus, { custom: P.modalCustom as string });
179 }
181 /** Short notes at height levels: their own instrument and level. */
182 function ensureHeight() {
183 if (!audio || !out) return;
184 const P = params();
185 const ctx = audio.ctx;
186 if (!heightBus) {
187 heightBus = ctx.createGain();
188 heightBus.connect(out);
189 }
190 heightBus.gain.setTargetAtTime(dbToGain(P.heightLevel as number), ctx.currentTime, 0.05);
191 const name = P.heightInstrument as string;
192 const key = P.heightNotes ? `${name}\n${name === "modal: custom" ? P.modalCustom : ""}` : "";
193 if (heightKey === key && (heightInst || !key)) return;
194 heightInst?.dispose();
195 heightInst = null;
196 heightKey = key;
197 if (!key) return;
198 const factory = (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
199 heightInst = factory(ctx, heightBus, { custom: P.modalCustom as string });
200 }
202 /** The ladder: scale notes between the low and high pitch, every `step`-th. */
203 function makeLevels(P: Params): number[] {
204 const lo = P.heightLow as number, hi = P.heightHigh as number;
205 const root = NOTE_NAMES.indexOf(P.root as string);
206 const all: number[] = [];
207 if (P.scale === "continuous") for (let m = Math.ceil(lo); m <= hi; m++) all.push(m);
208 else for (let m = Math.ceil(lo); m <= hi; m++) if (Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) all.push(m);
209 const step = Math.max(1, Math.round(P.heightStep as number));
210 return all.filter((_, i) => i % step === 0);
211 }
213 /** The bob's height as a pitch position on the ladder (bottom → heightLow, top → heightHigh). */
214 function pitchPos(P: Params, y: number): number {
215 const L = cfg.l1 + cfg.l2;
216 const hn = (L - y) / (2 * L); // 0 at the bottom, 1 at the top
217 return (P.heightLow as number) + ((P.heightHigh as number) - (P.heightLow as number)) * hn;
218 }
220 function countBelow(p: number): number {
221 let i = 0;
222 while (i < levels.length && levels[i] < p) i++;
223 return i;
224 }
226 // ── transport ──
228 async function start(a: AudioEngine, offset: number) {
229 stop();
230 const token = ++startToken;
231 audio = a;
232 const P = params();
233 const ctx = a.ctx;
234 stream = !!P.streamAudio;
235 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
236 const wanted = Math.round(P.maxCrashes as number);
237 voicesAllowed = wanted;
238 if (P.deviceLimit) {
239 checking = true;
240 try {
241 capacity = await crashCapacity(P, ctx.sampleRate, wanted);
242 voicesAllowed = capacity.cap;
243 } finally {
244 checking = false;
245 }
246 if (token !== startToken) return;
247 }
248 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
249 const rng = mulberry32(seedUsed);
250 makePendulum(P, () => rng());
251 levels = makeLevels(P);
252 levelIdx = countBelow(pitchPos(P, bob(cfg, pend!.y)[1]));
253 heightCount = 0;
254 simPieceT = 0;
255 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
257 out = ctx.createGain();
258 out.connect(a.input);
259 ensureInstrument();
260 ensureClick();
261 ensureHeight();
262 await Promise.all([inst?.ready, clickInst?.ready, heightInst?.ready]);
263 if (token !== startToken) return;
264 pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
265 playing = true;
266 tick();
267 timer = window.setInterval(tick, TICK_MS);
268 }
270 function stop() {
271 startToken++;
272 if (timer !== undefined) window.clearInterval(timer);
273 timer = undefined;
274 if (playing) {
275 stoppedAt = now();
276 playing = false;
277 }
278 if (!audio) return;
279 const t = audio.ctx.currentTime;
280 const o = out;
281 if (o) {
282 o.gain.setTargetAtTime(0, t, 0.05);
283 window.setTimeout(() => o.disconnect(), 600);
284 }
285 inst?.dispose();
286 inst = null;
287 instKey = "";
288 clickInst?.dispose();
289 clickInst = null;
290 clickKey = "";
291 clickBus = null;
292 heightInst?.dispose();
293 heightInst = null;
294 heightKey = "";
295 heightBus = null;
296 noteBus = null;
297 out = null;
298 }
300 // ── simulation ──
302 function pushHistory(t: number) {
303 if (!pend) return;
304 history.push({ t, th1: pend.y[0], th2: pend.y[1] });
305 lastHistT = t;
306 }
308 /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
309 function damping(P: Params, t: number): number {
310 const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
311 const s = u * u * (3 - 2 * u);
312 return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
313 }
315 function advanceTo(target: number, sound: boolean) {
316 if (!pend) return;
317 const P = params();
318 const speed = P.speed as number;
319 const end = (P.freeTime as number) + (P.dampTime as number);
320 const restE = P.restEnergy as number;
321 const minY = (P.minDepth as number) * (cfg.l1 + cfg.l2);
322 const p = pend;
323 while (simPieceT < target) {
324 const t0 = simPieceT;
325 simPieceT += DT / speed;
326 p.damping = damping(P, t0);
327 p.step(DT);
328 const [x, y] = bob(cfg, p.y);
329 if (restAt === null && levels.length) heightLevels(t0, pitchPos(P, y), P, sound);
330 // the outer bob crossing the vertical below the pivot (not near the pivot itself: a folded
331 // pendulum sweeping its bob through the middle doesn't count)
332 if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
333 // sweeping past the pivot: a click
334 const f = prevX / (prevX - x);
335 const tc = t0 + f * (simPieceT - t0);
336 clickCount++;
337 if (sound) click(tc, y, P);
338 } else if (restAt === null && y > minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
339 const f = prevX / (prevX - x);
340 const tc = t0 + f * (simPieceT - t0);
341 crashCount++;
342 if (sound) crash(tc, y, P);
343 else crashes.push({ t: tc, x: 0, y, strength: 0.5 });
344 }
345 prevX = x;
346 if (restAt === null && simPieceT >= end && (p.energyNorm() < restE || simPieceT >= end + MAX_SETTLE)) {
347 restAt = simPieceT;
348 if (sound && lastNote) lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
349 }
350 if (simPieceT - lastHistT >= HISTORY_DT) pushHistory(simPieceT);
351 }
352 }
354 /** Notes for every level the bob's pitch position has passed since the last step (with hysteresis). */
355 function heightLevels(t0: number, pos: number, P: Params, sound: boolean) {
356 const h = HEIGHT_HYST * (levels.length > 1 ? (levels[levels.length - 1] - levels[0]) / (levels.length - 1) : 1);
357 // moving up past levels[levelIdx]
358 while (levelIdx < levels.length && pos > levels[levelIdx] + h) {
359 if (sound) heightNote(t0, levels[levelIdx], P);
360 levelIdx++;
361 }
362 // moving down past levels[levelIdx − 1]
363 while (levelIdx > 0 && pos < levels[levelIdx - 1] - h) {
364 levelIdx--;
365 if (sound) heightNote(t0, levels[levelIdx], P);
366 }
367 }
369 function heightNote(t0: number, midi: number, P: Params) {
370 if (!audio || !heightInst || !pend) return;
371 const tc = t0 + DT / (P.speed as number);
372 const when = pieceStart + tc;
373 if (when < audio.ctx.currentTime - 0.02) return;
374 // strength: ramps in over the opening, fades with the energy at the end
375 const ru = (P.heightRamp as number) > 0 ? Math.max(0, Math.min(1, tc / (P.heightRamp as number))) : 1;
376 const from = P.heightRampFrom as number;
377 const ramp = from + (1 - from) * ru * ru * (3 - 2 * ru);
378 const e = Math.min(1, Math.max(0, pend.energy()) / E0);
379 const velocity = (P.heightVel as number) * ramp * Math.pow(e, P.heightFollow as number);
380 heightInst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: P.heightLength as number });
381 heightCount++;
382 }
384 function crash(tc: number, y: number, P: Params) {
385 if (!audio || !inst || !pend) return;
386 const when = pieceStart + tc;
387 if (when < audio.ctx.currentTime - 0.02) return;
388 const L = cfg.l1 + cfg.l2;
389 // pitch: lowest with the bob straight down (y = L), highest at the shallowest crossing that counts
390 const yMin = (P.minDepth as number) * L;
391 const u = Math.max(0, Math.min(1, (L - y) / Math.max(1e-9, L - yMin)));
392 const midi = (P.crashLow as number) + ((P.crashHigh as number) - (P.crashLow as number)) * Math.pow(u, P.crashCurve as number);
393 // strength: the first crash is the accent; later ones follow the bob's speed
394 const velocity = crashCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength(P);
395 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan: 0, duration: 0.5 });
396 if (handle) lastNote = { handle, when };
397 crashes.push({ t: tc, x: 0, y, strength: velocity });
398 }
400 /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
401 function speedStrength(P: Params): number {
402 if (!pend) return 0;
403 const w = pend.derived();
404 const yv = pend.y;
405 const vx = cfg.l1 * Math.cos(yv[0]) * w.w1 + cfg.l2 * Math.cos(yv[1]) * w.w2;
406 const vy = cfg.l1 * Math.sin(yv[0]) * w.w1 + cfg.l2 * Math.sin(yv[1]) * w.w2;
407 const xs = Math.min(1, Math.hypot(vx, vy) / ((P.loudRef as number) * vmax));
408 const floor = P.loudFloor as number;
409 return floor + (1 - floor) * Math.pow(xs, P.loudCurve as number);
410 }
412 function click(tc: number, y: number, P: Params) {
413 if (!audio || !clickInst) return;
414 const when = pieceStart + tc;
415 if (when < audio.ctx.currentTime - 0.02) return;
416 const velocity = (P.clickMaxVel as number) * speedStrength(P);
417 clickInst.play({ when, freq: midiToFreq(P.clickPitch as number), velocity, pan: 0, duration: P.clickLength as number });
418 crashes.push({ t: tc, x: 0, y, strength: velocity, click: true });
419 }
421 function endTime(P: Params): number {
422 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
423 return (restAt ?? (P.freeTime as number) + (P.dampTime as number) + 3) + ring;
424 }
426 function tick() {
427 if (!audio || !playing || !pend) return;
428 const P = params();
429 ensureInstrument();
430 const ctx = audio.ctx;
431 const t = ctx.currentTime - pieceStart;
432 const total = endTime(P);
433 if (restAt !== null && t >= total) {
434 stop();
435 stoppedAt = total;
436 piece.onEnded?.();
437 return;
438 }
439 ensureClick();
440 ensureHeight();
441 advanceTo(t + simAhead, true);
442 for (const i of [inst, clickInst, heightInst]) i?.horizon?.(pieceStart + simPieceT);
444 // keep the states drawing, blur and trail still need
445 const keep = t - (P.trailLength as number) - 0.5;
446 let i = 0;
447 while (i < history.length - 2 && history[i + 1].t < keep) i++;
448 if (i > 0) history.splice(0, i);
449 while (crashes.length && crashes[0].t < t - RING_S - 1) crashes.shift();
450 }
452 // ── drawing ──
454 function stateAt(t: number): Snap {
455 const n = history.length;
456 if (!n) return { t, th1: pend?.y[0] ?? Math.PI, th2: pend?.y[1] ?? Math.PI };
457 if (t <= history[0].t) return history[0];
458 if (t >= history[n - 1].t) return history[n - 1];
459 let lo = 0, hi = n - 1;
460 while (hi - lo > 1) {
461 const mid = (lo + hi) >> 1;
462 if (history[mid].t <= t) lo = mid;
463 else hi = mid;
464 }
465 const a = history[lo], b = history[hi];
466 const f = (t - a.t) / (b.t - a.t);
467 return { t, th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
468 }
470 let lastWall = 0;
471 let frameDt = 1 / 60;
473 function draw() {
474 const P = params();
475 if (!pend) makePendulum(P, null); // preview: balanced straight up
476 const t = now();
477 const wall = performance.now() / 1000;
478 const dtw = wall - lastWall;
479 lastWall = wall;
480 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
481 const g = fitCanvas(canvas);
482 const w = canvas.clientWidth, h = canvas.clientHeight;
483 g.clearRect(0, 0, w, h);
484 const fg = cssColor(view, "--fg");
485 const l1 = cfg.l1, l2 = cfg.l2;
486 const scale = (0.46 * Math.min(w, h)) / (l1 + l2);
487 const x0 = w / 2, y0 = h / 2;
488 const pos = (s: { th1: number; th2: number }) => {
489 const x1 = x0 + scale * l1 * Math.sin(s.th1), y1 = y0 + scale * l1 * Math.cos(s.th1);
490 return [x1, y1, x1 + scale * l2 * Math.sin(s.th2), y1 + scale * l2 * Math.cos(s.th2)];
491 };
493 // trail of the outer bob, fading with age
494 if (P.trails && history.length > 1) {
495 const len = P.trailLength as number;
496 const BANDS = 6;
497 g.strokeStyle = fg;
498 g.lineWidth = 1;
499 g.lineJoin = g.lineCap = "round";
500 for (let band = 0; band < BANDS; band++) {
501 const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS;
502 g.globalAlpha = 0.45 * (1 - (band + 0.5) / BANDS);
503 g.beginPath();
504 let started = false;
505 for (let i = 0; i < history.length; i += 2) {
506 const hs = history[i];
507 if (hs.t < aOld - 0.01 || hs.t > aNew + 0.01) continue;
508 if (hs.t > t) break;
509 const [, , bx, by] = pos(hs);
510 if (started) g.lineTo(bx, by);
511 else g.moveTo(bx, by), (started = true);
512 }
513 g.stroke();
514 }
515 g.globalAlpha = 1;
516 }
518 // crash rings, where each crash happened
519 if (P.crashRings) {
520 for (const c of crashes) {
521 const age = t - c.t;
522 const life = c.click ? CLICK_RING_S : RING_S;
523 if (age < 0 || age > life) continue;
524 const s = stateAt(c.t);
525 const [, , bx, by] = pos(s);
526 g.strokeStyle = fg;
527 g.globalAlpha = (1 - age / life) * (0.4 + 0.6 * c.strength);
528 g.lineWidth = c.click ? 1 : 1.2;
529 g.beginPath();
530 const grow = c.click ? 14 : 60 * (0.5 + c.strength);
531 g.arc(bx, by, (c.click ? 3 : 6) + grow * Math.sqrt(age / life), 0, 2 * Math.PI);
532 g.stroke();
533 }
534 g.globalAlpha = 1;
535 }
537 // the pendulum, with motion blur
538 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
539 let k = 1;
540 if (shutter > 0) {
541 let path = 0;
542 let a = stateAt(t);
543 for (let j = 1; j <= 8; j++) {
544 const b = stateAt(t - (shutter * j) / 8);
545 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
546 a = b;
547 }
548 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
549 }
550 const alpha = k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k);
551 const r1 = 4, r2 = 4 * Math.cbrt(cfg.m2);
552 g.strokeStyle = fg;
553 g.fillStyle = fg;
554 g.lineWidth = 1.5;
555 g.lineCap = "round";
556 g.globalAlpha = alpha;
557 for (let i = 0; i < k; i++) {
558 const [x1, y1, x2, y2] = pos(stateAt(t - (shutter * i) / Math.max(1, k - 1)));
559 g.beginPath();
560 g.moveTo(x0, y0);
561 g.lineTo(x1, y1);
562 g.lineTo(x2, y2);
563 g.stroke();
564 g.beginPath();
565 g.arc(x1, y1, r1, 0, 2 * Math.PI);
566 g.moveTo(x2 + r2, y2);
567 g.arc(x2, y2, r2, 0, 2 * Math.PI);
568 g.fill();
569 }
570 g.globalAlpha = 1;
571 g.beginPath();
572 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
573 g.fill();
574 }
576 function notice(): string | null {
577 if (checking) return "checking what this device can play…";
578 const P = params();
579 if (!P.deviceLimit || !capacity || capacity.perVoice === 0) return null;
580 if (capacity.perVoice > CRASH_BUDGET) return "this device can't render the crashes in real time; expect glitches";
581 const want = Math.round(P.maxCrashes as number);
582 return voicesAllowed < want ? `${voicesAllowed} overlapping crash${voicesAllowed > 1 ? "es" : ""} (of ${want}): reduced to what this device can play` : null;
583 }
585 function readouts(): Record<string, string> {
586 const P = params();
587 const t = now();
588 const free = P.freeTime as number, damp = P.dampTime as number;
589 const phase = restAt !== null && simPieceT >= restAt ? "at rest" : crashCount === 0 ? "falling" : t < free ? "swinging" : t < free + damp ? "damping" : "settling";
590 return {
591 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
592 phase,
593 energy: pend ? `${(pend.energy() / E0).toFixed(3)} of start` : "–",
594 crashes: String(crashCount),
595 clicks: String(clickCount),
596 "height notes": String(heightCount),
597 nudge: `${nudge.d.toExponential(2)} rad ${nudge.side > 0 ? "→" : "←"} (shape ${nudge.ratio.toFixed(2)}), tips at ${nudge.tipsAt.toFixed(1)} s`,
598 friction: `${damping(P, t).toFixed(4)} /sim s`,
599 "seed used": seedUsed ? String(seedUsed) : "–",
600 "crash voices": capacity ? `${voicesAllowed} (one ringing crash: ${Math.round(100 * capacity.perVoice)}% of a core)` : String(voicesAllowed),
601 "audio load": stream ? `renderer ${Math.round(100 * (inst?.load?.() ?? 0))}%, ${inst?.underruns?.() ?? 0} underruns` : `${Math.round(100 * (inst?.load?.() ?? 0))}%`,
602 };
603 }
605 return piece;
606}