// Islands in a sea of chaos: the Poincaré section of the driven Duffing // oscillator (js/duffing.js), filled in live, with clickable orbits and a // sonification (js/voices.js). // // - Seed orbits, started on the axes of the view at drive phase 0, fill the // section in the background, a few thousand points per frame. // - A click adds an orbit from that point (drive phase 0), up to MAX_CLICKED; // clicking an orbit's start ring removes it. Its dots fill in fast and // larger, and a playhead walks it one drive period per beat: a live trail // traces the motion through the period, and at each return to the section // a note is played, its pitch set by x (left to right over three octaves // of the chosen scale). All the clicked orbits play together, on the same // beat, each in its own voice (harp, marimba, ...), listed in the panel. // - Rhythm 'natural' instead plays the motion in slowed time (still one // drive period per beat) and plucks wherever x' crosses 0 upward (the // left turning point of each swing), at that x: each orbit makes its own // rhythm, regular on an island, irregular in the sea. // - Changing a parameter or preset restarts everything from the same starts, // the clicked orbits included. import { createStepper, physicsOf, X_MAX } from './js/duffing.js'; import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js'; import { PRESETS } from './js/presets.js'; const SEEDS_X = 24; // seed orbits along x' = 0 const SEEDS_V = 8; // and along x = 0 const SEED_POINTS = 1500; const CLICK_POINTS = 4000; const CLICK_PER_FRAME = 40; // so a clicked orbit visibly grows const MAX_CLICKED = 8; const HIT_RADIUS = 9; // px: a click this close to a start ring removes it const FRAME_BUDGET = 7; // ms of integration per frame const TAIL = 2; // trail length, in drive periods const LOOKAHEAD = 0.12; // s of notes scheduled ahead const RING = 0.35; // s a pluck's ring takes to fade (at most 3 beats) const MARGIN = { left: 56, right: 12, top: 12, bottom: 34 }; const SLIDERS = [ { name: 'freq', label: 'f0', unit: 'Hz', min: -1000, max: 1000, step: 5, fmt: (v) => `${v < 0 ? '−' : ''}${Math.abs(v)} Hz` }, { name: 'alpha', label: 'α', min: -5, max: 10, step: 0.1, scale: 1e7, fmt: (v) => `${v.toFixed(1)}·10⁷` }, { name: 'delta', label: 'δ', min: 0, max: 50, step: 0.5, fmt: (v) => `${v.toFixed(1)} s⁻¹` }, { name: 'F', label: 'F', min: 0, max: 30, step: 0.1, scale: 1e4, fmt: (v) => `${v.toFixed(1)}·10⁴` }, { name: 'drive', label: 'Ω / 2π', min: 20, max: 2000, step: 5, fmt: (v) => `${v} Hz` }, { name: 'view', label: 'View ±x', min: 0.1, max: X_MAX, step: 0.05, fmt: (v) => v.toFixed(2) }, ]; const $ = (id) => document.getElementById(id); const canvas = $('plot'); const ctx = canvas.getContext('2d'); // the section points, accumulated: seed orbits, and clicked ones on top const dots = document.createElement('canvas'); const top = document.createElement('canvas'); const layers = [dots, top]; let params = { ...PRESETS[0].params }; let stepper; let view; // { xr, vr }: half-ranges of x and x' let orbits = []; // seed and clicked orbits let clicked = []; // clicked orbits: { x, v, hue, voice, ph }, ph its playhead let nextBeat = 0; // clock time of the next beat not yet scheduled let synth = null; let key = DEFAULT_KEY; // 0 = C, ..., 11 = B let soundOn = false; let hueCounter = 0; let theme; // ---- physics --------------------------------------------------------------- // x' half-range: the speed at the bottom of the well of a free orbit that // just reaches x = +/-xr, so the view frames the motions of that size function speedRange(p, xr) { const V = (x) => 0.5 * p.omega2 * x * x + 0.25 * p.alpha * x ** 4; const vMin = p.omega2 < 0 && p.alpha > 0 ? -(p.omega2 ** 2) / (4 * p.alpha) : 0; const v = Math.sqrt(Math.max(0, 2 * (V(xr) - vMin))); return Math.max(v, 0.3 * xr * p.Omega, 1); } // skip: drive periods to run before recording (a seed's transient) function newOrbit(x, v, cap, hue, isClicked, skip = 0) { return { x0: x, v0: v, s: { x, v, escaped: false }, pts: new Float32Array(2 * cap), n: 0, cap, hue, clicked: isClicked, skip }; } function reset() { const p = physicsOf(params); stepper = createStepper(p); view = { xr: params.view, vr: speedRange(p, params.view) }; // damped: the seeds settle onto the attractors before they are drawn, // for about 5 / delta (clicked orbits show the way in) const skip = p.delta > 0 ? Math.min(5000, Math.ceil((5 / p.delta) / stepper.T)) : 0; orbits = []; for (let i = 0; i < SEEDS_X; i++) { const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X); orbits.push(newOrbit(x, 0, SEED_POINTS, (i * 0.618) % 1, false, skip)); } for (let i = 0; i < SEEDS_V; i++) { const v = 0.9 * view.vr * (-1 + (2 * (i + 0.5)) / SEEDS_V); orbits.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip)); } for (const c of clicked) { orbits.unshift(newOrbit(c.x, c.v, CLICK_POINTS, c.hue, true)); c.ph = newPlayhead(c.x, c.v); } clearDots(); } // ---- playhead and sound ----------------------------------------------------- const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000); const noteDt = () => 1 / Number($('tempo').value); const ringTime = () => Math.min(RING, 3 * noteDt()); // a playhead: the orbit's state, and its scheduled beats ({ time, path, // last, notes }) still needed for the trail; notes: [{ t, x, v }] const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [] }); // The upward crossings of x' = 0 along a drive period's path (N + 1 points, // evenly spaced in time over dt from time t0), interpolated linearly. function upwardCrossings(path, t0, dt) { const N = path.length / 2 - 1; const notes = []; for (let j = 1; j <= N; j++) { const v0 = path[2 * j - 1]; const v1 = path[2 * j + 1]; if (v0 < 0 && v1 >= 0) { const f = v0 / (v0 - v1); notes.push({ t: t0 + ((j - 1 + f) / N) * dt, x: path[2 * j - 2] + f * (path[2 * j] - path[2 * j - 2]), v: 0 }); } } return notes; } // schedule the beats due within LOOKAHEAD: on each, every playhead advances // one drive period (keeping the path for the trail) and plucks its notes // (steady: one at the section point; natural: at each upward x' = 0), // softer the more orbits there are function schedule() { const now = clock(); // fallen behind (a stalled frame, a hidden tab), or nothing playing: carry // on from now rather than play the missed notes in a burst if (nextBeat < now) nextBeat = now + 0.02; if (!clicked.length) return; const scale = SCALES[$('scale').selectedIndex]; const gain = 1 / Math.sqrt(clicked.length); const natural = $('rhythm').value === 'natural'; const dt = noteDt(); while (nextBeat < now + LOOKAHEAD) { for (const { ph, voice } of clicked) { if (ph.s.escaped) continue; const { x, v } = ph.s; const path = new Float32Array(2 * (stepper.N + 1)); stepper.step(ph.s, path); // (natural: none in the period it escapes, whose path ends at rest) const notes = !natural ? [{ t: nextBeat, x, v }] : ph.s.escaped ? [] : upwardCrossings(path, nextBeat, dt); ph.queue.push({ time: nextBeat, path, last: ph.s.escaped, notes }); if (soundOn && synth) { for (const n of notes) { const u = (n.x / view.xr + 1) / 2; synth.play(voice, pitchOf(u, scale, key), n.t, Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain); } } } nextBeat += dt; } const keep = Math.max((TAIL + 1) * dt, ringTime() + dt); for (const { ph } of clicked) { while (ph.queue.length > 1 && ph.queue[1].time < now - keep) ph.queue.shift(); } } function setSound(on) { soundOn = on; const btn = $('sound'); btn.setAttribute('aria-pressed', on); btn.textContent = on ? '♪ Sound on' : '♪ Sound off'; if (on && !synth) { // the clock switches to the audio context's synth = createSynth(); synth.setSustain(Number($('sustain').value)); for (const { ph } of clicked) ph.queue = []; nextBeat = 0; } if (synth) { synth.ctx.resume(); synth.setVolume(on ? Number($('volume').value) : 0); } } // ---- drawing ----------------------------------------------------------------- function readTheme() { const cs = getComputedStyle(document.documentElement); theme = { bg: cs.getPropertyValue('--bg').trim(), fg: cs.getPropertyValue('--fg').trim(), muted: cs.getPropertyValue('--muted').trim(), line: cs.getPropertyValue('--line').trim(), accent: cs.getPropertyValue('--accent').trim(), light: cs.getPropertyValue('--dot-light').trim(), }; } const orbitColor = (hue, clickedOrbit, alpha = 1) => `hsla(${Math.round(hue * 360)}, ${clickedOrbit ? 85 : 50}%, ${theme.light}, ${alpha})`; function plotRect() { const dpr = devicePixelRatio || 1; const w = canvas.width / dpr; const h = canvas.height / dpr; 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) }; } const toPx = (r, x, v) => [r.x + ((x / view.xr + 1) / 2) * r.w, r.y + ((1 - v / view.vr) / 2) * r.h]; function drawPoints(o, from) { const r = plotRect(); const dctx = (o.clicked ? top : dots).getContext('2d'); dctx.fillStyle = orbitColor(o.hue, o.clicked, o.clicked ? 0.95 : 0.7); const size = o.clicked ? 2.2 : 1.4; for (let i = from; i < o.n; i++) { const [px, py] = toPx(r, o.pts[2 * i], o.pts[2 * i + 1]); dctx.fillRect(px - size / 2, py - size / 2, size, size); } } function clearDots(which = layers) { const dpr = devicePixelRatio || 1; for (const layer of which) { const c = layer.getContext('2d'); c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, layer.width, layer.height); c.setTransform(dpr, 0, 0, dpr, 0, 0); } } function resize() { const dpr = devicePixelRatio || 1; const { width, height } = canvas.getBoundingClientRect(); canvas.width = dots.width = top.width = Math.round(width * dpr); canvas.height = dots.height = top.height = Math.round(height * dpr); clearDots(); for (const o of orbits) drawPoints(o, 0); } // advance the orbits within the frame's budget, drawing their new points function fill() { const deadline = performance.now() + FRAME_BUDGET; const advance = (o, count) => { const from = o.n; for (let k = 0; k < count && o.n < o.cap && !o.s.escaped; k++) { stepper.step(o.s); if (o.s.escaped) break; if (o.skip > 0) { o.skip--; continue; } o.pts[2 * o.n] = o.s.x; o.pts[2 * o.n + 1] = o.s.v; o.n++; } drawPoints(o, from); }; for (const o of orbits) if (o.clicked) advance(o, CLICK_PER_FRAME); let busy = true; while (busy && performance.now() < deadline) { busy = false; for (const o of orbits) { if (o.clicked || o.n >= o.cap || o.s.escaped) continue; advance(o, 10); busy = true; } } } function drawAxes(r) { ctx.strokeStyle = theme.line; ctx.lineWidth = 1; ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1); ctx.beginPath(); ctx.moveTo(r.x + r.w / 2, r.y); ctx.lineTo(r.x + r.w / 2, r.y + r.h); ctx.moveTo(r.x, r.y + r.h / 2); ctx.lineTo(r.x + r.w, r.y + r.h / 2); ctx.stroke(); ctx.fillStyle = theme.muted; ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif'; ctx.textBaseline = 'top'; ctx.textAlign = 'left'; ctx.fillText(`−${view.xr.toFixed(2)}`, r.x, r.y + r.h + 6); ctx.textAlign = 'right'; ctx.fillText(view.xr.toFixed(2), r.x + r.w, r.y + r.h + 6); ctx.textAlign = 'center'; ctx.fillText('displacement x', r.x + r.w / 2, r.y + r.h + 6); ctx.save(); ctx.translate(r.x - 8, r.y + r.h / 2); ctx.rotate(-Math.PI / 2); ctx.textBaseline = 'bottom'; ctx.fillText('velocity ẋ (s⁻¹)', 0, 0); ctx.textAlign = 'right'; ctx.fillText(`${Math.round(view.vr)}`, r.h / 2, 0); ctx.textAlign = 'left'; ctx.fillText(`−${Math.round(view.vr)}`, -r.h / 2, 0); ctx.restore(); } function drawPlayhead(r, ph, hue) { if (!ph.queue.length) return; const now = clock(); const dt = noteDt(); const N = stepper.N; const q = ph.queue; let cur = -1; for (let k = 0; k < q.length; k++) if (q[k].time <= now) cur = k; if (cur < 0) return; ctx.save(); ctx.beginPath(); ctx.rect(r.x, r.y, r.w, r.h); ctx.clip(); ctx.lineWidth = 1.6; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; const CHUNK = Math.max(4, Math.ceil(N / 24)); let head = null; for (let k = 0; k <= cur; k++) { const e = q[k]; const span = q[k + 1] ? q[k + 1].time - e.time : dt; const f = Math.min(1, (now - e.time) / span); const end = Math.floor(f * N); for (let j0 = 0; j0 < end; j0 += CHUNK) { const age = (now - (e.time + (j0 / N) * span)) / dt; const alpha = 1 - age / TAIL; if (alpha <= 0) continue; ctx.strokeStyle = orbitColor(hue, true, 0.85 * alpha); ctx.beginPath(); for (let j = j0; j <= Math.min(end, j0 + CHUNK); j++) { const [px, py] = toPx(r, e.path[2 * j], e.path[2 * j + 1]); if (j === j0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.stroke(); } if (k === cur) { const j = Math.min(N, f * N); const i0 = Math.floor(j); const i1 = Math.min(N, i0 + 1); const w = j - i0; 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]); if (e.last) head = null; } // each pluck: a ring growing and fading where it was played for (const n of e.notes) { const g = (now - n.t) / ringTime(); if (g < 0 || g >= 1) continue; const [sx, sy] = toPx(r, n.x, n.v); ctx.strokeStyle = orbitColor(hue, true); ctx.globalAlpha = 1 - g; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI); ctx.stroke(); ctx.globalAlpha = 1; } } if (head) { ctx.fillStyle = orbitColor(hue, true); ctx.beginPath(); ctx.arc(head[0], head[1], 4.5, 0, 2 * Math.PI); ctx.fill(); } ctx.restore(); } function drawStarts(r) { for (const o of orbits) { if (!o.clicked) continue; const [px, py] = toPx(r, o.x0, o.v0); ctx.strokeStyle = orbitColor(o.hue, true); ctx.lineWidth = 1.5; ctx.beginPath(); if (o.s.escaped) { // escaped: a cross at its start ctx.moveTo(px - 5, py - 5); ctx.lineTo(px + 5, py + 5); ctx.moveTo(px + 5, py - 5); ctx.lineTo(px - 5, py + 5); } else { ctx.arc(px, py, 5, 0, 2 * Math.PI); } ctx.stroke(); } } function frame() { requestAnimationFrame(frame); if (!canvas.width || !canvas.height) return; fill(); schedule(); const dpr = devicePixelRatio || 1; const r = plotRect(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = theme.bg; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(dots, 0, 0); ctx.drawImage(top, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); drawAxes(r); drawStarts(r); for (const c of clicked) drawPlayhead(r, c.ph, c.hue); } // ---- controls ---------------------------------------------------------------- function buildControls() { const presetSel = $('preset'); presetSel.innerHTML = PRESETS.map((pr, i) => ``).join('') + ''; $('sliders').innerHTML = SLIDERS.map((s) => ` `).join(''); const show = () => { for (const s of SLIDERS) { const v = params[s.name] / (s.scale ?? 1); $(`s-${s.name}`).value = v; $(`o-${s.name}`).textContent = s.fmt(Number($(`s-${s.name}`).value)); } }; for (const s of SLIDERS) { $(`s-${s.name}`).addEventListener('input', (e) => { params[s.name] = Number(e.target.value) * (s.scale ?? 1); $(`o-${s.name}`).textContent = s.fmt(Number(e.target.value)); presetSel.value = 'custom'; reset(); }); } presetSel.addEventListener('change', () => { if (presetSel.value === 'custom') return; // the clicked orbits stay, restarted from the same (x, x') under the new // parameters (a start outside the new view still plays; its chip in the // legend removes it) params = { ...PRESETS[presetSel.value].params }; show(); reset(); }); show(); $('scale').innerHTML = SCALES.map((s) => ``).join(''); $('keys').innerHTML = KEYS.map((k, i) => ``).join(''); $('keys').addEventListener('click', (e) => { const btn = e.target.closest('button[data-key]'); if (!btn) return; key = Number(btn.dataset.key); for (const b of $('keys').children) b.setAttribute('aria-pressed', b === btn); }); const sus = $('sustain'); Object.assign(sus, { min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, value: SUSTAIN.default }); const susOut = () => { sus.nextElementSibling.textContent = `${Number(sus.value).toFixed(1)} s`; }; sus.addEventListener('input', () => { susOut(); synth?.setSustain(Number(sus.value)); }); susOut(); const tempoOut = () => { $('tempo-out').textContent = `${$('tempo').value} /s`; }; $('tempo').addEventListener('input', tempoOut); tempoOut(); const vol = $('volume'); const volOut = () => { vol.nextElementSibling.textContent = `${Math.round(100 * vol.value)}%`; }; vol.addEventListener('input', () => { volOut(); if (synth && soundOn) synth.setVolume(Number(vol.value)); }); volOut(); $('sound').addEventListener('click', () => setSound(!soundOn)); $('clear').addEventListener('click', () => { clicked = []; reset(); renderLegend(); }); $('orbit-list').addEventListener('click', (e) => { const btn = e.target.closest('button[data-hue]'); if (btn) removeOrbit(clicked.find((c) => String(c.hue) === btn.dataset.hue)); }); canvas.addEventListener('pointerdown', (e) => { const rect = canvas.getBoundingClientRect(); const r = plotRect(); const px = e.clientX - rect.left; const py = e.clientY - rect.top; if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return; // on a start ring: remove that orbit; otherwise add one from here const hit = clicked.find((c) => { const [cx, cy] = toPx(r, c.x, c.v); return Math.hypot(cx - px, cy - py) <= HIT_RADIUS; }); if (hit) { removeOrbit(hit); return; } const x = ((px - r.x) / r.w * 2 - 1) * view.xr; const v = (1 - (py - r.y) / r.h * 2) * view.vr; if (clicked.length >= MAX_CLICKED) removeOrbit(clicked[0]); // the first voice no other orbit is playing const voice = VOICES.findIndex((_, i) => !clicked.some((c) => c.voice === i)); const hue = (0.08 + hueCounter++ * 0.382) % 1; clicked.push({ x, v, hue, voice, ph: newPlayhead(x, v) }); orbits.unshift(newOrbit(x, v, CLICK_POINTS, hue, true)); renderLegend(); }); } function removeOrbit(c) { if (!c) return; clicked = clicked.filter((q) => q !== c); orbits = orbits.filter((o) => !o.clicked || o.hue !== c.hue); // redraw the clicked layer, so its dots go clearDots([top]); for (const o of orbits) if (o.clicked) drawPoints(o, 0); renderLegend(); } // the playing orbits: their color and voice, and a button to remove each function renderLegend() { $('orbit-list').innerHTML = clicked.map((c) => `