2//
3// Several double pendulums at once, all steered along the same energy envelope from random
4// starting states. Only the Poincaré section is shown: each orbit traces its crossings in its own
5// color, and plays its own instrument (orbit n uses instrument slot n, cycling) in its own register.
6// A hum follows the energy. Each orbit plays until it comes to rest; its last note rings out,
7// and the piece ends when every orbit has rested and faded.
9import type { AudioEngine } from "../../core/audio.ts";
10import { dbToGain } from "../../core/audio.ts";
11import type { Piece } from "../../core/composition.ts";
12import type { Params } from "../../core/params.ts";
13import { mulberry32, randomSeed } from "../../core/rng.ts";
14import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
15import type { NoteHandle, NoteInstrument } from "../../instruments/types.ts";
16import { midiToFreq } from "../../music/scales.ts";
17import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
18import { energyTarget } from "../shared/form.ts";
19import { Hum } from "../shared/hum.ts";
20import { noteFor } from "../shared/noteMap.ts";
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 21import { PortraitLayer, type PortraitSettings } from "../shared/portrait.ts";
5c043e1Add composition 2: orbitsJeremy Magland 22import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 23import { orbitCapacity, type CapacityResult } from "./capacity.ts";
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 25import { SharedReverb } from "../../instruments/reverb.ts";
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 26import { SCHEDULE_AHEAD, streamedModalInstruments } from "../../instruments/stream/streamed.ts";
27import type { NoteInstrumentFactory } from "../../instruments/types.ts";
29// rendered-ahead (worker) versions of the modal instruments
30const STREAMED = streamedModalInstruments();
31const STREAM_PREBUFFER = 0.4; // extra delay before the piece starts, so the renderers fill up
5c043e1Add composition 2: orbitsJeremy Magland 32
33const DT = 0.003; // simulation step (sim seconds)
34const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
35const TICK_MS = 25;
36const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
38interface Crossing {
39 t: number; // piece time
40 th2: number; // wrapped
41 p2: number; // normalized
42}
44interface Orbit {
45 index: number;
46 pend: DoublePendulum;
47 prev: number; // wrapped θ1 at the previous step
48 prevTh2: number;
49 prevP2: number;
50 points: Crossing[];
51 lastNote: { handle: NoteHandle; when: number } | null;
52 restAt: number | null;
53}
55export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece {
56 view.classList.add("c02");
57 const canvas = document.createElement("canvas");
58 view.append(canvas);
59 const plot = new SectionPlot(canvas);
60 const hum = new Hum();
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 61 const portrait = new PortraitLayer(() => now(), () => playing);
62 const portraitSettings = (P: Params): PortraitSettings => ({
63 show: P.portrait as boolean,
64 count: P.portraitCount as number,
65 cpu: P.portraitCpu as number,
66 life: P.portraitLife as number,
67 band: P.portraitBand as number,
68 minHold: P.portraitMinHold as number,
69 maxPoints: P.portraitMaxPoints as number,
70 xfade: P.portraitXfade as number,
71 alpha: P.portraitAlpha as number,
72 size: P.portraitSize as number,
73 tracks: P.traces as boolean,
74 trackMax: P.traceMax as number,
75 trackAlpha: P.traceAlpha as number,
76 trackSize: P.traceSize as number,
77 });
78 const postPortrait = (running: boolean) => {
79 const P = params();
80 // each pendulum's current state, so the worker can trace the orbit it is on
81 const tracks = orbits.filter((o) => o.restAt === null).map((o) => ({ id: o.index, y: Array.from(o.pend.y) }));
82 portrait.post(running, portraitSettings(P), meanEnergy(), P.massRatio as number, P.lengthRatio as number, tracks);
83 };
5c043e1Add composition 2: orbitsJeremy Magland 84
85 let orbits: Orbit[] = [];
86 let audio: AudioEngine | null = null;
87 let out: GainNode | null = null;
88 let noteBus: GainNode | null = null;
89 let instruments = new Map<string, NoteInstrument>(); // by instrument name (+ custom settings)
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 90 let reverb: SharedReverb | null = null; // one reverb for all the orbit instruments
92 let playing = false;
93 let startToken = 0;
94 let pieceStart = 0;
95 let simPieceT = 0;
96 let seedUsed = 0;
97 let noteCount = 0;
98 let stoppedAt = 0;
99 let restAll: number | null = null; // piece time every orbit had come to rest
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 100 let stream = false; // instruments rendered ahead in workers (fixed per play)
101 let simAhead = LOOKAHEAD; // how far the simulation (and note scheduling) runs ahead
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 102 // device limit (measured on the first play, then cached)
103 let capacity: CapacityResult | null = null;
104 let checking = false;
5c043e1Add composition 2: orbitsJeremy Magland 105
106 const piece: Piece = {
107 get playing() {
108 return playing;
109 },
110 start,
111 stop,
112 draw,
113 now,
114 length: () => endTime(params()),
115 readouts,
118 stop();
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 119 portrait.dispose();
121 view.replaceChildren();
122 },
123 };
125 function now(): number {
126 if (!audio || !playing) return stoppedAt;
127 return audio.ctx.currentTime - pieceStart;
128 }
130 // ── orbits ──
132 function makeOrbit(P: Params, index: number, e: number): Orbit {
133 const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
134 pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1));
135 pend.tau = P.tau as number;
136 return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null };
137 }
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 139 function wantedOrbits(P: Params): number {
140 return Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
141 }
143 /** Orbits actually played: the setting, limited to what this device can handle. */
144 function playableOrbits(P: Params): number {
145 const want = wantedOrbits(P);
146 return P.deviceLimit && capacity ? Math.min(want, capacity.cap) : want;
147 }
5c043e1Add composition 2: orbitsJeremy Magland 149 /** Match the number of orbits to the setting (new ones start at the current target energy). */
150 function syncOrbitCount(P: Params) {
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 151 const n = playableOrbits(P);
153 while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT))));
154 if (orbits.length > n) orbits.length = n;
155 }
157 // ── instruments ──
159 function slotOf(o: Orbit): number {
160 return o.index % SLOTS;
161 }
163 function instrumentKey(P: Params, slot: number): { name: string; key: string } {
164 const name = P[`slot${slot + 1}Instrument`] as string;
165 return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name };
166 }
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 168 function factory(name: string): NoteInstrumentFactory {
169 return (stream && STREAMED[name]) || NOTE_INSTRUMENTS[name];
170 }
5c043e1Add composition 2: orbitsJeremy Magland 172 /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */
173 function ensureInstruments() {
174 if (!audio || !out) return;
175 const P = params();
176 if (!noteBus) {
177 noteBus = audio.ctx.createGain();
178 noteBus.connect(out);
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 179 reverb = new SharedReverb(audio.ctx, noteBus, P.reverbTime as number);
181 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
182 const wanted = new Map<string, string>();
183 for (const o of orbits) {
184 const { name, key } = instrumentKey(P, slotOf(o));
185 wanted.set(key, name);
186 }
187 for (const [key, inst] of instruments) {
188 if (!wanted.has(key)) {
189 inst.dispose();
190 instruments.delete(key);
191 }
192 }
193 for (const [key, name] of wanted) {
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 194 if (!instruments.has(key))
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 195 instruments.set(key, factory(name)(audio.ctx, noteBus, { custom: P.modalCustom as string, effects: { send: reverb!.input } }));
197 hum.ensure(audio.ctx, out, P, playing);
198 }
200 // ── transport ──
202 async function start(a: AudioEngine, offset: number) {
203 stop();
204 const token = ++startToken;
205 audio = a;
206 const P = params();
207 const ctx = a.ctx;
209 simAhead = stream ? SCHEDULE_AHEAD : LOOKAHEAD;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 210 if (P.deviceLimit) {
211 checking = true;
212 try {
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 213 capacity = await orbitCapacity(ctx, P, wantedOrbits(P), SLOTS, stream);
215 checking = false;
216 }
217 if (token !== startToken) return; // stopped or restarted meanwhile
218 }
5c043e1Add composition 2: orbitsJeremy Magland 219 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
220 simPieceT = 0;
221 restAll = null;
222 noteCount = 0;
223 orbits = [];
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 224 portrait.reset(); // the worker starts a fresh portrait
5c043e1Add composition 2: orbitsJeremy Magland 225 syncOrbitCount(P); // random starts at the starting energy, from the seed
226 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
228 out = ctx.createGain();
229 out.connect(a.input);
230 ensureInstruments();
231 await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]);
232 if (token !== startToken) return;
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 233 pieceStart = ctx.currentTime + 0.1 + (stream ? STREAM_PREBUFFER : 0) - offset;
235 playing = true;
236 tick();
237 timer = window.setInterval(tick, TICK_MS);
238 }
240 function stop() {
241 startToken++;
242 if (timer !== undefined) window.clearInterval(timer);
243 timer = undefined;
244 const wasPlaying = playing;
245 if (playing) {
246 stoppedAt = now();
247 playing = false;
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 248 postPortrait(false);
250 if (!audio) return;
251 const t = audio.ctx.currentTime;
252 hum.release(audio.ctx, wasPlaying);
253 const o = out;
254 if (o) {
255 o.gain.setTargetAtTime(0, t, 0.05);
256 window.setTimeout(() => o.disconnect(), 600);
257 }
258 for (const inst of instruments.values()) inst.dispose();
259 instruments = new Map();
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 260 reverb?.dispose();
261 reverb = null;
263 out = null;
264 }
266 // ── simulation ──
268 function advanceTo(target: number, sound: boolean) {
269 const P = params();
270 const speed = P.speed as number;
271 const duration = P.duration as number;
272 const restE = P.restEnergy as number;
273 for (const o of orbits) {
274 o.pend.cfg.m2 = P.massRatio as number;
275 o.pend.cfg.l2 = P.lengthRatio as number;
276 o.pend.tau = P.tau as number;
277 }
278 while (simPieceT < target) {
279 const eT = energyTarget(P, simPieceT);
280 const t0 = simPieceT;
281 simPieceT += DT / speed;
282 for (const o of orbits) {
283 const pend = o.pend, y = pend.y;
284 pend.eTarget = eT * pend.vTop;
285 pend.step(DT);
286 const cur = wrapAngle(y[0]);
287 if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
288 const f = -o.prev / (cur - o.prev);
289 const c: Crossing = {
290 t: t0 + f * (simPieceT - t0),
291 th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)),
292 p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale,
293 };
294 o.points.push(c);
295 if (sound) playNote(o, c, P);
296 }
297 if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
298 o.restAt = simPieceT;
299 // let this orbit's last real note ring: sustain, then fade
300 if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number);
301 }
302 o.prev = cur;
303 o.prevTh2 = y[1];
304 o.prevP2 = y[3];
305 }
306 if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT;
307 }
308 }
310 function playNote(o: Orbit, c: Crossing, P: Params) {
311 if (!audio) return;
312 const when = pieceStart + c.t;
313 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
314 const slot = slotOf(o);
315 const inst = instruments.get(instrumentKey(P, slot).key);
316 if (!inst) return;
317 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number);
318 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number });
319 if (handle) o.lastNote = { handle, when };
320 noteCount++;
321 }
323 /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */
324 function endTime(P: Params): number {
325 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
326 return (restAll ?? (P.duration as number) + 0.5) + ring;
327 }
329 function meanEnergy(): number {
330 if (!orbits.length) return 0;
331 return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length;
332 }
334 function tick() {
335 if (!audio || !playing) return;
336 const P = params();
337 syncOrbitCount(P);
338 ensureInstruments();
339 const ctx = audio.ctx;
340 const t = ctx.currentTime - pieceStart;
341 const total = endTime(P);
342 if (restAll !== null && t >= total) {
343 stop();
344 stoppedAt = total;
345 piece.onEnded?.();
346 return;
347 }
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 348 advanceTo(t + simAhead, true);
349 // tell the renderers every note up to here has been sent
350 for (const inst of instruments.values()) inst.horizon?.(pieceStart + simPieceT);
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 351 postPortrait(true);
5c043e1Add composition 2: orbitsJeremy Magland 352 hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null);
353 }
355 // ── drawing ──
357 function colors(P: Params): string[] {
358 const list = String(P.colors)
359 .split(",")
360 .map((s) => s.trim())
361 .filter(Boolean);
362 return list.length ? list : [cssColor(view, "--fg")];
363 }
365 function draw() {
366 const P = params();
367 const t = now();
368 const ref = orbits[0]?.pend ?? null;
369 const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null;
370 const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim"));
371 const fade = P.fade as number;
372 const size = P.pointSize as number;
373 const cols = colors(P);
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 374 portrait.draw(f, t, portraitSettings(P), cssColor(view, "--fg"), (id) => cols[id % cols.length]);
376 let drop = 0;
377 while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++;
378 if (drop > 0) o.points.splice(0, drop);
379 const col = cols[o.index % cols.length];
380 for (const c of o.points) {
381 const age = t - c.t;
382 if (age < 0) break; // not sounded yet
383 drawCrossing(f, c.th2, c.p2, age, fade, size, col);
384 }
385 }
386 }
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 388 function notice(): string | null {
389 if (checking) return "checking what this device can play…";
390 const P = params();
391 const want = wantedOrbits(P);
392 const n = playableOrbits(P);
393 return n < want ? `${n} of ${want} orbits: reduced to what this device can play live` : null;
394 }
397 const P = params();
398 const t = now();
399 return {
400 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
401 "energy target": energyTarget(P, t).toFixed(4),
402 "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–",
403 notes: String(noteCount),
404 "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 405 "device limit": capacity ? `${capacity.cap} orbits (synth load ${(100 * capacity.load).toFixed(0)}% with ${capacity.at})` : "–",
408 ? `renderers ${Math.round(100 * Math.max(0, ...[...instruments.values()].map((i) => i.load?.() ?? 0)))}% (busiest), ` +
409 `${[...instruments.values()].reduce((s, i) => s + (i.underruns?.() ?? 0), 0)} underruns; hum ${Math.round(100 * (hum.inst?.load?.() ?? 0))}%`
410 : `${Math.round(100 * ([...instruments.values()].reduce((s, i) => s + (i.load?.() ?? 0), 0) + (hum.inst?.load?.() ?? 0)))}%`,
412 hum: hum.describe(),
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 413 portrait: portrait.describe(),
415 }
417 return piece;
418}