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