// The background portrait of the section (grey), plus optional "tracks": the orbit each live // pendulum is on at the moment the portrait was computed, drawn in the pendulum's color. // Both are computed at frozen energy in a throttled worker (see orbitWorker.ts); when the energy // has moved enough, a new portrait starts and the old one crossfades out. import type { OrbitBatch, OrbitConfig, TrackSeed } from "./orbitWorker.ts"; import type { SectionFrame } from "./section.ts"; const LAYER_MS = 100; export interface PortraitSettings { show: boolean; count: number; cpu: number; life: number; band: number; minHold: number; maxPoints: number; xfade: number; alpha: number; size: number; /** trace each live pendulum's current orbit */ tracks: boolean; trackMax: number; trackAlpha: number; trackSize: number; } interface Portrait { gen: number; energy: number; pts: number[]; // [θ2, p2, …] tracks: Map; retiredAt: number | null; } export class PortraitLayer { private worker: Worker | null = null; private portraits: Portrait[] = []; private resetPending = false; private latestGen = 0; private ignoreBelow = 0; // batches from portraits started before the last reset private rate = 0; // points per second, for the readout private newPts = 0; private rateT = 0; private now: () => number; private live: () => boolean; /** now: piece time; live: whether the piece is playing (batches are ignored otherwise) */ constructor(now: () => number, live: () => boolean) { this.now = now; this.live = live; } /** New play or seek: drop what's shown; the worker starts a fresh portrait. */ reset() { this.dirty = true; this.portraits = []; this.ignoreBelow = this.latestGen + 1; this.resetPending = true; } private ensureWorker(): Worker { if (!this.worker) { this.worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" }); this.worker.onmessage = (ev: MessageEvent) => this.receive(ev.data); } return this.worker; } private receive({ gen, energy, pts, tracks }: OrbitBatch) { if (!this.live()) return; this.latestGen = Math.max(this.latestGen, gen); if (gen < this.ignoreBelow) return; let cur = this.portraits[this.portraits.length - 1]; if (!cur || gen > cur.gen) { const t = this.now(); for (const p of this.portraits) p.retiredAt ??= t; cur = { gen, energy, pts: [], tracks: new Map(), retiredAt: null }; this.portraits.push(cur); } else if (gen < cur.gen) return; // stale batch for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]); for (const tb of tracks) { let arr = cur.tracks.get(tb.id); if (!arr) cur.tracks.set(tb.id, (arr = [])); for (let i = 0; i < tb.pts.length; i++) arr.push(tb.pts[i]); } this.newPts += pts.length / 2 + tracks.reduce((s, tb) => s + tb.pts.length / 2, 0); this.dirty = true; } /** Send the current state; call every tick while playing (running=false pauses the worker). */ post(running: boolean, s: PortraitSettings, energy: number, m2: number, l2: number, tracks: TrackSeed[]) { if (!s.show && !s.tracks && !this.worker) return; const msg: OrbitConfig = { running: running && (s.show || s.tracks), reset: this.resetPending, energy, m2, l2, count: s.show ? Math.round(s.count) : 0, life: s.life, band: s.band, minHold: s.minHold, maxPoints: s.show ? s.maxPoints : 0, cpu: s.cpu, tracks: s.tracks ? tracks : [], trackMax: s.trackMax, }; this.resetPending = false; this.ensureWorker().postMessage(msg); } // The portrait and traces can be tens of thousands of points: they are drawn into an offscreen // layer, redrawn at most every LAYER_MS (when points arrive, a crossfade runs, or the zoom // moves), and copied onto the plot every frame. private layer: HTMLCanvasElement | null = null; private layerAt = 0; private layerKey = ""; private dirty = true; // the mapping the layer was drawn with: x = cx + kx·θ2, y = cy + ky·p2 private lm = { cx: 0, kx: 1, cy: 0, ky: 1 }; /** Draw the grey portrait and the colored tracks (call before drawing the live crossings). */ draw(f: SectionFrame, t: number, s: PortraitSettings, grey: string, trackColor: (id: number) => string) { const { g, w, h, sx, sy } = f; const before = this.portraits.length; this.portraits = this.portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < s.xfade); if (this.portraits.length !== before) this.dirty = true; const fading = this.portraits.some((p) => p.retiredAt !== null); const dpr = window.devicePixelRatio || 1; // appearance the layer was drawn with; the zoom is handled by stretching the cached layer, // which is redrawn only once the zoom has drifted noticeably const key = [w, h, dpr, s.show, s.tracks, s.alpha, s.size, s.trackAlpha, s.trackSize, grey].join("|"); const cur = { cx: sx(0), kx: sx(1) - sx(0), cy: sy(0), ky: sy(1) - sy(0) }; const rx = cur.kx / this.lm.kx, ry = cur.ky / this.lm.ky; const drift = Math.abs(Math.log(rx)) > 0.05 || Math.abs(Math.log(ry)) > 0.05; const now = performance.now(); if (!this.layer) this.layer = document.createElement("canvas"); const L = this.layer; if ((this.dirty || fading || drift || key !== this.layerKey) && now - this.layerAt >= LAYER_MS) { const pw = Math.round(w * dpr), ph = Math.round(h * dpr); if (L.width !== pw || L.height !== ph) { L.width = pw; L.height = ph; } const lg = L.getContext("2d")!; lg.setTransform(dpr, 0, 0, dpr, 0, 0); lg.clearRect(0, 0, w, h); for (const p of this.portraits) { const k = p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / s.xfade); if (s.show && p.pts.length) { const sz = s.size; lg.fillStyle = grey; lg.globalAlpha = s.alpha * k; lg.beginPath(); const d = p.pts; for (let i = 0; i < d.length; i += 2) lg.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz); lg.fill(); } if (s.tracks) { const sz = s.trackSize; for (const [id, d] of p.tracks) { lg.fillStyle = trackColor(id); lg.globalAlpha = s.trackAlpha * k; lg.beginPath(); for (let i = 0; i < d.length; i += 2) lg.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz); lg.fill(); } } } lg.globalAlpha = 1; this.layerAt = now; this.layerKey = key; this.lm = cur; this.dirty = false; } if (L.width) { // map the layer's coordinates onto the current zoom const ax = cur.kx / this.lm.kx, ay = cur.ky / this.lm.ky; g.save(); g.setTransform(dpr * ax, 0, 0, dpr * ay, dpr * (cur.cx - ax * this.lm.cx), dpr * (cur.cy - ay * this.lm.cy)); g.drawImage(L, 0, 0, w, h); g.restore(); } } describe(): string { const wall = performance.now() / 1000; if (wall - this.rateT > 1) { this.rate = this.newPts / (wall - this.rateT || 1); this.newPts = 0; this.rateT = wall; } const p = this.portraits.find((q) => q.retiredAt === null); if (!p) return "–"; const tr = [...p.tracks.values()].reduce((s, a) => s + a.length / 2, 0); return `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts${p.tracks.size ? ` + ${tr} traced` : ""}, ${Math.round(this.rate)}/s`; } dispose() { this.worker?.terminate(); this.worker = null; } }