// Ensemble lab: six audio-rate pendulums; a steady tempo pushes energy into pendulums 1…k. // Keys 0–6 set k; R resets them all to rest. Not part of the album; reachable at #/ensemble. 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 { cssColor, fitCanvas } from "../shared/section.ts"; const loaded = new WeakMap>(); 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 lastBeat = -1; const flash = new Array(ENSEMBLE).fill(0); // wall time of each pendulum's last pulse const settings = (P: Params): EnsembleSettings => ({ voices: Array.from({ length: ENSEMBLE }, (_, i) => ({ pitch: P[`pitch${i + 1}`] as number, massRatio: P[`mass${i + 1}`] as number, lengthRatio: P[`length${i + 1}`] as number, ringTime: P[`ring${i + 1}`] as number, level: dbToGain(P[`level${i + 1}`] as number), })), tempo: P.tempo as number, pulseAdds: P.pulseAdds as number, active: Math.round(P.active as number), build: Math.round(P.build as number), signal: P.signal as Signal, gain: dbToGain(P.gain as number), dcCut: P.dcCut as number, spread: P.spread 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 (/^[0-6]$/.test(e.key)) send({ type: "active", k: Number(e.key) }); 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) }); } out.gain.setTargetAtTime(dbToGain(P.level as number), audio.ctx.currentTime, 0.05); } 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; out = ctx.createGain(); out.gain.value = 0; node = new AudioWorkletNode(ctx, "pendulum-ensemble", { numberOfInputs: 0, outputChannelCount: [2] }); node.port.onmessage = (e: MessageEvent) => { const s = e.data; if (s.beat !== lastBeat) { lastBeat = s.beat; const now = performance.now() - s.sinceBeat * 1000; for (let i = 0; i < s.active; i++) flash[i] = now; } snap = s; }; 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; } 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"), dim = cssColor(view, "--dim"), muted = cssColor(view, "--muted"); const cols = 3, rows = 2, cw = w / cols, ch = h / rows; const TR = snap ? snap.trails.length / (2 * ENSEMBLE) : 0; const now = performance.now(); for (let i = 0; i < ENSEMBLE; i++) { const cx = (i % cols) * cw + cw / 2, cy = Math.floor(i / cols) * ch + ch / 2; const active = snap ? i < snap.active : false; const L = 1 + (P[`length${i + 1}`] as number); const sc = (0.4 * Math.min(cw, ch)) / L; // pulse flash: a ring that fades const age = (now - flash[i]) / 1000; if (age < 0.35) { g.strokeStyle = fg; g.globalAlpha = 0.5 * (1 - age / 0.35); g.beginPath(); g.arc(cx, cy, 0.42 * Math.min(cw, ch), 0, 2 * Math.PI); g.stroke(); } g.globalAlpha = 1; if (snap) { const o = i * 2 * TR; g.strokeStyle = active ? fg : muted; g.globalAlpha = active ? 0.9 : 0.35; g.lineWidth = 1; g.beginPath(); for (let j = 0; j < TR; j++) { const x = cx + sc * snap.trails[o + 2 * j], y = cy + sc * snap.trails[o + 2 * j + 1]; if (j) g.lineTo(x, y); else g.moveTo(x, y); } g.stroke(); g.globalAlpha = 1; } g.fillStyle = active ? fg : dim; g.font = "11px ui-monospace, monospace"; g.fillText(`${i + 1} · ${Math.round(P[`pitch${i + 1}`] as number)} Hz${snap ? ` · E ${snap.energy[i].toFixed(2)}` : ""}`, (i % cols) * cw + 6, Math.floor(i / cols) * ch + 14); } if (!playing) { g.fillStyle = muted; g.font = "12px ui-monospace, monospace"; g.fillText("play; keys 0–6 choose how many get the pulse; R resets", 6, h - 8); } } function readouts(): Record { return { active: snap ? `${snap.active} of ${ENSEMBLE}` : "–", beat: snap ? String(snap.beat) : "–", energies: snap ? snap.energy.map((e) => e.toFixed(2)).join(" ") : "–", keys: "0–6: how many get the pulse · R: reset to rest", }; } return { get playing() { return playing; }, start: (a) => start(a), stop, draw, now: () => (playing && audio ? audio.ctx.currentTime - startedAt : 0), length: () => Infinity, readouts, dispose() { stop(); window.removeEventListener("keydown", onKey); view.replaceChildren(); }, }; }