// Mass on a frictionless spring. Positions are in units of the maximum // swing drawn on screen, so q lies in [-1, 1]. function color(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); } // Slides are laid out at 1920 x 1080 and the whole deck is scaled to fit the // window (see fitDeck below). Diagrams are drawn in units of DRAW_SCALE slide // pixels, so their geometry and fonts read well on a full-size slide. const DRAW_SCALE = 1.5; let deckScale = 1; // Size a canvas's backing store to its on-screen pixels (slide size x deck // scale x device pixel ratio) and return a context and size in drawing units. function prepare(canvas) { const ctx = canvas.getContext('2d'); const k = deckScale * (window.devicePixelRatio || 1); const bw = Math.max(1, Math.round(canvas.clientWidth * k)); const bh = Math.max(1, Math.round(canvas.clientHeight * k)); if (canvas.width !== bw || canvas.height !== bh) { canvas.width = bw; canvas.height = bh; } ctx.setTransform(k * DRAW_SCALE, 0, 0, k * DRAW_SCALE, 0, 0); const w = canvas.clientWidth / DRAW_SCALE; const h = canvas.clientHeight / DRAW_SCALE; ctx.clearRect(0, 0, w, h); return { ctx, w, h }; } // Horizontal layout shared by the spring diagram, the q0 slider and the phase plot, // so that a given q sits at the same x on all of them. function layout(w) { const rest = w * 0.5; const swing = Math.min(w * 0.3, 200); return { rest, swing, qToX: (q) => rest + q * swing }; } // Wall, floor and a spring reaching a block centered at position q. drawBody // draws whatever is attached (it gets the scene geometry), before the // rest-position marker goes on top. Returns the geometry for labels. function drawSpringScene(ctx, w, h, q, drawBody) { const fg = color('--fg'); const { rest, swing, qToX } = layout(w); const wallX = 20; const floorY = h * 0.62; const box = 50; const center = qToX(q); const springY = floorY - box / 2; // wall and floor ctx.strokeStyle = fg; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(wallX, floorY - box * 1.6); ctx.lineTo(wallX, floorY); ctx.lineTo(w - 10, floorY); ctx.stroke(); // spring (zig-zag) const coils = 12; const amp = 10; const start = wallX; const end = center - box / 2; const lead = 12; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(start, springY); ctx.lineTo(start + lead, springY); const len = end - start - 2 * lead; for (let i = 0; i < coils; i++) { const sx = start + lead + ((i + 0.5) / coils) * len; ctx.lineTo(sx, springY + (i % 2 ? amp : -amp)); } ctx.lineTo(end - lead, springY); ctx.lineTo(end, springY); ctx.stroke(); const scene = { rest, swing, qToX, floorY, box, springY, amp, start, end, center }; drawBody(scene); // rest position marker ctx.strokeStyle = fg; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(rest, floorY - box * 1.4); ctx.lineTo(rest, floorY + 34); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; return scene; } // params: { k, m, q0, b }, read live so sliders can change them; the damping // coefficient b is optional (default 0, no damping). // labels: which of 'm', 'k', 'q', 'F', 'p', 'q0' to draw. // pScale: length of the p arrow per unit momentum, as a fraction of the swing; // by default the arrow peaks at the same length as q. function createSpring({ canvas, button, params, labels = [], speed = 1, pScale, onDraw = () => {} }) { let q = params.q0; let p = 0; function step(dt) { // velocity Verlet on dq/dt = p/m, dp/dt = -k q. Damping, dp/dt = -(b/m) p, // is solved exactly and split around it (Strang splitting), so phase-space // area shrinks at exactly the rate exp(-b t / m). const { k, m, b = 0 } = params; const decay = Math.exp((-0.5 * b * dt) / m); p *= decay; const f = -k * q; q += (p / m) * dt + (0.5 * f / m) * dt * dt; p += 0.5 * (f - k * q) * dt; p *= decay; } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const { rest, swing, qToX, floorY, box, springY, amp, start, end, center } = drawSpringScene(ctx, w, h, q, (sc) => { ctx.fillStyle = color('--accent'); ctx.fillRect(sc.center - sc.box / 2, sc.floorY - sc.box, sc.box, sc.box); }); onDraw(q, p); if (!labels.length) return; ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); ctx.textBaseline = 'middle'; ctx.fillText('m', center, floorY - box / 2); } if (labels.includes('k')) { ctx.fillStyle = fg; ctx.textBaseline = 'bottom'; ctx.fillText('k', (start + end) / 2, springY - amp - 4); } if (labels.includes('q0')) { // where the block was let go from const x0 = qToX(params.q0); ctx.strokeStyle = fg; ctx.globalAlpha = 0.5; ctx.setLineDash([2, 3]); ctx.beginPath(); ctx.moveTo(x0, floorY - box - 48); ctx.lineTo(x0, floorY); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.fillStyle = fg; ctx.textBaseline = 'bottom'; // the serif font has no subscript zero, so draw it smaller and lower ctx.fillText('q', x0 - 4, floorY - box - 52); ctx.font = 'italic 12px Georgia, serif'; ctx.fillText('0', x0 + 5, floorY - box - 48); ctx.font = 'italic 18px Georgia, serif'; } // q below the floor; F and p above the block const { k, m } = params; const pLen = (pScale ?? 1 / Math.sqrt(k * m)) * swing; if (labels.includes('q')) arrow(ctx, rest, center, floorY + 22, fg, 'q', 'below'); if (labels.includes('F')) arrow(ctx, center, center - q * swing, floorY - box - 40, color('--force'), 'F', 'above'); if (labels.includes('p')) arrow(ctx, center, center + p * pLen, floorY - box - 14, color('--momentum'), 'p', 'above'); } function setLabels(value) { labels = value; draw(); } const loop = createLoop({ button, step, draw, speed }); // Back to being held at q0, at rest. function reset() { q = params.q0; p = 0; loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } // Animation driven by a Start / Stop / Continue button. speed is a number, or // a function read every frame so it can change while running. function createLoop({ button, step, draw, speed = 1 }) { let running = false; let lastTime = null; let rafId = null; function frame(t) { if (!running) return; if (lastTime !== null) { const dt = (typeof speed === 'function' ? speed() : speed) * Math.min((t - lastTime) / 1000, 0.05); const n = 4; for (let i = 0; i < n; i++) step(dt / n); } lastTime = t; draw(); rafId = requestAnimationFrame(frame); } function setRunning(value) { running = value; cancelAnimationFrame(rafId); if (running) { lastTime = null; rafId = requestAnimationFrame(frame); } if (running || button.textContent !== 'Start') { button.textContent = running ? 'Stop' : 'Continue'; } } button.addEventListener('click', () => setRunning(!running)); return { pause: () => running && setRunning(false), reset: () => { setRunning(false); button.textContent = 'Start'; draw(); }, }; } // Pendulum: a bob of mass m on a massless rod of length L, angle theta from // straight down, kept in [-pi, pi]. // params: { m, L, g, theta0, p0 }, read live so sliders can change them. // labels: which of 'm', 'L', 'theta', 'p', 'g' to draw. // centered: put the pivot mid-canvas so the bob can go over the top; the rod // is then drawn to scale, with L = 1.2 (the slider's maximum) filling the canvas. // pScale: length of the p arrow in px per unit momentum; by default the arrow // peaks at 70px when let go from theta0 at rest. function createPendulum({ canvas, button, params, labels = [], centered = false, pScale, onDraw = () => {} }) { let theta = params.theta0; let p = params.p0; function step(dt) { // leapfrog on dtheta/dt = p / (m L^2), dp/dt = -m g L sin(theta) const { m, L, g } = params; p -= 0.5 * dt * m * g * L * Math.sin(theta); theta += dt * p / (m * L * L); p -= 0.5 * dt * m * g * L * Math.sin(theta); if (theta > Math.PI) theta -= 2 * Math.PI; if (theta < -Math.PI) theta += 2 * Math.PI; } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const fg = color('--fg'); const accent = color('--accent'); const { m, L, g } = params; const px = w / 2; const py = centered ? h / 2 : 30; const maxRod = centered ? h / 2 - 28 : Math.min(h - 80, w * 0.4); const rod = centered ? maxRod * L / 1.2 : maxRod; const bx = px + rod * Math.sin(theta); const by = py + rod * Math.cos(theta); const r = 18; // ceiling (only when hanging from the top) and pivot ctx.strokeStyle = fg; ctx.lineWidth = 2; if (!centered) { ctx.beginPath(); ctx.moveTo(px - 50, py); ctx.lineTo(px + 50, py); ctx.stroke(); } // vertical reference ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + rod + r + 10); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // rod and bob ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(bx, by); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(bx, by, r, 0, 2 * Math.PI); ctx.fill(); onDraw(theta, p); ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); ctx.fillText('m', bx, by); } if (labels.includes('L')) { // beside the middle of the rod, on the side away from the vertical const side = theta >= 0 ? 1 : -1; ctx.fillStyle = fg; ctx.fillText('L', (px + bx) / 2 + side * 14 * Math.cos(theta), (py + by) / 2 - side * 14 * Math.sin(theta)); } if (labels.includes('theta')) { // arc from the vertical to the rod const arcR = Math.min(44, rod * 0.45); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(px, py, arcR, Math.PI / 2, Math.PI / 2 - theta, theta > 0); ctx.stroke(); const mid = Math.PI / 2 - theta / 2; ctx.fillText('θ', px + (arcR + 14) * Math.cos(mid), py + (arcR + 14) * Math.sin(mid)); } if (labels.includes('p')) { // along the direction of motion, perpendicular to the rod const peak = Math.sqrt(2 * m * m * g * L * L * L * (1 - Math.cos(params.theta0))); const len = p * (pScale ?? (peak ? 70 / peak : 0)); const tx = Math.cos(theta); const ty = -Math.sin(theta); const momentum = color('--momentum'); ctx.strokeStyle = momentum; ctx.fillStyle = momentum; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(bx, by); ctx.lineTo(bx + tx * len, by + ty * len); ctx.stroke(); if (Math.abs(len) > 8) { const d = Math.sign(len); const ex = bx + tx * len; const ey = by + ty * len; ctx.beginPath(); ctx.moveTo(ex, ey); ctx.lineTo(ex - d * 8 * tx - 4 * ty, ey - d * 8 * ty + 4 * tx); ctx.lineTo(ex - d * 8 * tx + 4 * ty, ey - d * 8 * ty - 4 * tx); ctx.closePath(); ctx.fill(); ctx.fillText('p', ex + d * 12 * tx, ey + d * 12 * ty); } } if (labels.includes('g')) { // gravity, pointing down, off to the side const gx = Math.min(px + maxRod + 50, w - 20); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(gx, py + 40); ctx.lineTo(gx, py + 90); ctx.stroke(); ctx.beginPath(); ctx.moveTo(gx, py + 90); ctx.lineTo(gx - 4, py + 82); ctx.lineTo(gx + 4, py + 82); ctx.closePath(); ctx.fill(); ctx.fillText('g', gx + 14, py + 65); } } const loop = createLoop({ button, step, draw }); function setLabels(value) { labels = value; draw(); } // Back to the initial state, held still. function reset() { theta = params.theta0; p = params.p0; loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } function arrow(ctx, from, to, y, col, label, side) { const dir = Math.sign(to - from); ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(from, y); ctx.lineTo(to, y); ctx.stroke(); if (Math.abs(to - from) > 8) { ctx.beginPath(); ctx.moveTo(to, y); ctx.lineTo(to - dir * 8, y - 4); ctx.lineTo(to - dir * 8, y + 4); ctx.closePath(); ctx.fill(); } ctx.textBaseline = side === 'above' ? 'bottom' : 'top'; ctx.fillText(label, (from + to) / 2, side === 'above' ? y - 4 : y + 4); } // Horizontal bars for kinetic, potential and total energy, scaled to the total. function drawEnergyBars(canvas, params, q, p) { if (!canvas.clientWidth) return; const { ctx, w } = prepare(canvas); const { k, m, q0 } = params; const kinetic = (p * p) / (2 * m); const potential = 0.5 * k * q * q; const total = 0.5 * k * q0 * q0; const fg = color('--fg'); const kColor = color('--momentum'); const pColor = color('--potential'); const labelW = 90; const barW = Math.min(w - labelW - 10, 400); const left = Math.max(0, (w - labelW - barW) / 2); const barX = left + labelW; const rowH = 30; const barH = 18; ctx.font = `15px ${color('--font-body')}`; ctx.textBaseline = 'middle'; ctx.textAlign = 'right'; const rows = [ ['Kinetic', [[kinetic, kColor]]], ['Potential', [[potential, pColor]]], ['Total', [[kinetic, kColor], [potential, pColor]]], ]; rows.forEach(([label, segments], i) => { const y = 10 + i * rowH; ctx.fillStyle = fg; ctx.fillText(label, barX - 12, y + barH / 2); // outline at full scale, then filled segments ctx.strokeStyle = fg; ctx.globalAlpha = 0.25; ctx.lineWidth = 1; ctx.strokeRect(barX + 0.5, y + 0.5, barW, barH); ctx.globalAlpha = 1; let sx = barX; for (const [value, col] of segments) { const sw = Math.min(value / total, 1) * barW; ctx.fillStyle = col; ctx.fillRect(sx, y, sw, barH); sx += sw; } }); } // Phase plot: q horizontal (lined up with the spring diagram), p vertical. // The axes are fixed so changing k and m visibly reshapes the orbit. const pMax = 3; // Draw the q and p axes; returns the mapping from (q, p) to canvas coordinates. function springAxes(ctx, w, h) { const { rest, swing, qToX } = layout(w); const mid = h / 2; const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16); const fg = color('--fg'); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(rest - swing - 20, mid); ctx.lineTo(rest + swing + 20, mid); ctx.moveTo(rest, 8); ctx.lineTo(rest, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; ctx.fillText('q', rest + swing + 26, mid); ctx.textBaseline = 'top'; ctx.fillText('p', rest + 8, 6); return { rest, swing, mid, qToX, pToY }; } function drawPhase(canvas, params, trail, q, p) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { rest, swing, mid, qToX, pToY } = springAxes(ctx, w, h); const fg = color('--fg'); const accent = color('--accent'); // level curve H = k q0^2 / 2: an ellipse with semi-axes q0 and q0 sqrt(k m) const { k, m, q0 } = params; const rx = Math.abs(q0) * swing; const ry = Math.abs(pToY(Math.abs(q0) * Math.sqrt(k * m)) - mid); ctx.strokeStyle = fg; ctx.globalAlpha = 0.35; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.ellipse(rest, mid, rx, ry, 0, 0, 2 * Math.PI); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // trail, then the current state ctx.strokeStyle = accent; ctx.lineWidth = 2; ctx.beginPath(); trail.forEach(([tq, tp], i) => { if (i === 0) ctx.moveTo(qToX(tq), pToY(tp)); else ctx.lineTo(qToX(tq), pToY(tp)); }); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(qToX(q), pToY(p), 6, 0, 2 * Math.PI); ctx.fill(); } // Page 1: the spring and its equations of motion const springParams = { k: 6.25, m: 1, q0: 0.6 }; const spring = createSpring({ canvas: document.getElementById('spring-canvas'), button: document.getElementById('spring-toggle'), params: springParams, }); // Page 2: the same spring, with energy bars. Slower and without the arrows, // so the moving bars are the only thing to watch. const energyBars = document.getElementById('energy-bars'); const energy = createSpring({ canvas: document.getElementById('energy-canvas'), button: document.getElementById('energy-toggle'), params: springParams, speed: 0.5, onDraw: (q, p) => drawEnergyBars(energyBars, springParams, q, p), }); // The spring in phase space, with a slider for each of the named params. // Elements are found by id: `${id}-canvas`, `${id}-plot`, `${id}-${name}`. // Reset clears the trail as well. function createSpringPhase({ id, params, names }) { const canvas = document.getElementById(`${id}-canvas`); const plot = document.getElementById(`${id}-plot`); const q0Slider = document.getElementById(`${id}-q0`); let trail = []; const sim = createSpring({ canvas, button: document.getElementById(`${id}-toggle`), params, labels: ['q', 'p', 'k', 'q0'], pScale: 1 / pMax, onDraw: (q, p) => { trail.push([q, p]); if (trail.length > 2000) trail.shift(); drawPhase(plot, params, trail, q, p); alignSlider(); }, }); // Stretch the q0 slider so its thumb sits directly under q0 on the diagram. // The thumb is 30 slide pixels wide (style.css). function alignSlider() { const { rest, swing } = layout(canvas.clientWidth / DRAW_SCALE); const thumb = 30; q0Slider.style.width = `${2 * swing * DRAW_SCALE + thumb}px`; q0Slider.style.marginLeft = `${(rest - swing) * DRAW_SCALE - thumb / 2}px`; } function reset() { trail = []; sim.reset(); } for (const name of names) { const input = document.getElementById(`${id}-${name}`); const output = document.getElementById(`${id}-${name}-value`); input.value = params[name]; output.textContent = params[name]; input.addEventListener('input', () => { params[name] = Number(input.value); output.textContent = input.value; reset(); }); } return { ...sim, reset }; } // Page 4: phase space, with adjustable q0, k and m const phase = createSpringPhase({ id: 'phase', params: { k: 4, m: 1, q0: 0.6 }, names: ['q0', 'k', 'm'] }); // Page 5: the pendulum const pendulum = createPendulum({ canvas: document.getElementById('pendulum-canvas'), button: document.getElementById('pendulum-toggle'), params: { m: 1, L: 1, g: 9.8, theta0: 1.0, p0: 0 }, }); // Page 6: pendulum phase space. theta runs across [-pi, pi]; p is fixed at // +/- pendulumPMax. The separatrix peaks at p = 2 m L sqrt(g L), and the m, L // and g slider ranges keep that under 12 even at their maximums. const pendulumPMax = 12; const pendulumDefaults = { m: 1, L: 1, g: 9.8 }; const pendulumParams = { ...pendulumDefaults, theta0: 0.3, p0: 0 }; const pendulumPresets = { small: { theta0: 0.3, p0: 0 }, large: { theta0: 2.5, p0: 0 }, top: { theta0: 3.1, p0: 0 }, rotation: { theta0: 0, p0: 8 }, balanced: { theta0: Math.PI - 1e-6, p0: 0 }, // a tiny nudge, so it falls after a few seconds rest: { theta0: 0, p0: 0 }, }; const pendulumPlot = document.getElementById('pendulum-plot'); let pendulumTrail = []; const pendulumPhase = createPendulum({ canvas: document.getElementById('pendulum-phase-canvas'), button: document.getElementById('pendulum-phase-toggle'), params: pendulumParams, labels: ['theta', 'p'], centered: true, pScale: 60 / pendulumPMax, onDraw: (theta, p) => { pendulumTrail.push([theta, p]); if (pendulumTrail.length > 3000) pendulumTrail.shift(); drawPendulumPhase(pendulumPlot, pendulumParams, pendulumTrail, theta, p); }, }); // Draw the pendulum phase portrait (level curves of H) and the theta and p // axes; returns the mapping from (theta, p) to canvas coordinates. function pendulumAxes(ctx, w, h, params) { const { m, L, g } = params; const halfW = Math.min(w / 2 - 30, 300); const cx = w / 2; const mid = h / 2; const thetaToX = (t) => cx + (t / Math.PI) * halfW; const pToY = (pv) => mid - (pv / pendulumPMax) * (h / 2 - 16); const fg = color('--fg'); ctx.save(); ctx.beginPath(); ctx.rect(cx - halfW, 0, 2 * halfW, h); ctx.clip(); // background phase portrait: level curves of H, in units of m g L. // Level 1 is the separatrix between swinging and rotating. const levels = [-0.9, -0.6, -0.2, 0.3, 0.7, 1, 1.5, 2.5, 4]; const n = 300; for (const c of levels) { ctx.strokeStyle = fg; ctx.globalAlpha = c === 1 ? 0.45 : 0.15; ctx.lineWidth = c === 1 ? 1.5 : 1; for (const sign of [1, -1]) { ctx.beginPath(); let drawing = false; for (let i = 0; i <= n; i++) { const t = -Math.PI + (2 * Math.PI * i) / n; // p^2 / (2 m L^2) - m g L cos(t) = c m g L const p2 = 2 * m * L * L * m * g * L * (c + Math.cos(t)); if (p2 < 0) { drawing = false; continue; } const x = thetaToX(t); const y = pToY(sign * Math.sqrt(p2)); if (drawing) ctx.lineTo(x, y); else ctx.moveTo(x, y); drawing = true; } ctx.stroke(); } } ctx.globalAlpha = 1; ctx.restore(); // axes ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - halfW, mid); ctx.lineTo(cx + halfW, mid); ctx.moveTo(cx, 8); ctx.lineTo(cx, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.font = 'italic 18px Georgia, serif'; ctx.textBaseline = 'middle'; ctx.textAlign = 'left'; ctx.fillText('θ', cx + halfW + 6, mid); ctx.textBaseline = 'top'; ctx.fillText('p', cx + 8, 6); ctx.font = `13px ${color('--font-body')}`; ctx.textAlign = 'center'; ctx.fillText('−π', cx - halfW, mid + 6); ctx.fillText('π', cx + halfW, mid + 6); return { thetaToX, pToY }; } function drawPendulumPhase(canvas, params, trail, theta, p) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { thetaToX, pToY } = pendulumAxes(ctx, w, h, params); const accent = color('--accent'); // trail, broken where theta wraps around ctx.strokeStyle = accent; ctx.lineWidth = 2; ctx.beginPath(); trail.forEach(([tt, tp], i) => { const jump = i > 0 && Math.abs(tt - trail[i - 1][0]) > Math.PI; if (i === 0 || jump) ctx.moveTo(thetaToX(tt), pToY(tp)); else ctx.lineTo(thetaToX(tt), pToY(tp)); }); ctx.stroke(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(thetaToX(theta), pToY(p), 6, 0, 2 * Math.PI); ctx.fill(); } const pendulumPreset = document.getElementById('pendulum-preset'); const pendulumInputs = ['theta0', 'p0', 'm', 'L', 'g'].map((name) => ({ name, input: document.getElementById(`pendulum-${name}`), output: document.getElementById(`pendulum-${name}-value`), })); function syncPendulumInputs() { for (const { name, input, output } of pendulumInputs) { input.value = pendulumParams[name]; output.textContent = pendulumParams[name].toFixed(2); } } function resetPendulumPhase() { pendulumTrail = []; pendulumPhase.reset(); } for (const { name, input, output } of pendulumInputs) { input.addEventListener('input', () => { pendulumParams[name] = Number(input.value); output.textContent = pendulumParams[name].toFixed(2); pendulumPreset.value = 'custom'; resetPendulumPhase(); }); } // A preset restores the default m, L and g along with its initial state. pendulumPreset.addEventListener('change', () => { const preset = pendulumPresets[pendulumPreset.value]; if (!preset) return; Object.assign(pendulumParams, pendulumDefaults, preset); syncPendulumInputs(); resetPendulumPhase(); }); syncPendulumInputs(); // Liouville's theorem: a disk of starting points evolves under the flow, and // the area enclosed by its boundary stays constant. // force(q) gives dp/dt; m is the mass term in dq/dt = p / m. // center and radii set the disk in (q, p); the single simulation started from // the center is evolved alongside it. drawDiagram(ctx, w, h, points, jitter, // central) and axes(ctx, w, h) draw the physical picture and the phase-plane axes. function createLiouville({ id, force, m, center, radii, drawDiagram, axes }) { const canvas = document.getElementById(`${id}-canvas`); const diagram = document.getElementById(`${id}-diagram`); const areaOut = document.getElementById(`${id}-area`); const [rq, rp] = radii; // a fine boundary, so the area stays accurate as the disk stretches const nb = 2000; let boundary; let interior; let jitter; let central; function makeDisk() { central = [center[0], center[1]]; boundary = []; for (let i = 0; i < nb; i++) { const a = (2 * Math.PI * i) / nb; boundary.push([center[0] + rq * Math.cos(a), center[1] + rp * Math.sin(a)]); } interior = []; while (interior.length < 600) { const u = 2 * Math.random() - 1; const v = 2 * Math.random() - 1; if (u * u + v * v <= 1) interior.push([center[0] + rq * u, center[1] + rp * v]); } // each point gets a fixed random offset on the diagram, so they form a cloud jitter = interior.map(() => Math.random()); } makeDisk(); function step(dt) { // leapfrog on dq/dt = p / m, dp/dt = force(q), for every point for (const pts of [boundary, interior, [central]]) { for (const pt of pts) { pt[1] += 0.5 * dt * force(pt[0]); pt[0] += dt * pt[1] / m; pt[1] += 0.5 * dt * force(pt[0]); } } } // shoelace formula on the boundary polygon function area() { let a = 0; for (let i = 0; i < nb; i++) { const [q1, p1] = boundary[i]; const [q2, p2] = boundary[(i + 1) % nb]; a += q1 * p2 - q2 * p1; } return Math.abs(a) / 2; } function draw() { if (!canvas.clientWidth) return; const d = prepare(diagram); drawDiagram(d.ctx, d.w, d.h, interior, jitter, central); const { ctx, w, h } = prepare(canvas); const { toX, toY } = axes(ctx, w, h); const accent = color('--accent'); ctx.fillStyle = accent; ctx.globalAlpha = 0.15; ctx.beginPath(); boundary.forEach(([q, p], i) => (i ? ctx.lineTo(toX(q), toY(p)) : ctx.moveTo(toX(q), toY(p)))); ctx.closePath(); ctx.fill(); ctx.globalAlpha = 1; ctx.strokeStyle = accent; ctx.lineWidth = 1.5; ctx.stroke(); for (const [q, p] of interior) ctx.fillRect(toX(q) - 1, toY(p) - 1, 2, 2); areaOut.textContent = area().toFixed(4); } const loop = createLoop({ button: document.getElementById(`${id}-toggle`), step, draw, speed: 0.5 }); function reset() { makeDisk(); loop.reset(); } return { draw, reset, pause: loop.pause }; } // Page 7: the spring, with every block drawn as a point and the spring // reaching the block simulated from the disk's center. The disk's radii look // round at the default scale. const liouvilleSpringK = 4; const liouville = createLiouville({ id: 'liouville', force: (q) => -liouvilleSpringK * q, m: 1, center: [0.5, 0], radii: [0.15, 0.6], drawDiagram: (ctx, w, h, points, jitter, [centralQ]) => { drawSpringScene(ctx, w, h, centralQ, ({ qToX, floorY, box }) => { ctx.fillStyle = color('--accent'); points.forEach(([q], i) => ctx.fillRect(qToX(q) - 1, floorY - 4 - jitter[i] * (box - 8), 2, 2)); }); }, axes: (ctx, w, h) => { const { qToX, pToY } = springAxes(ctx, w, h); return { toX: qToX, toY: pToY }; }, }); // Page 8: the pendulum, with every bob drawn as a point and the rod pointing // at the bob simulated from the disk's center. With m = L = 1, p = dtheta/dt. const liouvillePendulumParams = { m: 1, L: 1, g: 9.8 }; const liouvillePendulum = createLiouville({ id: 'liouville-pendulum', force: (theta) => -liouvillePendulumParams.g * Math.sin(theta), m: 1, center: [1.2, 0], radii: [0.35, 3.5], drawDiagram: (ctx, w, h, points, jitter, [centralTheta]) => { const fg = color('--fg'); const px = w / 2; const py = 30; const rod = Math.min(h - 80, w * 0.4); ctx.strokeStyle = fg; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px - 50, py); ctx.lineTo(px + 50, py); ctx.stroke(); ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + rod + 28); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px + (rod - 18) * Math.sin(centralTheta), py + (rod - 18) * Math.cos(centralTheta)); ctx.stroke(); ctx.fillStyle = color('--accent'); points.forEach(([theta], i) => { const r = rod + (jitter[i] - 0.5) * 30; ctx.fillRect(px + r * Math.sin(theta) - 1, py + r * Math.cos(theta) - 1, 2, 2); }); }, axes: (ctx, w, h) => { const { thetaToX, pToY } = pendulumAxes(ctx, w, h, liouvillePendulumParams); return { toX: thetaToX, toY: pToY }; }, }); // Page 9: the spring in phase space again, with damping const damped = createSpringPhase({ id: 'damped', params: { k: 4, m: 1, q0: 0.6, b: 0.3 }, names: ['q0', 'k', 'm', 'b'] }); // Double pendulum: rod angles theta1, theta2 from straight down and their // momenta p1, p2, as the state z = [theta1, theta2, p1, p2]. // params: { m1, m2, L1, L2, g } plus the initial state { theta1, theta2, p1, p2 }. function doubleKinetic({ m1, m2, L1, L2 }, delta, p1, p2) { const D = m1 + m2 * Math.sin(delta) ** 2; return (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * Math.cos(delta)) / (2 * m2 * L1 * L1 * L2 * L2 * D); } function doublePotential({ m1, m2, L1, L2, g }, t1, t2) { return -(m1 + m2) * g * L1 * Math.cos(t1) - m2 * g * L2 * Math.cos(t2); } function doubleEnergy(params, [t1, t2, p1, p2]) { return doubleKinetic(params, t1 - t2, p1, p2) + doublePotential(params, t1, t2); } // Hamilton's equations, as written in the recipe: the rates of change of // (theta1, theta2, p1, p2), written into out. With params.b (page 16) there // is also friction, a force -b dtheta_k/dt on each angle, as on the damped // spring page; the system is then no longer Hamiltonian. function doubleRates(params, t1, t2, p1, p2, out) { const { m1, m2, L1, L2, g } = params; const delta = t1 - t2; const s = Math.sin(delta); const c = Math.cos(delta); const D = m1 + m2 * s * s; // T as in doubleKinetic, and sin(2 delta) = 2 s c, reusing s and c: this is // the inner loop of every double pendulum simulation const T = (m2 * L2 * L2 * p1 * p1 + (m1 + m2) * L1 * L1 * p2 * p2 - 2 * m2 * L1 * L2 * p1 * p2 * c) / (2 * m2 * L1 * L1 * L2 * L2 * D); const dTdDelta = (p1 * p2 * s / (L1 * L2) - 2 * m2 * T * s * c) / D; out[0] = (L2 * p1 - L1 * p2 * c) / (L1 * L1 * L2 * D); out[1] = ((m1 + m2) * L1 * p2 - m2 * L2 * p1 * c) / (m2 * L1 * L2 * L2 * D); out[2] = -(m1 + m2) * g * L1 * Math.sin(t1) - dTdDelta; out[3] = -m2 * g * L2 * Math.sin(t2) + dTdDelta; if (params.b) { out[2] -= params.b * out[0]; out[3] -= params.b * out[1]; } } // One step of the implicit midpoint rule, z' = z + h f((z + z') / 2), solved by // fixed-point iteration, updating z in place. It is symplectic, and unlike // leapfrog it does not need H to split into a kinetic part in p and a // potential part in q (here the kinetic energy depends on the angles too). // Allocation-free, since the Liouville slide steps hundreds of these per frame. const doubleRate = [0, 0, 0, 0]; function doubleStep(params, z, h) { const [t1, t2, p1, p2] = z; let a1 = t1; let a2 = t2; let b1 = p1; let b2 = p2; for (let it = 0; it < 20; it++) { doubleRates(params, 0.5 * (t1 + a1), 0.5 * (t2 + a2), 0.5 * (p1 + b1), 0.5 * (p2 + b2), doubleRate); const n1 = t1 + h * doubleRate[0]; const n2 = t2 + h * doubleRate[1]; const n3 = p1 + h * doubleRate[2]; const n4 = p2 + h * doubleRate[3]; const change = Math.max(Math.abs(n1 - a1), Math.abs(n2 - a2), Math.abs(n3 - b1), Math.abs(n4 - b2)); a1 = n1; a2 = n2; b1 = n3; b2 = n4; if (change < 1e-12) break; } z[0] = wrapAngle(a1); z[1] = wrapAngle(a2); z[2] = b1; z[3] = b2; } // One step of the 2-stage Gauss-Legendre method. The implicit midpoint rule // above is the 1-stage member of this family; this one is also symplectic but // of order 4, so for the same accuracy it can take steps several times // longer. Its two stage slopes, k[0..3] and k[4..7], are solved by fixed-point // iteration starting from the previous step's, so each trajectory keeps its // own k (fill it with the rates at the starting state). const GAUSS_A12 = 0.25 - Math.sqrt(3) / 6; const GAUSS_A21 = 0.25 + Math.sqrt(3) / 6; const gaussRate1 = [0, 0, 0, 0]; const gaussRate2 = [0, 0, 0, 0]; function gaussStep(params, z, h, k) { for (let it = 0; it < 30; it++) { doubleRates(params, z[0] + h * (0.25 * k[0] + GAUSS_A12 * k[4]), z[1] + h * (0.25 * k[1] + GAUSS_A12 * k[5]), z[2] + h * (0.25 * k[2] + GAUSS_A12 * k[6]), z[3] + h * (0.25 * k[3] + GAUSS_A12 * k[7]), gaussRate1); doubleRates(params, z[0] + h * (GAUSS_A21 * k[0] + 0.25 * k[4]), z[1] + h * (GAUSS_A21 * k[1] + 0.25 * k[5]), z[2] + h * (GAUSS_A21 * k[2] + 0.25 * k[6]), z[3] + h * (GAUSS_A21 * k[3] + 0.25 * k[7]), gaussRate2); let change = 0; for (let i = 0; i < 4; i++) { change = Math.max(change, Math.abs(gaussRate1[i] - k[i]), Math.abs(gaussRate2[i] - k[i + 4])); k[i] = gaussRate1[i]; k[i + 4] = gaussRate2[i]; } if (change * h < 1e-10) break; } for (let i = 0; i < 4; i++) z[i] += 0.5 * h * (k[i] + k[i + 4]); z[0] = wrapAngle(z[0]); z[1] = wrapAngle(z[1]); } // Where a step of length h from state a to state b crosses theta1 = 0 (theta1 // increasing), by cubic Hermite interpolation with the rates at both ends, // which stays accurate for long steps; returns [theta2, p2] there. const hermiteA = [0, 0, 0, 0]; const hermiteB = [0, 0, 0, 0]; function sectionCrossing(params, a, b, h) { doubleRates(params, a[0], a[1], a[2], a[3], hermiteA); doubleRates(params, b[0], b[1], b[2], b[3], hermiteB); const end = (i) => (i === 1 ? a[1] + wrapAngle(b[1] - a[1]) : b[i]); const at = (i, s) => { const s2 = s * s; const s3 = s2 * s; return (2 * s3 - 3 * s2 + 1) * a[i] + (s3 - 2 * s2 + s) * h * hermiteA[i] + (3 * s2 - 2 * s3) * end(i) + (s3 - s2) * h * hermiteB[i]; }; let lo = 0; let hi = 1; for (let it = 0; it < 30; it++) { const m = 0.5 * (lo + hi); if (at(0, m) < 0) lo = m; else hi = m; } const s = 0.5 * (lo + hi); return [wrapAngle(at(1, s)), at(3, s)]; } function wrapAngle(t) { return t - 2 * Math.PI * Math.round(t / (2 * Math.PI)); } function doubleInitial({ theta1, theta2, p1, p2 }) { return [theta1, theta2, p1, p2]; } // A label with a subscript, e.g. m with 1, centered at (x, y). The serif font // has no subscript digits, so the digit is drawn smaller and lower. function subText(ctx, base, sub, x, y) { const font = 'italic 18px Georgia, serif'; const small = 'italic 12px Georgia, serif'; ctx.font = font; const bw = ctx.measureText(base).width; ctx.font = small; const sw = ctx.measureText(sub).width; const left = x - (bw + sw + 1) / 2; const align = ctx.textAlign; ctx.textAlign = 'left'; ctx.font = font; ctx.fillText(base, left, y); ctx.font = small; ctx.fillText(sub, left + bw + 1, y + 5); ctx.font = font; ctx.textAlign = align; } // L1 + L2 at the slider maximums. The rods are drawn to scale, with a total // length of maxLength reaching from the pivot (mid-canvas) to the edge, so // either bob can go over the top. const DOUBLE_REACH = 2.5; // labels: which of 'm', 'L', 'theta', 'g' to draw. function drawDoublePendulum(ctx, w, h, params, [t1, t2], labels, maxLength = DOUBLE_REACH) { const fg = color('--fg'); const accent = color('--accent'); const { L1, L2 } = params; const px = w / 2; const py = h / 2; const reach = Math.min(h, w) / 2 - 8; const r = Math.max(9, Math.min(18, reach * 0.1)); const unit = (reach - r) / maxLength; const x1 = px + unit * L1 * Math.sin(t1); const y1 = py + unit * L1 * Math.cos(t1); const x2 = x1 + unit * L2 * Math.sin(t2); const y2 = y1 + unit * L2 * Math.cos(t2); // vertical reference through the pivot ctx.strokeStyle = fg; ctx.lineWidth = 1; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + unit * (L1 + L2) + r); if (labels.includes('theta')) { // and through the upper bob, for theta2 ctx.moveTo(x1, y1); ctx.lineTo(x1, y1 + unit * L2 * 0.7); } ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; // rods, pivot and bobs ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = accent; for (const [bx, by] of [[x1, y1], [x2, y2]]) { ctx.beginPath(); ctx.arc(bx, by, r, 0, 2 * Math.PI); ctx.fill(); } ctx.font = 'italic 18px Georgia, serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; if (labels.includes('m')) { ctx.fillStyle = color('--bg'); subText(ctx, 'm', '1', x1, y1); subText(ctx, 'm', '2', x2, y2); } if (labels.includes('L')) { // beside the middle of each rod, on the side away from the vertical ctx.fillStyle = fg; for (const [sub, ax, ay, bx, by, t] of [['1', px, py, x1, y1, t1], ['2', x1, y1, x2, y2, t2]]) { const side = t >= 0 ? 1 : -1; subText(ctx, 'L', sub, (ax + bx) / 2 + side * 16 * Math.cos(t), (ay + by) / 2 - side * 16 * Math.sin(t)); } } if (labels.includes('theta')) { // arcs from the vertical to each rod ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; for (const [sub, cx, cy, t, len] of [['1', px, py, t1, L1], ['2', x1, y1, t2, L2]]) { const arcR = Math.min(40, unit * len * 0.45); ctx.beginPath(); ctx.arc(cx, cy, arcR, Math.PI / 2, Math.PI / 2 - t, t > 0); ctx.stroke(); const mid = Math.PI / 2 - t / 2; subText(ctx, 'θ', sub, cx + (arcR + 14) * Math.cos(mid), cy + (arcR + 14) * Math.sin(mid)); } } if (labels.includes('g')) { // gravity, pointing down, in the bottom-right corner const gx = w - 24; const gy = h - 40; ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(gx, gy - 25); ctx.lineTo(gx, gy + 25); ctx.stroke(); ctx.beginPath(); ctx.moveTo(gx, gy + 25); ctx.lineTo(gx - 4, gy + 17); ctx.lineTo(gx + 4, gy + 17); ctx.closePath(); ctx.fill(); ctx.fillText('g', gx - 14, gy); } } // onStep(z, h) is called after every integrator step of length h, for // recording trails. speed: see createLoop. // maxLength: see drawDoublePendulum; a number, or a function read at each draw. function createDoublePendulum({ canvas, button, params, labels = [], maxLength, speed = 1, onStep = () => {}, onDraw = () => {} }) { let state = doubleInitial(params); function step(dt) { const n = Math.ceil(dt / 0.0025); for (let i = 0; i < n; i++) { doubleStep(params, state, dt / n); onStep(state, dt / n); } } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); drawDoublePendulum(ctx, w, h, params, state, labels, typeof maxLength === 'function' ? maxLength() : maxLength); onDraw(state); } const loop = createLoop({ button, step, draw, speed }); function setLabels(value) { labels = value; draw(); } // Back to the initial state, held still. function reset() { state = doubleInitial(params); loop.reset(); } return { draw, setLabels, reset, pause: loop.pause }; } // Page 10: the double pendulum, let go with both rods horizontal const doubleDefaults = { m1: 1, m2: 1, L1: 1, L2: 1, g: 9.8 }; const doublePendulum = createDoublePendulum({ canvas: document.getElementById('double-canvas'), button: document.getElementById('double-toggle'), params: { ...doubleDefaults, theta1: Math.PI / 2, theta2: Math.PI / 2, p1: 0, p2: 0 }, maxLength: doubleDefaults.L1 + doubleDefaults.L2, // lengths are fixed here, so fill the canvas }); // Pages 11 to 13: double pendulum phase space, projected onto the (theta1, p1) // and (theta2, p2) planes. The p axes cover the momentum sliders' range, which // the high-energy kicks need. const DOUBLE_PMAX = 20; // Draw the theta_k and p_k axes, with p_k running over +/- pMax; returns the // mapping to canvas coordinates. function doubleAxes(ctx, w, h, k, pMax = DOUBLE_PMAX) { const halfW = w / 2 - 30; const cx = w / 2; const mid = h / 2; const thetaToX = (t) => cx + (t / Math.PI) * halfW; const pToY = (pv) => mid - (pv / pMax) * (h / 2 - 16); const fg = color('--fg'); ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(cx - halfW, mid); ctx.lineTo(cx + halfW, mid); ctx.moveTo(cx, 8); ctx.lineTo(cx, h - 8); ctx.stroke(); ctx.globalAlpha = 1; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; subText(ctx, 'θ', String(k), cx + halfW + 16, mid); subText(ctx, 'p', String(k), cx + 18, 16); ctx.font = `13px ${color('--font-body')}`; ctx.textBaseline = 'top'; ctx.fillText('−π', cx - halfW, mid + 6); ctx.fillText('π', cx + halfW, mid + 6); return { thetaToX, pToY }; } // The trail in the (theta_k, p_k) plane (k = 0 or 1), fading with age and // broken where theta wraps around, then the current state. function drawDoublePlane(canvas, k, trail, state) { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1); const accent = color('--accent'); ctx.save(); ctx.beginPath(); ctx.rect(0, 0, w, h); ctx.clip(); ctx.strokeStyle = accent; ctx.lineWidth = 1.5; const chunks = 6; for (let c = 0; c < chunks; c++) { const from = Math.floor((trail.length * c) / chunks); const to = Math.min(trail.length, Math.floor((trail.length * (c + 1)) / chunks) + 1); ctx.globalAlpha = 0.15 + (0.75 * (c + 1)) / chunks; ctx.beginPath(); for (let i = from; i < to; i++) { const z = trail[i]; const x = thetaToX(z[k]); const y = pToY(z[k + 2]); if (i === from || Math.abs(z[k] - trail[i - 1][k]) > Math.PI) ctx.moveTo(x, y); else ctx.lineTo(x, y); } ctx.stroke(); } ctx.restore(); ctx.fillStyle = accent; ctx.beginPath(); ctx.arc(thetaToX(state[k]), pToY(state[k + 2]), 6, 0, 2 * Math.PI); ctx.fill(); } // Presets grouped by energy, all with the default masses, lengths and g. // Within a group every preset has the same energy H, so their Poincare // sections lie on the same energy surface. Above the resting state // (H = -3 m g L) the groups have 0.5, 1.5 and 3 m g L. Finite-time Lyapunov // exponents put almost all motion at the low energy as regular, a mix at the // medium one ("upper rod only" and "lower rod kicked" weakly chaotic, the rest // regular), and all of it at the high one as chaotic. // State: [theta1, theta2, p1, p2]. A kick starts both rods hanging straight // down with the named rod turning and the other not (yet); "both rods kicked" // starts them turning together. const doublePresetGroups = { low: { inphase: ['Normal mode, in phase', [0.5081, 0.7186, 0, 0]], // theta2 = sqrt(2) theta1 outphase: ['Normal mode, out of phase', [0.5081, -0.7186, 0, 0]], upper: ['Upper rod only', [0.7227, 0, 0, 0]], lower: ['Lower rod only', [0, 1.0472, 0, 0]], }, medium: { together: ['Rods together', [Math.PI / 3, Math.PI / 3, 0, 0]], opposite: ['Rods opposite', [Math.PI / 3, -Math.PI / 3, 0, 0]], upper: ['Upper rod only', [1.3181, 0, 0, 0]], lower: ['Lower rod only', [0, 2 * Math.PI / 3, 0, 0]], kickupper: ['Upper rod kicked', [0, 0, 7.6681, 3.8341]], kicklower: ['Lower rod kicked', [0, 0, 5.4222, 5.4222]], }, high: { together: ['Both rods horizontal', [Math.PI / 2, Math.PI / 2, 0, 0]], opposite: ['Rods horizontal, opposite', [Math.PI / 2, -Math.PI / 2, 0, 0]], lowerup: ['Lower rod upright', [Math.PI / 3, Math.PI, 0, 0]], kickupper: ['Upper rod kicked', [0, 0, 10.8444, 5.4222]], kicklower: ['Lower rod kicked', [0, 0, 7.6681, 7.6681]], both: ['Both rods kicked', [0, 0, 10.2879, 6.8586]], }, }; function doublePreset(level, name) { const [theta1, theta2, p1, p2] = doublePresetGroups[level][name][1]; return { theta1, theta2, p1, p2 }; } // The pivot, rods for the central simulation (started from the ball's // center), and every pendulum's two bobs as points. function drawDoubleCloud(ctx, w, h, params, points, [t1, t2]) { const fg = color('--fg'); const { L1, L2 } = params; const px = w / 2; const py = h / 2; const unit = (Math.min(h, w) / 2 - 8) / (L1 + L2); const x1 = px + unit * L1 * Math.sin(t1); const y1 = py + unit * L1 * Math.cos(t1); ctx.strokeStyle = fg; ctx.lineWidth = 1; ctx.globalAlpha = 0.3; ctx.setLineDash([4, 4]); ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(px, py + unit * (L1 + L2)); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, py); ctx.lineTo(x1, y1); ctx.lineTo(x1 + unit * L2 * Math.sin(t2), y1 + unit * L2 * Math.cos(t2)); ctx.stroke(); ctx.fillStyle = fg; ctx.beginPath(); ctx.arc(px, py, 4, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = color('--accent'); for (const [a1, a2] of points) { const bx = px + unit * L1 * Math.sin(a1); const by = py + unit * L1 * Math.cos(a1); ctx.fillRect(bx - 1, by - 1, 2, 2); ctx.fillRect(bx + unit * L2 * Math.sin(a2) - 1, by + unit * L2 * Math.cos(a2) - 1, 2, 2); } } // Pages 11 to 13 share a layout: the preset and sliders on the left, and the // pendulum above the (theta1, p1) and (theta2, p2) planes on the right. Each // page has its own state and controls, found by id: `${id}-canvas`, // `${id}-plane1`, `${id}-${name}` and so on. mode chooses what the planes show: // 'trail' (page 11) the trajectory in both planes, fading with age; // 'section' (page 12) the trajectory in the (theta1, p1) plane, and in the // (theta2, p2) plane only a dot each time theta1 passes through // zero (straight down) with p1 > 0, a Poincare section; // 'cloud' (page 13) a small 4D ball of starting points around the initial // state, evolving as on the Liouville slides, with every // pendulum's bobs drawn as points and the rods following the // simulation started from the ball's center. function createDoublePhasePage({ id, mode }) { const params = { ...doubleDefaults, ...doublePreset('low', 'upper') }; const canvas = document.getElementById(`${id}-canvas`); const button = document.getElementById(`${id}-toggle`); const planes = [1, 2].map((k) => document.getElementById(`${id}-plane${k}`)); const energyOut = document.getElementById(`${id}-energy`); const level = document.getElementById(`${id}-level`); const preset = document.getElementById(`${id}-preset`); // the speed-up menu, on the trail and section pages only const speedSelect = document.getElementById(`${id}-speed`); function showEnergy(z) { const e = doubleEnergy(params, z); energyOut.textContent = (Math.abs(e) < 0.005 ? 0 : e).toFixed(2); } let sim; let reset; if (mode === 'cloud') { // half-widths of the ball in theta1, theta2, p1, p2; roughly round on screen const radii = [0.2, 0.2, 1.2, 1.2]; let points; let central; function makeCloud() { const center = doubleInitial(params); central = center.slice(); points = []; while (points.length < 600) { const u = [0, 1, 2, 3].map(() => 2 * Math.random() - 1); if (u.reduce((sum, v) => sum + v * v, 0) > 1) continue; const z = center.map((c, i) => c + radii[i] * u[i]); z[0] = wrapAngle(z[0]); z[1] = wrapAngle(z[1]); points.push(z); } } makeCloud(); function step(dt) { const n = Math.ceil(dt / 0.0025); for (const z of [central, ...points]) { for (let i = 0; i < n; i++) doubleStep(params, z, dt / n); } } function draw() { if (!canvas.clientWidth) return; const d = prepare(canvas); drawDoubleCloud(d.ctx, d.w, d.h, params, points, central); planes.forEach((plane, k) => { const { ctx, w, h } = prepare(plane); const { thetaToX, pToY } = doubleAxes(ctx, w, h, k + 1); ctx.save(); ctx.beginPath(); ctx.rect(0, 0, w, h); ctx.clip(); ctx.fillStyle = color('--accent'); for (const z of points) ctx.fillRect(thetaToX(z[k]) - 1, pToY(z[k + 2]) - 1, 2, 2); ctx.restore(); }); showEnergy(central); } // the same pace as the other Liouville slides const loop = createLoop({ button, step, draw, speed: 0.5 }); sim = { draw, pause: loop.pause }; reset = () => { makeCloud(); loop.reset(); }; } else { // the trail is sampled every TRAIL_DT of simulated time, so it looks the // same at every speed, and holds up to TRAIL_MAX samples (1000 s) const TRAIL_DT = 0.01; const TRAIL_MAX = 100000; let trail = []; let sinceSample = 0; // section mode: (theta2, p2) at each crossing, and the previous state let dots = []; let prev = null; function recordCrossing(z) { // theta1 passes through zero (straight down) in either direction, and not // by wrapping around at +/- pi; interpolate linearly to the crossing and // keep it if p1 is positive there const crossed = prev && (prev[0] < 0) !== (z[0] < 0) && Math.abs(z[0] - prev[0]) < Math.PI; const f = crossed ? -prev[0] / (z[0] - prev[0]) : 0; if (crossed && prev[2] + f * (z[2] - prev[2]) > 0) { dots.push([wrapAngle(prev[1] + f * wrapAngle(z[1] - prev[1])), prev[3] + f * (z[3] - prev[3])]); if (dots.length > 50000) dots = dots.slice(-40000); } prev = z.slice(); } function drawDots(plane) { if (!plane.clientWidth) return; const { ctx, w, h } = prepare(plane); const { thetaToX, pToY } = doubleAxes(ctx, w, h, 2); ctx.save(); ctx.beginPath(); ctx.rect(0, 0, w, h); ctx.clip(); ctx.fillStyle = color('--accent'); ctx.beginPath(); for (const [t2, p2] of dots) { const x = thetaToX(t2); const y = pToY(p2); ctx.moveTo(x + 0.8, y); ctx.arc(x, y, 0.8, 0, 2 * Math.PI); } ctx.fill(); ctx.restore(); } sim = createDoublePendulum({ canvas, button, params, // the canvas is short, so fill it: the rods are drawn to scale relative to // each other, but not across changes of L1 + L2 maxLength: () => params.L1 + params.L2, speed: () => Number(speedSelect.value), onStep: (z, h) => { sinceSample += h; if (sinceSample >= TRAIL_DT) { sinceSample = 0; trail.push(z.slice()); if (trail.length > TRAIL_MAX) trail = trail.slice(-0.8 * TRAIL_MAX); } if (mode === 'section') recordCrossing(z); }, onDraw: (z) => { drawDoublePlane(planes[0], 0, trail, z); if (mode === 'section') drawDots(planes[1]); else drawDoublePlane(planes[1], 1, trail, z); showEnergy(z); }, }); reset = () => { trail = []; sinceSample = 0; dots = []; prev = null; sim.reset(); }; } const inputs = ['theta1', 'theta2', 'p1', 'p2', 'm1', 'm2', 'L1', 'L2', 'g'].map((name) => ({ name, input: document.getElementById(`${id}-${name}`), output: document.getElementById(`${id}-${name}-value`), })); function syncInputs() { for (const { name, input, output } of inputs) { input.value = params[name]; output.textContent = params[name].toFixed(2); } } for (const { name, input, output } of inputs) { input.addEventListener('input', () => { params[name] = Number(input.value); output.textContent = params[name].toFixed(2); preset.value = 'custom'; reset(); }); } // The preset menu lists the chosen energy's presets, then a Custom entry // that the sliders select. function fillPresets() { preset.replaceChildren(); for (const [value, [label]] of Object.entries(doublePresetGroups[level.value])) { preset.add(new Option(label, value)); } const custom = new Option('Custom', 'custom'); custom.disabled = true; preset.add(custom); } // A preset restores the default masses, lengths and g along with its initial state. function applyPreset() { Object.assign(params, doubleDefaults, doublePreset(level.value, preset.value)); syncInputs(); reset(); } level.addEventListener('change', () => { fillPresets(); applyPreset(); }); preset.addEventListener('change', applyPreset); fillPresets(); preset.value = 'upper'; syncInputs(); return { draw: sim.draw, pause: sim.pause, reset }; } const doublePhase = createDoublePhasePage({ id: 'double-phase', mode: 'trail' }); const doublePoincare = createDoublePhasePage({ id: 'double-poincare', mode: 'section' }); const doubleDispersion = createDoublePhasePage({ id: 'double-dispersion', mode: 'cloud' }); // Page 14: Poincare section explorer, with the default masses, lengths and g. // The section is theta1 = 0 with theta1 increasing. Given (theta2, p2) on it // and the energy H, the kinetic energy is quadratic in p1 with two roots, and // the larger one is exactly the one with dtheta1/dt > 0, so each point inside // the allowed region is one state. (With p1 > 0 as the condition instead, // both roots can be positive, and two states would share a point.) // // Clicking starts an orbit there, integrated in the background (with // gaussStep, and crossings found by sectionCrossing) until it is complete or // the next click stops it: its dots are binned on a grid of about 5 x 5 slide // pixels, and it stops once EXPLORER_WINDOW dots in a row reach fewer than // EXPLORER_NEW_CELLS new cells (a curve has closed up, or a chaotic region has // mostly filled), or at EXPLORER_MAX_DOTS dots (or 4 simulated seconds per // allowed dot). // // Auto starts each new orbit in the middle of the largest gap: the cell // farthest from any dot and from the edge of the allowed region (a chamfer // distance transform on the grid). Each press adds up to AUTO_BATCH orbits, // stopping early when no gap is more than AUTO_MIN_GAP cells from a dot, or // on a click. A press when the gaps are already that small fills smaller ones, // down to 3/4 of the largest gap left (at least one cell); this finds small // islands in a chaotic sea. // // Each orbit is colored by an estimate of the dimension of its dots: a regular // orbit lies on a curve (1), a chaotic one fills an area (2). The estimate is // the correlation dimension: the number of pairs of dots closer than r grows // like r^d, so d = log2(C(r) / C(r/2)), with r = 0.03 of the region's half // width (large enough r would see the two sides of a thin loop as an area). // It uses one dot per cell of a grid twice as fine as the one above (the first // to land there), so it measures where the orbit has been rather than how // often: a chaotic orbit that lingers near an island would otherwise look // regular. // Regular orbits all measure about 1, so to tell them apart each orbit has its // own cool color, blended toward red as d goes from 1.25 to 1.85. const EXPLORER_STEP = 0.025; const EXPLORER_GRID = [300, 140]; const EXPLORER_FINE_GRID = [600, 280]; const EXPLORER_WINDOW = 1000; const EXPLORER_NEW_CELLS = 10; const EXPLORER_MAX_DOTS = 20000; const EXPLORER_MAX_ORBITS = 2000; const AUTO_MIN_GAP = 3; const AUTO_BATCH = 40; // GPU fill: orbits per press, their dot cap, and the crossings each may // report per dispatch const GPU_ORBITS = 256; const GPU_MAX_DOTS = 4000; const GPU_DOTS_PER_DISPATCH = 128; const EXPLORER_COLORS = ['#537eba', '#2e8b57', '#1a9cb0', '#6a4fb3', '#2c5aa0', '#5f9e2f', '#8a5fbf', '#17806d']; // GPU fill: doubleRates, gaussStep and sectionCrossing in WGSL, one orbit per // thread. WebGPU only has 32-bit floats, so this is less precise than the CPU // path (each finished fill logs its largest energy error to the console). Each // dispatch advances every active orbit by P.steps steps and records up to // P.maxDots crossings; the fixed-point iteration stops at a tolerance suited // to 32-bit floats. const EXPLORER_SHADER = ` struct Params { m1: f32, m2: f32, L1: f32, L2: f32, g: f32, h: f32, steps: u32, maxDots: u32, n: u32, b: f32 } @group(0) @binding(0) var P: Params; @group(0) @binding(1) var state: array; @group(0) @binding(2) var slopes: array; @group(0) @binding(3) var dots: array; @group(0) @binding(4) var counts: array; @group(0) @binding(5) var running: array; const PI = 3.141592653589793; const A12 = 0.25 - 0.28867513459481287; const A21 = 0.25 + 0.28867513459481287; fn wrapAngle(t: f32) -> f32 { return t - 2.0 * PI * round(t / (2.0 * PI)); } fn maxAbs(v: vec4f) -> f32 { let a = abs(v); return max(max(a.x, a.y), max(a.z, a.w)); } fn rates(z: vec4f) -> vec4f { let d = z.x - z.y; let s = sin(d); let c = cos(d); let D = P.m1 + P.m2 * s * s; let T = (P.m2 * P.L2 * P.L2 * z.z * z.z + (P.m1 + P.m2) * P.L1 * P.L1 * z.w * z.w - 2.0 * P.m2 * P.L1 * P.L2 * z.z * z.w * c) / (2.0 * P.m2 * P.L1 * P.L1 * P.L2 * P.L2 * D); let dT = (z.z * z.w * s / (P.L1 * P.L2) - 2.0 * P.m2 * T * s * c) / D; let w1 = (P.L2 * z.z - P.L1 * z.w * c) / (P.L1 * P.L1 * P.L2 * D); let w2 = ((P.m1 + P.m2) * P.L1 * z.w - P.m2 * P.L2 * z.z * c) / (P.m2 * P.L1 * P.L2 * P.L2 * D); return vec4f(w1, w2, -(P.m1 + P.m2) * P.g * P.L1 * sin(z.x) - dT - P.b * w1, -P.m2 * P.g * P.L2 * sin(z.y) + dT - P.b * w2); } fn hermite(y0: vec4f, f0: vec4f, y1: vec4f, f1: vec4f, h: f32, s: f32) -> vec4f { let s2 = s * s; let s3 = s2 * s; return (2.0 * s3 - 3.0 * s2 + 1.0) * y0 + (s3 - 2.0 * s2 + s) * h * f0 + (3.0 * s2 - 2.0 * s3) * y1 + (s3 - s2) * h * f1; } fn crossing(a: vec4f, b: vec4f, h: f32) -> vec2f { var bu = b; bu.y = a.y + wrapAngle(b.y - a.y); let fa = rates(a); let fb = rates(b); var lo = 0.0; var hi = 1.0; for (var it = 0; it < 24; it++) { let m = 0.5 * (lo + hi); if (hermite(a, fa, bu, fb, h, m).x < 0.0) { lo = m; } else { hi = m; } } let y = hermite(a, fa, bu, fb, h, 0.5 * (lo + hi)); return vec2f(wrapAngle(y.y), y.w); } @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3u) { let i = id.x; if (i >= P.n) { return; } counts[i] = 0u; if (running[i] == 0u) { return; } var z = state[i]; var k1 = slopes[2u * i]; var k2 = slopes[2u * i + 1u]; let h = P.h; var count = 0u; for (var n = 0u; n < P.steps; n++) { let a = z; for (var it = 0; it < 12; it++) { let n1 = rates(z + h * (0.25 * k1 + A12 * k2)); let n2 = rates(z + h * (A21 * k1 + 0.25 * k2)); let change = max(maxAbs(n1 - k1), maxAbs(n2 - k2)); k1 = n1; k2 = n2; if (change * h < 1e-6) { break; } } z += 0.5 * h * (k1 + k2); z.x = wrapAngle(z.x); z.y = wrapAngle(z.y); if (a.x < 0.0 && z.x >= 0.0 && z.x - a.x < PI && count < P.maxDots) { dots[i * P.maxDots + count] = crossing(a, z, h); count++; } } state[i] = z; slopes[2u * i] = k1; slopes[2u * i + 1u] = k2; counts[i] = count; } `; // WebGPU device and pipeline for the GPU fill, set up once and shared by the // explorer pages: a promise of { device, pipeline }, or of null without WebGPU. let explorerGpu = null; function explorerGpuSetup() { explorerGpu ??= (async () => { const unavailable = (why) => { console.warn(`[explorer] GPU fill unavailable: ${why}`); return null; }; try { if (!window.isSecureContext) return unavailable(`WebGPU needs a secure context (use http://localhost, not ${location.host})`); if (!navigator.gpu) return unavailable('this browser has no navigator.gpu'); const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); if (!adapter) return unavailable('requestAdapter() found no GPU adapter (see chrome://gpu)'); const device = await adapter.requestDevice(); const module = device.createShaderModule({ code: EXPLORER_SHADER }); const info = await module.getCompilationInfo(); for (const m of info.messages) console[m.type === 'error' ? 'error' : 'warn'](`[explorer] shader ${m.type} at line ${m.lineNum}:${m.linePos}: ${m.message}`); const pipeline = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'main' } }); console.info('[explorer] GPU fill ready'); return { device, pipeline }; } catch (err) { return unavailable(err); } })(); return explorerGpu; } // listen: also play orbits as sound, with createListener (page 15). // damping: with a damping slider (page 16); orbits then spiral inward, so // they are not colored by dimension, and H is the energy they start with. function createExplorer({ id, listen = false, damping = false }) { const canvas = document.getElementById(`${id}-canvas`); const slider = document.getElementById(`${id}-energy`); const output = document.getElementById(`${id}-energy-value`); const autoButton = document.getElementById(`${id}-auto`); const gpuButton = document.getElementById(`${id}-gpu`); const params = { ...doubleDefaults }; const [gx, gy] = EXPLORER_GRID; let H = -14.7; let orbits = []; let orbitCount = 0; let auto = false; // the orbit being listened to, lit up like a hovered one while it plays let selected = null; const listener = listen ? createListener({ id, params, onChange: () => active && draw() }) : null; // cells reached by any orbit; the grid spans the allowed region, // |theta2| <= gridThetaMax and |p2| <= gridPMax let covered = new Uint8Array(gx * gy); // the last orbit to reach each cell, for finding the orbit under the mouse let owner = new Array(gx * gy).fill(null); let hovered = null; let gridPMax = 0; let gridThetaMax = Math.PI; let inside = new Uint8Array(gx * gy); // cells whose center is in the allowed region let rafId = null; let active = false; let view = null; // the latest mapping, for clicks and the dot layer // dots are drawn once onto this layer and copied to the canvas each frame; // it is redrawn in full only when the size changes or orbits are removed const layer = document.createElement('canvas'); let layerDirty = true; // the largest |p2| on the section, at theta2 = 0 const sectionPMax = () => Math.sqrt(Math.max(0, 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, 0)))); // the largest |theta2| on the section, where H - V(0, theta2) reaches zero function sectionThetaMax() { const { m1, m2, L1, L2, g } = params; return Math.acos(Math.min(1, Math.max(-1, -(H + (m1 + m2) * g * L1) / (m2 * g * L2)))); } function sizeGrid() { gridPMax = sectionPMax(); gridThetaMax = sectionThetaMax(); inside = new Uint8Array(gx * gy); for (let j = 0; j < gy; j++) { const p = cellP(j); for (let i = 0; i < gx; i++) { inside[j * gx + i] = p * p <= 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, cellTheta(i))) ? 1 : 0; } } } // the state on the section at (theta2, p2), or null outside the allowed region function sectionState(t2, p2) { const { m1, m2, L1, L2 } = params; const s = 2 * m2 * L2 * L2 * (H - doublePotential(params, 0, t2)) - p2 * p2; if (s < 0) return null; const D = m1 + m2 * Math.sin(t2) ** 2; return [0, t2, (L1 / L2) * p2 * Math.cos(t2) + Math.sqrt(m2 * L1 * L1 * L2 * L2 * D * s) / (m2 * L2 * L2), p2]; } // on at most 4000 of the given dots, evenly spread through the orbit function correlationDimension(dots) { const all = dots.length / 2; const stride = Math.ceil(all / 4000); const n = Math.floor(all / stride); const m = Math.min(300, n); const r2 = 0.03 * 0.03; let c1 = 0; let c2 = 0; for (let k = 0; k < m; k++) { const i = Math.floor((k * n) / m) * stride; const ti = dots[2 * i]; const pi = dots[2 * i + 1]; for (let jj = 0; jj < n; jj++) { const j = jj * stride; if (j === i) continue; const dx = wrapAngle(ti - dots[2 * j]) / gridThetaMax; const dy = (pi - dots[2 * j + 1]) / gridPMax; const d = dx * dx + dy * dy; if (d < r2) { c1++; if (d < r2 / 4) c2++; } } } return c2 ? Math.log2(c1 / c2) : 0; } // the orbit's own cool color, blended toward red from d = 1.25 to d = 1.85 function orbitColor(o) { if (damping) return o.base; if (o.d === null) return null; const t = Math.min(1, Math.max(0, (o.d - 1.25) / 0.6)); const a = o.base; const b = color('--force'); const mix = (k) => Math.round((1 - t) * parseInt(a.slice(k, k + 2), 16) + t * parseInt(b.slice(k, k + 2), 16)); return `rgb(${mix(1)}, ${mix(3)}, ${mix(5)})`; } function cellOf(t2, p2, [nx, ny] = EXPLORER_GRID) { const i = Math.min(nx - 1, Math.max(0, Math.floor(((t2 / gridThetaMax + 1) / 2) * nx))); const j = Math.min(ny - 1, Math.max(0, Math.floor(((p2 / gridPMax + 1) / 2) * ny))); return j * nx + i; } const cellTheta = (i) => (((i + 0.5) / gx) * 2 - 1) * gridThetaMax; const cellP = (j) => (((j + 0.5) / gy) * 2 - 1) * gridPMax; // the empty cell farthest from any dot (any cell set in mask) and from the // edge of the allowed region, as { i, j, gap } with gap in cells function largestGap(mask = covered) { const dist = new Float32Array(gx * gy); for (let c = 0; c < gx * gy; c++) dist[c] = inside[c] && !mask[c] ? Infinity : 0; const r2 = Math.SQRT2; for (let j = 0; j < gy; j++) { for (let i = 0; i < gx; i++) { const c = j * gx + i; let d = dist[c]; if (i > 0) d = Math.min(d, dist[c - 1] + 1); if (j > 0) { d = Math.min(d, dist[c - gx] + 1); if (i > 0) d = Math.min(d, dist[c - gx - 1] + r2); if (i < gx - 1) d = Math.min(d, dist[c - gx + 1] + r2); } dist[c] = d; } } let best = { i: 0, j: 0, gap: 0 }; for (let j = gy - 1; j >= 0; j--) { for (let i = gx - 1; i >= 0; i--) { const c = j * gx + i; let d = dist[c]; if (i < gx - 1) d = Math.min(d, dist[c + 1] + 1); if (j < gy - 1) { d = Math.min(d, dist[c + gx] + 1); if (i < gx - 1) d = Math.min(d, dist[c + gx + 1] + r2); if (i > 0) d = Math.min(d, dist[c + gx - 1] + r2); } dist[c] = d; if (d > best.gap && d < Infinity) best = { i, j, gap: d }; } } return best; } // this press's smallest gap to fill, and how many orbits it may still add let autoGap = AUTO_MIN_GAP; let autoLeft = 0; function setAuto(on) { auto = on; autoButton.textContent = on ? 'Stop' : 'Auto'; if (!on) return; const gap = largestGap().gap; autoGap = gap >= AUTO_MIN_GAP ? AUTO_MIN_GAP : Math.max(1, 0.75 * gap); autoLeft = AUTO_BATCH; if (!orbits.some(unfinishedCpu)) nextAuto(); } // up to n starting points spread over the gaps: each goes in the largest gap // left, then claims a disk of half that gap's radius function spreadStarts(n) { const mask = covered.slice(); const starts = []; while (starts.length < n) { const { i, j, gap } = largestGap(mask); if (gap < 1) break; starts.push([cellTheta(i), cellP(j)]); const r = Math.max(1, gap / 2); const m = Math.ceil(r); for (let dj = -m; dj <= m; dj++) { for (let di = -m; di <= m; di++) { const ii = i + di; const jj = j + dj; if (di * di + dj * dj <= r * r && ii >= 0 && ii < gx && jj >= 0 && jj < gy) mask[jj * gx + ii] = 1; } } } return starts; } function nextAuto() { const { i, j, gap } = largestGap(); if (autoLeft <= 0 || gap < autoGap) { setAuto(false); return; } autoLeft--; addOrbit(cellTheta(i), cellP(j)); } // A new orbit at (theta2, p2) on the section, or null outside the allowed // region. gpu: integrated by the GPU fill rather than on the CPU. function makeOrbit(t2, p2, { gpu = false, maxDots = EXPLORER_MAX_DOTS } = {}) { const z = sectionState(t2, p2); if (!z) return null; const k = [0, 0, 0, 0, 0, 0, 0, 0]; doubleRates(params, z[0], z[1], z[2], z[3], k); for (let i = 0; i < 4; i++) k[i + 4] = k[i]; const o = { z, start: z.slice(), prev: z.slice(), k, dots: [], firsts: [], d: null, steps: 0, done: false, drawn: 0, gpu, maxDots, base: EXPLORER_COLORS[orbitCount++ % EXPLORER_COLORS.length], // cells of the two grids this orbit has reached (dropped when it finishes) cells: new Set(), fine: new Set(), windowDots: 0, windowNew: 0, }; addDot(o, t2, p2); orbits.push(o); if (orbits.length > EXPLORER_MAX_ORBITS) { orbits.shift(); layerDirty = true; covered = new Uint8Array(gx * gy); owner = new Array(gx * gy).fill(null); for (const other of orbits) { for (let i = 0; i < other.dots.length; i += 2) { const c = cellOf(other.dots[i], other.dots[i + 1]); covered[c] = 1; owner[c] = other; } } if (!orbits.includes(hovered)) hovered = null; if (!orbits.includes(selected)) selected = null; } return o; } // a clicked or Auto orbit; it stops any orbit still being filled in function addOrbit(t2, p2) { if (!sectionState(t2, p2)) return null; stopGpu(); for (const prev of orbits) finish(prev); const o = makeOrbit(t2, p2); resume(); return o; } const unfinishedCpu = (o) => !o.done && !o.gpu; function addDot(o, t2, p2) { o.dots.push(t2, p2); const c = cellOf(t2, p2); if (!o.cells.has(c)) { o.cells.add(c); covered[c] = 1; owner[c] = o; o.windowNew++; } const f = cellOf(t2, p2, EXPLORER_FINE_GRID); if (!o.fine.has(f)) { o.fine.add(f); o.firsts.push(t2, p2); } const n = o.dots.length / 2; // the dimension estimate at 500 dots, then each time the count doubles if (!damping && (n === 500 || (n > 1000 && (n & (n - 1)) === 0))) { o.d = correlationDimension(o.firsts); o.drawn = 0; // redraw the whole orbit in its new color } if (++o.windowDots === EXPLORER_WINDOW) { if (o.windowNew < EXPLORER_NEW_CELLS) finish(o); o.windowDots = 0; o.windowNew = 0; } if (n >= o.maxDots) finish(o); } // the step cap: 4 simulated seconds per allowed dot const maxSteps = (o) => (4 / EXPLORER_STEP) * o.maxDots; function finish(o) { if (o.done) return; o.done = true; o.cells = null; // only needed while dots arrive o.fine = null; // too few dots for an estimate (stopped early by a click): it stays gray if (damping || o.dots.length / 2 < 300) return; o.d = correlationDimension(o.firsts); o.drawn = 0; } // integrate orbit o for about ms milliseconds function advance(o, ms) { const until = performance.now() + ms; const { z, prev, k } = o; const cap = maxSteps(o); while (!o.done && performance.now() < until) { for (let i = 0; i < 50 && !o.done; i++) { prev[0] = z[0]; prev[1] = z[1]; prev[2] = z[2]; prev[3] = z[3]; gaussStep(params, z, EXPLORER_STEP, k); if (++o.steps > cap) finish(o); if (prev[0] < 0 && z[0] >= 0 && z[0] - prev[0] < Math.PI) { const [t2, p2] = sectionCrossing(params, prev, z, EXPLORER_STEP); addDot(o, t2, p2); } } } } function frame() { rafId = null; const busy = orbits.filter(unfinishedCpu); for (const o of busy) advance(o, 12 / busy.length); if (auto && !orbits.some(unfinishedCpu)) nextAuto(); draw(); } function resume() { if (active && rafId === null && orbits.some(unfinishedCpu)) rafId = requestAnimationFrame(frame); if (active && gpuRun && !gpuRun.looping) gpuLoop(gpuRun); } // GPU fill: GPU_ORBITS orbits at once, spread over the gaps, each integrated // by one thread of EXPLORER_SHADER. Their dots go through addDot like any // other orbit's, with a cap of GPU_MAX_DOTS. The button only appears if // WebGPU is available. let gpu = null; // { device, pipeline } once set up let gpuRun = null; // the fill in progress explorerGpuSetup().then((g) => { if (!g) return; gpu = g; gpuButton.hidden = false; }); function startGpu() { setAuto(false); for (const o of orbits) finish(o); const run = { orbits: [], steps: 256, looping: false, started: performance.now() }; for (const [t2, p2] of spreadStarts(GPU_ORBITS)) { const o = makeOrbit(t2, p2, { gpu: true, maxDots: GPU_MAX_DOTS }); if (o) run.orbits.push(o); } const n = run.orbits.length; if (!n) return; const { device, pipeline } = gpu; const buffer = (size, usage) => device.createBuffer({ size, usage }); const { STORAGE, COPY_SRC, COPY_DST, UNIFORM, MAP_READ } = GPUBufferUsage; run.params = buffer(48, UNIFORM | COPY_DST); run.state = buffer(n * 16, STORAGE | COPY_SRC | COPY_DST); run.slopes = buffer(n * 32, STORAGE | COPY_DST); run.dots = buffer(n * GPU_DOTS_PER_DISPATCH * 8, STORAGE | COPY_SRC); run.counts = buffer(n * 4, STORAGE | COPY_SRC); run.running = buffer(n * 4, STORAGE | COPY_DST); run.readDots = buffer(n * GPU_DOTS_PER_DISPATCH * 8, MAP_READ | COPY_DST); run.readCounts = buffer(n * 4, MAP_READ | COPY_DST); run.readState = buffer(n * 16, MAP_READ | COPY_DST); device.queue.writeBuffer(run.state, 0, Float32Array.from(run.orbits.flatMap((o) => o.z))); device.queue.writeBuffer(run.slopes, 0, Float32Array.from(run.orbits.flatMap((o) => o.k))); run.bindGroup = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [run.params, run.state, run.slopes, run.dots, run.counts, run.running] .map((b, binding) => ({ binding, resource: { buffer: b } })), }); gpuRun = run; gpuButton.textContent = 'Stop'; resume(); } function stopGpu() { const run = gpuRun; if (!run) return; gpuRun = null; gpuButton.textContent = 'GPU fill'; for (const o of run.orbits) finish(o); if (!run.looping) destroyRun(run); } function destroyRun(run) { for (const key of ['params', 'state', 'slopes', 'dots', 'counts', 'running', 'readDots', 'readCounts', 'readState']) run[key].destroy(); } // dispatch, read back the crossings, repeat; aims for about 30 ms a round async function gpuLoop(run) { run.looping = true; const { device, pipeline } = gpu; const n = run.orbits.length; const per = GPU_DOTS_PER_DISPATCH; try { while (gpuRun === run && active) { const t0 = performance.now(); const p = new ArrayBuffer(48); new Float32Array(p).set([params.m1, params.m2, params.L1, params.L2, params.g, EXPLORER_STEP]); new Uint32Array(p).set([run.steps, per, n], 6); new Float32Array(p)[9] = params.b ?? 0; device.queue.writeBuffer(run.params, 0, p); device.queue.writeBuffer(run.running, 0, Uint32Array.from(run.orbits, (o) => (o.done ? 0 : 1))); const encoder = device.createCommandEncoder(); const pass = encoder.beginComputePass(); pass.setPipeline(pipeline); pass.setBindGroup(0, run.bindGroup); pass.dispatchWorkgroups(Math.ceil(n / 64)); pass.end(); encoder.copyBufferToBuffer(run.counts, 0, run.readCounts, 0, n * 4); encoder.copyBufferToBuffer(run.dots, 0, run.readDots, 0, n * per * 8); device.queue.submit([encoder.finish()]); await Promise.all([run.readCounts.mapAsync(GPUMapMode.READ), run.readDots.mapAsync(GPUMapMode.READ)]); const counts = new Uint32Array(run.readCounts.getMappedRange()).slice(); const dots = new Float32Array(run.readDots.getMappedRange()).slice(); run.readCounts.unmap(); run.readDots.unmap(); if (gpuRun !== run) break; run.orbits.forEach((o, i) => { if (o.done) return; for (let j = 0; j < counts[i] && !o.done; j++) addDot(o, dots[2 * (i * per + j)], dots[2 * (i * per + j) + 1]); o.steps += run.steps; if (o.steps > maxSteps(o)) finish(o); }); draw(); if (run.orbits.every((o) => o.done)) { await reportGpu(run); gpuRun = null; gpuButton.textContent = 'GPU fill'; break; } const ms = performance.now() - t0; run.steps = Math.max(32, Math.min(4096, Math.round(run.steps * (ms < 20 ? 1.5 : ms > 50 ? 0.7 : 1)))); } } catch (err) { console.error('[explorer] GPU fill failed:', err); if (gpuRun === run) { gpuRun = null; gpuButton.textContent = 'GPU fill'; for (const o of run.orbits) finish(o); } } run.looping = false; if (gpuRun !== run) destroyRun(run); } // log how well the 32-bit integration kept the energy async function reportGpu(run) { const { device } = gpu; const n = run.orbits.length; const encoder = device.createCommandEncoder(); encoder.copyBufferToBuffer(run.state, 0, run.readState, 0, n * 16); device.queue.submit([encoder.finish()]); await run.readState.mapAsync(GPUMapMode.READ); const z = new Float32Array(run.readState.getMappedRange()).slice(); run.readState.unmap(); let worst = 0; for (let i = 0; i < n; i++) worst = Math.max(worst, Math.abs(doubleEnergy(params, z.slice(4 * i, 4 * i + 4)) - H)); const dots = run.orbits.reduce((sum, o) => sum + o.dots.length / 2, 0); const seconds = ((performance.now() - run.started) / 1000).toFixed(1); console.info(`[explorer] GPU fill: ${n} orbits, ${dots} dots in ${seconds} s; largest energy error ${worst.toExponential(1)} at H = ${H}`); } // draw dots not yet on the layer function updateLayer(thetaToX, pToY) { if (layer.width !== canvas.width || layer.height !== canvas.height) { layer.width = canvas.width; layer.height = canvas.height; layerDirty = true; } const lctx = layer.getContext('2d'); lctx.setTransform(canvas.getContext('2d').getTransform()); if (layerDirty) { lctx.clearRect(0, 0, view.w, view.h); for (const o of orbits) o.drawn = 0; layerDirty = false; } const fg = color('--fg'); for (const o of orbits) { const col = orbitColor(o); lctx.fillStyle = col ?? fg; lctx.globalAlpha = col ? 1 : 0.4; // an orbit with no estimate yet goes underneath, so its gray never // covers colored dots (a new orbit in a chaotic sea spreads over it); // once colored it is redrawn on top lctx.globalCompositeOperation = col ? 'source-over' : 'destination-over'; const { dots } = o; for (let i = 2 * o.drawn; i < dots.length; i += 2) lctx.fillRect(thetaToX(dots[i]) - 0.7, pToY(dots[i + 1]) - 0.7, 1.4, 1.4); o.drawn = dots.length / 2; } lctx.globalAlpha = 1; lctx.globalCompositeOperation = 'source-over'; } function draw() { active = true; if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); const pMax = Math.max(sectionPMax(), 0.5) * 1.08; if (!view || view.w !== w || view.h !== h || view.pMax !== pMax) layerDirty = true; const { thetaToX, pToY } = doubleAxes(ctx, w, h, 2, pMax); view = { w, h, pMax }; const fg = color('--fg'); // boundary of the allowed region, p2 = +/- sqrt(2 m2 L2^2 (H - V(0, theta2))) ctx.strokeStyle = fg; ctx.globalAlpha = 0.4; ctx.lineWidth = 1; for (const sign of [1, -1]) { ctx.beginPath(); let drawing = false; for (let i = 0; i <= 400; i++) { const t = -Math.PI + (2 * Math.PI * i) / 400; const k = 2 * params.m2 * params.L2 ** 2 * (H - doublePotential(params, 0, t)); if (k < 0) { drawing = false; continue; } const x = thetaToX(t); const y = pToY(sign * Math.sqrt(k)); if (drawing) ctx.lineTo(x, y); else ctx.moveTo(x, y); drawing = true; } ctx.stroke(); } ctx.globalAlpha = 1; updateLayer(thetaToX, pToY); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); // the orbit under the mouse lights up: the rest dims, and it is drawn // on top with larger dots // (or, with no hover, the one playing) const lit = hovered ?? (listener?.playing ? selected : null); if (lit) ctx.globalAlpha = 0.25; ctx.drawImage(layer, 0, 0); ctx.restore(); if (lit) { ctx.fillStyle = orbitColor(lit) ?? fg; const { dots } = lit; for (let i = 0; i < dots.length; i += 2) ctx.fillRect(thetaToX(dots[i]) - 1.2, pToY(dots[i + 1]) - 1.2, 2.4, 2.4); } if (!orbits.length) { ctx.fillStyle = fg; ctx.globalAlpha = 0.6; ctx.font = `18px ${color('--font-body')}`; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; const hint = listener ? 'Click inside the curve to start an orbit and listen to it, or press Auto' : 'Click inside the curve to start an orbit, or press Auto'; ctx.fillText(hint, w / 2, h - 12); ctx.globalAlpha = 1; } resume(); } // (theta2, p2) under a mouse event, inverting doubleAxes' mapping function eventPoint(e) { const rect = canvas.getBoundingClientRect(); const x = ((e.clientX - rect.left) / rect.width) * view.w; const y = ((e.clientY - rect.top) / rect.height) * view.h; return [((x - view.w / 2) / (view.w / 2 - 30)) * Math.PI, ((view.h / 2 - y) / (view.h / 2 - 16)) * view.pMax]; } canvas.addEventListener('click', (e) => { if (!view) return; const [t2, p2] = eventPoint(e); if (Math.abs(t2) > Math.PI) return; // the clicked orbit lights up, and stays lit until the mouse moves away // (otherwise the orbit that was under the mouse stays lit, and dims the // new one to almost nothing) clickAt = [e.clientX, e.clientY]; // listening: a click on an orbit's dots plays it, and a click elsewhere // starts a new orbit and plays that const near = listener && orbitNear(t2, p2, 1); if (near) { selected = near; setHovered(near); listener.play(near.start); return; } setAuto(false); const o = addOrbit(t2, p2); if (!o) return; setHovered(o); if (listener) { selected = o; listener.play(o.start); } }); // the orbit with a dot in the nearest cell within r cells of (t2, p2) function orbitNear(t2, p2, r = 3) { if (Math.abs(t2) > gridThetaMax + 0.1 || Math.abs(p2) > gridPMax * 1.05) return null; const c0 = cellOf(t2, p2); const i0 = c0 % gx; const j0 = (c0 - i0) / gx; let best = null; let bestD = Infinity; for (let dj = -r; dj <= r; dj++) { for (let di = -r; di <= r; di++) { const i = i0 + di; const j = j0 + dj; if (i < 0 || i >= gx || j < 0 || j >= gy) continue; const o = owner[j * gx + i]; const d = di * di + dj * dj; if (o && d < bestD) { best = o; bestD = d; } } } return best; } let hoverFrame = null; function setHovered(o) { if (o === hovered) return; hovered = o; if (hoverFrame === null) { hoverFrame = requestAnimationFrame(() => { hoverFrame = null; draw(); }); } } // where the last click was, in client pixels, until the mouse leaves it let clickAt = null; canvas.addEventListener('mousemove', (e) => { if (!view) return; if (clickAt && Math.hypot(e.clientX - clickAt[0], e.clientY - clickAt[1]) < 12) return; clickAt = null; setHovered(orbitNear(...eventPoint(e))); }); canvas.addEventListener('mouseleave', () => { clickAt = null; setHovered(null); }); autoButton.addEventListener('click', () => { stopGpu(); setAuto(!auto); }); gpuButton.addEventListener('click', () => { if (gpuRun) stopGpu(); else if (gpu) startGpu(); }); function reset() { setAuto(false); stopGpu(); orbits = []; orbitCount = 0; covered = new Uint8Array(gx * gy); owner = new Array(gx * gy).fill(null); hovered = null; selected = null; listener?.clear(); sizeGrid(); layerDirty = true; draw(); } slider.value = H; output.textContent = H.toFixed(1); sizeGrid(); slider.addEventListener('input', () => { H = Number(slider.value); output.textContent = H.toFixed(1); reset(); }); if (damping) { const bSlider = document.getElementById(`${id}-damping`); const bOutput = document.getElementById(`${id}-damping-value`); params.b = DAMPED_B; bSlider.value = params.b; bOutput.textContent = params.b.toFixed(4); bSlider.addEventListener('input', () => { params.b = Number(bSlider.value); bOutput.textContent = params.b.toFixed(4); reset(); }); } function pause() { active = false; cancelAnimationFrame(rafId); rafId = null; listener?.stop(); } const drawAll = () => { draw(); listener?.draw(); }; return { draw: drawAll, pause, reset }; } // Page 15: listening to orbits. The explorer of page 14, plus sound: a click // on an orbit plays it, and a click on an empty spot starts a new orbit there // and plays that. The sound is one coordinate of the orbit (or the lower bob's // horizontal position) as a waveform, with the motion sped up by the // Frequency slider's factor so that it is audible. For scale: with the // default masses and lengths the two small-swing normal modes have // omega^2 = (g / L)(2 -/+ sqrt 2), or 0.38 and 0.92 Hz, so x400 puts them at // 150 and 370 Hz. // // For the sound the orbit is integrated on its own, from its first point on // the section, with gaussStep at EXPLORER_STEP; samples between steps come // from cubic Hermite interpolation with the rates at both ends (as in // sectionCrossing). The waveform is centered and scaled by the range it // covers over a warm-up of LISTEN_WARMUP steps, and the scale shrinks if it // later goes further. It is made in chunks of LISTEN_CHUNK samples, scheduled // up to LISTEN_AHEAD seconds ahead of playback, so the slider and the signal // menu take effect within that time. // // The spectrogram is the AnalyserNode's spectrum of what is playing (before // the volume), a column every 1/60 s, linear in frequency up to LISTEN_FMAX. const LISTEN_WARMUP = 4000; const LISTEN_CHUNK = 2048; const LISTEN_AHEAD = 0.25; const LISTEN_VOLUME = 0.3; const LISTEN_FFT = 8192; const LISTEN_FMAX = 2000; const LISTEN_COLUMNS = 480; const LISTEN_COLUMN_MS = 1000 / 60; // the menu's signals, from the state (theta1, theta2, p1, p2) const listenSignals = { theta1: (params, z) => wrapAngle(z[0]), theta2: (params, z) => wrapAngle(z[1]), p1: (params, z) => z[2], p2: (params, z) => z[3], x: ({ L1, L2 }, z) => L1 * Math.sin(z[0]) + L2 * Math.sin(z[1]), }; // The orbit from state start as a waveform: next(out, speed) fills out with // the following samples, at speed simulated seconds per second of sound. function orbitWaveform(params, start, signalName, sampleRate) { const h = EXPLORER_STEP; const z = start.slice(); const k = [0, 0, 0, 0, 0, 0, 0, 0]; const a = [0, 0, 0, 0]; // the state at the last step, and its rates const fa = [0, 0, 0, 0]; const fb = [0, 0, 0, 0]; // the rates at z const y = [0, 0, 0, 0]; doubleRates(params, z[0], z[1], z[2], z[3], fb); for (let i = 0; i < 4; i++) k[i] = k[i + 4] = fb[i]; let tau = 0; // simulated time since the last step let signal = null; let mid = 0; let dev = 1; function step() { for (let i = 0; i < 4; i++) { a[i] = z[i]; fa[i] = fb[i]; } gaussStep(params, z, h, k); doubleRates(params, z[0], z[1], z[2], z[3], fb); } // the state at fraction s of the last step, into y function interpolate(s) { const s2 = s * s; const s3 = s2 * s; for (let i = 0; i < 4; i++) { const b = i < 2 ? a[i] + wrapAngle(z[i] - a[i]) : z[i]; y[i] = (2 * s3 - 3 * s2 + 1) * a[i] + (s3 - 2 * s2 + s) * h * fa[i] + (3 * s2 - 2 * s3) * b + (s3 - s2) * h * fb[i]; } } // the signal's range over the warm-up, on a copy of the current state function setSignal(name) { signal = listenSignals[name]; const zc = z.slice(); const kc = k.slice(); let lo = Infinity; let hi = -Infinity; for (let n = 0; n < LISTEN_WARMUP; n++) { gaussStep(params, zc, h, kc); const v = signal(params, zc); lo = Math.min(lo, v); hi = Math.max(hi, v); } mid = 0.5 * (lo + hi); dev = Math.max(1e-6, 0.5 * (hi - lo)); } function next(out, speed) { const dt = speed / sampleRate; for (let n = 0; n < out.length; n++) { tau += dt; while (tau >= h) { step(); tau -= h; } interpolate(tau / h); const v = signal(params, y) - mid; dev = Math.max(dev, Math.abs(v)); out[n] = (0.9 * v) / dev; } } step(); setSignal(signalName); return { next, setSignal }; } // Sound and spectrogram for the listening page; play(start) plays the orbit // from state start, and onChange is called when playback starts or stops. function createListener({ id, params, onChange }) { const canvas = document.getElementById(`${id}-spectrogram`); const button = document.getElementById(`${id}-play`); const signalMenu = document.getElementById(`${id}-signal`); const speedSlider = document.getElementById(`${id}-speed`); const speedOutput = document.getElementById(`${id}-speed-value`); let audio = null; // set up on the first play, which comes from a click let start = null; let wave = null; let playing = false; let timer = null; let nextTime = 0; let sources = []; let rafId = null; let lastColumn = 0; // the slider runs over x100 to x2000, evenly in log const speed = () => 100 * 20 ** Number(speedSlider.value); speedSlider.value = Math.log(4) / Math.log(20); function showSpeed() { const s = speed(); speedOutput.textContent = `×${s < 1000 ? Math.round(s / 10) * 10 : Math.round(s / 100) * 100}`; } showSpeed(); speedSlider.addEventListener('input', showSpeed); signalMenu.addEventListener('change', () => wave?.setSignal(signalMenu.value)); function setupAudio() { const ctx = new AudioContext(); const analyser = ctx.createAnalyser(); analyser.fftSize = LISTEN_FFT; analyser.smoothingTimeConstant = 0; analyser.minDecibels = -100; analyser.maxDecibels = -20; const gain = ctx.createGain(); gain.gain.value = 0; analyser.connect(gain); gain.connect(ctx.destination); const rows = Math.round(LISTEN_FMAX / (ctx.sampleRate / LISTEN_FFT)); const spec = document.createElement('canvas'); spec.width = LISTEN_COLUMNS; spec.height = rows; const sctx = spec.getContext('2d'); // colors from the background through the accent to the text color const hex = (name) => [1, 3, 5].map((i) => parseInt(color(name).slice(i, i + 2), 16)); const stops = [hex('--bg'), hex('--accent'), hex('--fg')]; const lut = new Uint8Array(256 * 3); for (let v = 0; v < 256; v++) { const t = (2 * v) / 255; const [c0, c1] = t < 1 ? [stops[0], stops[1]] : [stops[1], stops[2]]; const f = t < 1 ? t : t - 1; for (let c = 0; c < 3; c++) lut[3 * v + c] = Math.round((1 - f) * c0[c] + f * c1[c]); } audio = { ctx, analyser, gain, rows, spec, sctx, lut, bytes: new Uint8Array(analyser.frequencyBinCount), column: sctx.createImageData(1, rows) }; clearSpectrogram(); } function clearSpectrogram() { if (!audio) return; audio.sctx.fillStyle = color('--bg'); audio.sctx.fillRect(0, 0, LISTEN_COLUMNS, audio.rows); } // make and queue chunks up to LISTEN_AHEAD seconds ahead function schedule() { const { ctx, analyser } = audio; if (nextTime < ctx.currentTime + 0.01) nextTime = ctx.currentTime + 0.05; // fell behind while (nextTime < ctx.currentTime + LISTEN_AHEAD) { const buffer = ctx.createBuffer(1, LISTEN_CHUNK, ctx.sampleRate); wave.next(buffer.getChannelData(0), speed()); const src = ctx.createBufferSource(); src.buffer = buffer; src.connect(analyser); src.start(nextTime); src.onended = () => { sources = sources.filter((s) => s !== src); }; sources.push(src); nextTime += LISTEN_CHUNK / ctx.sampleRate; } } // fade out what is queued over 30 ms function silence() { const { ctx, gain } = audio; const now = ctx.currentTime; gain.gain.cancelScheduledValues(now); gain.gain.setValueAtTime(gain.gain.value, now); gain.gain.linearRampToValueAtTime(0, now + 0.03); for (const src of sources) src.stop(now + 0.035); sources = []; } function play(s) { if (s) start = s; if (!start) return; if (!audio) setupAudio(); const { ctx, gain } = audio; ctx.resume(); clearInterval(timer); silence(); wave = orbitWaveform(params, start, signalMenu.value, ctx.sampleRate); nextTime = ctx.currentTime + 0.05; gain.gain.setValueAtTime(0, nextTime); gain.gain.linearRampToValueAtTime(LISTEN_VOLUME, nextTime + 0.03); schedule(); timer = setInterval(schedule, 40); playing = true; button.disabled = false; button.textContent = 'Stop'; lastColumn = performance.now(); if (rafId === null) rafId = requestAnimationFrame(loop); onChange(); } function stop() { if (!playing) return; playing = false; clearInterval(timer); silence(); button.textContent = 'Play'; onChange(); } // stop, and forget the orbit (its energy level is gone) function clear() { stop(); start = null; wave = null; button.disabled = true; clearSpectrogram(); draw(); } // shift the spectrogram left and add the current spectrum on the right function addColumn() { const { analyser, rows, spec, sctx, lut, bytes, column } = audio; analyser.getByteFrequencyData(bytes); sctx.drawImage(spec, -1, 0); for (let r = 0; r < rows; r++) { const v = bytes[rows - 1 - r]; column.data[4 * r] = lut[3 * v]; column.data[4 * r + 1] = lut[3 * v + 1]; column.data[4 * r + 2] = lut[3 * v + 2]; column.data[4 * r + 3] = 255; } sctx.putImageData(column, LISTEN_COLUMNS - 1, 0); } function loop() { rafId = null; if (!playing) return; const now = performance.now(); if (now - lastColumn > 200) lastColumn = now - LISTEN_COLUMN_MS; // after a stall while (now - lastColumn >= LISTEN_COLUMN_MS) { addColumn(); lastColumn += LISTEN_COLUMN_MS; } draw(); rafId = requestAnimationFrame(loop); } function draw() { if (!canvas.clientWidth) return; const { ctx, w, h } = prepare(canvas); // room on top for the Play button, and on the left for the axis const x0 = 46; const y0 = 40; const x1 = w - 4; const y1 = h - 24; const fg = color('--fg'); if (audio) { ctx.imageSmoothingEnabled = true; ctx.drawImage(audio.spec, x0, y0, x1 - x0, y1 - y0); } ctx.strokeStyle = fg; ctx.fillStyle = fg; ctx.globalAlpha = 0.5; ctx.lineWidth = 1; ctx.strokeRect(x0, y0, x1 - x0, y1 - y0); ctx.globalAlpha = 1; ctx.font = `13px ${color('--font-body')}`; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; for (let f = 0; f <= LISTEN_FMAX; f += 500) ctx.fillText(String(f), x0 - 6, y1 - (f / LISTEN_FMAX) * (y1 - y0)); ctx.textAlign = 'left'; ctx.textBaseline = 'bottom'; ctx.fillText('Hz', 4, y0 - 12); ctx.textAlign = 'right'; ctx.textBaseline = 'top'; ctx.fillText('time →', x1, y1 + 6); if (!start) { ctx.globalAlpha = 0.6; ctx.font = `16px ${color('--font-body')}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText('Click an orbit to listen to it', (x0 + x1) / 2, (y0 + y1) / 2); ctx.globalAlpha = 1; } } button.addEventListener('click', () => { if (playing) stop(); else play(); }); return { play, stop, clear, draw, get playing() { return playing; }, }; } const doubleExplorer = createExplorer({ id: 'double-explorer' }); const doubleListen = createExplorer({ id: 'double-listen', listen: true }); // Page 16: listening to orbits with damping. The default b gives a decay time // of very roughly 1000 simulated seconds, a few seconds of sound at x400. const DAMPED_B = 0.002; const doubleDamped = createExplorer({ id: 'double-damped', listen: true, damping: true }); const sims = { spring, energy, phase, pendulum, 'pendulum-phase': pendulumPhase, liouville, 'liouville-pendulum': liouvillePendulum, damped, double: doublePendulum, 'double-phase': doublePhase, 'double-poincare': doublePoincare, 'double-dispersion': doubleDispersion, 'double-explorer': doubleExplorer, 'double-listen': doubleListen, 'double-damped': doubleDamped, }; // Reset buttons next to Start: back to the initial state, with trails cleared. const resets = { 'pendulum-phase': resetPendulumPhase, }; for (const [name, sim] of Object.entries(sims)) { document.getElementById(`${name}-reset`).addEventListener('click', resets[name] ?? sim.reset); } const pages = [...document.querySelectorAll('.page')]; const pageIds = pages.map((p) => p.id); const navPrev = document.getElementById('nav-prev'); const navNext = document.getElementById('nav-next'); const navPos = document.getElementById('nav-pos'); // Flatiron logo on every slide. pages.forEach((p) => { const img = document.createElement('img'); img.className = 'logo'; img.alt = 'Flatiron Institute'; img.src = 'assets/flatiron-logo.png'; p.appendChild(img); }); // Table of contents: the slide counter in the nav bar opens a list of slide // titles; T toggles it and Escape closes it. const toc = document.getElementById('toc'); const tocList = document.getElementById('toc-list'); pages.forEach((p) => { const li = document.createElement('li'); const b = document.createElement('button'); b.textContent = p.querySelector('h1, h2').textContent; b.addEventListener('click', () => { location.hash = p.id; setTocOpen(false); }); li.appendChild(b); tocList.appendChild(li); }); function setTocOpen(open) { toc.hidden = !open; navPos.setAttribute('aria-expanded', String(open)); if (open) tocList.querySelector('.current')?.scrollIntoView({ block: 'nearest' }); } navPos.addEventListener('click', (e) => { e.stopPropagation(); setTocOpen(toc.hidden); }); document.addEventListener('click', (e) => { if (!toc.hidden && !toc.contains(e.target)) setTocOpen(false); }); function show(id) { pages.forEach((p) => p.classList.toggle('active', p.id === id)); const i = pageIds.indexOf(id); const prev = pages[i - 1]; const next = pages[i + 1]; // label each button with a one-word hint of where it goes navPrev.textContent = prev ? `← ${prev.dataset.hint}` : '←'; navNext.textContent = next ? `${next.dataset.hint} →` : '→'; navPrev.disabled = !prev; navNext.disabled = !next; navPos.textContent = `${i + 1} / ${pages.length} \u2630`; tocList.querySelectorAll('button').forEach((b, j) => b.classList.toggle('current', j === i)); for (const [name, sim] of Object.entries(sims)) { if (name === id) sim.draw(); else sim.pause(); } } // Scale the 1920 x 1080 deck to the largest size that fits, centered, and // redraw the visible diagram at the new resolution. const SLIDE_W = 1920; const SLIDE_H = 1080; const MARGIN = 16; const stage = document.querySelector('main'); const deck = document.getElementById('deck'); function fitDeck() { stage.style.bottom = `${document.querySelector('.pager').offsetHeight}px`; const w = stage.clientWidth; const h = stage.clientHeight; deckScale = Math.min((w - 2 * MARGIN) / SLIDE_W, (h - 2 * MARGIN) / SLIDE_H); deck.style.transform = `scale(${deckScale})`; deck.style.left = `${(w - SLIDE_W * deckScale) / 2}px`; deck.style.top = `${(h - SLIDE_H * deckScale) / 2}px`; const active = document.querySelector('.page.active'); if (active) sims[active.id]?.draw(); } window.addEventListener('resize', fitDeck); // Canvas text uses the bundled fonts, so redraw once they have loaded. document.fonts?.ready.then(fitDeck); document.querySelectorAll('[data-tex]').forEach((el) => { katex.render(el.dataset.tex, el, { displayMode: el.tagName === 'DIV' }); }); document.querySelectorAll('[data-solution]').forEach((toggle) => { toggle.addEventListener('click', () => { const solution = document.getElementById(toggle.dataset.solution); solution.hidden = !solution.hidden; toggle.textContent = solution.hidden ? 'Show solution' : 'Hide solution'; }); }); // Pages that start centered: revealing splits them into text and diagram // panels and labels the diagram. const revealLabels = { spring: ['m', 'k', 'q', 'F', 'p'], energy: [], // stays unlabeled, so the bars are the only thing moving pendulum: ['m', 'L', 'theta', 'p', 'g'], double: ['m', 'L', 'theta', 'g'], }; document.querySelectorAll('[data-reveal]').forEach((button) => { button.addEventListener('click', () => { const id = button.dataset.reveal; const section = document.getElementById(id); button.hidden = true; section.classList.add('split'); section.querySelector('.text').hidden = false; sims[id].setLabels(revealLabels[id]); }); }); // Replay of how recipe.md was written, from app/crafted-link.js (npm run crafted-link). if (window.CRAFTED_LINK) { const link = document.getElementById('crafted-link'); link.href = window.CRAFTED_LINK; link.hidden = false; } // The current page lives in the URL hash, so reloading stays put. function showFromHash() { const id = location.hash.slice(1); show(document.getElementById(id)?.classList.contains('page') ? id : 'landing'); window.scrollTo(0, 0); } window.addEventListener('hashchange', showFromHash); fitDeck(); showFromHash(); document.querySelectorAll('[data-goto]').forEach((el) => { el.addEventListener('click', () => { location.hash = el.dataset.goto; }); }); function goToIndex(i) { location.hash = pageIds[Math.max(0, Math.min(pageIds.length - 1, i))]; } function currentIndex() { return pageIds.indexOf(document.querySelector('.page.active').id); } navPrev.addEventListener('click', () => goToIndex(currentIndex() - 1)); navNext.addEventListener('click', () => goToIndex(currentIndex() + 1)); document.addEventListener('keydown', (e) => { if (e.altKey || e.ctrlKey || e.metaKey) return; if (e.target.closest?.('input, select, textarea')) return; // arrow keys belong to the control if (e.key === 't' || e.key === 'T') { setTocOpen(toc.hidden); return; } if (e.key === 'Escape' && !toc.hidden) { setTocOpen(false); return; } const target = { ArrowLeft: currentIndex() - 1, ArrowRight: currentIndex() + 1, Home: 0, End: pageIds.length - 1, }[e.key]; if (target === undefined) return; e.preventDefault(); goToIndex(target); });