// Ensemble lab: six audio-rate pendulums sharing one time scale, so each one's pitch comes from its // size; their proportions are solved from musical ratios (see harmony.ts). A score pushes them in // chords (e.g. "36 25 … 1!4"); keys 1–6 also push that pendulum, R resets them all to rest. import { dbToGain, type AudioEngine } from "../../core/audio.ts"; import type { Piece } from "../../core/composition.ts"; import type { Params } from "../../core/params.ts"; import workletUrl from "../../lab/ensembleWorklet.ts?worker&url"; import { ENSEMBLE, type EnsembleMsg, type EnsembleSettings, type EnsembleSnap, type Signal } from "../../lab/protocol.ts"; import { randomSeed } from "../../core/rng.ts"; import { cssColor, fitCanvas } from "../shared/section.ts"; import { build, parseRatio, timeScale, type Built } from "./harmony.ts"; const loaded = new WeakMap>(); const START_DELAY = 0.4; // s before the first step /** "36 25 1!4": one step per word, the pendulums pushed together; ! accents the digit before it. */ export function parseScore(text: string, add: number, accent: number): { i: number; add: number }[][] { return text .trim() .split(/\s+/) .filter(Boolean) .map((w) => { const step: { i: number; add: number }[] = []; for (let c = 0; c < w.length; c++) { if (!/[1-6]/.test(w[c])) continue; const loud = w[c + 1] === "!"; step.push({ i: Number(w[c]) - 1, add: add * (loud ? accent : 1) }); } return step; }); } export function createEnsemblePiece(view: HTMLElement, params: () => Params): Piece { const canvas = document.createElement("canvas"); view.append(canvas); let audio: AudioEngine | null = null; let node: AudioWorkletNode | null = null; let out: GainNode | null = null; let timer: number | undefined; let playing = false; let startedAt = 0; let snap: EnsembleSnap | null = null; let lastSent = ""; let token = 0; let ended = false; let seedUsed = 0; /** Physics for every pendulum from the musical ratios: one time scale, sizes and masses solved. */ function physics(P: Params): { k: number; built: Built[] } { const base = P.basePitch as number; const v = Array.from({ length: ENSEMBLE }, (_, i) => ({ ratio: parseRatio(P[`ratio${i + 1}`] as string), partial: parseRatio(P[`partial${i + 1}`] as string), shape: P[`shape${i + 1}`] as number, })); // the lowest-pitched pendulum is the biggest: give it l1 = 1 const low = v.reduce((a, b) => (b.ratio < a.ratio ? b : a)); const k = timeScale(base, low.ratio, low.partial, low.shape); return { k, built: v.map((x) => build(base, x.ratio, x.partial, x.shape, k)) }; } const settings = (P: Params): EnsembleSettings => { const { k, built } = physics(P); return { voices: built.map((b, i) => ({ l1: b.l1, l2: b.l2, m2: b.m2, upperHz: b.upper, ringTime: P[`ring${i + 1}`] as number, level: dbToGain(P[`level${i + 1}`] as number), })), k, pulseAdds: P.pulseAdds as number, score: parseScore(P.score as string, P.pulseAdds as number, P.accent as number), stepSec: stepSec(P), startDelay: START_DELAY, seed: seedUsed, signal: P.signal as Signal, gain: dbToGain(P.gain as number), dcCut: P.dcCut as number, spread: P.spread as number, }; }; const stepSec = (P: Params) => ((P.stepBeats as number) * 60) / Math.max(1, P.tempo as number); const scoreEnd = (P: Params) => START_DELAY + parseScore(P.score as string, 0, 1).length * stepSec(P); const total = (P: Params) => scoreEnd(P) + (P.tail as number); const send = (m: EnsembleMsg) => node?.port.postMessage(m); const onKey = (e: KeyboardEvent) => { const el = e.target; if (el instanceof Element && el.closest("input, select, textarea")) return; if (/^[1-6]$/.test(e.key)) send({ type: "strike", i: Number(e.key) - 1 }); else if (e.key === "r" || e.key === "R") send({ type: "reset" }); }; window.addEventListener("keydown", onKey); function sync() { if (!node || !audio || !out) return; const P = params(); const key = JSON.stringify(settings(P)); if (key !== lastSent) { lastSent = key; send({ type: "settings", s: settings(P) }); } // the end: fade over the last `fade` s of the ring-out, then stop const t = audio.ctx.currentTime - startedAt, T = total(P); const fade = Math.min(P.fade as number, P.tail as number); const k = Math.max(0, Math.min(1, (T - t) / fade)); out.gain.setTargetAtTime(dbToGain(P.level as number) * k * k, audio.ctx.currentTime, 0.05); if (t >= T && !ended) { ended = true; stop(); piece.onEnded?.(); } } async function start(a: AudioEngine) { stop(); const my = ++token; audio = a; const ctx = a.ctx; let p = loaded.get(ctx); if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(workletUrl))); await p; if (my !== token) return; ended = false; snap = null; const P0 = params(); seedUsed = (P0.seed as number) > 0 ? Math.round(P0.seed as number) : randomSeed(); out = ctx.createGain(); out.gain.value = 0; node = new AudioWorkletNode(ctx, "pendulum-ensemble", { numberOfInputs: 0, outputChannelCount: [2] }); node.port.onmessage = (e: MessageEvent) => (snap = e.data); node.connect(out).connect(a.input); lastSent = ""; sync(); playing = true; startedAt = ctx.currentTime; timer = window.setInterval(sync, 50); } function stop() { token++; if (timer !== undefined) window.clearInterval(timer); timer = undefined; playing = false; if (!audio) return; const o = out, n = node; if (o) o.gain.setTargetAtTime(0, audio.ctx.currentTime, 0.03); window.setTimeout(() => { n?.disconnect(); o?.disconnect(); }, 300); node = out = null; } // Layout: the pendulums hang from one line, left to right as listed, each given room in proportion // to its size (most of its sideways reach: big swings may overlap a neighbour). function layout(dr: number[], w: number, h: number) { const ROOM = 1.5, GAP = 0.2; // drawn reaches of room per pendulum, and between pendulums const fit = (rows: number[][]) => { const rh = h / rows.length; let unit = Infinity; for (const r of rows) { const span = r.reduce((a, i) => a + ROOM * dr[i], 0) + GAP * (r.length - 1); unit = Math.min(unit, (0.92 * w) / span, (0.5 * rh) / Math.max(...r.map((i) => dr[i]))); } return { rows, rh, unit }; }; const { rows, rh, unit } = fit([[0, 1, 2, 3, 4, 5]]); const at: { x: number; y: number }[] = []; rows.forEach((r, ri) => { const span = (r.reduce((a, i) => a + ROOM * dr[i], 0) + GAP * (r.length - 1)) * unit; // hang the row so its resting pendulums sit centred in the row const y = ri * rh + rh / 2 - (Math.max(...r.map((i) => dr[i])) * unit) / 2; let x = (w - span) / 2; for (const i of r) { at[i] = { x: x + (ROOM / 2) * dr[i] * unit, y }; x += (ROOM * dr[i] + GAP) * unit; } }); return { unit, at }; } function draw() { const P = params(); const g = fitCanvas(canvas); const w = canvas.clientWidth, h = canvas.clientHeight; g.clearRect(0, 0, w, h); const fg = cssColor(view, "--fg"), muted = cssColor(view, "--muted"); const { built } = physics(P); // compared sizes: length^sizeExp (true scale would make the highest a speck) const ex = P.sizeExp as number; const reach = built.map((b) => b.l1 + b.l2); const dr = reach.map((r) => Math.pow(r, ex)); const { unit, at } = layout(dr, w, h); const TR = snap ? snap.trails.length / (2 * ENSEMBLE) : 0; const trailA = P.trail as number; g.lineCap = "round"; g.lineJoin = "round"; for (let i = 0; i < ENSEMBLE; i++) { const { x: cx, y: cy } = at[i]; const f = (unit * dr[i]) / reach[i]; // physical units → px for this pendulum if (snap && trailA > 0) { const o = i * 2 * TR; g.strokeStyle = muted; g.globalAlpha = trailA; g.lineWidth = 1; g.beginPath(); for (let j = 0; j < TR; j++) { const x = cx + f * snap.trails[o + 2 * j], y = cy + f * snap.trails[o + 2 * j + 1]; if (j) g.lineTo(x, y); else g.moveTo(x, y); } g.stroke(); } const jt = snap ? snap.joints.subarray(4 * i, 4 * i + 4) : [0, built[i].l1, 0, reach[i]]; const x1 = cx + f * jt[0], y1 = cy + f * jt[1], x2 = cx + f * jt[2], y2 = cy + f * jt[3]; // a push brightens the pendulum, fading over a second const age = snap ? snap.struck[i] : 1e9; g.globalAlpha = 0.6 + 0.4 * Math.max(0, 1 - age); g.strokeStyle = fg; g.fillStyle = fg; g.lineWidth = 1.5; g.beginPath(); g.moveTo(cx, cy); g.lineTo(x1, y1); g.lineTo(x2, y2); g.stroke(); const r2 = 2.2 * Math.cbrt(built[i].m2) + 1; g.beginPath(); g.arc(x1, y1, 2, 0, 2 * Math.PI); g.moveTo(x2 + r2, y2); g.arc(x2, y2, r2, 0, 2 * Math.PI); g.moveTo(cx + 1.5, cy); g.arc(cx, cy, 1.5, 0, 2 * Math.PI); g.fill(); } g.globalAlpha = 1; } function readouts(): Record { const { k, built } = physics(params()); const r: Record = { keys: "1–6: push that pendulum · R: reset to rest", score: snap ? `step ${snap.step} of ${parseScore(params().score as string, 0, 1).length}` : "–", length: `${total(params()).toFixed(1)} s`, "seed used": seedUsed ? String(seedUsed) : "–", "time scale": `${k.toFixed(0)} sim s per s`, }; built.forEach((b, i) => { r[`pendulum ${i + 1}`] = `${b.lower.toFixed(1)} + ${b.upper.toFixed(1)} Hz; l1 ${b.l1.toFixed(3)}, l2 ${b.l2.toFixed(3)}, m2/m1 ${b.m2.toFixed(2)}${snap ? `; E ${snap.energy[i].toFixed(2)}` : ""}`; }); return r; } const piece: Piece = { get playing() { return playing; }, start: (a) => start(a), stop, draw, now: () => (playing && audio ? audio.ctx.currentTime - startedAt : ended ? total(params()) : 0), length: () => total(params()), readouts, dispose() { stop(); window.removeEventListener("keydown", onKey); view.replaceChildren(); }, }; return piece; }