/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c02-orbits / piece.ts
399 lines · 14.2 KBCodeBlameHistory
5c043e1Add composition 2: orbitsJeremy Magland 1// Composition 2: orbits.
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";
5c043e1Add composition 2: orbitsJeremy Magland 24import { SLOTS } from "./schema.ts";
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 25import { SharedReverb } from "../../instruments/reverb.ts";
5c043e1Add composition 2: orbitsJeremy Magland 26
27const DT = 0.003; // simulation step (sim seconds)
28const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
29const TICK_MS = 25;
30const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
32interface Crossing {
33 t: number; // piece time
34 th2: number; // wrapped
35 p2: number; // normalized
38interface Orbit {
39 index: number;
40 pend: DoublePendulum;
41 prev: number; // wrapped θ1 at the previous step
42 prevTh2: number;
43 prevP2: number;
44 points: Crossing[];
45 lastNote: { handle: NoteHandle; when: number } | null;
46 restAt: number | null;
49export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece {
50 view.classList.add("c02");
51 const canvas = document.createElement("canvas");
52 view.append(canvas);
53 const plot = new SectionPlot(canvas);
54 const hum = new Hum();
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 55 const portrait = new PortraitLayer(() => now(), () => playing);
56 const portraitSettings = (P: Params): PortraitSettings => ({
57 show: P.portrait as boolean,
58 count: P.portraitCount as number,
59 cpu: P.portraitCpu as number,
60 life: P.portraitLife as number,
61 band: P.portraitBand as number,
62 minHold: P.portraitMinHold as number,
63 maxPoints: P.portraitMaxPoints as number,
64 xfade: P.portraitXfade as number,
65 alpha: P.portraitAlpha as number,
66 size: P.portraitSize as number,
67 tracks: P.traces as boolean,
68 trackMax: P.traceMax as number,
69 trackAlpha: P.traceAlpha as number,
70 trackSize: P.traceSize as number,
71 });
72 const postPortrait = (running: boolean) => {
73 const P = params();
74 // each pendulum's current state, so the worker can trace the orbit it is on
75 const tracks = orbits.filter((o) => o.restAt === null).map((o) => ({ id: o.index, y: Array.from(o.pend.y) }));
76 portrait.post(running, portraitSettings(P), meanEnergy(), P.massRatio as number, P.lengthRatio as number, tracks);
77 };
5c043e1Add composition 2: orbitsJeremy Magland 78
79 let orbits: Orbit[] = [];
80 let audio: AudioEngine | null = null;
81 let out: GainNode | null = null;
82 let noteBus: GainNode | null = null;
83 let instruments = new Map<string, NoteInstrument>(); // by instrument name (+ custom settings)
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 84 let reverb: SharedReverb | null = null; // one reverb for all the orbit instruments
5c043e1Add composition 2: orbitsJeremy Magland 85 let timer: number | undefined;
86 let playing = false;
87 let startToken = 0;
88 let pieceStart = 0;
89 let simPieceT = 0;
90 let seedUsed = 0;
91 let noteCount = 0;
92 let stoppedAt = 0;
93 let restAll: number | null = null; // piece time every orbit had come to rest
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 94 // device limit (measured on the first play, then cached)
95 let capacity: CapacityResult | null = null;
96 let checking = false;
5c043e1Add composition 2: orbitsJeremy Magland 97
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,
5c043e1Add composition 2: orbitsJeremy Magland 109 dispose() {
110 stop();
5c043e1Add composition 2: orbitsJeremy Magland 112 view.classList.remove("c02");
113 view.replaceChildren();
114 },
115 };
117 function now(): number {
118 if (!audio || !playing) return stoppedAt;
119 return audio.ctx.currentTime - pieceStart;
120 }
122 // ── orbits ──
124 function makeOrbit(P: Params, index: number, e: number): Orbit {
125 const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
126 pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1));
127 pend.tau = P.tau as number;
128 return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null };
129 }
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 131 function wantedOrbits(P: Params): number {
132 return Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
133 }
135 /** Orbits actually played: the setting, limited to what this device can handle. */
136 function playableOrbits(P: Params): number {
137 const want = wantedOrbits(P);
138 return P.deviceLimit && capacity ? Math.min(want, capacity.cap) : want;
139 }
5c043e1Add composition 2: orbitsJeremy Magland 141 /** Match the number of orbits to the setting (new ones start at the current target energy). */
142 function syncOrbitCount(P: Params) {
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 143 const n = playableOrbits(P);
5c043e1Add composition 2: orbitsJeremy Magland 144 if (restAll !== null) return;
145 while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT))));
146 if (orbits.length > n) orbits.length = n;
147 }
149 // ── instruments ──
151 function slotOf(o: Orbit): number {
152 return o.index % SLOTS;
153 }
155 function instrumentKey(P: Params, slot: number): { name: string; key: string } {
156 const name = P[`slot${slot + 1}Instrument`] as string;
157 return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name };
158 }
160 /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */
161 function ensureInstruments() {
162 if (!audio || !out) return;
163 const P = params();
164 if (!noteBus) {
165 noteBus = audio.ctx.createGain();
166 noteBus.connect(out);
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 167 reverb = new SharedReverb(audio.ctx, noteBus, P.reverbTime as number);
5c043e1Add composition 2: orbitsJeremy Magland 168 }
169 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
170 const wanted = new Map<string, string>();
171 for (const o of orbits) {
172 const { name, key } = instrumentKey(P, slotOf(o));
173 wanted.set(key, name);
174 }
175 for (const [key, inst] of instruments) {
176 if (!wanted.has(key)) {
177 inst.dispose();
178 instruments.delete(key);
179 }
180 }
181 for (const [key, name] of wanted) {
183 instruments.set(key, NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string, effects: { send: reverb!.input } }));
5c043e1Add composition 2: orbitsJeremy Magland 184 }
185 hum.ensure(audio.ctx, out, P, playing);
186 }
188 // ── transport ──
190 async function start(a: AudioEngine, offset: number) {
191 stop();
192 const token = ++startToken;
193 audio = a;
194 const P = params();
195 const ctx = a.ctx;
197 checking = true;
198 try {
199 capacity = await orbitCapacity(ctx, P, wantedOrbits(P), SLOTS);
200 } finally {
201 checking = false;
202 }
203 if (token !== startToken) return; // stopped or restarted meanwhile
204 }
5c043e1Add composition 2: orbitsJeremy Magland 205 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
206 simPieceT = 0;
207 restAll = null;
208 noteCount = 0;
209 orbits = [];
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 210 portrait.reset(); // the worker starts a fresh portrait
5c043e1Add composition 2: orbitsJeremy Magland 211 syncOrbitCount(P); // random starts at the starting energy, from the seed
212 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
214 out = ctx.createGain();
215 out.connect(a.input);
216 ensureInstruments();
217 await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]);
218 if (token !== startToken) return;
219 pieceStart = ctx.currentTime + 0.1 - offset;
220 hum.start(ctx, P);
221 playing = true;
222 tick();
223 timer = window.setInterval(tick, TICK_MS);
224 }
226 function stop() {
227 startToken++;
228 if (timer !== undefined) window.clearInterval(timer);
229 timer = undefined;
230 const wasPlaying = playing;
231 if (playing) {
232 stoppedAt = now();
233 playing = false;
5c043e1Add composition 2: orbitsJeremy Magland 235 }
236 if (!audio) return;
237 const t = audio.ctx.currentTime;
238 hum.release(audio.ctx, wasPlaying);
239 const o = out;
240 if (o) {
241 o.gain.setTargetAtTime(0, t, 0.05);
242 window.setTimeout(() => o.disconnect(), 600);
243 }
244 for (const inst of instruments.values()) inst.dispose();
245 instruments = new Map();
247 reverb = null;
5c043e1Add composition 2: orbitsJeremy Magland 248 noteBus = null;
249 out = null;
250 }
252 // ── simulation ──
254 function advanceTo(target: number, sound: boolean) {
255 const P = params();
256 const speed = P.speed as number;
257 const duration = P.duration as number;
258 const restE = P.restEnergy as number;
259 for (const o of orbits) {
260 o.pend.cfg.m2 = P.massRatio as number;
261 o.pend.cfg.l2 = P.lengthRatio as number;
262 o.pend.tau = P.tau as number;
263 }
264 while (simPieceT < target) {
265 const eT = energyTarget(P, simPieceT);
266 const t0 = simPieceT;
267 simPieceT += DT / speed;
268 for (const o of orbits) {
269 const pend = o.pend, y = pend.y;
270 pend.eTarget = eT * pend.vTop;
271 pend.step(DT);
272 const cur = wrapAngle(y[0]);
273 if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
274 const f = -o.prev / (cur - o.prev);
275 const c: Crossing = {
276 t: t0 + f * (simPieceT - t0),
277 th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)),
278 p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale,
279 };
280 o.points.push(c);
281 if (sound) playNote(o, c, P);
282 }
283 if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
284 o.restAt = simPieceT;
285 // let this orbit's last real note ring: sustain, then fade
286 if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number);
287 }
288 o.prev = cur;
289 o.prevTh2 = y[1];
290 o.prevP2 = y[3];
291 }
292 if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT;
293 }
294 }
296 function playNote(o: Orbit, c: Crossing, P: Params) {
297 if (!audio) return;
298 const when = pieceStart + c.t;
299 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
300 const slot = slotOf(o);
301 const inst = instruments.get(instrumentKey(P, slot).key);
302 if (!inst) return;
303 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number);
304 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number });
305 if (handle) o.lastNote = { handle, when };
306 noteCount++;
307 }
309 /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */
310 function endTime(P: Params): number {
311 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
312 return (restAll ?? (P.duration as number) + 0.5) + ring;
313 }
315 function meanEnergy(): number {
316 if (!orbits.length) return 0;
317 return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length;
318 }
320 function tick() {
321 if (!audio || !playing) return;
322 const P = params();
323 syncOrbitCount(P);
324 ensureInstruments();
325 const ctx = audio.ctx;
326 const t = ctx.currentTime - pieceStart;
327 const total = endTime(P);
328 if (restAll !== null && t >= total) {
329 stop();
330 stoppedAt = total;
331 piece.onEnded?.();
332 return;
333 }
334 advanceTo(t + LOOKAHEAD, true);
5c043e1Add composition 2: orbitsJeremy Magland 336 hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null);
337 }
339 // ── drawing ──
341 function colors(P: Params): string[] {
342 const list = String(P.colors)
343 .split(",")
344 .map((s) => s.trim())
345 .filter(Boolean);
346 return list.length ? list : [cssColor(view, "--fg")];
347 }
349 function draw() {
350 const P = params();
351 const t = now();
352 const ref = orbits[0]?.pend ?? null;
353 const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null;
354 const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim"));
355 const fade = P.fade as number;
356 const size = P.pointSize as number;
357 const cols = colors(P);
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 358 portrait.draw(f, t, portraitSettings(P), cssColor(view, "--fg"), (id) => cols[id % cols.length]);
5c043e1Add composition 2: orbitsJeremy Magland 359 for (const o of orbits) {
360 let drop = 0;
361 while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++;
362 if (drop > 0) o.points.splice(0, drop);
363 const col = cols[o.index % cols.length];
364 for (const c of o.points) {
365 const age = t - c.t;
366 if (age < 0) break; // not sounded yet
367 drawCrossing(f, c.th2, c.p2, age, fade, size, col);
368 }
369 }
370 }
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 372 function notice(): string | null {
373 if (checking) return "checking what this device can play…";
374 const P = params();
375 const want = wantedOrbits(P);
376 const n = playableOrbits(P);
377 return n < want ? `${n} of ${want} orbits: reduced to what this device can play live` : null;
378 }
5c043e1Add composition 2: orbitsJeremy Magland 380 function readouts(): Record<string, string> {
381 const P = params();
382 const t = now();
383 return {
384 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
385 "energy target": energyTarget(P, t).toFixed(4),
386 "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–",
387 notes: String(noteCount),
388 "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 389 "device limit": capacity ? `${capacity.cap} orbits (synth load ${(100 * capacity.load).toFixed(0)}% with ${capacity.at})` : "–",
5c043e1Add composition 2: orbitsJeremy Magland 390 instruments: String(instruments.size),
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 391 "audio load": `${Math.round(100 * ([...instruments.values()].reduce((s, i) => s + (i.load?.() ?? 0), 0) + (hum.inst?.load?.() ?? 0)))}%`,
5c043e1Add composition 2: orbitsJeremy Magland 392 "seed used": seedUsed ? String(seedUsed) : "–",
393 hum: hum.describe(),
01b86bforbits: show the section portrait and each pendulum's traced orbitJeremy Magland 394 portrait: portrait.describe(),
5c043e1Add composition 2: orbitsJeremy Magland 395 };
396 }
398 return piece;
↑↓ move↵openescclose