/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / lab / ensembleWorklet.ts
159 lines · 5.8 KBCodeBlameHistory
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 1// Ensemble lab: six audio-rate double pendulums with their own physics (pitch, mass and length
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 2// ratios, ring time), mixed across the stereo field. A score, kept here on the audio clock so it is
3// sample-accurate, pushes energy into chosen pendulums at each step; keys on the page push too.
5import { DoublePendulum } from "../physics/doublePendulum.ts";
6import { mulberry32 } from "../core/rng.ts";
7import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap } from "./protocol.ts";
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 8import { DcBlock, kick, signal } from "./voice.ts";
10declare const sampleRate: number;
11declare class AudioWorkletProcessor {
12 readonly port: MessagePort;
13 constructor();
15declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
17const TRAIL = 192; // bob positions per pendulum in each snapshot
18const DECIM = 3; // one trail sample every DECIM audio samples
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 19const STEPS_PER_CYCLE = 40; // RK4 steps per cycle of a pendulum's faster mode, at least
21interface V {
22 p: DoublePendulum;
23 dc: DcBlock;
24 trail: Float32Array;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 25 struck: number; // samples since the last push
28class Ensemble extends AudioWorkletProcessor {
29 private s: EnsembleSettings | null = null;
30 private v: V[] = [];
31 private rand = mulberry32(777);
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 32 private seed = 0;
33 private clock = 0; // samples since the score began
34 private step = 0; // score steps played
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 35 private trailW = 0;
36 private count = 0;
37 private sinceSnap = 0;
39 constructor() {
40 super();
41 for (let i = 0; i < ENSEMBLE; i++) {
42 const p = new DoublePendulum({ m1: 1, m2: 1, l1: 1, l2: 1, g: 1 });
43 p.controlled = false;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 44 this.v.push({ p, dc: new DcBlock(), trail: new Float32Array(2 * TRAIL), struck: 1e9 });
46 this.port.onmessage = (e: MessageEvent<EnsembleMsg>) => {
47 const m = e.data;
48 if (m.type === "settings") {
49 this.s = m.s;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 50 if (m.s.seed !== this.seed) {
51 this.seed = m.s.seed;
52 this.rand = mulberry32(m.s.seed);
53 }
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 54 for (let i = 0; i < ENSEMBLE; i++) {
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 55 const cfg = this.v[i].p.cfg, vs = m.s.voices[i];
56 cfg.m1 = 1;
57 cfg.g = 1;
58 cfg.m2 = vs.m2;
59 cfg.l1 = vs.l1;
60 cfg.l2 = vs.l2;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 62 } else if (m.type === "strike") {
63 const v = this.v[m.i];
64 if (v && this.s) {
65 kick(v.p, this.s.pulseAdds * v.p.vTop, this.rand);
66 v.struck = 0;
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 69 else if (m.type === "reset") {
70 for (const v of this.v) v.p.y.fill(0);
71 }
72 };
73 }
75 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
76 const out = outputs[0];
77 const Lo = out[0], Ro = out[1] ?? out[0];
78 const s = this.s;
79 if (!s) return true;
80 const n = Lo.length;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 81 const stepSamples = Math.max(1, s.stepSec * sampleRate), delay = s.startDelay * sampleRate;
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 82 const dcR = 1 - (2 * Math.PI * s.dcCut) / sampleRate;
83 // per-voice constants for this block
84 const per = this.v.map((v, i) => {
85 const vs = s.voices[i];
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 86 const k = s.k; // one time scale: each pendulum's pitch comes from its size
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 87 const dtS = k / sampleRate;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 88 // RK4 is very accurate at ≥ 40 steps per cycle: at audio rate that is usually one per sample
89 const sub = Math.max(1, Math.ceil((STEPS_PER_CYCLE * vs.upperHz) / sampleRate));
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 90 const pan = ENSEMBLE > 1 ? s.spread * ((2 * i) / (ENSEMBLE - 1) - 1) : 0;
91 const a = ((pan + 1) * Math.PI) / 4; // equal-power
92 v.p.damping = vs.ringTime > 0 ? (2 * 6.9078) / (vs.ringTime * k) : 0;
93 return { h: dtS / sub, sub, gl: Math.cos(a) * vs.level, gr: Math.sin(a) * vs.level };
94 });
95 for (let t = 0; t < n; t++) {
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 96 // the score: step k falls at delay + k·step
97 if (this.step < s.score.length && this.clock >= delay + this.step * stepSamples) {
98 for (const { i, add } of s.score[this.step]) {
99 const v = this.v[i];
100 if (!v) continue;
101 kick(v.p, add * v.p.vTop, this.rand);
102 v.struck = 0;
103 }
104 this.step++;
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 107 let l = 0, r = 0;
108 for (let i = 0; i < ENSEMBLE; i++) {
109 const v = this.v[i], c = per[i], p = v.p;
110 for (let j = 0; j < c.sub; j++) p.step(c.h);
111 if (!Number.isFinite(p.y[0])) p.y.fill(0);
112 const d = p.derived();
113 const x = Math.tanh(s.gain * v.dc.run(signal(p, s.signal, d.w1, d.w2), dcR));
114 l += c.gl * x;
115 r += c.gr * x;
116 }
117 Lo[t] = l;
118 Ro[t] = r;
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 119 for (const v of this.v) v.struck++;
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 120 if (++this.count % DECIM === 0) {
121 for (const v of this.v) {
122 const y = v.p.y, cfg = v.p.cfg, o = 2 * this.trailW;
123 v.trail[o] = cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]);
124 v.trail[o + 1] = cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1]);
125 }
126 this.trailW = (this.trailW + 1) % TRAIL;
127 }
128 }
129 this.sinceSnap += n;
130 if (this.sinceSnap >= sampleRate / 30) {
131 this.sinceSnap = 0;
132 const trails = new Float32Array(ENSEMBLE * 2 * TRAIL);
133 this.v.forEach((v, i) => {
134 const o = i * 2 * TRAIL;
135 trails.set(v.trail.subarray(2 * this.trailW), o);
136 trails.set(v.trail.subarray(0, 2 * this.trailW), o + 2 * (TRAIL - this.trailW));
137 });
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 138 const joints = new Float32Array(4 * ENSEMBLE);
139 this.v.forEach((v, i) => {
140 const y = v.p.y, c = v.p.cfg;
141 const x1 = c.l1 * Math.sin(y[0]), y1 = c.l1 * Math.cos(y[0]);
142 joints.set([x1, y1, x1 + c.l2 * Math.sin(y[1]), y1 + c.l2 * Math.cos(y[1])], 4 * i);
143 });
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 144 const snap: EnsembleSnap = {
145 type: "snap",
147 struck: this.v.map((v) => v.struck / sampleRate),
148 time: this.clock / sampleRate,
149 step: this.step,
c2dfd6cLab: six pulsed pendulums (#/ensemble/edit)Jeremy Magland 150 energy: this.v.map((v) => v.p.energyNorm()),
151 trails,
152 };
b7d8818Add "ensemble" as track 5; louder piano in descentJeremy Magland 153 this.port.postMessage(snap, [trails.buffer, joints.buffer]);
155 return true;
156 }
159registerProcessor("pendulum-ensemble", Ensemble);
↑↓ move↵openescclose