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