73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 1// Composition 1: a double pendulum and its Poincaré section.
2//
3// Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2).
4// Each crossing plays a note: θ2 → pitch, |p2| → loudness, θ2 → pan.
5// A hum runs throughout; its timbre follows the energy.
6// Energy is steered along an envelope: small → peak → hold → zero.
7// Notes stop at the end and the last one is held and faded.
8// Behind the live crossings, a worker draws the section's orbits at the current energy.
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";
5c043e1Add composition 2: orbitsJeremy Magland 15import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
16import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
17import { midiToFreq } from "../../music/scales.ts";
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 18import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
20import { Hum } from "../shared/hum.ts";
21import { noteFor } from "../shared/noteMap.ts";
22import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 23import type { OrbitBatch, OrbitConfig } from "./orbitWorker.ts";
25const DT = 0.002; // simulation step (sim seconds)
26const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
27const TICK_MS = 25;
28const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
29const HISTORY_DT = 1 / 960; // piece-time spacing of stored pendulum snapshots
30const BLUR_MAX_SAMPLES = 64; // cap on sub-frame positions drawn for motion blur
31const BLUR_SPACING_PX = 2; // target distance the tip moves between blur samples
33interface Snapshot {
34 t: number;
35 th1: number;
36 th2: number;
37}
39interface Crossing {
40 t: number; // piece time
41 th2: number; // wrapped
42 p2: number; // normalized
43}
45export function createPoincarePiece(view: HTMLElement, params: () => Params): Piece {
46 view.classList.add("c01");
47 // one canvas: the Poincaré section, with the pendulum as an inset in its upper-left corner
48 const plotCanvas = document.createElement("canvas");
49 view.append(plotCanvas);
51 const hum = new Hum();
53 let pend: DoublePendulum | null = null;
54 let audio: AudioEngine | null = null;
55 let notes: NoteInstrument | null = null;
56 let noteKey = ""; // instrument name (+ custom settings) the current instance was built from
57 let noteBus: GainNode | null = null; // notes level
58 let startToken = 0;
59 let out: GainNode | null = null;
60 let timer: number | undefined;
61 let playing = false;
62 let pieceStart = 0; // AudioContext time of piece time 0
63 let simPieceT = 0; // piece time of the simulation state
64 let seedUsed = 0;
65 let noteCount = 0;
66 let stoppedAt = 0;
67 let history: Snapshot[] = [];
68 let lastHistT = -Infinity;
69 let points: Crossing[] = [];
70 // final note
71 let lastNote: { handle: NoteHandle; when: number } | null = null;
72 // The ending comes from the simulation: once the energy target is zero and the pendulum's
73 // energy falls below restEnergy it is at rest. No crossings register after that; the last
74 // real note is held and faded, the hum fades with it, and the piece ends with the fade.
75 let restAt: number | null = null; // piece time the pendulum came to rest
77 // background orbit portraits (worker). Each portrait is at one fixed energy; when a new one
78 // arrives, the older ones are retired and crossfade out.
79 interface Portrait {
80 gen: number;
81 energy: number;
82 pts: number[]; // [θ2, p2, …]
83 retiredAt: number | null;
84 }
85 let worker: Worker | null = null;
86 let portraits: Portrait[] = [];
87 let resetOrbits = false;
88 let latestGen = 0;
89 let ignoreBelow = 0; // batches from portraits started before the last reset
90 let orbitRate = 0; // points per second, smoothed, for the readout
91 let orbitNew = 0;
92 let orbitRateT = 0;
94 const piece: Piece = {
95 get playing() {
96 return playing;
97 },
98 start,
99 stop,
100 draw,
101 now,
102 length: () => endTime(params()),
103 readouts,
104 dispose() {
105 stop();
106 worker?.terminate();
107 worker = null;
108 view.classList.remove("c01");
109 view.replaceChildren();
110 },
111 };
113 function now(): number {
114 if (!audio || !playing) return stoppedAt;
115 return audio.ctx.currentTime - pieceStart;
116 }
118 // ── orbits ──
120 function ensureWorker(): Worker {
121 if (!worker) {
122 worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" });
123 worker.onmessage = (ev: MessageEvent<OrbitBatch>) => {
124 if (!playing) return;
125 const { gen, energy, pts } = ev.data;
126 latestGen = Math.max(latestGen, gen);
127 if (gen < ignoreBelow) return;
128 let cur = portraits[portraits.length - 1];
129 if (!cur || gen > cur.gen) {
130 const t = now();
131 for (const p of portraits) p.retiredAt ??= t;
132 cur = { gen, energy, pts: [], retiredAt: null };
133 portraits.push(cur);
134 } else if (gen < cur.gen) return; // stale batch from before a reset
135 for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]);
136 orbitNew += pts.length / 2;
137 };
138 }
139 return worker;
140 }
142 function postOrbitConfig(running: boolean) {
143 const P = params();
144 if (!P.orbits && !worker) return;
145 const msg: OrbitConfig = {
146 running: running && (P.orbits as boolean),
147 reset: resetOrbits,
148 energy: pend ? pend.energyNorm() : 0,
149 m2: P.massRatio as number,
150 l2: P.lengthRatio as number,
151 count: Math.round(P.orbitCount as number),
152 life: P.orbitLife as number,
153 band: P.orbitBand as number,
154 minHold: P.orbitMinHold as number,
155 maxPoints: P.orbitMaxPoints as number,
156 cpu: P.orbitCpu as number,
157 };
158 resetOrbits = false;
159 ensureWorker().postMessage(msg);
160 }
162 // ── transport ──
164 function makePendulum(P: Params): DoublePendulum {
165 return new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
166 }
168 async function start(a: AudioEngine, offset: number) {
169 stop();
170 const token = ++startToken;
171 audio = a;
172 const P = params();
173 const ctx = a.ctx;
174 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
175 pend = makePendulum(P);
176 pend.randomize(energyTarget(P, 0), mulberry32(seedUsed));
177 pend.tau = P.tau as number;
178 simPieceT = 0;
179 history = [];
180 lastHistT = -Infinity;
181 points = [];
182 // the worker starts a fresh portrait
183 portraits = [];
184 ignoreBelow = latestGen + 1;
185 resetOrbits = true;
186 noteCount = 0;
187 lastNote = null;
188 restAt = null;
189 // fast-forward silently to the start offset (author "start at")
190 if (offset > 0) advanceTo(offset, false);
192 out = ctx.createGain();
193 out.connect(a.input);
194 ensureInstruments();
5c043e1Add composition 2: orbitsJeremy Magland 195 await Promise.all([notes?.ready, hum.ready]); // e.g. the modal-synth worklet loading
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 196 if (token !== startToken) return; // stopped or restarted meanwhile
197 pieceStart = ctx.currentTime + 0.1 - offset;
200 tick();
201 timer = window.setInterval(tick, TICK_MS);
202 }
204 function ensureInstruments() {
205 if (!audio || !out) return;
206 const P = params();
207 if (!noteBus) {
208 noteBus = audio.ctx.createGain();
209 noteBus.connect(out);
210 }
211 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
212 const name = P.noteInstrument as string;
213 const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
214 if (!notes || noteKey !== key) {
215 notes?.dispose();
216 noteKey = key;
217 notes = NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string });
218 }
222 function stop() {
223 startToken++;
224 if (timer !== undefined) window.clearInterval(timer);
225 timer = undefined;
226 const wasPlaying = playing;
227 if (playing) {
228 stoppedAt = now();
229 playing = false;
230 postOrbitConfig(false);
231 }
232 // release the audio graph (also when a start is still waiting for its instrument to load)
233 if (!audio) return;
234 const t = audio.ctx.currentTime;
237 if (o) {
238 o.gain.setTargetAtTime(0, t, 0.05);
239 window.setTimeout(() => o.disconnect(), 600);
240 }
241 notes?.dispose();
242 notes = null;
243 noteKey = "";
244 noteBus = null;
245 out = null;
246 }
248 // ── simulation ──
250 /** Simulate up to piece time `target`; schedule notes if `sound`. */
251 function advanceTo(target: number, sound: boolean) {
252 if (!pend) return;
253 const P = params();
254 pend.cfg.m2 = P.massRatio as number;
255 pend.cfg.l2 = P.lengthRatio as number;
256 pend.tau = P.tau as number;
257 const speed = P.speed as number;
258 const duration = P.duration as number;
259 const restE = P.restEnergy as number;
260 const y = pend.y;
261 let prev = wrapAngle(y[0]);
262 let prevTh2 = y[1];
263 let prevP2 = y[3];
264 let prevT = simPieceT;
265 while (simPieceT < target) {
266 pend.eTarget = energyTarget(P, simPieceT) * pend.vTop;
267 pend.step(DT);
268 simPieceT += DT / speed;
269 const cur = wrapAngle(y[0]);
270 if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) {
271 const f = -prev / (cur - prev);
272 const c: Crossing = {
273 t: prevT + f * (simPieceT - prevT),
274 th2: wrapAngle(prevTh2 + f * (y[1] - prevTh2)),
275 p2: (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale,
276 };
277 points.push(c);
278 if (sound) playNote(c, P);
279 }
280 if (restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
281 restAt = simPieceT;
282 if (sound) holdFinalNote(P);
283 }
284 prev = cur;
285 prevTh2 = y[1];
286 prevP2 = y[3];
287 prevT = simPieceT;
288 if (simPieceT - lastHistT >= HISTORY_DT) {
289 history.push({ t: simPieceT, th1: y[0], th2: y[1] });
290 lastHistT = simPieceT;
291 }
292 }
293 }
295 function playNote(c: Crossing, P: Params) {
296 if (!audio || !notes) return;
297 const when = pieceStart + c.t;
298 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
5c043e1Add composition 2: orbitsJeremy Magland 300 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2);
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 301 const freq = midiToFreq(midi);
5c043e1Add composition 2: orbitsJeremy Magland 302 const handle = notes.play({ when, freq, velocity, pan, duration: P.noteLength as number });
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 303 if (handle) lastNote = { handle, when };
304 noteCount++;
305 }
307 /** Let the last real note ring: sustain it for finalHold, then fade over finalFade. */
308 function holdFinalNote(P: Params) {
309 if (!lastNote) return;
310 lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
311 }
313 /** Piece time at which everything has faded: known once the pendulum is at rest, estimated before. */
314 function endTime(P: Params): number {
315 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
316 return (restAt ?? (P.duration as number) + 0.5) + ring;
317 }
319 function tick() {
320 if (!audio || !pend || !playing) return;
321 const P = params();
322 ensureInstruments();
323 const ctx = audio.ctx;
324 const t = ctx.currentTime - pieceStart;
325 const total = endTime(P);
326 if (restAt !== null && t >= total) {
327 stop();
328 stoppedAt = total;
329 piece.onEnded?.();
330 return;
331 }
332 advanceTo(t + LOOKAHEAD, true);
333 postOrbitConfig(true);
5c043e1Add composition 2: orbitsJeremy Magland 335 hum.update(ctx, P, pend.energyNorm(), t, restAt !== null ? total : null);
337 // trim history to what drawing still needs
338 let i = 0;
339 while (i < history.length - 1 && history[i + 1].t <= t - 0.1) i++;
340 if (i > 0) history.splice(0, i);
341 }
343 // ── drawing ──
345 function color(name: string): string {
349 /** Pendulum angles at piece time t, interpolated between stored snapshots. */
350 function stateAt(t: number): { th1: number; th2: number } {
351 const n = history.length;
352 if (!n) return pend ? { th1: pend.y[0], th2: pend.y[1] } : { th1: 0, th2: 0 };
353 if (t <= history[0].t) return history[0];
354 if (t >= history[n - 1].t) return history[n - 1];
355 let lo = 0, hi = n - 1; // history[lo].t <= t < history[hi].t
356 while (hi - lo > 1) {
357 const mid = (lo + hi) >> 1;
358 if (history[mid].t <= t) lo = mid;
359 else hi = mid;
360 }
361 const a = history[lo], b = history[hi];
362 const f = (t - a.t) / (b.t - a.t);
363 return { th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
364 }
366 let lastDrawWall = 0;
367 let frameDt = 1 / 60; // smoothed display frame interval (s)
369 /**
370 * The pendulum as an inset in the plot's upper-left corner (outside the energetically allowed
371 * region of the section most of the time), drawn as before: solid arms and filled bobs.
372 * Motion blur: several faint positions spread over the last frame interval.
373 */
374 function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number) {
375 const opacity = P.pendulumAlpha as number;
376 if (opacity <= 0) return;
377 const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
378 const l1 = 1, l2 = P.lengthRatio as number;
379 const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2; // inset radius
380 const scale = (0.9 * R) / (l1 + l2);
381 const x0 = 8 + R, y0 = 8 + R; // pivot
383 // enough samples that the tip moves ~BLUR_SPACING_PX between them
384 let k = 1;
385 if (shutter > 0) {
386 let path = 0;
387 let a = stateAt(t);
388 for (let j = 1; j <= 8; j++) {
389 const b = stateAt(t - (shutter * j) / 8);
390 path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
391 a = b;
392 }
393 k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
394 }
395 // per-sample alpha so a still pendulum still draws (nearly) fully opaque
396 const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k));
397 const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number);
398 const fg = color("--fg");
399 g.strokeStyle = fg;
400 g.fillStyle = fg;
401 g.lineWidth = 1.5;
402 g.lineCap = "round";
403 g.globalAlpha = alpha;
404 for (let i = 0; i < k; i++) {
405 const { th1, th2 } = stateAt(t - (shutter * i) / Math.max(1, k - 1));
406 const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
407 const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2);
408 g.beginPath();
409 g.moveTo(x0, y0);
410 g.lineTo(x1, y1);
411 g.lineTo(x2, y2);
412 g.stroke();
413 g.beginPath();
414 g.arc(x1, y1, r1, 0, 2 * Math.PI);
415 g.moveTo(x2 + r2, y2);
416 g.arc(x2, y2, r2, 0, 2 * Math.PI);
417 g.fill();
418 }
419 g.globalAlpha = opacity;
420 g.beginPath();
421 g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
422 g.fill();
423 g.globalAlpha = 1;
424 }
426 function draw() {
427 const P = params();
428 const t = now();
429 const wall = performance.now() / 1000;
430 const dtw = wall - lastDrawWall;
431 lastDrawWall = wall;
432 if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
433 const fg = color("--fg");
434 const dim = color("--dim");
436 // Poincaré section
437 {
5c043e1Add composition 2: orbitsJeremy Magland 438 const f = plot.begin(P, pend ? pend.energyNorm() : null, pend?.cfg ?? null, pend?.vTop ?? 1, dim);
439 const { g, w, h, sx, sy } = f;
441 // background orbit portraits
442 if (P.orbits) {
443 const xfade = P.orbitXfade as number;
444 const alpha = P.orbitAlpha as number;
445 const sz = P.orbitSize as number;
446 portraits = portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < xfade);
447 g.fillStyle = fg;
448 for (const p of portraits) {
449 g.globalAlpha = alpha * (p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / xfade));
450 g.beginPath();
451 const d = p.pts;
452 for (let i = 0; i < d.length; i += 2) g.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
453 g.fill();
454 }
455 g.globalAlpha = 1;
456 }
458 // the pendulum's own crossings
459 const fade = P.fade as number;
460 const size = P.pointSize as number;
461 let drop = 0;
462 while (drop < points.length && t - points[drop].t > 4.6 * fade) drop++;
463 if (drop > 0) points.splice(0, drop);
464 for (const c of points) {
465 const age = t - c.t;
466 if (age < 0) break; // not sounded yet
5c043e1Add composition 2: orbitsJeremy Magland 467 drawCrossing(f, c.th2, c.p2, age, fade, size, fg);
469 drawPendulum(g, w, h, P, t);
470 }
471 }
473 function readouts(): Record<string, string> {
474 const P = params();
475 const t = now();
476 const wall = performance.now() / 1000;
477 if (wall - orbitRateT > 1) {
478 orbitRate = orbitNew / (wall - orbitRateT || 1);
479 orbitNew = 0;
480 orbitRateT = wall;
481 }
482 return {
483 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
484 "energy target": energyTarget(P, t).toFixed(4),
485 energy: pend ? pend.energyNorm().toFixed(4) : "–",
486 notes: String(noteCount),
487 "seed used": seedUsed ? String(seedUsed) : "–",
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 489 "orbit portrait": (() => {
490 const p = portraits.find((q) => q.retiredAt === null);
491 return p ? `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts, ${Math.round(orbitRate)}/s` : "–";
492 })(),
493 };
494 }
496 return piece;
497}