// The phase-space slide: orbits of the oscillator in the (x, x') plane, with
// x' = p/m (see orbits.js for which orbits), computed in a worker whenever the
// parameters change. The orbits show the structure of the phase plane; they
// all keep one style. Playing means the sound (as on the other slides, normalized to the orbit's largest
// |x|) and a point running along it with a fading tail, at 1/100 x or real
// time. Stop, or changing a parameter, stops it. Clicking any point of the
// plot, on an orbit or not, adds the orbit from that point and plays it from
// there (on an existing orbit, the same curve); for a driven system it
// starts at drive phase 0, and the path to its settled motion is drawn
// faintly. Added orbits are marked at their start and kept (the last
// MAX_ADDED) until a parameter changes.
//
// controls: the element for the presets dropdown and sliders. container: the
// element for the plot and its buttons. params: initial slider values (see
// controls.js; no x0, since each orbit has its own start). sliders: per-slider
// overrides. presets: [{ name, group?, params }]. instruments: also offer
// instruments, fixed linear filters applied to the sound (instruments.js),
// with a dry / wet mix and loudness normalization, and optionally a notch
// (NOTCH_Q) removing the driving frequency first; tuned ones follow the
// current |f0| (220 Hz when f0 = 0). An optional live spectrogram shows what
// is heard (before the volume); while it shows, the plot is shorter.
import { color, DRAW_SCALE, prepare } from './canvas.js';
import { bindSliders, createPresetSelect, physicsOf, sliderSpecs, slidersHTML, volumeHTML } from './controls.js';
import { amplitude, omegaBound, step, X_MAX } from './duffing.js';
import { createInstrumentChain } from './instrument-chain.js';
import { DEFAULT_SCALE, impulseResponse, INSTRUMENTS, SCALES } from './instruments.js';
import { createSound } from './sound.js';
import { createSpectrogram, SPEC_FFT } from './spectrogram.js';
const SPEEDS = [{ label: '1/100×', value: 0.01 }, { label: 'real time', value: 1 }];
const TAIL_SECONDS = 0.5; // on screen
const MAX_TAIL = 6000;
const MAX_ADDED = 8;
const NOTCH_Q = 30; // the drive notch: about (Omega / 2 pi) / NOTCH_Q wide
// round steps for axis ticks
function tickStep(range) {
const raw = range / 4;
const mag = 10 ** Math.floor(Math.log10(raw));
return [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw);
}
export function createPhasePage({ controls, container, params, sliders = {}, presets, instruments = false }) {
const { names, spec } = sliderSpecs(params, sliders);
const instrumentOptions = Object.entries(INSTRUMENTS).map(([key, { label }]) => ``).join('');
controls.innerHTML = `
${slidersHTML(names, spec)}${instruments ? `
` : ''}`;
container.innerHTML = `
${volumeHTML()}
`;
const canvas = container.querySelector('canvas.phase');
const role = (name) => container.querySelector(`[data-role="${name}"]`);
const speedButton = role('speed');
const stopButton = role('stop');
let p = physicsOf(params);
let result = null; // { orbits, xmax, vmax }
let computing = false;
let playing = -1;
let speed = 0; // index into SPEEDS
let view = null; // the mapping used by the last draw, for hovering
// --- the sound and the point along the orbit
let playParams = null;
// the instrument the sound drives (when offered), live while playing
const inst = { name: 'raw', scale: DEFAULT_SCALE, wet: 0.95, normalize: true, notch: false };
// the notch before the instrument: on only with a drive; otherwise an all-pass
// (which leaves every frequency's level alone)
let notch = null;
const setNotch = () => {
if (!notch) return;
const on = inst.notch && p.F > 0 && p.Omega > 0;
notch.type = on ? 'notch' : 'allpass';
notch.frequency.value = on ? p.Omega / (2 * Math.PI) : 1000;
};
let chain = null;
const instrumentSettings = () => ({ name: inst.name, base: Math.abs(params.freq) || 220, scale: inst.scale, wet: inst.wet });
if (instruments) {
const q = (r) => controls.querySelector(`[data-role="${r}"]`);
const select = q('instrument');
const wetInput = q('wet');
const wetOutput = q('wet-value');
const normalize = q('normalize');
normalize.checked = inst.normalize;
const notchBox = q('notch');
notchBox.checked = inst.notch;
notchBox.addEventListener('change', () => {
inst.notch = notchBox.checked;
setNotch();
});
normalize.addEventListener('change', () => {
inst.normalize = normalize.checked;
chain?.setNormalize(inst.normalize);
});
const scaleSelect = q('scale');
// the scale applies to the marimba and harp only
const showScale = () => { scaleSelect.disabled = !INSTRUMENTS[inst.name].usesScale; };
select.value = inst.name;
scaleSelect.value = inst.scale;
showScale();
wetInput.value = inst.wet;
wetOutput.textContent = inst.wet.toFixed(2);
select.addEventListener('change', () => {
inst.name = select.value;
showScale();
chain?.set(instrumentSettings());
});
scaleSelect.addEventListener('change', () => {
inst.scale = scaleSelect.value;
chain?.set(instrumentSettings());
});
wetInput.addEventListener('input', () => {
inst.wet = Number(wetInput.value);
wetOutput.textContent = inst.wet.toFixed(2);
chain?.setWet(inst.wet);
});
}
// the live spectrogram: of the instrument when there is one, else of the oscillator
const specCanvas = container.querySelector('canvas.spectrogram');
const spectrogram = createSpectrogram(specCanvas);
const specToggle = role('spectrogram-toggle');
specToggle.addEventListener('click', () => {
specCanvas.hidden = !specCanvas.hidden;
container.classList.toggle('with-spectrogram', !specCanvas.hidden);
specToggle.textContent = specCanvas.hidden ? 'Show spectrogram' : 'Hide spectrogram';
draw();
spectrogram.draw();
});
const route = instruments
? async (ctx, osc) => {
chain = await createInstrumentChain(ctx, impulseResponse);
notch = ctx.createBiquadFilter();
notch.Q.value = NOTCH_Q;
setNotch();
osc.connect(notch).connect(chain.input);
chain.set(instrumentSettings());
chain.setNormalize(inst.normalize);
const analyser = ctx.createAnalyser();
analyser.fftSize = SPEC_FFT;
analyser.smoothingTimeConstant = 0;
chain.output.connect(analyser);
spectrogram.attach(analyser);
return chain.output;
}
: null;
const sound = createSound({
volume: role('volume'),
params: () => playParams,
route,
fftSize: instruments ? 0 : SPEC_FFT,
onPlay: (analyser) => { if (analyser) spectrogram.attach(analyser); },
onStop: () => {
chain = null;
notch = null;
spectrogram.detach();
},
});
let trace = null; // { s, t, tail: [t, x, v, ...] }
let rafId = null;
let lastFrame = null;
function stopPlaying() {
playing = -1;
trace = null;
cancelAnimationFrame(rafId);
sound.stop();
stopButton.disabled = true;
draw();
}
function play(i) {
const o = result.orbits[i];
playing = i;
playParams = { ...p, x0: o.start.x, ref: o.ref };
sound.play({ ...o.start });
trace = { s: { ...o.start, escaped: false }, t: 0, tail: [0, o.start.x, o.start.v] };
stopButton.disabled = false;
lastFrame = null;
cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(frame);
}
function frame(now) {
if (!trace) return;
if (lastFrame !== null && !trace.s.escaped) {
const dt = Math.min((now - lastFrame) / 1000, 0.05) * SPEEDS[speed].value;
// record about 40 points per oscillation
const w = Math.max(omegaBound(p, 0.5), p.F ? p.Omega : 0, 2 * Math.PI);
const n = Math.min(4000, Math.max(1, Math.ceil(dt / ((2 * Math.PI) / (w * 40)))));
const { s } = trace;
for (let i = 0; i < n && !s.escaped; i++) {
step(p, s, dt / n, omegaBound(p, Math.min(X_MAX, 1.2 * Math.max(amplitude(p, s.x, s.v), Math.abs(s.x)))));
trace.t += dt / n;
trace.tail.push(trace.t, s.x, s.v);
}
const keep = TAIL_SECONDS * SPEEDS[speed].value;
let cut = 0;
while (cut < trace.tail.length - 3 && (trace.tail[cut] < trace.t - keep || trace.tail.length - cut > 3 * MAX_TAIL)) cut += 3;
if (cut) trace.tail.splice(0, cut);
}
lastFrame = now;
draw();
rafId = requestAnimationFrame(frame);
}
speedButton.addEventListener('click', () => {
speed = (speed + 1) % SPEEDS.length;
speedButton.textContent = `Speed: ${SPEEDS[speed].label}`;
if (trace) trace.tail = trace.tail.slice(-3);
});
stopButton.addEventListener('click', stopPlaying);
// --- computing the orbits, in a worker; a new request replaces a running one
let worker = null;
let busy = false;
let requestId = 0;
let timer = null;
function compute() {
if (busy) {
worker.terminate();
worker = null;
}
if (!worker) {
worker = new Worker(new URL('./orbits-worker.js', import.meta.url), { type: 'module' });
worker.onmessage = (e) => {
if (e.data.id !== requestId) return;
busy = false;
computing = false;
result = e.data;
draw();
};
}
busy = true;
computing = true;
requestId++;
worker.postMessage({ id: requestId, p });
draw();
}
// the orbit from a clicked point, in a second worker, so the full set keeps
// its own; a new click replaces a pending one
let oneWorker = null;
let oneBusy = false;
let oneId = 0;
let pendingPoint = null; // { x, v } being computed
function cancelAdded() {
if (oneBusy) {
oneWorker.terminate();
oneWorker = null;
oneBusy = false;
}
oneId++;
pendingPoint = null;
}
function addOrbitFrom(point) {
stopPlaying();
cancelAdded();
if (!oneWorker) {
oneWorker = new Worker(new URL('./orbits-worker.js', import.meta.url), { type: 'module' });
oneWorker.onmessage = (e) => {
if (e.data.id !== oneId || !result) return;
oneBusy = false;
pendingPoint = null;
const added = result.orbits.filter((o) => o.added);
if (added.length >= MAX_ADDED) result.orbits.splice(result.orbits.indexOf(added[0]), 1);
result.orbits.push({ ...e.data.orbit, added: true });
play(result.orbits.length - 1);
};
}
oneBusy = true;
pendingPoint = point;
oneWorker.postMessage({ id: oneId, p, from: point });
draw();
}
function changed() {
cancelAdded();
stopPlaying();
p = physicsOf(params);
computing = true;
clearTimeout(timer);
timer = setTimeout(compute, 100);
draw();
}
let presetSelect = null;
const sliderControls = bindSliders({
root: controls,
names,
spec,
params,
onInput: () => {
presetSelect?.markCustom();
changed();
},
});
presetSelect = createPresetSelect({
container: controls.querySelector('[data-presets]'),
presets,
params,
names,
onChoose: () => {
sliderControls.showAll();
changed();
},
});
// --- drawing
function draw() {
if (!canvas.clientWidth) return;
const { ctx, w, h } = prepare(canvas);
const fg = color('--fg');
const left = 64;
const right = 14;
const top = 40; // below the buttons
const bottom = 36;
const pw = w - left - right;
const ph = h - top - bottom;
// axes: symmetric, fitted to the orbits; escaping paths do not set x'
const orbits = result?.orbits ?? [];
let xmax = result?.xmax ?? 0.5;
for (const o of orbits) {
if (!o.added) continue;
for (const arr of [o.pts, o.path ?? []]) for (let i = 0; i < arr.length; i += 2) xmax = Math.max(xmax, Math.abs(arr[i]));
}
const xr = 1.08 * Math.max(Math.min(xmax, X_MAX), 0.05);
let vmax = 0;
for (const o of orbits) {
if (o.kind === 'escape') continue;
for (let i = 1; i < o.pts.length; i += 2) vmax = Math.max(vmax, Math.abs(o.pts[i]));
}
if (!vmax) vmax = result?.vmax || 1;
const vr = 1.08 * vmax;
const X = (x) => left + ((x + xr) / (2 * xr)) * pw;
const Y = (v) => top + ph / 2 - (v / vr) * (ph / 2);
view = { X, Y, left, top, pw, ph, xr, vr };
ctx.font = '13px "Hanken Grotesk", system-ui, sans-serif';
ctx.strokeStyle = fg;
ctx.fillStyle = fg;
ctx.lineWidth = 1;
ctx.strokeRect(left, top, pw, ph);
ctx.globalAlpha = 0.25;
ctx.beginPath();
ctx.moveTo(X(0), top);
ctx.lineTo(X(0), top + ph);
ctx.moveTo(left, Y(0));
ctx.lineTo(left + pw, Y(0));
ctx.stroke();
ctx.globalAlpha = 1;
// ticks
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
const xs = tickStep(2 * xr);
for (let x = -Math.floor(xr / xs) * xs; x <= xr + 1e-9; x += xs) {
ctx.beginPath();
ctx.moveTo(X(x), top + ph);
ctx.lineTo(X(x), top + ph + 4);
ctx.stroke();
ctx.fillText(Math.abs(x) < 1e-9 ? '0' : x.toFixed(2).replace(/0$/, ''), X(x), top + ph + 6);
}
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
const vs = tickStep(2 * vr);
for (let v = -Math.floor(vr / vs) * vs; v <= vr + 1e-9; v += vs) {
ctx.beginPath();
ctx.moveTo(left - 4, Y(v));
ctx.lineTo(left, Y(v));
ctx.stroke();
ctx.fillText(Math.abs(v) < 1e-9 ? '0' : String(Math.round(v)), left - 6, Y(v));
}
ctx.font = 'italic 17px Georgia, serif';
ctx.textAlign = 'right';
ctx.textBaseline = 'bottom';
ctx.fillText('x', left + pw - 4, Y(0) - 4);
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText('ẋ = p/m', X(0) + 6, top + 4);
// orbits, clipped to the plot
ctx.save();
ctx.beginPath();
ctx.rect(left, top, pw, ph);
ctx.clip();
const accent = color('--accent');
const force = color('--force');
// a playing added driven orbit's path from the clicked point to its
// settled motion, faint (only while it plays, or the paths would bury the
// plot)
if (playing >= 0 && orbits[playing]?.path) {
ctx.globalAlpha = 0.35;
ctx.lineWidth = 0.8;
ctx.strokeStyle = accent;
polyline(ctx, orbits[playing].path, X, Y);
}
orbits.forEach((o) => {
ctx.globalAlpha = o.kind === 'irregular' ? 0.5 : 0.85;
ctx.lineWidth = o.kind === 'irregular' ? 0.5 : 1.2;
ctx.strokeStyle = o.kind === 'escape' ? force : accent;
polyline(ctx, o.pts, X, Y);
});
// where each added orbit starts, and a click still being computed
ctx.globalAlpha = 1;
ctx.lineWidth = 1.5;
orbits.forEach((o) => {
if (!o.added) return;
ctx.strokeStyle = o.kind === 'escape' ? force : accent;
ctx.beginPath();
ctx.arc(X(o.start.x), Y(o.start.v), 4, 0, 2 * Math.PI);
ctx.stroke();
});
if (pendingPoint) {
ctx.strokeStyle = fg;
ctx.beginPath();
ctx.arc(X(pendingPoint.x), Y(pendingPoint.v), 4, 0, 2 * Math.PI);
ctx.stroke();
}
// the point along the playing orbit, with its fading tail
if (trace) {
const tail = trace.tail;
const orange = color('--brand-orange');
ctx.strokeStyle = orange;
ctx.lineWidth = 2.5;
const keep = TAIL_SECONDS * SPEEDS[speed].value;
const segs = 24;
for (let k = 0; k < segs; k++) {
// the tail in segs pieces, older ones fainter
const t0 = trace.t - keep * (1 - k / segs);
const t1 = trace.t - keep * (1 - (k + 1) / segs);
ctx.globalAlpha = (k + 1) / segs;
ctx.beginPath();
let started = false;
for (let j = 0; j < tail.length; j += 3) {
if (tail[j] < t0 || tail[j] > t1 + 1e-12) continue;
if (!started) {
// start from the previous point, so the pieces join up
const k0 = Math.max(0, j - 3);
ctx.moveTo(X(tail[k0 + 1]), Y(tail[k0 + 2]));
started = true;
}
ctx.lineTo(X(tail[j + 1]), Y(tail[j + 2]));
}
ctx.stroke();
}
ctx.globalAlpha = 1;
if (!trace.s.escaped) {
ctx.fillStyle = orange;
ctx.beginPath();
ctx.arc(X(trace.s.x), Y(trace.s.v), 5, 0, 2 * Math.PI);
ctx.fill();
}
}
ctx.restore();
ctx.globalAlpha = 1;
if (computing || pendingPoint) {
ctx.fillStyle = fg;
ctx.globalAlpha = 0.6;
ctx.font = '15px "Hanken Grotesk", system-ui, sans-serif';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(computing ? 'Computing orbits\u2026' : 'Computing the orbit\u2026', left + 8, top + 8);
ctx.globalAlpha = 1;
}
}
function polyline(ctx, pts, X, Y) {
ctx.beginPath();
ctx.moveTo(X(pts[0]), Y(pts[1]));
for (let i = 2; i < pts.length; i += 2) ctx.lineTo(X(pts[i]), Y(pts[i + 1]));
ctx.stroke();
}
// --- hovering and clicking
// the pointer in drawing units
function pointer(e) {
const rect = canvas.getBoundingClientRect();
const scale = canvas.clientWidth / rect.width / DRAW_SCALE; // client pixels to drawing units
return [(e.clientX - rect.left) * scale, (e.clientY - rect.top) * scale];
}
// the point of the plane under the pointer, { x, v }, or null outside the plot
function pointAt(e) {
if (!view) return null;
const [mx, my] = pointer(e);
const { left, top, pw, ph, xr, vr } = view;
if (mx < left || mx > left + pw || my < top || my > top + ph) return null;
const x = ((mx - left) / pw) * 2 * xr - xr;
const v = ((top + ph / 2 - my) / (ph / 2)) * vr;
return Math.abs(x) < X_MAX ? { x, v } : null;
}
canvas.addEventListener('mousemove', (e) => {
canvas.style.cursor = pointAt(e) ? 'crosshair' : '';
});
// a click anywhere in the plot starts the orbit from that point
canvas.addEventListener('click', (e) => {
const point = pointAt(e);
if (point) addOrbitFrom(point);
});
compute();
return {
draw: () => {
draw();
spectrogram.draw();
},
pause: stopPlaying,
};
}