/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / c02-orbits / piece.ts
329 lines · 11.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";
21import { SectionPlot, cssColor, drawCrossing } from "../shared/section.ts";
22import { SLOTS } from "./schema.ts";
24const DT = 0.003; // simulation step (sim seconds)
25const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
26const TICK_MS = 25;
27const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
29interface Crossing {
30 t: number; // piece time
31 th2: number; // wrapped
32 p2: number; // normalized
35interface Orbit {
36 index: number;
37 pend: DoublePendulum;
38 prev: number; // wrapped θ1 at the previous step
39 prevTh2: number;
40 prevP2: number;
41 points: Crossing[];
42 lastNote: { handle: NoteHandle; when: number } | null;
43 restAt: number | null;
46export function createOrbitsPiece(view: HTMLElement, params: () => Params): Piece {
47 view.classList.add("c02");
48 const canvas = document.createElement("canvas");
49 view.append(canvas);
50 const plot = new SectionPlot(canvas);
51 const hum = new Hum();
53 let orbits: Orbit[] = [];
54 let audio: AudioEngine | null = null;
55 let out: GainNode | null = null;
56 let noteBus: GainNode | null = null;
57 let instruments = new Map<string, NoteInstrument>(); // by instrument name (+ custom settings)
58 let timer: number | undefined;
59 let playing = false;
60 let startToken = 0;
61 let pieceStart = 0;
62 let simPieceT = 0;
63 let seedUsed = 0;
64 let noteCount = 0;
65 let stoppedAt = 0;
66 let restAll: number | null = null; // piece time every orbit had come to rest
68 const piece: Piece = {
69 get playing() {
70 return playing;
71 },
72 start,
73 stop,
74 draw,
75 now,
76 length: () => endTime(params()),
77 readouts,
78 dispose() {
79 stop();
80 view.classList.remove("c02");
81 view.replaceChildren();
82 },
83 };
85 function now(): number {
86 if (!audio || !playing) return stoppedAt;
87 return audio.ctx.currentTime - pieceStart;
88 }
90 // ── orbits ──
92 function makeOrbit(P: Params, index: number, e: number): Orbit {
93 const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
94 pend.randomize(e, mulberry32(seedUsed * 1009 + index * 7919 + 1));
95 pend.tau = P.tau as number;
96 return { index, pend, prev: wrapAngle(pend.y[0]), prevTh2: pend.y[1], prevP2: pend.y[3], points: [], lastNote: null, restAt: null };
97 }
99 /** Match the number of orbits to the setting (new ones start at the current target energy). */
100 function syncOrbitCount(P: Params) {
101 const n = Math.max(1, Math.min(20, Math.round(P.orbitCount as number)));
102 if (restAll !== null) return;
103 while (orbits.length < n) orbits.push(makeOrbit(P, orbits.length, Math.max(1e-4, energyTarget(P, simPieceT))));
104 if (orbits.length > n) orbits.length = n;
105 }
107 // ── instruments ──
109 function slotOf(o: Orbit): number {
110 return o.index % SLOTS;
111 }
113 function instrumentKey(P: Params, slot: number): { name: string; key: string } {
114 const name = P[`slot${slot + 1}Instrument`] as string;
115 return { name, key: name === "modal: custom" ? `${name}\n${P.modalCustom}` : name };
116 }
118 /** One instance per distinct instrument; orbits on the same instrument share it (it's polyphonic). */
119 function ensureInstruments() {
120 if (!audio || !out) return;
121 const P = params();
122 if (!noteBus) {
123 noteBus = audio.ctx.createGain();
124 noteBus.connect(out);
125 }
126 noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
127 const wanted = new Map<string, string>();
128 for (const o of orbits) {
129 const { name, key } = instrumentKey(P, slotOf(o));
130 wanted.set(key, name);
131 }
132 for (const [key, inst] of instruments) {
133 if (!wanted.has(key)) {
134 inst.dispose();
135 instruments.delete(key);
136 }
137 }
138 for (const [key, name] of wanted) {
139 if (!instruments.has(key)) instruments.set(key, NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string }));
140 }
141 hum.ensure(audio.ctx, out, P, playing);
142 }
144 // ── transport ──
146 async function start(a: AudioEngine, offset: number) {
147 stop();
148 const token = ++startToken;
149 audio = a;
150 const P = params();
151 const ctx = a.ctx;
152 seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
153 simPieceT = 0;
154 restAll = null;
155 noteCount = 0;
156 orbits = [];
157 syncOrbitCount(P); // random starts at the starting energy, from the seed
158 if (offset > 0) advanceTo(offset, false); // fast-forward silently (author "start at")
160 out = ctx.createGain();
161 out.connect(a.input);
162 ensureInstruments();
163 await Promise.all([...[...instruments.values()].map((i) => i.ready), hum.ready]);
164 if (token !== startToken) return;
165 pieceStart = ctx.currentTime + 0.1 - offset;
166 hum.start(ctx, P);
167 playing = true;
168 tick();
169 timer = window.setInterval(tick, TICK_MS);
170 }
172 function stop() {
173 startToken++;
174 if (timer !== undefined) window.clearInterval(timer);
175 timer = undefined;
176 const wasPlaying = playing;
177 if (playing) {
178 stoppedAt = now();
179 playing = false;
180 }
181 if (!audio) return;
182 const t = audio.ctx.currentTime;
183 hum.release(audio.ctx, wasPlaying);
184 const o = out;
185 if (o) {
186 o.gain.setTargetAtTime(0, t, 0.05);
187 window.setTimeout(() => o.disconnect(), 600);
188 }
189 for (const inst of instruments.values()) inst.dispose();
190 instruments = new Map();
191 noteBus = null;
192 out = null;
193 }
195 // ── simulation ──
197 function advanceTo(target: number, sound: boolean) {
198 const P = params();
199 const speed = P.speed as number;
200 const duration = P.duration as number;
201 const restE = P.restEnergy as number;
202 for (const o of orbits) {
203 o.pend.cfg.m2 = P.massRatio as number;
204 o.pend.cfg.l2 = P.lengthRatio as number;
205 o.pend.tau = P.tau as number;
206 }
207 while (simPieceT < target) {
208 const eT = energyTarget(P, simPieceT);
209 const t0 = simPieceT;
210 simPieceT += DT / speed;
211 for (const o of orbits) {
212 const pend = o.pend, y = pend.y;
213 pend.eTarget = eT * pend.vTop;
214 pend.step(DT);
215 const cur = wrapAngle(y[0]);
216 if (o.restAt === null && o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
217 const f = -o.prev / (cur - o.prev);
218 const c: Crossing = {
219 t: t0 + f * (simPieceT - t0),
220 th2: wrapAngle(o.prevTh2 + f * (y[1] - o.prevTh2)),
221 p2: (o.prevP2 + f * (y[3] - o.prevP2)) / pend.p2Scale,
222 };
223 o.points.push(c);
224 if (sound) playNote(o, c, P);
225 }
226 if (o.restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
227 o.restAt = simPieceT;
228 // let this orbit's last real note ring: sustain, then fade
229 if (sound && o.lastNote) o.lastNote.handle.hold(o.lastNote.when, P.finalHold as number, P.finalFade as number);
230 }
231 o.prev = cur;
232 o.prevTh2 = y[1];
233 o.prevP2 = y[3];
234 }
235 if (restAll === null && orbits.length && orbits.every((o) => o.restAt !== null)) restAll = simPieceT;
236 }
237 }
239 function playNote(o: Orbit, c: Crossing, P: Params) {
240 if (!audio) return;
241 const when = pieceStart + c.t;
242 if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
243 const slot = slotOf(o);
244 const inst = instruments.get(instrumentKey(P, slot).key);
245 if (!inst) return;
246 const { midi, velocity, pan } = noteFor(P, c.th2, c.p2, P[`slot${slot + 1}Octave`] as number);
247 const handle = inst.play({ when, freq: midiToFreq(midi), velocity, pan, duration: P.noteLength as number });
248 if (handle) o.lastNote = { handle, when };
249 noteCount++;
250 }
252 /** Piece time at which everything has faded: known once every orbit is at rest, estimated before. */
253 function endTime(P: Params): number {
254 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
255 return (restAll ?? (P.duration as number) + 0.5) + ring;
256 }
258 function meanEnergy(): number {
259 if (!orbits.length) return 0;
260 return orbits.reduce((s, o) => s + o.pend.energyNorm(), 0) / orbits.length;
261 }
263 function tick() {
264 if (!audio || !playing) return;
265 const P = params();
266 syncOrbitCount(P);
267 ensureInstruments();
268 const ctx = audio.ctx;
269 const t = ctx.currentTime - pieceStart;
270 const total = endTime(P);
271 if (restAll !== null && t >= total) {
272 stop();
273 stoppedAt = total;
274 piece.onEnded?.();
275 return;
276 }
277 advanceTo(t + LOOKAHEAD, true);
278 hum.update(ctx, P, meanEnergy(), t, restAll !== null ? total : null);
279 }
281 // ── drawing ──
283 function colors(P: Params): string[] {
284 const list = String(P.colors)
285 .split(",")
286 .map((s) => s.trim())
287 .filter(Boolean);
288 return list.length ? list : [cssColor(view, "--fg")];
289 }
291 function draw() {
292 const P = params();
293 const t = now();
294 const ref = orbits[0]?.pend ?? null;
295 const eMax = orbits.length ? Math.max(...orbits.map((o) => o.pend.energyNorm())) : null;
296 const f = plot.begin(P, eMax, ref?.cfg ?? null, ref?.vTop ?? 1, cssColor(view, "--dim"));
297 const fade = P.fade as number;
298 const size = P.pointSize as number;
299 const cols = colors(P);
300 for (const o of orbits) {
301 let drop = 0;
302 while (drop < o.points.length && t - o.points[drop].t > 4.6 * fade) drop++;
303 if (drop > 0) o.points.splice(0, drop);
304 const col = cols[o.index % cols.length];
305 for (const c of o.points) {
306 const age = t - c.t;
307 if (age < 0) break; // not sounded yet
308 drawCrossing(f, c.th2, c.p2, age, fade, size, col);
309 }
310 }
311 }
313 function readouts(): Record<string, string> {
314 const P = params();
315 const t = now();
316 return {
317 time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
318 "energy target": energyTarget(P, t).toFixed(4),
319 "energy (mean)": orbits.length ? meanEnergy().toFixed(4) : "–",
320 notes: String(noteCount),
321 "at rest": `${orbits.filter((o) => o.restAt !== null).length} / ${orbits.length}`,
322 instruments: String(instruments.size),
323 "seed used": seedUsed ? String(seedUsed) : "–",
324 hum: hum.describe(),
325 };
326 }
328 return piece;
↑↓ move↵openescclose