Optional coupling of the clicked orbits
Spring and damper on each orbit's difference from the mean, critically
damped at rate r (log slider, off by default); strongly coupled orbits
lock and play in unison.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 changed files+155−10
README.mdmodified+2−0View file
@@ -19,9 +19,11 @@ Static `index.html`, `style.css` and ES modules, no build step; fonts bundled un
1919 - **Sound**: each return to the section plays a note, its pitch set by x (left to right across the view: C3 to C6), on a selectable scale (minor pentatonic by default; major pentatonic, major, minors, whole tone, chromatic, or continuous) in a selectable key (A by default). The key buttons keep the register (C3 to C6) and change which notes x snaps to, so switching key while playing shifts the harmony like a chord change. An island orbit plays a repeating pattern; a chaotic one wanders. Tempo sets drive periods per second (default 16, up to 40; the motion is slowed down to that), independent of the drive frequency.
2020 - **Voices**: the first orbit plays a harp; the next ones marimba, vibraphone, electric piano, music box, ocarina, pizzicato and kalimba (an orbit takes the first voice not in use). **Sustain** (0.1 to 4 s, default 2) sets how long every note rings, the same for all voices and pitches, so they differ only in timbre and attack, and all start equally loud.
2121 - **Rhythm**: *natural, upward* plucks wherever ẋ crosses 0 upward (the left turning point of each swing), at that x and at that moment in the slowed-down motion, so each orbit makes its own rhythm: a lilting, nearly regular one on an island, an uneven one in the sea, and several orbits make polyrhythms. *Both ways* (the default) also plucks at the right turning point (ẋ crossing 0 downward), so each swing plays its low and high end. *Steady* plucks once per drive period, at the section point.
22+- **Coupling** (optional, off by default; 1 to about 3000 s⁻¹ on a log scale): joins the clicked orbits into one system, each pulled toward their mean by a spring and a damper on its difference (critically damped at rate r), leaving the mean motion as it was. Weakly coupled they nudge each other (and lose the energy of their mismatch, often settling into islands); strongly coupled they fall into step and play in unison, even in the chaotic sea. On the first preset, three sea orbits lock above about 900 s⁻¹. While coupled, adding or removing an orbit, or changing the coupling, restarts the clicked orbits from their starts.
2223 - **Parameters**: f₀ (negative: a double well), α, δ, F, Ω/2π, and the view's half-width in x. Presets: double well (islands in a sea; gentle drive with a thin chaotic layer; strong drive), pure cubic, hardening resonance island, and a damped strange attractor.
2324
2425 ## Physics and sound
2526
2627 - `app/js/duffing.js`: each drive period in N equal steps of a 4th-order Yoshida composition of a damping/kick/drift/kick/damping leapfrog (symplectic when undamped, so islands keep their shape over long runs), with the drive tabulated at the kick times. ω h ≤ 0.08 for the stiffest local frequency up to |x| = 1, past which an orbit has escaped.
28+- Coupling (`stepMany` in `duffing.js`): each oscillator gets r² (x̄ − xₖ) + 2r (v̄ − vₖ), x̄ and v̄ the means of those not escaped. The damper part is solved exactly (the mean velocity is kept, differences decay by e^(−2rt)) in half steps around the kicks, the spring part joins the kicks. A damper alone would lock velocities but not positions (two orbits can glide along together in different wells), hence the spring.
2729 - `app/js/voices.js`: notes rendered once per voice, pitch and sustain into AudioBuffers, each ringing for the sustain (the fundamental's 60 dB decay time) and matched in loudness by the K-weighted RMS (ITU-R BS.1770's filter: +4 dB above about 1.7 kHz, high-pass at 38 Hz) over its first 0.3 s. Strings (harp, pizzicato) are Karplus-Strong. The string starts in a rounded triangle (plucked at 0.15 of its length, so harmonics 2 to 4 sit about 8, 14 and 21 dB below the fundamental), loops through a [¼, ½, ¼] low-pass (highs die away first) with an all-pass for fractional-delay tuning, and gets a 4 ms soft attack. Bars, tines and the ocarina are a few decaying sinusoids at the instrument's partial ratios (marimba 1 : 3.93 : 9.2; vibraphone 1 : 4 : 10 with tremolo); the electric piano is two-operator FM with a fading index. Then a gentle 3.5 kHz low-pass, a dark synthetic reverb and a limiter. Notes are scheduled on the audio clock a little ahead of time, softer the more orbits play; each orbit keeps at most 64 notes sounding (the oldest fades out in 40 ms), so fast tempos with long sustains stay light.
app/index.htmlmodified+5−0View file
@@ -19,6 +19,11 @@
1919 <select id="preset" aria-label="Preset"></select>
2020
2121 <div id="sliders" class="sliders"></div>
22+ <label class="row">
23+ <span>Coupling</span>
24+ <input id="coupling" type="range" min="0" max="70" step="1" value="0">
25+ <output></output>
26+ </label>
2227
2328 <div class="sound">
2429 <button id="sound" class="toggle" aria-pressed="false">♪ Sound off</button>
app/js/duffing.jsmodified+78−1View file
@@ -85,5 +85,82 @@ export function createStepper(p) {
8585 s.x = x;
8686 s.v = v;
8787 }
88- return { step, N, T };
88+
89+ // Several oscillators coupled through their differences from the mean (of
90+ // those not escaped): each gets r^2 (xbar - x_k) + 2 r (vbar - v_k), a
91+ // spring and a damper that pull any mismatch in, critically damped, at
92+ // rate r (s^-1), while the mean motion is left as it was. Above some r the
93+ // oscillators fall into step and move as one. (A damper alone locks the
94+ // velocities but not the positions: two oscillators can then glide along
95+ // together in different wells.) The damper is solved exactly (vbar is
96+ // kept, the differences decay by exp(-2 r t)), in half steps around the
97+ // kicks and drift like the own damping; the spring joins the kicks.
98+ // stepMany(states, r, outs) advances the states one drive period; outs
99+ // (optional) as for step, one per state.
100+ const cache = new Map();
101+ const couplingDecay = (r) => {
102+ if (!cache.has(r)) cache.set(r, COMPOSITION.map((w) => Math.exp(-r * w * h)));
103+ return cache.get(r);
104+ };
105+ function stepMany(states, r, outs) {
106+ const m = states.length;
107+ const X = Float64Array.from(states, (s) => s.x);
108+ const V = Float64Array.from(states, (s) => s.v);
109+ const live = states.map((s) => !s.escaped);
110+ const cd = couplingDecay(r);
111+ const k2 = r * r;
112+ const meanX = () => {
113+ let sum = 0;
114+ let n = 0;
115+ for (let k = 0; k < m; k++) if (live[k]) { sum += X[k]; n++; }
116+ return n ? sum / n : 0;
117+ };
118+ const couple = (f) => {
119+ let sum = 0;
120+ let n = 0;
121+ for (let k = 0; k < m; k++) if (live[k]) { sum += V[k]; n++; }
122+ if (n < 2) return;
123+ const mean = sum / n;
124+ for (let k = 0; k < m; k++) if (live[k]) V[k] = mean + (V[k] - mean) * f;
125+ };
126+ if (outs) for (let k = 0; k < m; k++) { outs[k][0] = X[k]; outs[k][1] = V[k]; }
127+ for (let i = 0; i < N; i++) {
128+ for (let j = 0; j < 3; j++) {
129+ const hj = COMPOSITION[j] * h;
130+ const d = decay[j];
131+ couple(cd[j]);
132+ // kick, drift, kick; the spring's pull on each uses the mean x at
133+ // its kick
134+ let xbar = meanX();
135+ for (let k = 0; k < m; k++) {
136+ if (!live[k]) continue;
137+ const x = X[k];
138+ V[k] = V[k] * d + 0.5 * hj * (drive[6 * i + 2 * j] - omega2 * x - alpha * x * x * x + k2 * (xbar - x));
139+ X[k] = x + hj * V[k];
140+ }
141+ xbar = meanX();
142+ for (let k = 0; k < m; k++) {
143+ if (!live[k]) continue;
144+ const x = X[k];
145+ V[k] = (V[k] + 0.5 * hj * (drive[6 * i + 2 * j + 1] - omega2 * x - alpha * x * x * x + k2 * (xbar - x))) * d;
146+ }
147+ couple(cd[j]);
148+ }
149+ for (let k = 0; k < m; k++) {
150+ if (live[k] && !(Math.abs(X[k]) <= X_MAX)) {
151+ live[k] = false;
152+ states[k].escaped = true;
153+ X[k] = Math.sign(X[k]) * X_MAX;
154+ V[k] = 0;
155+ if (outs) for (let q = i + 1; q <= N; q++) { outs[k][2 * q] = X[k]; outs[k][2 * q + 1] = 0; }
156+ }
157+ if (live[k] && outs) { outs[k][2 * i + 2] = X[k]; outs[k][2 * i + 3] = V[k]; }
158+ }
159+ }
160+ for (let k = 0; k < m; k++) {
161+ states[k].x = X[k];
162+ states[k].v = V[k];
163+ }
164+ }
165+ return { step, stepMany, N, T };
89166 }
app/main.jsmodified+70−9View file
@@ -18,6 +18,13 @@
1818 // both turning points of each swing, where x' crosses 0 either way.
1919 // - Changing a parameter or preset restarts everything from the same starts,
2020 // the clicked orbits included.
21+// - Coupling (optional; off by default) joins the clicked orbits into one
22+// system: a spring and damper on each one's difference from their mean
23+// (duffing.js, stepMany), so they pull together and, strong enough, fall
24+// into step. Coupled, the clicked orbits restart from their starts
25+// whenever one is added or removed, or the coupling changes (the dots are
26+// computed ahead from the starts, and the playheads must follow the same
27+// coupled motion).
2128
2229 import { createStepper, physicsOf, X_MAX } from './js/duffing.js';
2330 import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
@@ -63,6 +70,7 @@ let synth = null;
6370 let key = DEFAULT_KEY; // 0 = C, ..., 11 = B
6471 let soundOn = false;
6572 let hueCounter = 0;
73+let coupling = 0; // r (s^-1) of the coupling between clicked orbits; 0: off
6674 let theme;
6775
6876 // ---- physics ---------------------------------------------------------------
@@ -104,6 +112,22 @@ function reset() {
104112 clearDots();
105113 }
106114
115+// whether the clicked orbits move as one coupled system
116+const coupled = () => coupling > 0 && clicked.length > 1;
117+
118+// the clicked orbits' dot clouds, in the order of `clicked`
119+const clickedOrbits = () => clicked.map((c) => orbits.find((o) => o.clicked && o.hue === c.hue));
120+
121+// restart the clicked orbits (dots and playheads) from their starts
122+function restartClicked() {
123+ orbits = orbits.filter((o) => !o.clicked);
124+ for (const c of clicked) {
125+ orbits.unshift(newOrbit(c.x, c.v, CLICK_POINTS, c.hue, true));
126+ c.ph = newPlayhead(c.x, c.v);
127+ }
128+ clearDots([top]);
129+}
130+
107131 // ---- playhead and sound -----------------------------------------------------
108132
109133 const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
@@ -147,11 +171,15 @@ function schedule() {
147171 const rhythm = $('rhythm').value;
148172 const dt = noteDt();
149173 while (nextBeat < now + LOOKAHEAD) {
150- for (const { ph, voice } of clicked) {
151- if (ph.s.escaped) continue;
152- const { x, v } = ph.s;
153- const path = new Float32Array(2 * (stepper.N + 1));
154- stepper.step(ph.s, path);
174+ // advance every playhead one drive period: together if coupled
175+ const before = clicked.map(({ ph }) => ({ ...ph.s }));
176+ const paths = clicked.map(() => new Float32Array(2 * (stepper.N + 1)));
177+ if (coupled()) stepper.stepMany(clicked.map(({ ph }) => ph.s), coupling, paths);
178+ else clicked.forEach(({ ph }, k) => stepper.step(ph.s, paths[k]));
179+ for (const [k, { ph, voice }] of clicked.entries()) {
180+ if (before[k].escaped) continue;
181+ const { x, v } = before[k];
182+ const path = paths[k];
155183 // (at crossings: none in the period it escapes, whose path ends at rest)
156184 const notes = rhythm === 'steady' ? [{ t: nextBeat, x, v }]
157185 : ph.s.escaped ? [] : crossings(path, nextBeat, dt, rhythm === 'both');
@@ -260,7 +288,23 @@ function fill() {
260288 }
261289 drawPoints(o, from);
262290 };
263- for (const o of orbits) if (o.clicked) advance(o, CLICK_PER_FRAME);
291+ if (coupled()) {
292+ // the clicked orbits together, as the playheads will move
293+ const os = clickedOrbits();
294+ const from = os.map((o) => o.n);
295+ for (let k = 0; k < CLICK_PER_FRAME && os.some((o) => o.n < o.cap && !o.s.escaped); k++) {
296+ stepper.stepMany(os.map((o) => o.s), coupling);
297+ for (const o of os) {
298+ if (o.s.escaped || o.n >= o.cap) continue;
299+ o.pts[2 * o.n] = o.s.x;
300+ o.pts[2 * o.n + 1] = o.s.v;
301+ o.n++;
302+ }
303+ }
304+ os.forEach((o, k) => drawPoints(o, from[k]));
305+ } else {
306+ for (const o of orbits) if (o.clicked) advance(o, CLICK_PER_FRAME);
307+ }
264308 let busy = true;
265309 while (busy && performance.now() < deadline) {
266310 busy = false;
@@ -454,6 +498,16 @@ function buildControls() {
454498 key = Number(btn.dataset.key);
455499 for (const b of $('keys').children) b.setAttribute('aria-pressed', b === btn);
456500 });
501+ // coupling: off, then 1 to about 3000 s^-1 on a log scale
502+ const cpl = $('coupling');
503+ const cplOut = () => { cpl.nextElementSibling.textContent = coupling ? `${Math.round(coupling)} s⁻¹` : 'off'; };
504+ cpl.addEventListener('input', () => {
505+ const u = Number(cpl.value);
506+ coupling = u ? 10 ** (u / 20) : 0;
507+ cplOut();
508+ restartClicked();
509+ });
510+ cplOut();
457511 const sus = $('sustain');
458512 Object.assign(sus, { min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, value: SUSTAIN.default });
459513 const susOut = () => { sus.nextElementSibling.textContent = `${Number(sus.value).toFixed(1)} s`; };
@@ -506,6 +560,8 @@ function buildControls() {
506560 const hue = (0.08 + hueCounter++ * 0.382) % 1;
507561 clicked.push({ x, v, hue, voice, ph: newPlayhead(x, v) });
508562 orbits.unshift(newOrbit(x, v, CLICK_POINTS, hue, true));
563+ // coupled: the system has changed, so all restart together
564+ if (coupling > 0) restartClicked();
509565 renderLegend();
510566 });
511567 }
@@ -514,9 +570,14 @@ function removeOrbit(c) {
514570 if (!c) return;
515571 clicked = clicked.filter((q) => q !== c);
516572 orbits = orbits.filter((o) => !o.clicked || o.hue !== c.hue);
517- // redraw the clicked layer, so its dots go
518- clearDots([top]);
519- for (const o of orbits) if (o.clicked) drawPoints(o, 0);
573+ if (coupling > 0) {
574+ // coupled: the system has changed, so all restart together
575+ restartClicked();
576+ } else {
577+ // redraw the clicked layer, so its dots go
578+ clearDots([top]);
579+ for (const o of orbits) if (o.clicked) drawPoints(o, 0);
580+ }
520581 renderLegend();
521582 }
522583