// Islands in a sea of chaos: the Poincaré section of the driven Duffing
// oscillator (js/duffing.js), filled in live, with tracks that sonify orbits
// (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 track is an orbit (a start (x, x') picked on the plot, at drive phase
// 0) and how it plays: rhythm, scale, key, tempo multiple, sustain,
// volume, instrument and velocity. Its dots fill in fast and larger; while
// it plays, a playhead walks it one drive period per tick, with a
// live trail of the motion through the period, plucking notes whose pitch
// is set by x (left to right over three octaves of its scale and key).
// Tracks start paused; each can be played, paused and restarted from its
// start.
// - One global tempo (bpm) sets the beat; each track ticks at a multiple of
// it (x1, x2, x3, ..., x1/2, x1/3, ..., or any value), on a grid aligned to
// the beat, so x2 and x3 meet on every beat and x1/2 ticks on every other.
// - Each setting but the instrument can be linked: the linked tracks share
// one value (by default scale and key).
// - Rhythm 'steady' plucks at the section point, once per beat; 'natural'
// plays the motion in slowed time and plucks wherever x' crosses 0 upward
// (the left turning point of each swing), at that x; 'both' at either
// turning point.
// - Changing a parameter or preset doesn't restart anything: the tracks
// carry on from where they are under the new equation, their dots now
// computed from there, and the old dots fade out as the new ones fill in.
// Restart takes a track back to its start.
// - Coupling (optional; off by default) joins the playing tracks with the
// same tempo multiple into one system (one per multiple): a spring and
// damper on each one's difference from their mean (duffing.js, stepMany),
// so they pull together and, strong enough, fall into step. When such a
// set of tracks or the coupling changes, they carry on from where they are
// (their dots are recomputed from there, coupled as the playheads will
// move).
import { createStepper, physicsOf, X_MAX } from './js/duffing.js';
import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, OCTAVES, pitchOf, SCALES, SUSTAIN, VOICES } from './js/voices.js';
import { midiSupported, openMidi } from './js/midi.js';
import { forgetSoundFont, loadSaved, makeInstrument, parseSF2, saveSoundFont } from './js/soundfont.js';
import { PRESETS } from './js/presets.js';
import { download, downloadBlob, FORMAT, forgetLocal, fromBase64, loadKnobs, loadLocal, saveKnobs, saveLocal, toBase64 } from './js/session.js';
const SEEDS_X = 24; // seed orbits along x' = 0
const SEEDS_V = 8; // and along x = 0
const SEED_POINTS = 1500;
const TRACK_POINTS = 4000;
const TRACK_PER_FRAME = 40; // so a track's orbit visibly grows
const MAX_TRACKS = 8;
const HIT_RADIUS = 9; // px: a press this close to a start ring picks its track
const DRAG_START = 4; // px a press on a start ring moves before it drags
const FRAME_BUDGET = 7; // ms of integration per frame
const TAIL = 2; // trail length, in beats
const LOOKAHEAD = 0.12; // s of notes scheduled ahead
const FADE = 0.7; // s for replaced dots to fade out
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) },
];
// ---- track settings ------------------------------------------------------------
const RHYTHMS = [
{ value: 'steady', name: 'Steady: each drive period', short: 'steady' },
{ value: 'both', name: 'Natural: ẋ = 0 both ways', short: 'both ways' },
{ value: 'natural', name: 'Natural: ẋ = 0 upward', short: 'upward' },
];
const SCALE_SHORT = {
'Major pentatonic': 'maj. pent.', 'Minor pentatonic': 'min. pent.', Major: 'major',
'Natural minor': 'minor', 'Harmonic minor': 'harm. minor', 'Whole tone': 'whole tone',
Chromatic: 'chromatic', Continuous: 'continuous',
};
// the settings that can be linked (shared by the linked tracks), and their defaults
const SETTINGS = ['rhythm', 'scale', 'key', 'octave', 'rate', 'sustain', 'mono', 'volume', 'velocity'];
const DEFAULTS = {
rhythm: 'steady', scale: SCALES.findIndex((s) => s.name === DEFAULT_SCALE), key: DEFAULT_KEY, octave: 0,
rate: '1', sustain: SUSTAIN.default, mono: false, volume: 1, velocity: 100,
};
const LINKED_BY_DEFAULT = ['scale', 'key'];
// a track's range: its octave, the shift (octaves) of everything it plays
// (so the view's left edge is C3 shifted), and 'span', the number of octaves
// across the view, linked along with the octave
const OCTAVE_SHIFTS = [-3, -2, -1, 0, 1, 2, 3];
const SPANS = [1, 2, 3, 4, 5, 6];
DEFAULTS.span = OCTAVES;
const octaveLabel = (o) => (o > 0 ? `+${o}` : o < 0 ? `−${-o}` : '0');
const cName = (o) => `C${3 + o}`; // the note at the left edge, octave o
// The 'Custom notes' scale (the scale setting's value CUSTOM): its notes are
// in the setting 'notes', which is linked along with the scale: MIDI note
// numbers (sorted), as entered in key `ref`, so a change of key transposes
// them (the nearer way); every: their pitch classes in every octave (a scale
// across the usual three octaves), rather than just those notes.
const CUSTOM = 'custom';
DEFAULTS.notes = { notes: [], ref: DEFAULT_KEY, every: true };
const VALUES = [...SETTINGS, 'notes', 'span']; // a track's values (the settings, the custom notes, and the span)
const COMPANIONS = { notes: 'scale', span: 'octave' };
const linkOf = (p) => COMPANIONS[p] ?? p;
// the global tempo (bpm)
const TEMPO = { min: 40, max: 240, default: 120 };
// a track's tempo multiple: ticks (drive periods) per beat, as text ('3',
// '1/2', '1.5'); the menu's choices, and the range of custom ones
const RATES = ['64', '48', '32', '24', '16', '12', '8', '6', '4', '3', '2', '1', '1/2', '1/3', '1/4', '1/6', '1/8'];
const RATE_RANGE = { min: 1 / 16, max: 128 };
const RANGES = {
sustain: { label: 'Sustain', min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, fmt: (v) => `${v.toFixed(1)} s`, title: 'How long each note rings (built-in instruments)' },
volume: { label: 'Volume', min: 0, max: 1, step: 0.01, fmt: (v) => `${Math.round(100 * v)}%` },
velocity: { label: 'Velocity', min: 1, max: 127, step: 1, fmt: (v) => `${v}`, title: 'MIDI velocity (SoundFont instruments)' },
};
const $ = (id) => document.getElementById(id);
const canvas = $('plot');
const ctx = canvas.getContext('2d');
// the section points, accumulated: seed orbits, and the tracks' on top
const dots = document.createElement('canvas');
const top = document.createElement('canvas');
const layers = [dots, top];
// replaced dots, fading out (and a spare canvas to composite into)
let ghost = document.createElement('canvas');
let spare = document.createElement('canvas');
let ghostStart = -Infinity;
let params = { ...PRESETS[0].params };
let stepper;
let view; // { xr, vr }: half-ranges of x and x'
let seeds = []; // the seed orbits
let tracks = []; // see newTrack
let selected = null; // the track whose controls are open, and whose start a click moves
let shared = { ...DEFAULTS }; // the linked tracks' settings
let tempo = TEMPO.default; // bpm
let anchor = { time: 0, beat: 0 }; // the beat at a clock time (moved when the tempo changes)
let synth = null;
let soundOn = false;
let nextId = 1;
let hueCounter = 0;
let coupling = 0; // r (s^-1) of the coupling; 0: off
let groups = []; // the sets of coupled tracks, as last restarted
let groupKey = '';
let dirty = false; // the equation changed: reset at the next frame
let theme;
let soundfonts = []; // the loaded .sf2 files: { id, fileName, bytes, sf (parsed), insts: Map(preset -> instrument) }
let nextFontId = 1;
let recording = null; // while recording: { kind: 'video', recorder, chunks, mime, started } or { kind: 'audio', stop, chunks, frames, rate, started }
let recorded = null; // { blob, mime, seconds, saved } once stopped
let restored = false; // the saved state has been restored (until then, nothing is saved)
// ---- tracks --------------------------------------------------------------------
// a track's setting: its own, or the shared one if linked
const val = (t, p) => (t.linked[linkOf(p)] ? shared : t.own)[p];
// a tempo multiple's value from its text ('3', '1/2', '1.5'), or NaN
function parseRate(text) {
const m = String(text).trim().match(/^(\d*\.?\d+)\s*(?:\/\s*(\d*\.?\d+))?$/);
const v = m ? Number(m[1]) / (m[2] ? Number(m[2]) : 1) : NaN;
return v >= RATE_RANGE.min && v <= RATE_RANGE.max ? v : NaN;
}
const rateOf = (t) => parseRate(val(t, 'rate')) || 1;
const rateLabel = (t) => `×${val(t, 'rate')}`;
// a track's tick: its length in beats, and in seconds (one drive period)
const tickBeats = (t) => 1 / rateOf(t);
const tickDt = (t) => 60 / (tempo * rateOf(t));
// the beat at clock time `time`, and the clock time of beat b
const beatAt = (time) => anchor.beat + ((time - anchor.time) * tempo) / 60;
const timeAt = (b) => anchor.time + ((b - anchor.beat) * 60) / tempo;
// the coupled set a track is in, if any
const groupOf = (t) => groups.find((g) => g.includes(t));
// a new track, paused, with the settings of `like` (a track) or the defaults
function newTrack(like) {
const own = like ? Object.fromEntries(VALUES.map((p) => [p, val(like, p)])) : { ...DEFAULTS };
return {
id: nextId++,
hue: (0.08 + hueCounter++ * 0.382) % 1,
instrument: freeInstrument(),
start: null, // { x, v }
orbit: null, // its dots
ph: null, // its playhead
playing: false,
tick: null, // its next tick, as a number of ticks from beat 0 (null: from the next one due)
own,
linked: Object.fromEntries(SETTINGS.map((p) => [p, LINKED_BY_DEFAULT.includes(p)])),
escaped: false,
};
}
function addTrack() {
if (tracks.length >= MAX_TRACKS) return null;
const t = newTrack(selected);
tracks.push(t);
selected = t;
applyVolumes();
renderTracks();
return t;
}
function removeTrack(t) {
tracks = tracks.filter((q) => q !== t);
if (selected === t) selected = tracks[tracks.length - 1] ?? null;
synth?.removeTrack(t.id);
redrawTop();
renderTracks();
}
function setValue(t, p, v) {
(t.linked[linkOf(p)] ? shared : t.own)[p] = v;
if (p === 'volume') applyVolumes();
if (p === 'rate') for (const q of tracks) q.tick = null; // onto the new grid
}
// link or unlink a track's setting: linking adopts the shared value (or, if
// no other track is linked, shares the track's own); unlinking keeps it
function setLinked(t, p, on) {
if (on === t.linked[p]) return;
const ps = VALUES.filter((q) => linkOf(q) === p);
if (on) {
if (!tracks.some((q) => q !== t && q.linked[p])) for (const q of ps) shared[q] = t.own[q];
} else {
for (const q of ps) t.own[q] = shared[q];
}
t.linked[p] = on;
if (p === 'volume') applyVolumes();
if (p === 'rate') t.tick = null;
}
const applyVolumes = () => { for (const t of tracks) synth?.setTrackVolume(t.id, val(t, 'volume')); };
const trackName = (t) => `${tracks.indexOf(t) + 1}`;
// the sets of coupled tracks: the playing ones with the same tempo multiple,
// two or more to a set
function coupledGroups() {
if (!coupling) return [];
const by = new Map();
for (const t of tracks) {
if (!t.start || !t.playing) continue;
const k = rateOf(t).toPrecision(9);
if (!by.has(k)) by.set(k, []);
by.get(k).push(t);
}
return [...by.values()].filter((g) => g.length > 1);
}
// ---- 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, isTrack, skip = 0) {
return { x0: x, v0: v, s: { x, v, escaped: false }, pts: new Float32Array(2 * cap), n: 0, cap, hue, isTrack, skip };
}
// a playhead: the orbit's state; its scheduled beats ({ time, dt, path,
// last, notes }) still needed for the trail, notes: [{ t, x, v }]; and the
// time its last scheduled beat ends
const newPlayhead = (x, v) => ({ s: { x, v, escaped: false }, queue: [], until: 0 });
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 (the tracks show the way in)
const skip = p.delta > 0 ? Math.min(5000, Math.ceil((5 / p.delta) / stepper.T)) : 0;
seeds = [];
for (let i = 0; i < SEEDS_X; i++) {
const x = view.xr * (-1 + (2 * (i + 0.5)) / SEEDS_X);
seeds.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);
seeds.push(newOrbit(0, v, SEED_POINTS, ((i + SEEDS_X) * 0.618) % 1, false, skip));
}
fadeOut(layers);
clearDots([dots]);
reseed(tracks, false);
}
// recompute tracks' dots from where their playheads are (coupled as they
// will move), the old ones fading out
function reseed(ts, fade = true) {
if (fade) fadeOut([top]);
for (const t of ts) {
if (!t.ph) continue;
const { x, v, escaped } = t.ph.s;
t.orbit = newOrbit(x, v, TRACK_POINTS, t.hue, true);
t.orbit.s.escaped = escaped;
}
redrawTop();
}
// restart tracks' playheads from their starts, and their dots too if they
// weren't computed from there
function restart(ts) {
let changed = false;
for (const t of ts) {
if (!t.start) continue;
t.ph = newPlayhead(t.start.x, t.start.v);
t.tick = null;
if (!t.orbit || t.orbit.x0 !== t.start.x || t.orbit.v0 !== t.start.v) {
t.orbit = newOrbit(t.start.x, t.start.v, TRACK_POINTS, t.hue, true);
changed = true;
}
}
if (changed) redrawTop();
}
// restart a track; if it is coupled, the others carry on, with it
function restartTrack(t) {
restart([t]);
const g = groupOf(t);
if (g) reseed(g);
}
// When the coupled sets change (a track played, paused, added or removed,
// its tempo multiple changed, or the coupling changed), the old and new
// members carry on from where they are, their dots recomputed.
function syncCoupling() {
const gs = coupledGroups();
const key = gs.length ? `${coupling}:${gs.map((g) => g.map((t) => t.id).join(',')).join(';')}` : '';
if (key === groupKey) return;
const was = groups.flat().filter((t) => tracks.includes(t));
groups = gs;
groupKey = key;
reseed([...new Set([...was, ...gs.flat()])]);
}
function setStart(t, x, v) {
const first = !t.start;
t.start = { x, v };
t.escaped = false;
restartTrack(t);
if (first) renderTracks();
else updateTrack(t);
renderHint();
}
// ---- playhead and sound -----------------------------------------------------
const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
const ringTime = (dt) => Math.min(RING, 3 * dt);
// The crossings of x' = 0 along a drive period's path (N + 1 points, evenly
// spaced in time over dt from time t0), interpolated linearly: upward only
// (from x' < 0 to x' >= 0), or both ways (also from x' > 0 to x' <= 0).
function crossings(path, t0, dt, both) {
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) || (both && 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;
}
// ---- pitch ---------------------------------------------------------------------
const midiHz = (m) => 440 * 2 ** ((m - 69) / 12);
const noteName = (m) => `${KEYS[m % 12]}${Math.floor(m / 12) - 1}`;
const pc = (n) => ((n % 12) + 12) % 12;
// the shift (semitones) of custom notes c in key `key`: the nearer way from c.ref
const shiftOf = (c, key) => { const d = pc(key - c.ref); return d > 6 ? d - 12 : d; };
// the shift (semitones) from a track's custom notes as stored to as they
// sound: its key's, and its octave's
const offsetOf = (t) => shiftOf(val(t, 'notes'), val(t, 'key')) + 12 * val(t, 'octave');
// a track's custom notes as they sound (in its key and octave)
const soundingNotes = (t) => { const d = offsetOf(t); return val(t, 'notes').notes.map((n) => n + d); };
const isCustom = (t) => val(t, 'scale') === CUSTOM;
// custom notes played as they are (not as a scale), so the span is moot
const exact = (t) => isCustom(t) && !val(t, 'notes').every;
// the pitch (Hz) a track plays at u in [0, 1] (the left to right edge of the
// view), or null (custom notes, but none yet): custom notes spread evenly
// over the view (or as a scale), or the scale's notes
function pitchFor(t, u) {
const key = val(t, 'key');
const up = 2 ** val(t, 'octave');
if (!isCustom(t)) return up * pitchOf(u, SCALES[val(t, 'scale')], key, val(t, 'span'));
const c = val(t, 'notes');
if (!c.notes.length) return null;
if (c.every) return up * pitchOf(u, { steps: [...new Set(c.notes.map((n) => pc(n - c.ref)))] }, key, val(t, 'span'));
const ns = soundingNotes(t);
return midiHz(ns[Math.round(Math.min(1, Math.max(0, u)) * (ns.length - 1))]);
}
// MIDI velocity for SoundFont notes: the track's, jittered a little so
// neighbouring velocity layers (or variations) alternate
function velocity(t) {
const v = val(t, 'velocity') + Math.round((Math.random() * 2 - 1) * 6);
return Math.max(1, Math.min(127, v));
}
// One tick at time `time` (lasting dt) for tracks ts: each playhead advances
// one drive period (together if coupled), keeping the path for the trail,
// and plucks its notes (steady: one at the section point; natural: at each
// upward x' = 0; both: at each x' = 0), at level gain.
function beat(ts, time, dt, together, gain) {
const before = ts.map((t) => ({ ...t.ph.s }));
const paths = ts.map(() => new Float32Array(2 * (stepper.N + 1)));
if (together) stepper.stepMany(ts.map((t) => t.ph.s), coupling, paths);
else ts.forEach((t, k) => stepper.step(t.ph.s, paths[k]));
for (const [k, t] of ts.entries()) {
t.ph.until = time + dt;
if (before[k].escaped) continue;
const { x, v } = before[k];
const rhythm = val(t, 'rhythm');
// (at crossings: none in the period it escapes, whose path ends at rest)
const notes = rhythm === 'steady' ? [{ t: time, x, v }]
: t.ph.s.escaped ? [] : crossings(paths[k], time, dt, rhythm === 'both');
t.ph.queue.push({ time, dt, path: paths[k], last: t.ph.s.escaped, notes });
if (soundOn && synth) {
const voice = voiceOf(t);
for (const n of notes) {
const u = (n.x / view.xr + 1) / 2;
const freq = pitchFor(t, u);
if (freq == null) continue;
synth.play(t.id, voice, freq, n.t, {
pan: Math.max(-1, Math.min(1, 1.4 * u - 0.7)), gain, sustain: val(t, 'sustain'), vel: velocity(t), mono: val(t, 'mono'),
});
}
}
}
}
// Run tracks ts (one, or a coupled set, sharing the tempo multiple) over
// their ticks due within LOOKAHEAD. Ticks fall on a grid aligned to beat 0,
// tickBeats apart; a track starting (or fallen behind: a stalled frame, a
// hidden tab, a pause) picks up at the next tick after now, rather than
// playing the missed ones in a burst.
function runTicks(ts, now, gain) {
const lead = ts[0];
const step = tickBeats(lead);
const dt = tickDt(lead);
const until = Math.max(...ts.map((t) => t.ph.until));
if (lead.tick == null || timeAt(lead.tick * step) < now) {
lead.tick = Math.ceil(beatAt(Math.max(now + 0.02, until)) / step - 1e-6);
}
let k = lead.tick;
for (let time = timeAt(k * step); time < now + LOOKAHEAD; time = timeAt(++k * step)) {
// (after a tempo change, the ticks already played wait out)
if (time < until - 1e-6) continue;
beat(ts, time, dt, ts.length > 1, gain);
}
for (const t of ts) t.tick = k;
}
// schedule the ticks due within LOOKAHEAD, softer the more tracks play
function schedule() {
const now = clock();
const playing = tracks.filter((t) => t.playing && t.ph);
const gain = 1 / Math.sqrt(Math.max(1, playing.length));
for (const g of groups) runTicks(g, now, gain);
for (const t of playing) if (!groupOf(t)) runTicks([t], now, gain);
for (const t of tracks) {
if (!t.ph) continue;
const dt = tickDt(t);
const keep = Math.max((TAIL + 1) * dt, ringTime(dt) + dt);
const q = t.ph.queue;
while (q.length > 1 && q[1].time < now - keep) q.shift();
}
}
// a new global tempo: the beat carries on from now
function setTempo(bpm) {
const now = clock();
anchor = { time: now, beat: beatAt(now) };
tempo = bpm;
}
function setSound(on) {
soundOn = on;
renderSoundButton();
if (on && !synth) {
// the clock switches to the audio context's
synth = createSynth();
applyVolumes();
anchor = { time: clock(), beat: 0 };
for (const t of tracks) {
t.tick = null;
if (t.ph) { t.ph.queue = []; t.ph.until = 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, isTrack, alpha = 1) =>
`hsla(${Math.round(hue * 360)}, ${isTrack ? 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.isTrack ? top : dots).getContext('2d');
dctx.fillStyle = orbitColor(o.hue, o.isTrack, o.isTrack ? 0.95 : 0.7);
const size = o.isTrack ? 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);
}
}
// redraw the tracks' dots
function redrawTop() {
clearDots([top]);
for (const t of tracks) if (t.orbit) drawPoints(t.orbit, 0);
}
// the opacity of the fading dots
const ghostAlpha = () => Math.max(0, 1 - (performance.now() / 1000 - ghostStart) / FADE);
// start fading out what the given layers show (on top of what is fading already)
function fadeOut(which) {
if (!canvas.width || !canvas.height) return;
const c = spare.getContext('2d');
c.setTransform(1, 0, 0, 1, 0, 0);
c.clearRect(0, 0, spare.width, spare.height);
const a = ghostAlpha();
if (a > 0) {
c.globalAlpha = a;
c.drawImage(ghost, 0, 0);
c.globalAlpha = 1;
}
for (const layer of which) c.drawImage(layer, 0, 0);
[ghost, spare] = [spare, ghost];
ghostStart = performance.now() / 1000;
}
function resize() {
const dpr = devicePixelRatio || 1;
const { width, height } = canvas.getBoundingClientRect();
canvas.width = dots.width = top.width = ghost.width = spare.width = Math.round(width * dpr);
canvas.height = dots.height = top.height = ghost.height = spare.height = Math.round(height * dpr);
ghostStart = -Infinity;
clearDots();
for (const o of seeds) drawPoints(o, 0);
redrawTop();
}
// 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 g of groups) {
// the coupled tracks together, as their playheads will move
const os = g.map((t) => t.orbit);
const from = os.map((o) => o.n);
for (let k = 0; k < TRACK_PER_FRAME && os.some((o) => o.n < o.cap && !o.s.escaped); k++) {
stepper.stepMany(os.map((o) => o.s), coupling);
for (const o of os) {
if (o.s.escaped || o.n >= o.cap) continue;
o.pts[2 * o.n] = o.s.x;
o.pts[2 * o.n + 1] = o.s.v;
o.n++;
}
}
os.forEach((o, k) => drawPoints(o, from[k]));
}
for (const t of tracks) if (t.orbit && !groupOf(t)) advance(t.orbit, TRACK_PER_FRAME);
let busy = true;
while (busy && performance.now() < deadline) {
busy = false;
for (const o of seeds) {
if (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(c, r, t) {
const { ph, hue } = t;
if (!ph?.queue.length) return;
const now = clock();
const dt = tickDt(t);
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;
c.save();
c.beginPath();
c.rect(r.x, r.y, r.w, r.h);
c.clip();
c.lineWidth = 1.6;
c.lineCap = 'round';
c.lineJoin = 'round';
let head = null;
for (let k = 0; k <= cur; k++) {
const e = q[k];
// (N, the steps per period, as when the path was computed)
const N = e.path.length / 2 - 1;
const CHUNK = Math.max(4, Math.ceil(N / 24));
const span = e.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;
c.strokeStyle = orbitColor(hue, true, 0.85 * alpha);
c.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) c.moveTo(px, py);
else c.lineTo(px, py);
}
c.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(e.dt);
if (g < 0 || g >= 1) continue;
const [sx, sy] = toPx(r, n.x, n.v);
c.strokeStyle = orbitColor(hue, true);
c.globalAlpha = 1 - g;
c.lineWidth = 2;
c.beginPath();
c.arc(sx, sy, 4 + 14 * g, 0, 2 * Math.PI);
c.stroke();
c.globalAlpha = 1;
}
}
if (head) {
c.beginPath();
c.arc(head[0], head[1], 4.5, 0, 2 * Math.PI);
if (t.playing) {
c.fillStyle = orbitColor(hue, true);
c.fill();
} else {
// paused: a hollow head
c.strokeStyle = orbitColor(hue, true);
c.lineWidth = 2;
c.stroke();
}
}
c.restore();
}
// the tracks' start rings (a cross if escaped), and their numbers if `labels`
function drawStarts(c, r, labels) {
for (const t of tracks) {
if (!t.start) continue;
const [px, py] = toPx(r, t.start.x, t.start.v);
const sel = t === selected;
c.strokeStyle = orbitColor(t.hue, true);
c.lineWidth = sel ? 2.5 : 1.5;
c.beginPath();
if (t.orbit?.s.escaped) {
// escaped: a cross at its start
c.moveTo(px - 5, py - 5); c.lineTo(px + 5, py + 5);
c.moveTo(px + 5, py - 5); c.lineTo(px - 5, py + 5);
} else {
c.arc(px, py, sel ? 7 : 5, 0, 2 * Math.PI);
}
c.stroke();
if (!labels) continue;
// its number, beside the ring
c.fillStyle = orbitColor(t.hue, true);
c.font = `${sel ? 600 : 400} 12px "Hanken Grotesk", system-ui, sans-serif`;
c.textAlign = 'left';
c.textBaseline = 'bottom';
c.fillText(trackName(t), px + 7, py - 5);
}
}
// The phase space within plot rect r, on context c (set up so r is in CSS
// px): the dots (and those fading out), then `under` (the axes, on screen),
// the start rings (numbered if `labels`) and the playheads.
function drawScene(c, r, { labels, under }) {
const dpr = devicePixelRatio || 1;
c.save();
c.beginPath();
c.rect(r.x, r.y, r.w, r.h);
c.clip();
c.fillStyle = theme.bg;
c.fillRect(r.x, r.y, r.w, r.h);
const w = canvas.width / dpr;
const h = canvas.height / dpr;
const a = ghostAlpha();
if (a > 0) {
c.globalAlpha = a;
c.drawImage(ghost, 0, 0, w, h);
c.globalAlpha = 1;
}
c.drawImage(dots, 0, 0, w, h);
c.drawImage(top, 0, 0, w, h);
c.restore();
under?.();
drawStarts(c, r, labels);
for (const t of tracks) drawPlayhead(c, r, t);
}
function frame() {
requestAnimationFrame(frame);
if (!canvas.width || !canvas.height) return;
if (dirty) {
dirty = false;
reset();
}
syncCoupling();
fill();
schedule();
for (const t of tracks) {
const esc = !!t.orbit?.s.escaped;
if (esc !== t.escaped) { t.escaped = esc; updateTrack(t); }
}
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.setTransform(dpr, 0, 0, dpr, 0, 0);
drawScene(ctx, r, { labels: true, under: () => drawAxes(r) });
if (recording) drawRecordingFrame(r);
}
// ---- instruments ---------------------------------------------------------------
// a track's instrument: 'b' (VOICES[i]) or 's:' (preset i of the
// loaded SoundFont with that id)
const isSoundFont = (t) => t.instrument[0] === 's';
const sfId = (font, preset) => `s${font.id}:${preset}`;
// a SoundFont instrument's { font, preset }, or null
function fontPreset(id) {
const m = /^s(\d+):(\d+)$/.exec(id);
const font = m && soundfonts.find((f) => f.id === Number(m[1]));
return font && Number(m[2]) < font.sf.presets.length ? { font, preset: Number(m[2]) } : null;
}
function voiceOf(t) {
if (!isSoundFont(t)) return Number(t.instrument.slice(1));
const { font, preset } = fontPreset(t.instrument);
if (!font.insts.has(preset)) font.insts.set(preset, makeInstrument(font.sf, preset));
return font.insts.get(preset);
}
function instrumentName(t) {
if (!isSoundFont(t)) return VOICES[Number(t.instrument.slice(1))].name;
const { font, preset } = fontPreset(t.instrument);
return font.sf.presets[preset].name;
}
// the first built-in voice no track is playing
function freeInstrument() {
const i = VOICES.findIndex((_, k) => !tracks.some((t) => t.instrument === `b${k}`));
return `b${i < 0 ? 0 : i}`;
}
// ---- the tracks panel ------------------------------------------------------------
const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
const svg = (body, attrs = '') => ``;
const STROKE = 'fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"';
const ICONS = {
play: svg(''),
pause: svg(''),
restart: svg('', STROKE),
remove: svg('', STROKE),
link: svg('', STROKE),
unlink: svg('', STROKE),
soundOn: svg('', 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"'),
keyboard: svg('', STROKE),
soundOff: svg('', 'fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"'),
};
function scaleText(t) {
if (isCustom(t)) {
const c = val(t, 'notes');
if (!c.notes.length) return 'no notes yet';
const n = c.every ? new Set(c.notes.map(pc)).size : c.notes.length;
return c.every ? `custom, ${n} per octave` : `${n} custom note${n === 1 ? '' : 's'}`;
}
const s = SCALES[val(t, 'scale')];
return `${KEYS[val(t, 'key')]} ${SCALE_SHORT[s.name] ?? s.name}`;
}
// a track's range, for its summary, if not the usual: C2–C4, or (exact
// custom notes) +1 oct
function rangeText(t) {
const o = val(t, 'octave');
const span = val(t, 'span');
if (exact(t)) return o ? ` ${octaveLabel(o)} oct` : '';
return o || span !== OCTAVES ? ` ${cName(o)}–${cName(o + span)}` : '';
}
function summary(t) {
if (!t.start) return 'No start yet: click the plot';
const r = RHYTHMS.find((q) => q.value === val(t, 'rhythm'));
const parts = [`${scaleText(t)}${rangeText(t)}`, rateLabel(t), r.short];
if (val(t, 'mono')) parts.push('mono');
if (t.escaped) parts.push('escaped');
return parts.join(' · ');
}
const fmtNum = (v) => (v < 0 ? '−' : '') + Math.abs(v);
const coordsText = (t) => (t.start
? `x = ${fmtNum(+t.start.x.toFixed(3))}, ẋ = ${fmtNum(Math.round(t.start.v))} s⁻¹`
: 'click the plot to place it');
function linkButton(t, p) {
const on = t.linked[p];
const title = on ? 'Linked: shared with the other linked tracks. Click to unlink.' : 'This track\'s own. Click to link it with the other tracks.';
return ``;
}
function rangeRow(t, p, disabled = false) {
const R = RANGES[p];
const v = val(t, p);
return `
${linkButton(t, p)}${R.label}
`;
}
// the tempo multiple: a menu of the usual ones, or a custom value typed in
function rateRow(t) {
const v = String(val(t, 'rate'));
const custom = !RATES.includes(v) || t.customRate;
const opts = RATES.map((r) => ``).join('');
return `
${linkButton(t, 'rate')}Tempo
${custom ? `` : ''}
`;
}
function instrumentOptions(t) {
const opt = (value, name) => ``;
let html = ``;
for (const f of soundfonts) {
const ps = f.sf.presets;
html += ``;
}
return html;
}
// the custom notes' editor: a piano (the notes as they sound, in the track's
// key; click a key, or press it on a MIDI keyboard, to add or remove it)
const BLACK = [1, 3, 6, 8, 10];
function notesEditor(t) {
const c = val(t, 'notes');
const sounding = soundingNotes(t);
const on = new Set(sounding);
const pcs = c.every ? new Set(sounding.map(pc)) : null;
// the range (every octave: the scale's, C3 to C6 shifted by the octave, or
// wider or narrower; else C3 to B5 shifted),
// widened by octaves to take in every note
const o = 12 * val(t, 'octave');
let lo = 48 + o;
let hi = (c.every ? 12 * val(t, 'span') : 35) + 48 + o;
if (sounding.length) {
lo = Math.min(lo, 12 * Math.floor(sounding[0] / 12));
hi = Math.max(hi, 12 * Math.ceil((sounding[sounding.length - 1] + 1) / 12) - 1);
}
const whites = [];
const blacks = [];
for (let m = lo; m <= hi; m++) (BLACK.includes(m % 12) ? blacks : whites).push({ m, at: whites.length });
const w = whites.length;
const key = ({ m, at }, black) => {
const lit = on.has(m);
const echo = !lit && pcs?.has(m % 12);
const cls = `${black ? 'bk' : 'wk'}${lit ? ' on' : ''}${echo ? ' echo' : ''}${midi.down.has(m) ? ' down' : ''}`;
return ``;
};
const listening = midi.listening && t === selected;
const names = c.every
? [...new Set(sounding.map(pc))].sort((a, b) => a - b).map((k) => KEYS[k]).join(' ')
: sounding.map(noteName).join(' ');
let status;
if (midi.error) status = `${midi.error}`;
else if (listening) {
status = midi.inputs.length
? `Listening to ${escapeHtml(midi.inputs.join(', '))}: hold down the notes you want, together or one after another without letting go (or with the sustain pedal down). Once you let go of everything, the next key starts a new set.`
: 'No MIDI keyboard found: plug one in (it is picked up when you do).';
} else status = 'Click keys to add or remove notes, or use a MIDI keyboard.';
return `
${names ? `${names}` : 'No notes yet: the track is silent.'} ${status}
`;
}
// redraw the selected track's notes editor (if it is open)
function refreshNotesEditor() {
const el = selected && trackEl(selected)?.querySelector('.notes-editor');
if (el) el.outerHTML = notesEditor(selected);
}
// add or remove sounding note m from a track's custom notes (every octave:
// its pitch class); true if added
function toggleNote(t, m) {
let c = val(t, 'notes');
if (!c.notes.length) c = { ...c, ref: val(t, 'key') };
const n = m - shiftOf(c, val(t, 'key')) - 12 * val(t, 'octave');
const has = c.every ? c.notes.some((q) => pc(q) === pc(n)) : c.notes.includes(n);
const notes = has
? c.notes.filter((q) => (c.every ? pc(q) !== pc(n) : q !== n))
: [...c.notes, n].sort((a, b) => a - b);
setValue(t, 'notes', { ...c, notes });
tracks.forEach(updateTrack);
return !has;
}
// sound a note on a track's instrument now (to hear a key clicked)
function previewNote(t, m, vel = 100) {
if (!soundOn || !synth) return;
synth.play(t.id, voiceOf(t), midiHz(m), synth.ctx.currentTime + 0.01, { pan: 0, gain: 0.8, sustain: Math.min(1.5, val(t, 'sustain')), vel });
}
// ---- the MIDI keyboard -------------------------------------------------------------
// access: once granted; listening: its keys go to the selected track's
// custom notes; inputs: the devices' names; down: the keys held
// (held: a set of notes is being played: a key has gone down since all were
// up, and some key, or the sustain pedal, is still down)
const midi = { access: null, listening: false, inputs: [], error: '', down: new Set(), pedal: false, held: false };
// open MIDI (once): '' if open, or why not
async function openMidiOnce() {
if (midi.access) return '';
if (!midiSupported()) return 'This browser has no Web MIDI (Chrome, Edge and Firefox do).';
try {
midi.access = await openMidi({
onNote: midiNote,
onPedal: (down) => {
midi.pedal = down;
if (!down && !midi.down.size) midi.held = false;
},
onControl: midiControl,
onInputs: (names) => { midi.inputs = names; refreshNotesEditor(); renderKnobs(); },
});
return '';
} catch {
return 'MIDI access was blocked: allow it for this page in the browser\'s site settings.';
}
}
async function setListening(on) {
midi.error = '';
midi.listening = false;
if (on) {
const err = await openMidiOnce();
if (err) midi.error = midiSupported() ? err : `${err} You can still click the keys.`;
else midi.listening = true;
}
refreshNotesEditor();
}
// ---- MIDI knobs ------------------------------------------------------------------
// The sliders a knob (a MIDI controller's control change) can be assigned
// to: the equation's and the coupling. knobs: { [slider id]: { ch, cc,
// mode } }; learning: the slider waiting for a knob to be turned.
//
// mode: how the knob sends its turns. 'abs': its position, 0 to 127 (only
// when it changes); or relative, as endless encoders (the MiniLab's
// clickable browse knobs, say) send them: each message a step left or right,
// as 64 ± n ('rel64'), 16 ± n ('rel16') or n in two's complement ('rel2c').
// Told apart by repeats: a relative knob turned steadily sends the same
// value again and again, which an absolute one never does.
const KNOB_TARGETS = () => [...SLIDERS.map((sl) => `s-${sl.name}`), 'coupling'];
let knobs = {};
let knobsShown = false;
let learning = null;
let knobError = '';
let candidate = null; // while learning: { ch, cc, values, timer }, the knob being turned
const lastValue = new Map(); // the last value of each control ('ch:cc')
const flashTimers = new Map();
const MODES = ['abs', 'rel64', 'rel16', 'rel2c'];
const isRelative = (k) => k.mode !== 'abs' && k.mode !== 'auto';
// the relative mode values (repeats seen) suggest
function relativeMode(values) {
if (values.every((v) => v >= 48 && v <= 80)) return 'rel64';
if (values.every((v) => v >= 8 && v <= 24)) return 'rel16';
return 'rel2c';
}
// a relative knob's message: the steps it turned (negative: to the left)
function relativeSteps(mode, v) {
if (mode === 'rel64') return v - 64;
if (mode === 'rel16') return v - 16;
return v < 64 ? v : v - 128;
}
function readKnobs(o) {
const r = {};
for (const id of KNOB_TARGETS()) {
const k = o?.[id];
if (k && Number.isInteger(k.ch) && k.ch >= 0 && k.ch < 16 && Number.isInteger(k.cc) && k.cc >= 0 && k.cc < 128) {
// (assigned before modes: 'auto', told by its next two values)
r[id] = { ch: k.ch, cc: k.cc, mode: MODES.includes(k.mode) ? k.mode : 'auto' };
}
}
return r;
}
const knobLabel = (k) => `CC${k.cc}${k.ch ? `/${k.ch + 1}` : ''}${isRelative(k) ? ' ↻' : ''}`;
function renderKnobs() {
$('knobs').setAttribute('aria-pressed', knobsShown);
document.querySelector('.eqn-panel').classList.toggle('knobs-on', knobsShown);
for (const id of KNOB_TARGETS()) {
const row = $(id).closest('.row');
let chip = row.querySelector('.knob');
if (!chip) {
chip = document.createElement('button');
chip.className = 'knob';
chip.dataset.knob = id;
chip.type = 'button';
row.append(chip);
}
const k = knobs[id];
const name = row.querySelector('span').textContent;
chip.classList.toggle('learning', learning === id);
chip.classList.toggle('set', !!k);
chip.textContent = learning === id ? 'turn…' : k ? knobLabel(k) : '+';
chip.title = learning === id ? 'Turn a knob to assign it (click to cancel)'
: k ? `${knobLabel(k)} (${isRelative(k) ? 'relative' : 'absolute'}) controls ${name}: click to change or unassign it`
: `Assign a knob to ${name}`;
}
const msg = $('knob-msg');
msg.hidden = !knobsShown;
msg.classList.toggle('error', !!knobError);
const none = midi.access && !midi.inputs.length ? ' No MIDI device found: plug one in.' : '';
if (knobError) msg.textContent = knobError;
else if (learning) {
const k = knobs[learning];
const kind = k ? ` Its ${knobLabel(k)} is ${isRelative(k) ? 'relative (endless)' : 'absolute (0 to 127)'}: · ` : '';
msg.innerHTML = `Turn a knob on your controller to assign it.${none}${kind}`;
} else msg.textContent = `Click a slider's + (or its knob's label), then turn a knob to assign it.${none}`;
}
async function learnKnob(id) {
knobError = '';
if (candidate) clearTimeout(candidate.timer);
candidate = null;
learning = learning === id ? null : id;
if (learning) knobError = await openMidiOnce();
if (knobError) learning = null;
renderKnobs();
}
// the knob turned while learning: assigned once it has sent a few values
// (or paused), as relative if any repeated
function assignCandidate() {
const { ch, cc, values, timer } = candidate;
clearTimeout(timer);
candidate = null;
if (!learning) return;
for (const [id, k] of Object.entries(knobs)) if (k.ch === ch && k.cc === cc) delete knobs[id];
const repeats = values.some((v, i) => i && v === values[i - 1]);
knobs[learning] = { ch, cc, mode: repeats ? relativeMode(values) : 'abs' };
learning = null;
saveKnobs(knobs);
renderKnobs();
}
// a knob turned (or another control change)
function midiControl(ch, cc, value) {
const key = `${ch}:${cc}`;
const seen = lastValue.has(key);
const repeat = lastValue.get(key) === value;
lastValue.set(key, value);
if (learning) {
if (candidate && (candidate.ch !== ch || candidate.cc !== cc)) return;
candidate ??= { ch, cc, values: [], timer: setTimeout(assignCandidate, 400) };
candidate.values.push(value);
if (candidate.values.length >= 5) assignCandidate();
return;
}
for (const [id, k] of Object.entries(knobs)) {
if (k.ch !== ch || k.cc !== cc) continue;
// an absolute knob repeating itself is a relative one after all
if (repeat && !isRelative(k)) {
k.mode = relativeMode([value]);
saveKnobs(knobs);
renderKnobs();
} else if (k.mode === 'auto') {
// (not known yet: wait for a second value)
if (!seen) continue;
k.mode = 'abs';
saveKnobs(knobs);
}
const input = $(id);
const lo = Number(input.min);
const hi = Number(input.max);
// absolute: the slider's range, 0 to 127; relative: steps of a 256th of
// it (at least the slider's step), more as the knob turns faster;
// snapped to the slider's step by the input
const v = isRelative(k)
? Number(input.value) + relativeSteps(k.mode, value) * Math.max(Number(input.step) || 0, (hi - lo) / 256)
: lo + ((hi - lo) * value) / 127;
const before = input.value;
input.value = v;
if (input.value === before) continue;
input.dispatchEvent(new Event('input', { bubbles: true }));
// (the row lights up a moment)
const row = input.closest('.row');
row.classList.add('turned');
clearTimeout(flashTimers.get(id));
flashTimers.set(id, setTimeout(() => row.classList.remove('turned'), 250));
}
}
function buildKnobControls() {
knobs = readKnobs(loadKnobs());
$('knobs').addEventListener('click', () => {
knobsShown = !knobsShown;
if (!knobsShown) learning = null;
knobError = '';
renderKnobs();
});
document.querySelector('.eqn-panel').addEventListener('click', (e) => {
if (e.target.closest('[data-mode]') && learning && knobs[learning]) {
const k = knobs[learning];
k.mode = isRelative(k) ? 'abs' : relativeMode([lastValue.get(`${k.ch}:${k.cc}`) ?? 64]);
saveKnobs(knobs);
renderKnobs();
return;
}
if (e.target.closest('[data-unassign]') && learning) {
delete knobs[learning];
learning = null;
saveKnobs(knobs);
renderKnobs();
return;
}
const chip = e.target.closest('.knob');
if (!chip) return;
e.preventDefault();
learnKnob(chip.dataset.knob);
});
renderKnobs();
// knobs assigned before: listen for them (MIDI access, if granted before,
// is given without asking)
if (Object.keys(knobs).length && midiSupported()) openMidiOnce();
}
// A key pressed on the MIDI keyboard: the keys pressed together (from the
// first one down until all are up, and the sustain pedal too) become the
// notes; the next press after that starts afresh.
function midiNote(m, on) {
const fresh = on && !midi.held;
if (on) {
midi.down.add(m);
midi.held = true;
} else {
midi.down.delete(m);
if (!midi.down.size && !midi.pedal) midi.held = false;
}
const t = selected;
// (not sounded: the keyboard makes its own sound, if any)
if (midi.listening && t && isCustom(t) && on) addNote(t, m, fresh);
refreshNotesEditor();
}
// add sounding note m to a track's custom notes, or (fresh) make it the only one
function addNote(t, m, fresh) {
let c = val(t, 'notes');
if (fresh || !c.notes.length) c = { ...c, notes: [], ref: val(t, 'key') };
const n = m - shiftOf(c, val(t, 'key')) - 12 * val(t, 'octave');
if (!c.notes.includes(n)) setValue(t, 'notes', { ...c, notes: [...c.notes, n].sort((a, b) => a - b) });
else setValue(t, 'notes', c);
tracks.forEach(updateTrack);
}
function trackBody(t) {
const sf = isSoundFont(t);
const lk = (p) => (t.linked[p] ? ' linked' : '');
const opt = (value, text, on) => ``;
const ex = exact(t);
return `