// Composition 3: divergence — drawing at the playhead: all the pendulums from one pivot, with the // bottom bobs' fading trails. import type { Params } from "../../core/params.ts"; import type { View } from "../../stream/piece.ts"; import { cssColor, fitCanvas } from "../shared/section.ts"; import { releaseAngles } from "./score.ts"; const FRAME_DT = 1 / 120; export function divergenceView(el: HTMLElement, params: () => Params): View { el.classList.add("c03"); const canvas = document.createElement("canvas"); el.append(canvas); let row = new Float64Array(0); const colorOf = (P: Params, i: number, n: number) => `hsl(${((30 + (360 * i) / Math.max(1, n)) % 360).toFixed(0)} ${P.saturation}% 70%)`; return { keep: (P) => (P.trailLength as number) + 0.5, draw(t, store) { const P = params(); const g = fitCanvas(canvas); const w = canvas.clientWidth, h = canvas.clientHeight; g.clearRect(0, 0, w, h); const n = Math.max(1, Math.round(P.count as number)); const l1 = 1, l2 = P.lengthRatio as number; const scale = (0.46 * Math.min(w, h)) / (l1 + l2); const x0 = w / 2, y0 = h / 2; const px = (th1: number, th2: number): [number, number, number, number] => { const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1); return [x1, y1, x1 + scale * l2 * Math.sin(th2), y1 + scale * l2 * Math.cos(th2)]; }; // trails: the bottom bobs' recent paths, fading with age (drawn in a few alpha bands) if (P.trails && store) { const len = P.trailLength as number; const BANDS = 6; g.lineWidth = P.trailWidth as number; g.lineJoin = g.lineCap = "round"; for (let i = 0; i < n; i++) { g.strokeStyle = colorOf(P, i, n); for (let band = 0; band < BANDS; band++) { const aNew = t - (band * len) / BANDS, aOld = t - ((band + 1) * len) / BANDS; g.globalAlpha = 0.7 * (1 - (band + 0.5) / BANDS); g.beginPath(); let started = false; store.rows(0, aOld - FRAME_DT, Math.min(t, aNew + FRAME_DT), (d, o) => { const [, , bx, by] = px(d[o + 1 + 2 * i], d[o + 2 + 2 * i]); if (started) g.lineTo(bx, by); else g.moveTo(bx, by), (started = true); }); g.stroke(); } } g.globalAlpha = 1; } // pendulums, all from the one pivot (before the first play: at the nominal release) if (row.length !== 2 * n) row = new Float64Array(2 * n); const s = store?.at(0, t, row) ?? null; const [a1, a2] = releaseAngles(P, null); g.lineWidth = 1.5; g.lineCap = "round"; const r = P.bobSize as number; for (let i = n - 1; i >= 0; i--) { const [x1, y1, x2, y2] = s ? px(s[2 * i], s[2 * i + 1]) : px(a1, a2); const col = colorOf(P, i, n); g.strokeStyle = col; g.fillStyle = col; g.globalAlpha = P.armAlpha as number; g.beginPath(); g.moveTo(x0, y0); g.lineTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.globalAlpha = 1; g.beginPath(); g.arc(x1, y1, r * 0.8, 0, 2 * Math.PI); g.moveTo(x2 + r, y2); g.arc(x2, y2, r, 0, 2 * Math.PI); g.fill(); } g.fillStyle = cssColor(el, "--fg"); g.beginPath(); g.arc(x0, y0, 1.5, 0, 2 * Math.PI); g.fill(); }, dispose() { el.classList.remove("c03"); }, }; }