/ interactive_tutorials / duffing_islands
Sign in
interactive_tutorials / duffing_islands
Islands in a sea of chaos: Duffing phase space with sonification
A minimal lab for the driven Duffing oscillator (the hardening and softening tutorial's equation and units): its Poincaré section filled in live, islands among chaos, with clickable orbits that play as notes. - Poincaré section from seed orbits; up to 8 clicked orbits, each with a live trail, its own color and voice, kept across parameter changes - 4th-order Yoshida symplectic integrator, one drive period per step call - Sound: notes when x' crosses 0 upward (natural rhythm, the default) or once per drive period; pitch from x on a chosen scale and key - Eight voices (Karplus-Strong strings, modal bars and tines, FM piano) with one shared sustain, matched in K-weighted loudness - Presets chosen from rendered sections (scripts/section-png.mjs) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit a1f5e15c7c04 Browse files
15 changed files+1503−0
.gitignoreadded+11−0View file
@@ -0,0 +1,11 @@
1+# macOS
2+.DS_Store
3+
4+# Editors
5+.vscode/
6+.idea/
7+*.swp
8+
9+# Logs and temp files
10+*.log
11+*.tmp
README.mdadded+27−0View file
@@ -0,0 +1,27 @@
1+# Islands in a sea of chaos
2+
3+A minimal lab for the driven Duffing oscillator's phase space, a companion to the hardening and softening tutorial (same equation and units):
4+
5+ ẍ + δẋ ± (2πf₀)² x + αx³ = F cos Ωt
6+
7+```bash
8+npm run dev # serves app/ at http://127.0.0.1:8002
9+npm run check # node --check on every module
10+node scripts/section-png.mjs out.png -220 2e7 0 5.6e4 490 1500 0.5 # render a section (for choosing presets)
11+```
12+
13+Static `index.html`, `style.css` and ES modules, no build step; fonts bundled under `app/vendor/`.
14+
15+## What's in it
16+
17+- **Poincaré section**: (x, ẋ) once per drive period, at drive phase 0. Seed orbits from the axes of the view fill it in live. Undamped, regular orbits draw closed curves (islands, island chains) and chaotic ones scatter over the sea. Damped, the seeds settle onto the attractors first.
18+- **Click** to add an orbit from that point (up to 8; click its start ring to remove it): its dots fill in (larger, brighter), and a playhead walks it one drive period per beat, with a fading trail of the continuous motion through each period and a ring at each return to the section. Changing a parameter or preset keeps them, restarted from the same (x, ẋ) under the new parameters. All the clicked orbits play together, on the same beat, each in its own voice (listed in the panel with its color; × removes it).
19+- **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.
20+- **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.
21+- **Rhythm**: *natural* (the default) 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. *Steady* plucks once per drive period, at the section point.
22+- **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.
23+
24+## Physics and sound
25+
26+- `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.
27+- `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.htmladded+69−0View file
@@ -0,0 +1,69 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>Duffing Islands</title>
7+ <link rel="stylesheet" href="style.css">
8+</head>
9+<body>
10+ <header>
11+ <h1>Islands in a sea of chaos</h1>
12+ <p class="eq">
13+ <i>ẍ</i> + <i>δ</i><i>ẋ</i> ± (2π<i>f</i><sub>0</sub>)<sup>2</sup><i>x</i> + <i>α</i><i>x</i><sup>3</sup> = <i>F</i> cos <i>Ωt</i>
14+ </p>
15+ </header>
16+
17+ <div class="layout">
18+ <aside class="panel">
19+ <select id="preset" aria-label="Preset"></select>
20+
21+ <div id="sliders" class="sliders"></div>
22+
23+ <div class="sound">
24+ <button id="sound" class="toggle" aria-pressed="false">♪ Sound off</button>
25+ <label class="row">
26+ <span>Rhythm</span>
27+ <select id="rhythm">
28+ <option value="natural" selected>Natural: ẋ crosses 0 upward</option>
29+ <option value="steady">Steady: each drive period</option>
30+ </select>
31+ </label>
32+ <label class="row">
33+ <span>Scale</span>
34+ <select id="scale"></select>
35+ </label>
36+ <div class="row">
37+ <span>Key</span>
38+ <div id="keys" class="keys" role="group" aria-label="Key"></div>
39+ </div>
40+ <label class="row">
41+ <span>Tempo</span>
42+ <input id="tempo" type="range" min="1" max="40" step="1" value="16">
43+ <output id="tempo-out"></output>
44+ </label>
45+ <label class="row">
46+ <span>Sustain</span>
47+ <input id="sustain" type="range">
48+ <output></output>
49+ </label>
50+ <label class="row">
51+ <span>Volume</span>
52+ <input id="volume" type="range" min="0" max="1" step="0.01" value="0.6">
53+ <output></output>
54+ </label>
55+ </div>
56+
57+ <ul id="orbit-list" class="orbit-list"></ul>
58+ <button id="clear" class="quiet">Clear orbits</button>
59+ </aside>
60+
61+ <div class="plot-wrap">
62+ <canvas id="plot"></canvas>
63+ <p id="hint" class="hint">Click to add orbits · click a start ring to remove it</p>
64+ </div>
65+ </div>
66+
67+ <script type="module" src="main.js"></script>
68+</body>
69+</html>
app/js/duffing.jsadded+89−0View file
@@ -0,0 +1,89 @@
1+// The driven Duffing oscillator, in the units of the hardening and softening
2+// tutorial:
3+// x'' + delta x' + omega2 x + alpha x^3 = F cos(Omega t)
4+// with x the displacement as a fraction of the spring's rest length, t in
5+// seconds, omega2 = sgn(f0) (2 pi f0)^2 (negative: a double well).
6+//
7+// The phase-space picture is the stroboscopic Poincaré section: (x, x') once
8+// per drive period, at drive phase 0. A Stepper advances a state by exactly
9+// one drive period in N equal steps, so each call lands on the section.
10+//
11+// Each step is a fourth-order Yoshida composition of a leapfrog, itself
12+// split as damping (exact) / kick / drift / kick / damping, with time
13+// advancing in the drift. Undamped, it is symplectic in the extended phase
14+// space (x, x', t), so the islands keep their shape over long runs.
15+
16+// Past |x| = X_MAX (the spring fully compressed, or stretched to twice its
17+// length) the motion stops: the orbit has escaped.
18+export const X_MAX = 1;
19+
20+// Slider values (as in the tutorial) to the physics.
21+export function physicsOf({ freq, alpha, delta, F, drive }) {
22+ return {
23+ omega2: Math.sign(freq) * (2 * Math.PI * freq) ** 2,
24+ alpha,
25+ delta,
26+ F,
27+ Omega: 2 * Math.PI * drive,
28+ };
29+}
30+
31+const CBRT2 = Math.cbrt(2);
32+const W1 = 1 / (2 - CBRT2);
33+const W0 = -CBRT2 * W1;
34+const COMPOSITION = [W1, W0, W1];
35+const OMEGA_H = 0.08; // largest omega h per step
36+
37+// The stepper for parameters p. step(s, out) advances s = { x, v, escaped }
38+// by one drive period; if out (a Float32Array of 2 (N + 1) values) is given,
39+// it receives (x, x') at each of the N + 1 step boundaries, for drawing the
40+// trail.
41+export function createStepper(p) {
42+ const T = (2 * Math.PI) / p.Omega;
43+ // the fastest local frequency for |x| up to X_MAX
44+ const omegaMax = Math.max(Math.sqrt(Math.abs(p.omega2) + 3 * Math.abs(p.alpha) * X_MAX * X_MAX), p.Omega);
45+ const N = Math.max(16, Math.ceil((omegaMax * T) / OMEGA_H));
46+ const h = T / N;
47+ // The kicks happen at the same times in every period, so tabulate the
48+ // driving force there: per step, per Yoshida stage, the two half kicks.
49+ const drive = new Float64Array(N * 6);
50+ const decay = COMPOSITION.map((w) => Math.exp(-0.5 * p.delta * w * h));
51+ let t = 0;
52+ for (let i = 0; i < N; i++) {
53+ for (let j = 0; j < 3; j++) {
54+ const hj = COMPOSITION[j] * h;
55+ drive[6 * i + 2 * j] = p.F * Math.cos(p.Omega * t);
56+ t += hj;
57+ drive[6 * i + 2 * j + 1] = p.F * Math.cos(p.Omega * t);
58+ }
59+ }
60+ const { omega2, alpha } = p;
61+ function step(s, out) {
62+ if (s.escaped) return;
63+ let { x, v } = s;
64+ if (out) { out[0] = x; out[1] = v; }
65+ for (let i = 0; i < N; i++) {
66+ for (let j = 0; j < 3; j++) {
67+ const hj = COMPOSITION[j] * h;
68+ const d = decay[j];
69+ v *= d;
70+ v += 0.5 * hj * (drive[6 * i + 2 * j] - omega2 * x - alpha * x * x * x);
71+ x += hj * v;
72+ v += 0.5 * hj * (drive[6 * i + 2 * j + 1] - omega2 * x - alpha * x * x * x);
73+ v *= d;
74+ }
75+ if (!(Math.abs(x) <= X_MAX)) {
76+ s.escaped = true;
77+ s.x = Math.sign(x) * X_MAX;
78+ s.v = 0;
79+ // the rest of the path stays where it escaped
80+ if (out) for (let k = i + 1; k <= N; k++) { out[2 * k] = s.x; out[2 * k + 1] = 0; }
81+ return;
82+ }
83+ if (out) { out[2 * i + 2] = x; out[2 * i + 3] = v; }
84+ }
85+ s.x = x;
86+ s.v = v;
87+ }
88+ return { step, N, T };
89+}
app/js/presets.jsadded+43−0View file
@@ -0,0 +1,43 @@
1+// Presets, in the tutorial's units: freq = f0 in Hz (negative: a double
2+// well), alpha in s^-2, delta in s^-1, F in s^-2, drive = Omega / 2 pi in Hz,
3+// and view, the half-width of the plot in x. Chosen from Poincaré sections
4+// rendered with scripts/section-png.mjs. All undamped but the last: with
5+// damping there are no islands, only attractors.
6+
7+export const PRESETS = [
8+ {
9+ // wells at x = +/-0.31; big islands around each, island chains, and a
10+ // sea of chaos between them
11+ name: 'Double well: islands in a sea of chaos',
12+ params: { freq: -220, alpha: 2e7, delta: 0, F: 5.6e4, drive: 490, view: 0.5 },
13+ },
14+ {
15+ // driven gently: regular motion almost everywhere, with a thin layer
16+ // of chaos along the separatrix between the wells
17+ name: 'Double well: gentle drive, thin chaotic layer',
18+ params: { freq: -220, alpha: 2e7, delta: 0, F: 0.5e4, drive: 400, view: 0.5 },
19+ },
20+ {
21+ // driven hard: chaos almost everywhere, a few small islands left
22+ name: 'Double well: strong drive, mostly chaos',
23+ params: { freq: -220, alpha: 2e7, delta: 0, F: 15e4, drive: 490, view: 0.6 },
24+ },
25+ {
26+ // no linear stiffness: one large island in a wide chaotic sea, ringed
27+ // by regular motion at larger swings
28+ name: 'Pure cubic (f₀ = 0): one island, wide sea',
29+ params: { freq: 0, alpha: 2e7, delta: 0, F: 5e4, drive: 150, view: 0.5 },
30+ },
31+ {
32+ // the drive above f0 bends the hardening resonance into a crescent
33+ // island beside the central one; nearly all regular
34+ name: 'Hardening spring: resonance island',
35+ params: { freq: 220, alpha: 3e7, delta: 0, F: 8e4, drive: 300, view: 0.5 },
36+ },
37+ {
38+ // damped: every start settles onto a chaotic attractor, hopping between
39+ // the wells (a preset of the tutorial)
40+ name: 'Damped double well: strange attractor',
41+ params: { freq: -220, alpha: 2e7, delta: 10, F: 12.5e4, drive: 295, view: 0.7 },
42+ },
43+];
app/js/voices.jsadded+308−0View file
@@ -0,0 +1,308 @@
1+// The instruments the orbits play, and the mapping from a point's x to its
2+// pitch. Each orbit plays its own voice, so several can be told apart.
3+//
4+// Each note is rendered once into an AudioBuffer (cached per voice, pitch
5+// and sustain), given a soft attack and a short fade at the end, and matched
6+// in loudness to all the others. Every voice and pitch rings for the same
7+// time: the sustain, the time for the fundamental to fade by 60 dB (set by
8+// the page). So the voices differ in timbre and attack, not in how long
9+// they ring, and loudness is matched by the RMS over each note's onset (its
10+// first LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high
11+// shelf of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a
12+// high-pass at 38 Hz): the same for every voice, pitch and sustain.
13+// - Strings (harp, pizzicato) are Karplus-Strong: the string starts in a
14+// rounded, fingertip-plucked shape and circulates in a delay line of one
15+// period, through a gentle low-pass (so the high harmonics die away first,
16+// leaving a warm tone) and a first-order all-pass that tunes the
17+// fractional part of the period.
18+// - Bars, tines and the ocarina are modal: a few decaying sinusoids, at the
19+// instrument's partial ratios (marimba 1 : 3.93 : 9.2, vibraphone
20+// 1 : 4 : 10 with tremolo, and so on).
21+// - The electric piano is two-operator FM with a fading modulation index.
22+// Everything goes through a soft low-pass, a dark synthetic reverb and a
23+// limiter.
24+
25+export const DEFAULT_SCALE = 'Minor pentatonic';
26+export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B'];
27+export const DEFAULT_KEY = 9; // A
28+
29+// Scales as semitone offsets within an octave; null: continuous pitch.
30+export const SCALES = [
31+ { name: 'Major pentatonic', steps: [0, 2, 4, 7, 9] },
32+ { name: 'Minor pentatonic', steps: [0, 3, 5, 7, 10] },
33+ { name: 'Major', steps: [0, 2, 4, 5, 7, 9, 11] },
34+ { name: 'Natural minor', steps: [0, 2, 3, 5, 7, 8, 10] },
35+ { name: 'Harmonic minor', steps: [0, 2, 3, 5, 7, 8, 11] },
36+ { name: 'Whole tone', steps: [0, 2, 4, 6, 8, 10] },
37+ { name: 'Chromatic', steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] },
38+ { name: 'Continuous', steps: null },
39+];
40+
41+const LOW = 130.81; // C3, the pitch at the left edge of the view
42+const OCTAVES = 3; // up to C6 at the right edge
43+
44+// The pitch (Hz) for u in [0, 1] (the left to right edge of the view): the
45+// notes of the scale in the given key (0 = C, ..., 11 = B) that lie within
46+// OCTAVES octaves from LOW, spread evenly across the view; or continuous.
47+// The register stays put when the key changes, so a key change shifts the
48+// harmony, like a chord change.
49+export function pitchOf(u, scale, key = 0) {
50+ u = Math.min(1, Math.max(0, u));
51+ if (!scale.steps) return LOW * 2 ** (OCTAVES * u);
52+ const notes = [];
53+ for (let s = 0; s <= 12 * OCTAVES; s++) {
54+ if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s);
55+ }
56+ return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12);
57+}
58+
59+export const SUSTAIN = { min: 0.1, max: 4, step: 0.1, default: 2 }; // s
60+const LOUD_WINDOW = 0.3; // s
61+const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW
62+
63+// Karplus-Strong string: t60 (s, for the fundamental to fade by 60 dB),
64+// pluck (where along the string it is plucked: smaller is brighter).
65+function string(sr, freq, t60, { pluck = 0.15 } = {}) {
66+ const len = Math.ceil(sr * t60);
67+ const out = new Float32Array(len);
68+ // Loop delay L = sr / freq: N samples, plus one for the [1/4, 1/2, 1/4]
69+ // loop filter, plus the all-pass's d (kept in [0.5, 1.5), where it is
70+ // accurate and well behaved).
71+ const L = sr / freq;
72+ const N = Math.floor(L - 1.5);
73+ const d = L - 1 - N;
74+ const c = (1 - d) / (1 + d);
75+ // the loop filter takes cos^2(pi f / sr) off each harmonic per pass, so
76+ // the highs die away within a few periods; the loop gain makes up the
77+ // fundamental's share, so it still fades over t60
78+ const H1 = Math.cos((Math.PI * freq) / sr) ** 2;
79+ const g = Math.min(0.99995, 10 ** (-3 / (t60 * freq)) / H1);
80+ // the pluck: the string's initial shape, a triangle peaked at `pluck` of
81+ // its length (harmonics falling as 1/k^2: at 0.15, about -8, -14, -21 dB
82+ // for the 2nd to 4th), its corner rounded off as by a fingertip, with a
83+ // trace of noise
84+ const tri = new Float32Array(N);
85+ for (let i = 0; i < N; i++) {
86+ const u = (i + 0.5) / N;
87+ tri[i] = u < pluck ? u / pluck : (1 - u) / (1 - pluck);
88+ }
89+ const w = Math.max(1, Math.round(N / 25));
90+ const line = new Float32Array(N);
91+ for (let i = 0; i < N; i++) {
92+ let acc = 0;
93+ for (let k = -w; k <= w; k++) acc += tri[(i + k + N) % N];
94+ line[i] = acc / (2 * w + 1);
95+ }
96+ let mean = 0;
97+ for (let i = 0; i < N; i++) { line[i] += 0.02 * (Math.random() * 2 - 1); mean += line[i] / N; }
98+ for (let i = 0; i < N; i++) line[i] -= mean;
99+ let pos = 0;
100+ let y1 = 0;
101+ let y2 = 0;
102+ let apIn = 0;
103+ let apOut = 0;
104+ for (let n = 0; n < len; n++) {
105+ const y = line[pos];
106+ const lp = 0.25 * y + 0.5 * y1 + 0.25 * y2;
107+ y2 = y1;
108+ y1 = y;
109+ const ap = c * lp + apIn - c * apOut;
110+ apIn = lp;
111+ apOut = ap;
112+ line[pos] = g * ap;
113+ pos = (pos + 1) % N;
114+ out[n] = y;
115+ }
116+ return out;
117+}
118+
119+// Decaying sinusoids. partials: [ratio, amplitude, t60 as a fraction of the
120+// fundamental's t60]; tremolo: { rate (Hz), depth }. Partials past 0.45 of
121+// the sample rate are left out.
122+function modal(sr, freq, t60, partials, { tremolo } = {}) {
123+ const len = Math.ceil(sr * t60);
124+ const out = new Float32Array(len);
125+ for (const [ratio, amp, frac] of partials) {
126+ if (ratio * freq > 0.45 * sr) continue;
127+ const w = (2 * Math.PI * ratio * freq) / sr;
128+ const k = -6.9 / (frac * t60 * sr);
129+ for (let n = 0; n < len; n++) out[n] += amp * Math.sin(w * n) * Math.exp(k * n);
130+ }
131+ if (tremolo) {
132+ const w = (2 * Math.PI * tremolo.rate) / sr;
133+ for (let n = 0; n < len; n++) out[n] *= 1 - tremolo.depth * (0.5 - 0.5 * Math.cos(w * n));
134+ }
135+ return out;
136+}
137+
138+// Two-operator FM (a soft electric piano): the modulator at the pitch, its
139+// index fading from about 1.4 to 0.15, so the tone mellows as it rings.
140+function fmPiano(sr, freq, t60) {
141+ const len = Math.ceil(sr * t60);
142+ const out = new Float32Array(len);
143+ const w = (2 * Math.PI * freq) / sr;
144+ const k = -6.9 / (t60 * sr);
145+ const kIndex = -1 / (Math.min(0.25, 0.4 * t60) * sr);
146+ for (let n = 0; n < len; n++) {
147+ const index = 1.25 * Math.exp(kIndex * n) + 0.15;
148+ out[n] = Math.sin(w * n + index * Math.sin(w * n)) * Math.exp(k * n);
149+ }
150+ return out;
151+}
152+
153+// The voices, in the order orbits take them. attack: s (raised cosine);
154+// render(sr, freq, t60).
155+export const VOICES = [
156+ { name: 'Harp', attack: 0.004, render: (sr, f, t) => string(sr, f, t) },
157+ { name: 'Marimba', attack: 0.002, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [3.93, 0.25, 0.3], [9.2, 0.08, 0.12]]) },
158+ { name: 'Vibraphone', attack: 0.003, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [4, 0.15, 0.35], [10, 0.04, 0.1]], { tremolo: { rate: 5, depth: 0.35 } }) },
159+ { name: 'Electric piano', attack: 0.003, render: fmPiano },
160+ { name: 'Music box', attack: 0.001, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [5.4, 0.2, 0.3], [11.3, 0.06, 0.12]]) },
161+ { name: 'Ocarina', attack: 0.035, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [2, 0.15, 0.8], [3, 0.05, 0.6]]) },
162+ { name: 'Pizzicato', attack: 0.003, render: (sr, f, t) => string(sr, f, t, { pluck: 0.25 }) },
163+ { name: 'Kalimba', attack: 0.0015, render: (sr, f, t) => modal(sr, f, t, [[1, 1, 1], [2, 0.06, 0.3], [6.27, 0.18, 0.12]]) },
164+];
165+
166+// A biquad filter applied to x, in place: [b0, b1, b2, a1, a2] (a0 = 1).
167+function biquad(x, [b0, b1, b2, a1, a2]) {
168+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
169+ for (let n = 0; n < x.length; n++) {
170+ const y = b0 * x[n] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
171+ x2 = x1; x1 = x[n]; y2 = y1; y1 = y;
172+ x[n] = y;
173+ }
174+}
175+
176+// The K-weighting of ITU-R BS.1770 at sample rate sr (its two stages, from
177+// their analog prototypes): a high shelf, then a high-pass.
178+function kWeighting(sr) {
179+ let K = Math.tan((Math.PI * 1681.974450955533) / sr);
180+ const Q1 = 0.7071752369554196;
181+ const Vh = 10 ** (3.999843853973347 / 20);
182+ const Vb = Vh ** 0.4996667741545416;
183+ let a0 = 1 + K / Q1 + K * K;
184+ const shelf = [(Vh + (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - Vh)) / a0, (Vh - (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - 1)) / a0, (1 - K / Q1 + K * K) / a0];
185+ K = Math.tan((Math.PI * 38.13547087602444) / sr);
186+ const Q2 = 0.5003270373238773;
187+ a0 = 1 + K / Q2 + K * K;
188+ const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0];
189+ return [shelf, highpass];
190+}
191+
192+// The K-weighted RMS of x (BS.1770's measure of loudness, without gating).
193+function loudness(x, sr) {
194+ const y = Float32Array.from(x);
195+ for (const stage of kWeighting(sr)) biquad(y, stage);
196+ let ss = 0;
197+ for (let n = 0; n < y.length; n++) ss += y[n] * y[n];
198+ return Math.sqrt(ss / y.length);
199+}
200+
201+// A voice's note at freq ringing for t60 s, as an AudioBuffer: with its
202+// attack and a short fade at the end, matched in loudness.
203+export function renderNote(ctx, voice, freq, t60) {
204+ const sr = ctx.sampleRate;
205+ const out = voice.render(sr, freq, t60);
206+ const att = Math.max(1, Math.floor(voice.attack * sr));
207+ const fade = Math.min(Math.floor(0.05 * sr), Math.floor(out.length / 4));
208+ for (let n = 0; n < out.length; n++) {
209+ const a = n < att ? 0.5 - 0.5 * Math.cos((Math.PI * n) / att) : 1;
210+ out[n] *= a * Math.min(1, (out.length - n) / fade);
211+ }
212+ const onset = out.subarray(0, Math.min(out.length, Math.floor(LOUD_WINDOW * sr)));
213+ const scale = LOUDNESS / (loudness(onset, sr) + 1e-12);
214+ for (let n = 0; n < out.length; n++) out[n] *= scale;
215+ const buf = ctx.createBuffer(1, out.length, sr);
216+ buf.copyToChannel(out, 0);
217+ return buf;
218+}
219+
220+// An exponentially decaying stereo noise tail, for the reverb.
221+function reverbImpulse(ctx, seconds = 1.6) {
222+ const len = Math.floor(ctx.sampleRate * seconds);
223+ const buf = ctx.createBuffer(2, len, ctx.sampleRate);
224+ for (let ch = 0; ch < 2; ch++) {
225+ const data = buf.getChannelData(ch);
226+ // noise, low-passed (about 2 kHz) so the tail is warm, not hissy
227+ let lp = 0;
228+ for (let n = 0; n < len; n++) {
229+ lp += 0.25 * (Math.random() * 2 - 1 - lp);
230+ data[n] = lp * Math.exp((-6.9 * n) / len);
231+ }
232+ }
233+ return buf;
234+}
235+
236+export function createSynth() {
237+ const ctx = new AudioContext();
238+ const master = ctx.createGain();
239+ const limiter = ctx.createDynamicsCompressor();
240+ limiter.threshold.value = -6;
241+ limiter.knee.value = 6;
242+ limiter.ratio.value = 12;
243+ limiter.attack.value = 0.003;
244+ limiter.release.value = 0.2;
245+ const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs
246+ tone.type = 'lowpass';
247+ tone.frequency.value = 3500;
248+ tone.Q.value = 0.5;
249+ const dry = ctx.createGain();
250+ const wet = ctx.createGain();
251+ wet.gain.value = 0.45;
252+ const reverb = ctx.createConvolver();
253+ reverb.buffer = reverbImpulse(ctx);
254+ tone.connect(dry);
255+ dry.connect(master);
256+ dry.connect(reverb).connect(wet).connect(master);
257+ master.connect(limiter).connect(ctx.destination);
258+ const cache = new Map();
259+ // per channel (an orbit's voice), its notes still sounding, oldest first;
260+ // past MAX_SOUNDING the oldest is faded out, so fast tempos with long
261+ // sustains stay light (at 16 notes/s, 64 notes is 4 s)
262+ const MAX_SOUNDING = 64;
263+ const sounding = new Map();
264+ let sustain = SUSTAIN.default;
265+
266+ return {
267+ ctx,
268+ setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
269+ // the time (s) for each note to fade by 60 dB, for the notes from now on
270+ setSustain(s) {
271+ if (s === sustain) return;
272+ sustain = s;
273+ cache.clear();
274+ },
275+ // a note of VOICES[voice] at freq, at time `when` (the context's clock),
276+ // panned by pan in [-1, 1], at level gain
277+ play(voice, freq, when, pan = 0, gain = 1) {
278+ const key = `${voice}:${Math.round(freq * 10)}`;
279+ let buf = cache.get(key);
280+ if (!buf) {
281+ buf = renderNote(ctx, VOICES[voice], freq, sustain);
282+ if (cache.size > 400) cache.clear();
283+ cache.set(key, buf);
284+ }
285+ const src = ctx.createBufferSource();
286+ src.buffer = buf;
287+ const level = ctx.createGain();
288+ level.gain.value = gain;
289+ const panner = ctx.createStereoPanner();
290+ panner.pan.value = pan;
291+ src.connect(level).connect(panner).connect(tone);
292+ const t = Math.max(when, ctx.currentTime);
293+ src.start(t);
294+ const list = sounding.get(voice) ?? [];
295+ const end = t + buf.duration;
296+ list.push({ src, level, end });
297+ // drop those that have finished by now, then fade the excess
298+ while (list.length && list[0].end < ctx.currentTime) list.shift();
299+ while (list.length > MAX_SOUNDING) {
300+ const old = list.shift();
301+ old.level.gain.setValueAtTime(old.level.gain.value, t);
302+ old.level.gain.linearRampToValueAtTime(0, t + 0.04);
303+ old.src.stop(t + 0.05);
304+ }
305+ sounding.set(voice, list);
306+ },
307+ };
308+}
app/main.jsadded+535−0View file
@@ -0,0 +1,535 @@
1+// Islands in a sea of chaos: the Poincaré section of the driven Duffing
2+// oscillator (js/duffing.js), filled in live, with clickable orbits and a
3+// sonification (js/voices.js).
4+//
5+// - Seed orbits, started on the axes of the view at drive phase 0, fill the
6+// section in the background, a few thousand points per frame.
7+// - A click adds an orbit from that point (drive phase 0), up to MAX_CLICKED;
8+// clicking an orbit's start ring removes it. Its dots fill in fast and
9+// larger, and a playhead walks it one drive period per beat: a live trail
10+// traces the motion through the period, and at each return to the section
11+// a note is played, its pitch set by x (left to right over three octaves
12+// of the chosen scale). All the clicked orbits play together, on the same
13+// beat, each in its own voice (harp, marimba, ...), listed in the panel.
14+// - Rhythm 'natural' instead plays the motion in slowed time (still one
15+// drive period per beat) and plucks wherever x' crosses 0 upward (the
16+// left turning point of each swing), at that x: each orbit makes its own
17+// rhythm, regular on an island, irregular in the sea.
18+// - Changing a parameter or preset restarts everything from the same starts,
19+// the clicked orbits included.
20+
21+import { createStepper, physicsOf, X_MAX } from './js/duffing.js';
22+import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
23+import { PRESETS } from './js/presets.js';
24+
25+const SEEDS_X = 24; // seed orbits along x' = 0
26+const SEEDS_V = 8; // and along x = 0
27+const SEED_POINTS = 1500;
28+const CLICK_POINTS = 4000;
29+const CLICK_PER_FRAME = 40; // so a clicked orbit visibly grows
30+const MAX_CLICKED = 8;
31+const HIT_RADIUS = 9; // px: a click this close to a start ring removes it
32+const FRAME_BUDGET = 7; // ms of integration per frame
33+const TAIL = 2; // trail length, in drive periods
34+const LOOKAHEAD = 0.12; // s of notes scheduled ahead
35+const RING = 0.35; // s a pluck's ring takes to fade (at most 3 beats)
36+const MARGIN = { left: 56, right: 12, top: 12, bottom: 34 };
37+
38+const SLIDERS = [
39+ { name: 'freq', label: 'f<sub>0</sub>', unit: 'Hz', min: -1000, max: 1000, step: 5, fmt: (v) => `${v < 0 ? '−' : ''}${Math.abs(v)} Hz` },
40+ { name: 'alpha', label: 'α', min: -5, max: 10, step: 0.1, scale: 1e7, fmt: (v) => `${v.toFixed(1)}·10⁷` },
41+ { name: 'delta', label: 'δ', min: 0, max: 50, step: 0.5, fmt: (v) => `${v.toFixed(1)} s⁻¹` },
42+ { name: 'F', label: 'F', min: 0, max: 30, step: 0.1, scale: 1e4, fmt: (v) => `${v.toFixed(1)}·10⁴` },
43+ { name: 'drive', label: 'Ω / 2π', min: 20, max: 2000, step: 5, fmt: (v) => `${v} Hz` },
44+ { name: 'view', label: 'View ±x', min: 0.1, max: X_MAX, step: 0.05, fmt: (v) => v.toFixed(2) },
45+];
46+
47+const $ = (id) => document.getElementById(id);
48+const canvas = $('plot');
49+const ctx = canvas.getContext('2d');
50+// the section points, accumulated: seed orbits, and clicked ones on top
51+const dots = document.createElement('canvas');
52+const top = document.createElement('canvas');
53+const layers = [dots, top];
54+
55+let params = { ...PRESETS[0].params };
56+let stepper;
57+let view; // { xr, vr }: half-ranges of x and x'
58+let orbits = []; // seed and clicked orbits
59+let clicked = []; // clicked orbits: { x, v, hue, voice, ph }, ph its playhead
60+let nextBeat = 0; // clock time of the next beat not yet scheduled
61+let synth = null;
62+let key = DEFAULT_KEY; // 0 = C, ..., 11 = B
63+let soundOn = false;
64+let hueCounter = 0;
65+let theme;
66+
67+// ---- physics ---------------------------------------------------------------
68+
69+// x' half-range: the speed at the bottom of the well of a free orbit that
70+// just reaches x = +/-xr, so the view frames the motions of that size
71+function speedRange(p, xr) {
72+ const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4;
73+ const vMin = p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0;
74+ const v = Math.sqrt(Math.max(0, 2 * (V(xr) - vMin)));
75+ return Math.max(v, 0.3 * xr * p.Omega, 1);
76+}
77+
78+// skip: drive periods to run before recording (a seed's transient)
79+function newOrbit(x, v, cap, hue, isClicked, skip = 0) {
80+ return { x0: x, v0: v, s: { x, v, escaped: false }, pts: new Float32Array(2 * cap), n: 0, cap, hue, clicked: isClicked, skip };
81+}
82+
83+function reset() {
84+ const p = physicsOf(params);
85+ stepper = createStepper(p);
86+ view = { xr: params.view, vr: speedRange(p, params.view) };
87+ // damped: the seeds settle onto the attractors before they are drawn,
88+ // for about 5 / delta (clicked orbits show the way in)
89+ const skip = p.delta > 0 ? Math.min(5000, Math.ceil((5 / p.delta) / stepper.T)) : 0;
90+ orbits = [];
91+ for (let i = 0; i < SEEDS_X; i++) {
92+ const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X);
93+ orbits.push(newOrbit(x, 0, SEED_POINTS, (i * 0.618) % 1, false, skip));
94+ }
95+ for (let i = 0; i < SEEDS_V; i++) {
96+ const v = 0.9 * view.vr * (-1 + (2 * (i + 0.5)) / SEEDS_V);
97+ orbits.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip));
98+ }
99+ for (const c of clicked) {
100+ orbits.unshift(newOrbit(c.x, c.v, CLICK_POINTS, c.hue, true));
101+ c.ph = newPlayhead(c.x, c.v);
102+ }
103+ clearDots();
104+}
105+
106+// ---- playhead and sound -----------------------------------------------------
107+
108+const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
109+const noteDt = () => 1 / Number($('tempo').value);
110+const ringTime = () => Math.min(RING, 3 * noteDt());
111+
112+// a playhead: the orbit's state, and its scheduled beats ({ time, path,
113+// last, notes }) still needed for the trail; notes: [{ t, x, v }]
114+const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [] });
115+
116+// The upward crossings of x' = 0 along a drive period's path (N + 1 points,
117+// evenly spaced in time over dt from time t0), interpolated linearly.
118+function upwardCrossings(path, t0, dt) {
119+ const N = path.length / 2 - 1;
120+ const notes = [];
121+ for (let j = 1; j <= N; j++) {
122+ const v0 = path[2 * j - 1];
123+ const v1 = path[2 * j + 1];
124+ if (v0 < 0 && v1 >= 0) {
125+ const f = v0 / (v0 - v1);
126+ notes.push({ t: t0 + ((j - 1 + f) / N) * dt, x: path[2 * j - 2] + f * (path[2 * j] - path[2 * j - 2]), v: 0 });
127+ }
128+ }
129+ return notes;
130+}
131+
132+// schedule the beats due within LOOKAHEAD: on each, every playhead advances
133+// one drive period (keeping the path for the trail) and plucks its notes
134+// (steady: one at the section point; natural: at each upward x' = 0),
135+// softer the more orbits there are
136+function schedule() {
137+ const now = clock();
138+ // fallen behind (a stalled frame, a hidden tab), or nothing playing: carry
139+ // on from now rather than play the missed notes in a burst
140+ if (nextBeat < now) nextBeat = now + 0.02;
141+ if (!clicked.length) return;
142+ const scale = SCALES[$('scale').selectedIndex];
143+ const gain = 1 / Math.sqrt(clicked.length);
144+ const natural = $('rhythm').value === 'natural';
145+ const dt = noteDt();
146+ while (nextBeat < now + LOOKAHEAD) {
147+ for (const { ph, voice } of clicked) {
148+ if (ph.s.escaped) continue;
149+ const { x, v } = ph.s;
150+ const path = new Float32Array(2 * (stepper.N + 1));
151+ stepper.step(ph.s, path);
152+ // (natural: none in the period it escapes, whose path ends at rest)
153+ const notes = !natural ? [{ t: nextBeat, x, v }] : ph.s.escaped ? [] : upwardCrossings(path, nextBeat, dt);
154+ ph.queue.push({ time: nextBeat, path, last: ph.s.escaped, notes });
155+ if (soundOn && synth) {
156+ for (const n of notes) {
157+ const u = (n.x / view.xr + 1) / 2;
158+ synth.play(voice, pitchOf(u, scale, key), n.t, Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain);
159+ }
160+ }
161+ }
162+ nextBeat += dt;
163+ }
164+ const keep = Math.max((TAIL + 1) * dt, ringTime() + dt);
165+ for (const { ph } of clicked) {
166+ while (ph.queue.length > 1 && ph.queue[1].time < now - keep) ph.queue.shift();
167+ }
168+}
169+
170+function setSound(on) {
171+ soundOn = on;
172+ const btn = $('sound');
173+ btn.setAttribute('aria-pressed', on);
174+ btn.textContent = on ? '♪ Sound on' : '♪ Sound off';
175+ if (on && !synth) {
176+ // the clock switches to the audio context's
177+ synth = createSynth();
178+ synth.setSustain(Number($('sustain').value));
179+ for (const { ph } of clicked) ph.queue = [];
180+ nextBeat = 0;
181+ }
182+ if (synth) {
183+ synth.ctx.resume();
184+ synth.setVolume(on ? Number($('volume').value) : 0);
185+ }
186+}
187+
188+// ---- drawing -----------------------------------------------------------------
189+
190+function readTheme() {
191+ const cs = getComputedStyle(document.documentElement);
192+ theme = {
193+ bg: cs.getPropertyValue('--bg').trim(),
194+ fg: cs.getPropertyValue('--fg').trim(),
195+ muted: cs.getPropertyValue('--muted').trim(),
196+ line: cs.getPropertyValue('--line').trim(),
197+ accent: cs.getPropertyValue('--accent').trim(),
198+ light: cs.getPropertyValue('--dot-light').trim(),
199+ };
200+}
201+
202+const orbitColor = (hue, clickedOrbit, alpha = 1) =>
203+ `hsla(${Math.round(hue * 360)}, ${clickedOrbit ? 85 : 50}%, ${theme.light}, ${alpha})`;
204+
205+function plotRect() {
206+ const dpr = devicePixelRatio || 1;
207+ const w = canvas.width / dpr;
208+ const h = canvas.height / dpr;
209+ return { x: MARGIN.left, y: MARGIN.top, w: Math.max(10, w - MARGIN.left - MARGIN.right), h: Math.max(10, h - MARGIN.top - MARGIN.bottom) };
210+}
211+
212+const toPx = (r, x, v) => [r.x + ((x / view.xr + 1) / 2) * r.w, r.y + ((1 - v / view.vr) / 2) * r.h];
213+
214+function drawPoints(o, from) {
215+ const r = plotRect();
216+ const dctx = (o.clicked ? top : dots).getContext('2d');
217+ dctx.fillStyle = orbitColor(o.hue, o.clicked, o.clicked ? 0.95 : 0.7);
218+ const size = o.clicked ? 2.2 : 1.4;
219+ for (let i = from; i < o.n; i++) {
220+ const [px, py] = toPx(r, o.pts[2 * i], o.pts[2 * i + 1]);
221+ dctx.fillRect(px - size / 2, py - size / 2, size, size);
222+ }
223+}
224+
225+function clearDots(which = layers) {
226+ const dpr = devicePixelRatio || 1;
227+ for (const layer of which) {
228+ const c = layer.getContext('2d');
229+ c.setTransform(1, 0, 0, 1, 0, 0);
230+ c.clearRect(0, 0, layer.width, layer.height);
231+ c.setTransform(dpr, 0, 0, dpr, 0, 0);
232+ }
233+}
234+
235+function resize() {
236+ const dpr = devicePixelRatio || 1;
237+ const { width, height } = canvas.getBoundingClientRect();
238+ canvas.width = dots.width = top.width = Math.round(width * dpr);
239+ canvas.height = dots.height = top.height = Math.round(height * dpr);
240+ clearDots();
241+ for (const o of orbits) drawPoints(o, 0);
242+}
243+
244+// advance the orbits within the frame's budget, drawing their new points
245+function fill() {
246+ const deadline = performance.now() + FRAME_BUDGET;
247+ const advance = (o, count) => {
248+ const from = o.n;
249+ for (let k = 0; k < count && o.n < o.cap && !o.s.escaped; k++) {
250+ stepper.step(o.s);
251+ if (o.s.escaped) break;
252+ if (o.skip > 0) { o.skip--; continue; }
253+ o.pts[2 * o.n] = o.s.x;
254+ o.pts[2 * o.n + 1] = o.s.v;
255+ o.n++;
256+ }
257+ drawPoints(o, from);
258+ };
259+ for (const o of orbits) if (o.clicked) advance(o, CLICK_PER_FRAME);
260+ let busy = true;
261+ while (busy && performance.now() < deadline) {
262+ busy = false;
263+ for (const o of orbits) {
264+ if (o.clicked || o.n >= o.cap || o.s.escaped) continue;
265+ advance(o, 10);
266+ busy = true;
267+ }
268+ }
269+}
270+
271+function drawAxes(r) {
272+ ctx.strokeStyle = theme.line;
273+ ctx.lineWidth = 1;
274+ ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
275+ ctx.beginPath();
276+ ctx.moveTo(r.x + r.w / 2, r.y);
277+ ctx.lineTo(r.x + r.w / 2, r.y + r.h);
278+ ctx.moveTo(r.x, r.y + r.h / 2);
279+ ctx.lineTo(r.x + r.w, r.y + r.h / 2);
280+ ctx.stroke();
281+ ctx.fillStyle = theme.muted;
282+ ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
283+ ctx.textBaseline = 'top';
284+ ctx.textAlign = 'left';
285+ ctx.fillText(`−${view.xr.toFixed(2)}`, r.x, r.y + r.h + 6);
286+ ctx.textAlign = 'right';
287+ ctx.fillText(view.xr.toFixed(2), r.x + r.w, r.y + r.h + 6);
288+ ctx.textAlign = 'center';
289+ ctx.fillText('displacement x', r.x + r.w / 2, r.y + r.h + 6);
290+ ctx.save();
291+ ctx.translate(r.x - 8, r.y + r.h / 2);
292+ ctx.rotate(-Math.PI / 2);
293+ ctx.textBaseline = 'bottom';
294+ ctx.fillText('velocity ẋ (s⁻¹)', 0, 0);
295+ ctx.textAlign = 'right';
296+ ctx.fillText(`${Math.round(view.vr)}`, r.h / 2, 0);
297+ ctx.textAlign = 'left';
298+ ctx.fillText(`−${Math.round(view.vr)}`, -r.h / 2, 0);
299+ ctx.restore();
300+}
301+
302+function drawPlayhead(r, ph, hue) {
303+ if (!ph.queue.length) return;
304+ const now = clock();
305+ const dt = noteDt();
306+ const N = stepper.N;
307+ const q = ph.queue;
308+ let cur = -1;
309+ for (let k = 0; k < q.length; k++) if (q[k].time <= now) cur = k;
310+ if (cur < 0) return;
311+ ctx.save();
312+ ctx.beginPath();
313+ ctx.rect(r.x, r.y, r.w, r.h);
314+ ctx.clip();
315+ ctx.lineWidth = 1.6;
316+ ctx.lineCap = 'round';
317+ ctx.lineJoin = 'round';
318+ const CHUNK = Math.max(4, Math.ceil(N / 24));
319+ let head = null;
320+ for (let k = 0; k <= cur; k++) {
321+ const e = q[k];
322+ const span = q[k + 1] ? q[k + 1].time - e.time : dt;
323+ const f = Math.min(1, (now - e.time) / span);
324+ const end = Math.floor(f * N);
325+ for (let j0 = 0; j0 < end; j0 += CHUNK) {
326+ const age = (now - (e.time + (j0 / N) * span)) / dt;
327+ const alpha = 1 - age / TAIL;
328+ if (alpha <= 0) continue;
329+ ctx.strokeStyle = orbitColor(hue, true, 0.85 * alpha);
330+ ctx.beginPath();
331+ for (let j = j0; j <= Math.min(end, j0 + CHUNK); j++) {
332+ const [px, py] = toPx(r, e.path[2 * j], e.path[2 * j + 1]);
333+ if (j === j0) ctx.moveTo(px, py);
334+ else ctx.lineTo(px, py);
335+ }
336+ ctx.stroke();
337+ }
338+ if (k === cur) {
339+ const j = Math.min(N, f * N);
340+ const i0 = Math.floor(j);
341+ const i1 = Math.min(N, i0 + 1);
342+ const w = j - i0;
343+ head = toPx(r, (1 - w) * e.path[2 * i0] + w * e.path[2 * i1], (1 - w) * e.path[2 * i0 + 1] + w * e.path[2 * i1 + 1]);
344+ if (e.last) head = null;
345+ }
346+ // each pluck: a ring growing and fading where it was played
347+ for (const n of e.notes) {
348+ const g = (now - n.t) / ringTime();
349+ if (g < 0 || g >= 1) continue;
350+ const [sx, sy] = toPx(r, n.x, n.v);
351+ ctx.strokeStyle = orbitColor(hue, true);
352+ ctx.globalAlpha = 1 - g;
353+ ctx.lineWidth = 2;
354+ ctx.beginPath();
355+ ctx.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI);
356+ ctx.stroke();
357+ ctx.globalAlpha = 1;
358+ }
359+ }
360+ if (head) {
361+ ctx.fillStyle = orbitColor(hue, true);
362+ ctx.beginPath();
363+ ctx.arc(head[0], head[1], 4.5, 0, 2 * Math.PI);
364+ ctx.fill();
365+ }
366+ ctx.restore();
367+}
368+
369+function drawStarts(r) {
370+ for (const o of orbits) {
371+ if (!o.clicked) continue;
372+ const [px, py] = toPx(r, o.x0, o.v0);
373+ ctx.strokeStyle = orbitColor(o.hue, true);
374+ ctx.lineWidth = 1.5;
375+ ctx.beginPath();
376+ if (o.s.escaped) {
377+ // escaped: a cross at its start
378+ ctx.moveTo(px - 5, py - 5); ctx.lineTo(px + 5, py + 5);
379+ ctx.moveTo(px + 5, py - 5); ctx.lineTo(px - 5, py + 5);
380+ } else {
381+ ctx.arc(px, py, 5, 0, 2 * Math.PI);
382+ }
383+ ctx.stroke();
384+ }
385+}
386+
387+function frame() {
388+ requestAnimationFrame(frame);
389+ if (!canvas.width || !canvas.height) return;
390+ fill();
391+ schedule();
392+ const dpr = devicePixelRatio || 1;
393+ const r = plotRect();
394+ ctx.setTransform(1, 0, 0, 1, 0, 0);
395+ ctx.fillStyle = theme.bg;
396+ ctx.fillRect(0, 0, canvas.width, canvas.height);
397+ ctx.drawImage(dots, 0, 0);
398+ ctx.drawImage(top, 0, 0);
399+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
400+ drawAxes(r);
401+ drawStarts(r);
402+ for (const c of clicked) drawPlayhead(r, c.ph, c.hue);
403+}
404+
405+// ---- controls ----------------------------------------------------------------
406+
407+function buildControls() {
408+ const presetSel = $('preset');
409+ presetSel.innerHTML = PRESETS.map((pr, i) => `<option value="${i}">${pr.name}</option>`).join('')
410+ + '<option value="custom" hidden>Custom</option>';
411+
412+ $('sliders').innerHTML = SLIDERS.map((s) => `
413+ <label class="row">
414+ <span>${s.label}</span>
415+ <input type="range" id="s-${s.name}" min="${s.min}" max="${s.max}" step="${s.step}">
416+ <output id="o-${s.name}"></output>
417+ </label>`).join('');
418+
419+ const show = () => {
420+ for (const s of SLIDERS) {
421+ const v = params[s.name] / (s.scale ?? 1);
422+ $(`s-${s.name}`).value = v;
423+ $(`o-${s.name}`).textContent = s.fmt(Number($(`s-${s.name}`).value));
424+ }
425+ };
426+ for (const s of SLIDERS) {
427+ $(`s-${s.name}`).addEventListener('input', (e) => {
428+ params[s.name] = Number(e.target.value) * (s.scale ?? 1);
429+ $(`o-${s.name}`).textContent = s.fmt(Number(e.target.value));
430+ presetSel.value = 'custom';
431+ reset();
432+ });
433+ }
434+ presetSel.addEventListener('change', () => {
435+ if (presetSel.value === 'custom') return;
436+ // the clicked orbits stay, restarted from the same (x, x') under the new
437+ // parameters (a start outside the new view still plays; its chip in the
438+ // legend removes it)
439+ params = { ...PRESETS[presetSel.value].params };
440+ show();
441+ reset();
442+ });
443+ show();
444+
445+ $('scale').innerHTML = SCALES.map((s) => `<option${s.name === DEFAULT_SCALE ? ' selected' : ''}>${s.name}</option>`).join('');
446+ $('keys').innerHTML = KEYS.map((k, i) => `<button data-key="${i}" aria-pressed="${i === key}">${k}</button>`).join('');
447+ $('keys').addEventListener('click', (e) => {
448+ const btn = e.target.closest('button[data-key]');
449+ if (!btn) return;
450+ key = Number(btn.dataset.key);
451+ for (const b of $('keys').children) b.setAttribute('aria-pressed', b === btn);
452+ });
453+ const sus = $('sustain');
454+ Object.assign(sus, { min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, value: SUSTAIN.default });
455+ const susOut = () => { sus.nextElementSibling.textContent = `${Number(sus.value).toFixed(1)} s`; };
456+ sus.addEventListener('input', () => {
457+ susOut();
458+ synth?.setSustain(Number(sus.value));
459+ });
460+ susOut();
461+ const tempoOut = () => { $('tempo-out').textContent = `${$('tempo').value} /s`; };
462+ $('tempo').addEventListener('input', tempoOut);
463+ tempoOut();
464+ const vol = $('volume');
465+ const volOut = () => { vol.nextElementSibling.textContent = `${Math.round(100 * vol.value)}%`; };
466+ vol.addEventListener('input', () => {
467+ volOut();
468+ if (synth && soundOn) synth.setVolume(Number(vol.value));
469+ });
470+ volOut();
471+ $('sound').addEventListener('click', () => setSound(!soundOn));
472+ $('clear').addEventListener('click', () => {
473+ clicked = [];
474+ reset();
475+ renderLegend();
476+ });
477+ $('orbit-list').addEventListener('click', (e) => {
478+ const btn = e.target.closest('button[data-hue]');
479+ if (btn) removeOrbit(clicked.find((c) => String(c.hue) === btn.dataset.hue));
480+ });
481+
482+ canvas.addEventListener('pointerdown', (e) => {
483+ const rect = canvas.getBoundingClientRect();
484+ const r = plotRect();
485+ const px = e.clientX - rect.left;
486+ const py = e.clientY - rect.top;
487+ if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return;
488+ // on a start ring: remove that orbit; otherwise add one from here
489+ const hit = clicked.find((c) => {
490+ const [cx, cy] = toPx(r, c.x, c.v);
491+ return Math.hypot(cx - px, cy - py) <= HIT_RADIUS;
492+ });
493+ if (hit) {
494+ removeOrbit(hit);
495+ return;
496+ }
497+ const x = ((px - r.x) / r.w * 2 - 1) * view.xr;
498+ const v = (1 - (py - r.y) / r.h * 2) * view.vr;
499+ if (clicked.length >= MAX_CLICKED) removeOrbit(clicked[0]);
500+ // the first voice no other orbit is playing
501+ const voice = VOICES.findIndex((_, i) => !clicked.some((c) => c.voice === i));
502+ const hue = (0.08 + hueCounter++ * 0.382) % 1;
503+ clicked.push({ x, v, hue, voice, ph: newPlayhead(x, v) });
504+ orbits.unshift(newOrbit(x, v, CLICK_POINTS, hue, true));
505+ renderLegend();
506+ });
507+}
508+
509+function removeOrbit(c) {
510+ if (!c) return;
511+ clicked = clicked.filter((q) => q !== c);
512+ orbits = orbits.filter((o) => !o.clicked || o.hue !== c.hue);
513+ // redraw the clicked layer, so its dots go
514+ clearDots([top]);
515+ for (const o of orbits) if (o.clicked) drawPoints(o, 0);
516+ renderLegend();
517+}
518+
519+// the playing orbits: their color and voice, and a button to remove each
520+function renderLegend() {
521+ $('orbit-list').innerHTML = clicked.map((c) => `
522+ <li>
523+ <span class="swatch" style="background: ${orbitColor(c.hue, true)}"></span>
524+ ${VOICES[c.voice].name}
525+ <button data-hue="${c.hue}" aria-label="Remove the ${VOICES[c.voice].name} orbit">×</button>
526+ </li>`).join('');
527+}
528+
529+readTheme();
530+matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); renderLegend(); });
531+buildControls();
532+reset();
533+new ResizeObserver(resize).observe(canvas);
534+resize();
535+requestAnimationFrame(frame);
app/style.cssadded+156−0View file
@@ -0,0 +1,156 @@
1+@font-face { font-family: "Source Serif 4"; font-weight: 300; src: url("vendor/fonts/source-serif-4-latin-300-normal.woff2") format("woff2"); }
2+@font-face { font-family: "Hanken Grotesk"; font-weight: 400; src: url("vendor/fonts/hanken-grotesk-latin-400-normal.woff2") format("woff2"); }
3+@font-face { font-family: "Hanken Grotesk"; font-weight: 600; src: url("vendor/fonts/hanken-grotesk-latin-600-normal.woff2") format("woff2"); }
4+
5+:root {
6+ --bg: #ffffff;
7+ --fg: #1c2954;
8+ --muted: #6b7491;
9+ --line: #dde1ea;
10+ --panel: #f5f6f9;
11+ --accent: #f6862d;
12+ --dot-light: 46%;
13+ --font-head: "Tiempos Headline", "Source Serif 4", Georgia, serif;
14+ --font-body: "Founders Grotesk", "Hanken Grotesk", system-ui, sans-serif;
15+}
16+
17+@media (prefers-color-scheme: dark) {
18+ :root {
19+ --bg: #121418;
20+ --fg: #e6e8ee;
21+ --muted: #8d94a8;
22+ --line: #2a2e38;
23+ --panel: #1a1d23;
24+ --dot-light: 66%;
25+ }
26+}
27+
28+* { box-sizing: border-box; }
29+
30+html, body { height: 100%; }
31+
32+body {
33+ margin: 0;
34+ display: flex;
35+ flex-direction: column;
36+ background: var(--bg);
37+ color: var(--fg);
38+ font-family: var(--font-body);
39+ font-size: 15px;
40+}
41+
42+header { padding: 14px 20px 6px; }
43+
44+h1 {
45+ margin: 0;
46+ font-family: var(--font-head);
47+ font-weight: 300;
48+ font-size: 26px;
49+}
50+
51+.eq { margin: 4px 0 0; font-family: var(--font-head); font-size: 17px; }
52+.eq i { font-family: var(--font-head); }
53+
54+.layout {
55+ flex: 1;
56+ min-height: 0;
57+ display: flex;
58+ gap: 16px;
59+ padding: 8px 20px 20px;
60+}
61+
62+.panel {
63+ flex: 0 0 290px;
64+ display: flex;
65+ flex-direction: column;
66+ gap: 14px;
67+ overflow-y: auto;
68+}
69+
70+.sliders, .sound { display: flex; flex-direction: column; gap: 8px; }
71+
72+.sound { padding-top: 14px; border-top: 1px solid var(--line); }
73+
74+.row {
75+ display: grid;
76+ grid-template-columns: 74px 1fr 64px;
77+ align-items: center;
78+ gap: 8px;
79+}
80+
81+.row > span { color: var(--muted); font-size: 14px; }
82+.row > select { grid-column: 2 / 4; }
83+.row output { font-variant-numeric: tabular-nums; font-size: 13px; text-align: right; }
84+.row sub, .row sup { font-size: 0.7em; }
85+
86+input[type="range"] { width: 100%; accent-color: var(--accent); }
87+
88+select, button {
89+ font: inherit;
90+ color: var(--fg);
91+ background: var(--panel);
92+ border: 1px solid var(--line);
93+ border-radius: 6px;
94+ padding: 6px 8px;
95+}
96+
97+button { cursor: pointer; }
98+
99+.keys { grid-column: 2 / 4; display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; }
100+.keys button { padding: 3px 0; font-size: 13px; }
101+
102+.toggle[aria-pressed="true"], .keys button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
103+
104+.quiet { background: none; color: var(--muted); align-self: flex-start; }
105+
106+.orbit-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
107+.orbit-list:empty { display: none; }
108+.orbit-list li {
109+ display: flex;
110+ align-items: center;
111+ gap: 6px;
112+ padding: 2px 2px 2px 8px;
113+ border: 1px solid var(--line);
114+ border-radius: 999px;
115+ font-size: 13px;
116+}
117+.orbit-list .swatch { width: 10px; height: 10px; border-radius: 50%; }
118+.orbit-list button { border: none; background: none; padding: 0 6px; color: var(--muted); line-height: 1; }
119+
120+.plot-wrap {
121+ position: relative;
122+ flex: 1;
123+ min-width: 0;
124+ min-height: 0;
125+}
126+
127+#plot {
128+ position: absolute;
129+ inset: 0;
130+ width: 100%;
131+ height: 100%;
132+ cursor: crosshair;
133+ touch-action: manipulation;
134+}
135+
136+.hint {
137+ position: absolute;
138+ top: 8px;
139+ left: 60px;
140+ margin: 0;
141+ padding: 4px 10px;
142+ border-radius: 6px;
143+ background: var(--panel);
144+ color: var(--muted);
145+ font-size: 14px;
146+ pointer-events: none;
147+}
148+
149+@media (max-width: 760px) {
150+ header { padding: 12px 16px 4px; }
151+ h1 { font-size: 22px; }
152+ .layout { flex-direction: column; padding: 8px 16px 16px; }
153+ .panel { flex: none; overflow: visible; }
154+ .plot-wrap { flex: none; height: min(90vw, 70vh); order: -1; }
155+ body { height: auto; }
156+}
app/vendor/fonts/LICENSE-hanken-groteskadded+93−0View file
@@ -0,0 +1,93 @@
1+Copyright 2021 The Hanken Grotesk Project Authors (https://github.com/marcologous/hanken-grotesk) HankenGrotesk-Italic[wght].ttf: Copyright 2021 The Hanken Grotesk Project Authors (https://github.com/marcologous/hanken-grotesk)
2+
3+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4+This license is copied below, and is also available with a FAQ at:
5+http://scripts.sil.org/OFL
6+
7+
8+-----------------------------------------------------------
9+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10+-----------------------------------------------------------
11+
12+PREAMBLE
13+The goals of the Open Font License (OFL) are to stimulate worldwide
14+development of collaborative font projects, to support the font creation
15+efforts of academic and linguistic communities, and to provide a free and
16+open framework in which fonts may be shared and improved in partnership
17+with others.
18+
19+The OFL allows the licensed fonts to be used, studied, modified and
20+redistributed freely as long as they are not sold by themselves. The
21+fonts, including any derivative works, can be bundled, embedded,
22+redistributed and/or sold with any software provided that any reserved
23+names are not used by derivative works. The fonts and derivatives,
24+however, cannot be released under any other type of license. The
25+requirement for fonts to remain under this license does not apply
26+to any document created using the fonts or their derivatives.
27+
28+DEFINITIONS
29+"Font Software" refers to the set of files released by the Copyright
30+Holder(s) under this license and clearly marked as such. This may
31+include source files, build scripts and documentation.
32+
33+"Reserved Font Name" refers to any names specified as such after the
34+copyright statement(s).
35+
36+"Original Version" refers to the collection of Font Software components as
37+distributed by the Copyright Holder(s).
38+
39+"Modified Version" refers to any derivative made by adding to, deleting,
40+or substituting -- in part or in whole -- any of the components of the
41+Original Version, by changing formats or by porting the Font Software to a
42+new environment.
43+
44+"Author" refers to any designer, engineer, programmer, technical
45+writer or other person who contributed to the Font Software.
46+
47+PERMISSION & CONDITIONS
48+Permission is hereby granted, free of charge, to any person obtaining
49+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50+redistribute, and sell modified and unmodified copies of the Font
51+Software, subject to the following conditions:
52+
53+1) Neither the Font Software nor any of its individual components,
54+in Original or Modified Versions, may be sold by itself.
55+
56+2) Original or Modified Versions of the Font Software may be bundled,
57+redistributed and/or sold with any software, provided that each copy
58+contains the above copyright notice and this license. These can be
59+included either as stand-alone text files, human-readable headers or
60+in the appropriate machine-readable metadata fields within text or
61+binary files as long as those fields can be easily viewed by the user.
62+
63+3) No Modified Version of the Font Software may use the Reserved Font
64+Name(s) unless explicit written permission is granted by the corresponding
65+Copyright Holder. This restriction only applies to the primary font name as
66+presented to the users.
67+
68+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69+Software shall not be used to promote, endorse or advertise any
70+Modified Version, except to acknowledge the contribution(s) of the
71+Copyright Holder(s) and the Author(s) or with their explicit written
72+permission.
73+
74+5) The Font Software, modified or unmodified, in part or in whole,
75+must be distributed entirely under this license, and must not be
76+distributed under any other license. The requirement for fonts to
77+remain under this license does not apply to any document created
78+using the Font Software.
79+
80+TERMINATION
81+This license becomes null and void if any of the above conditions are
82+not met.
83+
84+DISCLAIMER
85+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93+OTHER DEALINGS IN THE FONT SOFTWARE.
app/vendor/fonts/LICENSE-source-serif-4added+93−0View file
@@ -0,0 +1,93 @@
1+Google Inc.
2+
3+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4+This license is copied below, and is also available with a FAQ at:
5+http://scripts.sil.org/OFL
6+
7+
8+-----------------------------------------------------------
9+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10+-----------------------------------------------------------
11+
12+PREAMBLE
13+The goals of the Open Font License (OFL) are to stimulate worldwide
14+development of collaborative font projects, to support the font creation
15+efforts of academic and linguistic communities, and to provide a free and
16+open framework in which fonts may be shared and improved in partnership
17+with others.
18+
19+The OFL allows the licensed fonts to be used, studied, modified and
20+redistributed freely as long as they are not sold by themselves. The
21+fonts, including any derivative works, can be bundled, embedded,
22+redistributed and/or sold with any software provided that any reserved
23+names are not used by derivative works. The fonts and derivatives,
24+however, cannot be released under any other type of license. The
25+requirement for fonts to remain under this license does not apply
26+to any document created using the fonts or their derivatives.
27+
28+DEFINITIONS
29+"Font Software" refers to the set of files released by the Copyright
30+Holder(s) under this license and clearly marked as such. This may
31+include source files, build scripts and documentation.
32+
33+"Reserved Font Name" refers to any names specified as such after the
34+copyright statement(s).
35+
36+"Original Version" refers to the collection of Font Software components as
37+distributed by the Copyright Holder(s).
38+
39+"Modified Version" refers to any derivative made by adding to, deleting,
40+or substituting -- in part or in whole -- any of the components of the
41+Original Version, by changing formats or by porting the Font Software to a
42+new environment.
43+
44+"Author" refers to any designer, engineer, programmer, technical
45+writer or other person who contributed to the Font Software.
46+
47+PERMISSION & CONDITIONS
48+Permission is hereby granted, free of charge, to any person obtaining
49+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50+redistribute, and sell modified and unmodified copies of the Font
51+Software, subject to the following conditions:
52+
53+1) Neither the Font Software nor any of its individual components,
54+in Original or Modified Versions, may be sold by itself.
55+
56+2) Original or Modified Versions of the Font Software may be bundled,
57+redistributed and/or sold with any software, provided that each copy
58+contains the above copyright notice and this license. These can be
59+included either as stand-alone text files, human-readable headers or
60+in the appropriate machine-readable metadata fields within text or
61+binary files as long as those fields can be easily viewed by the user.
62+
63+3) No Modified Version of the Font Software may use the Reserved Font
64+Name(s) unless explicit written permission is granted by the corresponding
65+Copyright Holder. This restriction only applies to the primary font name as
66+presented to the users.
67+
68+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69+Software shall not be used to promote, endorse or advertise any
70+Modified Version, except to acknowledge the contribution(s) of the
71+Copyright Holder(s) and the Author(s) or with their explicit written
72+permission.
73+
74+5) The Font Software, modified or unmodified, in part or in whole,
75+must be distributed entirely under this license, and must not be
76+distributed under any other license. The requirement for fonts to
77+remain under this license does not apply to any document created
78+using the Font Software.
79+
80+TERMINATION
81+This license becomes null and void if any of the above conditions are
82+not met.
83+
84+DISCLAIMER
85+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93+OTHER DEALINGS IN THE FONT SOFTWARE.
app/vendor/fonts/hanken-grotesk-latin-400-normal.woff2added+0−0View file
Binary file not shown.
app/vendor/fonts/hanken-grotesk-latin-600-normal.woff2added+0−0View file
Binary file not shown.
app/vendor/fonts/source-serif-4-latin-300-normal.woff2added+0−0View file
Binary file not shown.
package.jsonadded+9−0View file
@@ -0,0 +1,9 @@
1+{
2+ "name": "duffing-islands",
3+ "private": true,
4+ "type": "module",
5+ "scripts": {
6+ "dev": "python3 -m http.server 8002 --bind 127.0.0.1 --directory app",
7+ "check": "for f in app/*.js app/js/*.js scripts/*.mjs; do node --check \"$f\" || exit 1; done"
8+ }
9+}
scripts/section-png.mjsadded+70−0View file
@@ -0,0 +1,70 @@
1+// Renders the Poincaré section for a parameter set to a PNG, for choosing
2+// presets: orbits from a row of starts on x' = 0 (and a few above it), each
3+// in its own color. Prints, per start, whether it escaped.
4+//
5+// node scripts/section-png.mjs out.png freq alpha delta F drive [points] [xr] [vr]
6+//
7+// freq, drive in Hz; alpha, F in s^-2; delta in s^-1 (the tutorial's units).
8+// xr, vr: the plotted half-ranges (default: from the orbits).
9+
10+import { writeFileSync } from 'node:fs';
11+import { deflateSync } from 'node:zlib';
12+import { createStepper, physicsOf } from '../app/js/duffing.js';
13+
14+const [out, freq, alpha, delta, F, drive, npts = '800', xr0, vr0] = process.argv.slice(2);
15+const p = physicsOf({ freq: +freq, alpha: +alpha, delta: +delta, F: +F, drive: +drive });
16+const { step, N } = createStepper(p);
17+const SEEDS = 40;
18+const XR = +xr0 || 0.9;
19+const pts = [];
20+const t0 = Date.now();
21+let escaped = 0;
22+for (let k = 0; k < SEEDS; k++) {
23+ const x0 = XR * (-1 + (2 * k) / (SEEDS - 1));
24+ const s = { x: x0, v: 0, escaped: false };
25+ const o = [];
26+ for (let i = 0; i < +npts && !s.escaped; i++) {
27+ step(s);
28+ if (!s.escaped) o.push(s.x, s.v);
29+ }
30+ if (s.escaped) escaped++;
31+ pts.push(o);
32+}
33+const ms = Date.now() - t0;
34+const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4;
35+let xr = +xr0 || 0;
36+let vr = +vr0 || (xr ? Math.sqrt(2 * (V(xr) - Math.min(V(0), p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0))) : 0);
37+if (!xr) for (const o of pts) for (let i = 0; i < o.length; i += 2) { xr = Math.max(xr, Math.abs(o[i])); vr = Math.max(vr, Math.abs(o[i + 1])); }
38+xr *= xr0 ? 1 : 1.05;
39+vr *= vr0 ? 1 : 1.05;
40+
41+const W = 700;
42+const H = 700;
43+const img = Buffer.alloc(W * H * 3, 255);
44+const hsl = (h) => {
45+ const f = (n) => { const k = (n + h * 12) % 12; return 0.45 - 0.4 * Math.max(-1, Math.min(k - 3, 9 - k, 1)); };
46+ return [f(0), f(8), f(4)].map((c) => Math.round(c * 255));
47+};
48+pts.forEach((o, k) => {
49+ const c = hsl((k * 0.618) % 1);
50+ for (let i = 0; i < o.length; i += 2) {
51+ const px = Math.round(((o[i] / xr + 1) / 2) * (W - 1));
52+ const py = Math.round(((1 - o[i + 1] / vr) / 2) * (H - 1));
53+ if (px >= 0 && px < W && py >= 0 && py < H) img.set(c, 3 * (py * W + px));
54+ }
55+});
56+// PNG: 8-bit RGB, no filtering
57+const raw = Buffer.alloc(H * (1 + 3 * W));
58+for (let y = 0; y < H; y++) img.copy(raw, y * (1 + 3 * W) + 1, 3 * y * W, 3 * (y + 1) * W);
59+const crcTable = Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
60+const crc = (b) => { let c = ~0; for (const x of b) c = crcTable[(c ^ x) & 255] ^ (c >>> 8); return (~c) >>> 0; };
61+const chunk = (type, data) => {
62+ const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
63+ const td = Buffer.concat([Buffer.from(type), data]);
64+ const c = Buffer.alloc(4); c.writeUInt32BE(crc(td));
65+ return Buffer.concat([len, td, c]);
66+};
67+const ihdr = Buffer.alloc(13);
68+ihdr.writeUInt32BE(W, 0); ihdr.writeUInt32BE(H, 4); ihdr[8] = 8; ihdr[9] = 2;
69+writeFileSync(out, Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]));
70+console.log(`${out}: N=${N} steps/period, ${ms} ms, ${escaped}/${SEEDS} escaped, x ±${xr.toFixed(3)}, x' ±${vr.toFixed(0)}`);
↑↓ move↵openescclose