// Release states and the offset that makes the pendulums separate at a chosen time. import { DoublePendulum, type PendulumConfig } from "../../physics/doublePendulum.ts"; export const DT = 0.002; // simulation step (sim seconds), shared with the piece /** Released from rest at angles (θ1, θ2), with the outer arm offset by `d`. */ export function released(cfg: PendulumConfig, th1: number, th2: number, d: number): DoublePendulum { const p = new DoublePendulum(cfg); p.controlled = false; p.y[0] = th1; p.y[1] = th2 + d; p.y[2] = 0; p.y[3] = 0; return p; } /** Bottom-bob position. */ export function bob(cfg: PendulumConfig, y: ArrayLike): [number, number] { return [cfg.l1 * Math.sin(y[0]) + cfg.l2 * Math.sin(y[1]), cfg.l1 * Math.cos(y[0]) + cfg.l2 * Math.cos(y[1])]; } /** Sim time at which two pendulums offset by ±d/2 first have their bobs `thr` apart (Infinity if not by maxT). */ function separationTime(cfg: PendulumConfig, th1: number, th2: number, d: number, thr: number, maxT: number): number { const a = released(cfg, th1, th2, -d / 2); const b = released(cfg, th1, th2, d / 2); for (let t = 0; t < maxT; t += DT) { a.step(DT); b.step(DT); const [ax, ay] = bob(cfg, a.y), [bx, by] = bob(cfg, b.y); if (Math.hypot(ax - bx, ay - by) > thr) return t + DT; } return Infinity; } /** * Total offset (between the two outermost pendulums) whose bobs separate by `thr` at sim time * `T`, found by bisection on log(offset). Separation in a chaotic system depends on the exact * state, so this is calibrated for each release. Offsets below ~1e-15 rad are lost to rounding, * which bounds how late separation can be. */ export function offsetForSeparation(cfg: PendulumConfig, th1: number, th2: number, T: number, thr: number): { offset: number; separatesAt: number } { const maxT = 3 * T + 10; let lo = 1e-15, hi = 1e-2; // separation happens late at lo, early at hi if (separationTime(cfg, th1, th2, lo, thr, maxT) <= T) return { offset: lo, separatesAt: separationTime(cfg, th1, th2, lo, thr, maxT) }; if (separationTime(cfg, th1, th2, hi, thr, maxT) >= T) return { offset: hi, separatesAt: separationTime(cfg, th1, th2, hi, thr, maxT) }; for (let i = 0; i < 16; i++) { const mid = Math.sqrt(lo * hi); if (separationTime(cfg, th1, th2, mid, thr, maxT) > T) lo = mid; else hi = mid; } const offset = Math.sqrt(lo * hi); return { offset, separatesAt: separationTime(cfg, th1, th2, offset, thr, maxT) }; }