diff --git a/docs/UI.md b/docs/UI.md index f39ef55..db24cf5 100644 --- a/docs/UI.md +++ b/docs/UI.md @@ -7,7 +7,7 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep - **Flowing** animates the projected orbits and the black hole's accretion disk. Pause or resume from the map toolbar. The map coasts to a visual stop, then reveals labels and moons in **Locked** mode, starting with the selected orbit. Resuming reverses that reveal. Selecting an orbit also locks the map. Reduced motion locks it immediately. - Select a star or use the orbit register. The register prioritizes failed and active jobs and supports the up/down arrow keys. The inspector includes the capture action and full snapshot history. - The first three recovery points of the selected orbit appear as moons when the map has room. Select a moon or history entry to review the snapshot and start a restore. Escape closes the console. Restore countdown and polling continue if the console closes. -- Hub connectivity is separate from backup health. Capture targets the named orbit. An incoming meteor represents a confirmed new snapshot. The source flares, the meteor spirals inward, and the core brightens and spins up before the new recovery point flashes. A failed capture pulses its source marker and shows text feedback. Rehearsals show text feedback. +- Hub connectivity is separate from backup health. Capture targets the named orbit. A running backup is a light circling its star; when it succeeds the light leaves for the black hole, and when it fails it is lost. See Orbit activity below. Rehearsals show text feedback and a ghost light. - The map shows up to 55 overview orbits and reserves one slot for inspecting an orbit beyond that limit. The register provides access to every orbit. On narrow screens the map, register, and inspector stack vertically. - **Big Screen** expands the map and keeps summary counts, motion controls, and a floating navigation dock. The map and dock spring into position within the current browser viewport. Use **Exit big screen** or Escape to return to the workspace. - Drag the active navbar item sideways and release to open the destination. The regular navbar uses text and a sliding underline. The Big Screen dock uses labeled icons and a liquid highlight. @@ -38,13 +38,26 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep - A realistic and a stylized radar look share the same trace. The radar look arrives as a wave spreading outward from the hole: each pixel picks its look from its distance to a spring-driven front, with a thin leading edge (mint going to radar, amber coming back). `look.ts` holds the spring and queues a request made mid-wave rather than reversing it. `web/blackhole-proto.html` is a standalone page for tuning the look; Vite serves it in development and the build ignores it. Add `?throttle=N` to emulate a GPU N times slower. +## Orbit activity + +What a backup is doing is shown by how a light moves, not by a drawing of a rocket. The light is a small glowing triangle that points where it is going, with a trail that follows the path it actually flew. The code is in `web/src/lib/orbitActivity.ts` (what happened), `rocket.ts` (the physics) and `trail.ts`, drawn by `RocketSprites.tsx`. + +- **Where the events come from.** The scene compares each orbit's status between polls. A click shows its own verdict until a poll that began after it has landed, so one backup is never animated twice and never flips through a stale status. A page that loads, or an orbit that appears, only sets a baseline: running orbits start circling and finished ones stay settled, so opening the page never replays history. A backup that finished between two polls still gets its outcome. +- **Queued.** The light waits docked on its star with a dim engine. +- **Running.** It circles its star, climbing and spinning up the longer it runs. +- **Success.** When the status turns completed, the light waits for a launch window, the point on its circle where its own motion already carries it round the black hole and a little inward, then departs with the velocity it has. It follows the pseudo-Newtonian pull of the black hole, `mu / (r - r_s)^2`, after a short burn that trims its angular momentum to just under the capture limit. The path curves with the orbits instead of running straight in, the speed rises all the way, and near the shadow the light reddens, dims and stretches as gravitational redshift and tidal forces would, so it is gone by the shadow's edge. The disk spins up as it feeds, then the new snapshot flashes once its confirmed entry is listed. +- **Failure.** If the hub can tell the cause (`dump_failed`, `upload_failed`), a failure before departure explodes in place; a failure while carrying the payload launches, loses power and falls back to its star. Otherwise it explodes. The star keeps its busy look until that moment and then turns red. +- **Rehearsal.** A faint dashed light circles, then lands back on its star without leaving. The result is amber, since nothing was stored. +- **Limits.** At most ten lights are drawn at once; further working orbits keep their busy ring. Reduced motion draws no lights, and every outcome shows at once. +- **Verification.** `capture-galaxy.mjs` checks the lights by `data-orbit`. The physics has unit tests that hold the properties that matter for every shell and launch phase: it always arrives, it curves, and it never slows on the way in. + ## Animation guideline - Use the installed Framer Motion API from `motion/react`. Declarative `motion` components inherit the physics spring from `MotionConfig` in `web/src/main.tsx`. Use `uiSpring` for direct controls, `gentleSpring` for reveal and layout travel, and `ambientSpring` for scene effects. The tokens in `web/src/lib/motion.ts` define stiffness, damping, mass, and rest thresholds. - Keep the element, its React key, and its MotionValues stable while a target can change. Update the scalar `animate` target, call `animate(value, nextTarget, uiSpring)` on the same MotionValue, or call `.set(nextTarget)` on a `useSpring` value. Motion automatically replaces the active animation and inherits the live value and velocity. Leave `from`, `velocity`, and fixed timing options unset for these retargets. For colors and other compound styles, spring a numeric mix amount or progress value and derive the visual property from it. - Keep `AnimatePresence` mounted and use a stable child key so a reopening element can reverse its exit. Make an exiting overlay inert and release its hit area immediately. Track direct manipulation one-to-one and seed the spring with release velocity when handing control over from an external gesture. - Keep CSS state changes immediate. Use Motion springs for visual transitions, including hover and loading feedback. Reserve repeating springs for ambient indicators and give them a static state under reduced motion. For continuous simulation, keep the path on its existing clock and spring its speed or progress. A new event can start a distinct path at its own origin. -- Use a single progress value for a staged effect. Derive the capture flare, flight, absorption, and recovery-point flash from the scene clock. If the snapshot list is still refreshing, let the impact finish and hold the flash until its confirmed snapshot arrives. +- Prefer a small physical simulation to keyframes when something travels. A rocket's position and velocity are integrated, and each state only changes which forces act on it and never resets its velocity, so every transition is continuous and any one can be interrupted by another. Drive the parameters that shape it (spin, radius, engine thrust, opacity) with springs from `motion.ts`. If the snapshot list is still refreshing, let the arrival finish and hold the flash until its confirmed snapshot arrives. - Measure the destination frame on a mode change or resize. Spring the map's center and size from its current visual rectangle, and recompute the collision layout once the frame settles. - Honor live changes to `prefers-reduced-motion`. The app applies declarative targets immediately. Imperative effects must stop and jump to the appropriate static state themselves. Verify reversals before settling, the final target, and reduced motion in a browser. diff --git a/web/scripts/capture-galaxy.mjs b/web/scripts/capture-galaxy.mjs index 3dfd01c..17c3a33 100644 --- a/web/scripts/capture-galaxy.mjs +++ b/web/scripts/capture-galaxy.mjs @@ -132,7 +132,8 @@ try { await page.getByRole("button", { name: "Capture Load test orbit 1", exact: true }).click(); await page.getByText("Snapshot secured from Load test orbit 1.", { exact: true }).waitFor(); - await page.waitForFunction(() => Number(document.querySelector(".capture-arrival").getAttribute("opacity")) > 0.1); + // The clicked orbit's rocket is on screen (rockets are marked with data-orbit; other orbits may be running too). + await page.waitForFunction(() => Number(document.querySelector('.rocket[data-orbit="orbit-0"]')?.getAttribute("opacity")) > 0.1); await page.waitForFunction(() => Number( document.querySelector("[data-vault-core]").style.getPropertyValue("--capture-absorption"), ) > 0.2); @@ -144,8 +145,10 @@ try { await page.locator("#register-orbit-1").click(); await page.getByRole("button", { name: "Capture Load test orbit 2", exact: true }).click(); await page.getByText("Capture failed for Load test orbit 2.", { exact: true }).waitFor(); - await page.waitForFunction(() => Number(document.querySelector(".capture-flare").getAttribute("opacity")) > 0.1); - assert.equal(await page.locator(".capture-arrival").getAttribute("opacity"), "0"); + await page.waitForFunction(() => Number(document.querySelector(".rocket-flare").getAttribute("opacity")) > 0.1); + // A failed backup explodes and its rocket is gone. + assert.equal(await page.evaluate(() => + [...document.querySelectorAll('.rocket[data-orbit="orbit-1"]')].filter(node => Number(node.getAttribute("opacity")) > 0).length), 0); const workspaceWidth = await frame.evaluate(element => element.getBoundingClientRect().width); await page.getByRole("button", { name: "Big screen", exact: true }).click(); diff --git a/web/scripts/galaxy.test.mjs b/web/scripts/galaxy.test.mjs index cc6cb1b..2f5c859 100644 --- a/web/scripts/galaxy.test.mjs +++ b/web/scripts/galaxy.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { capturePhases, assignOrbitSlots, orbitPose, groupSnapshots, moonPoses, trailAngle } from "../src/lib/galaxyLayout.ts"; +import { assignOrbitSlots, orbitPose, groupSnapshots, moonPoses, trailAngle } from "../src/lib/galaxyLayout.ts"; import { placeLabels } from "../src/lib/galaxyLabelLayout.ts"; test("slot identities survive reordering, insertion and removal", () => { @@ -63,21 +63,6 @@ test("labels respect screen bounds and preserve priority in a crowded scene", () assert.ok(labels[0].x >= 0 && labels[0].x + 72 <= 140); }); -test("capture flares before flight, then absorbs and highlights the snapshot", () => { - const flare = capturePhases(0.06); - assert.equal(flare.flare, 1); - assert.equal(flare.flight, 0); - assert.equal(flare.highlight, 0); - const arrival = capturePhases(0.84); - assert.equal(arrival.flight, 1); - assert.equal(arrival.absorption, 1); - assert.equal(arrival.highlight, 0); - assert.equal(capturePhases(0.94).absorption, 0); - assert.equal(capturePhases(0.94).highlight, 0); - assert.equal(capturePhases(0.97).highlight, 1); - assert.deepEqual(capturePhases(1), { flare: 0, flight: 1, absorption: 0, highlight: 0, failure: 0 }); -}); - test("the selected label searches farther when nearby orbit markers crowd it out", () => { const selected = { id: "focused", x: 140, y: 140, width: 60 }; const cluster = { x: 61, y: 61, width: 158, height: 158 }; diff --git a/web/scripts/orbitActivity.test.mjs b/web/scripts/orbitActivity.test.mjs new file mode 100644 index 0000000..2c6a74a --- /dev/null +++ b/web/scripts/orbitActivity.test.mjs @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createActivity, intentFor, observeStatuses } from "../src/lib/orbitActivity.ts"; + +const map = (entries) => new Map(Object.entries(entries)); +const run = (state, entries, causes) => observeStatuses(state, map(entries), causes ? map(causes) : undefined); + +test("the first observation is a baseline: running orbits start circling, finished ones stay settled", () => { + const state = createActivity(); + const events = run(state, { a: "running", b: "completed", c: "failed", d: "queued", e: "rehearsing", f: "idle" }); + assert.deepEqual(events, [ + { kind: "begin", id: "a", intent: "circle" }, + { kind: "begin", id: "d", intent: "pad" }, + { kind: "begin", id: "e", intent: "ghost" }, + ]); + assert.equal(state.intents.get("b"), "none"); +}); + +test("a status that has not changed produces nothing", () => { + const state = createActivity(); + run(state, { a: "running", b: "completed" }); + assert.deepEqual(run(state, { a: "running", b: "completed" }), []); +}); + +test("a running backup that completes launches, and one that fails reports its cause", () => { + const state = createActivity(); + run(state, { a: "running", b: "running", c: "running" }); + const events = run(state, { a: "completed", b: "failed", c: "failed" }, { c: "transfer" }); + assert.deepEqual(events, [ + { kind: "launch", id: "a" }, + { kind: "fail", id: "b", cause: "unknown" }, + { kind: "fail", id: "c", cause: "transfer" }, + ]); +}); + +test("queued becoming running is the same rocket changing pace, then it launches", () => { + const state = createActivity(); + run(state, { a: "queued" }); + assert.deepEqual(run(state, { a: "running" }), [{ kind: "begin", id: "a", intent: "circle" }]); + assert.deepEqual(run(state, { a: "completed" }), [{ kind: "launch", id: "a" }]); +}); + +test("a rehearsal lands instead of launching", () => { + const state = createActivity(); + run(state, { a: "rehearsing" }); + assert.deepEqual(run(state, { a: "rehearsed" }), [{ kind: "land", id: "a" }]); +}); + +test("a backup that finished between two polls still gets its outcome", () => { + const state = createActivity(); + run(state, { a: "idle", b: "failed", c: "completed", d: "completed" }); + const events = run(state, { a: "completed", b: "completed", c: "failed", d: "completed" }); + assert.deepEqual(events, [ + { kind: "launch", id: "a" }, + { kind: "launch", id: "b" }, + { kind: "fail", id: "c", cause: "unknown" }, + ]); +}); + +test("an orbit that appears later is treated like one present at load", () => { + const state = createActivity(); + run(state, { a: "completed" }); + const events = run(state, { a: "completed", b: "running", c: "completed" }); + assert.deepEqual(events, [{ kind: "begin", id: "b", intent: "circle" }]); +}); + +test("a backup that stops without a verdict, or whose orbit is deleted, lets the rocket go quietly", () => { + const state = createActivity(); + run(state, { a: "running", b: "running" }); + assert.deepEqual(run(state, { a: "idle", b: "running" }), [{ kind: "dismiss", id: "a" }]); + assert.deepEqual(run(state, { a: "idle" }), [{ kind: "dismiss", id: "b" }]); +}); + +test("intents follow the status while a backup is going", () => { + assert.equal(intentFor("queued"), "pad"); + assert.equal(intentFor("running"), "circle"); + assert.equal(intentFor("rehearsing"), "ghost"); + for (const status of ["completed", "failed", "idle", "rehearsed", "", "mystery"]) assert.equal(intentFor(status), "none"); +}); diff --git a/web/scripts/rocket.test.mjs b/web/scripts/rocket.test.mjs new file mode 100644 index 0000000..ec8f972 --- /dev/null +++ b/web/scripts/rocket.test.mjs @@ -0,0 +1,344 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + MAX_ROCKETS, SHADOW_EDGE, adoptCircle, applyActivity, createField, fieldActive, holding, infallLook, screenRadius, + starPose, stepField, +} from "../src/lib/rocket.ts"; + +const SHELLS = [[128, 0.047], [190, 0.033], [260, 0.023]]; +const DT = 1 / 60; + +function scene(radius, speed, angle, rate = 1) { + const slot = { radius, angle, speed }; + const state = { clock: 0, field: createField(), rate, slot }; + state.star = () => starPose(slot, state.clock, rate); + state.step = (seconds) => { + const events = []; + for (let i = 0; i < Math.round(seconds / DT); i++) { + state.clock += DT; + events.push(...stepField(state.field, DT, state.star)); + } + return events; + }; + state.apply = (event) => applyActivity(state.field, event, state.star(), 3); + return state; +} + +function fly(s, limit = 12) { + // Run until the rocket arrives. Returns how long it waited for its launch window, how long it flew, and how many + // degrees its path swept around the black hole. + let wait = 0; + let flight = 0; + let launched = false; + let previous = 0; + let swept = 0; + let arrived = false; + for (let i = 0; i < 60 * limit && !arrived; i++) { + const events = s.step(DT); + const r = s.field.rockets.get("a"); + if (r && r.mode === "launch") { + const angle = Math.atan2(r.y, r.x); + if (launched) swept += Math.atan2(Math.sin(angle - previous), Math.cos(angle - previous)); + launched = true; + previous = angle; + flight += DT; + } else if (!launched) wait += DT; + if (events.some((e) => e.kind === "arrive")) arrived = true; + } + return { arrived, wait, flight, sweep: (Math.abs(swept) * 180) / Math.PI }; +} + +test("every launch, from every shell and phase of the circle, spirals in and reaches the shadow", () => { + const sweeps = []; + for (const [radius, speed] of SHELLS) { + for (const rate of [0, 1]) { + for (let k = 0; k < 12; k++) { + const s = scene(radius, speed, (k / 12) * Math.PI * 2, rate); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "launch", id: "a" }); + const result = fly(s); + const label = `shell ${radius} phase ${k} rate ${rate}`; + assert.ok(result.arrived, `${label} never arrived`); + assert.ok(result.wait < 3.05, `${label} waited ${result.wait}`); + assert.ok(result.flight > 1 && result.flight < 4.5, `${label} flew for ${result.flight}`); + // The path follows the momentum of the circle round the black hole: it curves, it does not run straight in. + assert.ok(result.sweep > 50 && result.sweep < 520, `${label} swept ${result.sweep} degrees`); + sweeps.push(result.sweep); + assert.equal(s.field.rockets.size, 0); + } + } + } + sweeps.sort((x, y) => x - y); + assert.ok(sweeps[Math.floor(sweeps.length / 2)] > 120, `median sweep ${sweeps[Math.floor(sweeps.length / 2)]}`); +}); + +test("a launch spirals the way the orbits already go, never against them", () => { + for (let k = 0; k < 12; k++) { + const s = scene(190, 0.033, (k / 12) * Math.PI * 2); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "launch", id: "a" }); + let angular = 0; + for (let i = 0; i < 60 * 8; i++) { + s.step(DT); + const r = s.field.rockets.get("a"); + if (r?.mode === "launch") angular += (r.x * r.vy - r.y * r.vx) / (r.x * r.x + r.y * r.y) * DT; + } + assert.ok(angular > 0, `phase ${k} went round the wrong way`); + } +}); + +test("no launch ever slows down on its way in, from any shell, phase or map speed", () => { + for (const [radius, speed] of SHELLS) { + for (const rate of [0, 1]) { + for (let k = 0; k < 12; k++) { + const s = scene(radius, speed, (k / 12) * Math.PI * 2, rate); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "launch", id: "a" }); + let launchedAt; + let peak = 0; + for (let i = 0; i < 60 * 10; i++) { + const events = s.step(DT); + const r = s.field.rockets.get("a"); + if (r?.mode === "launch") { + launchedAt ??= i * DT; + if (i * DT - launchedAt > 1) { + const v = Math.hypot(r.vx, r.vy); + assert.ok(v >= peak * 0.97, `shell ${radius} phase ${k} rate ${rate} slowed from ${peak} to ${v}`); + peak = Math.max(peak, v); + } + } + if (events.some((e) => e.kind === "arrive")) break; + } + } + } + } +}); + +test("the rocket speeds up as it falls toward the black hole", () => { + const s = scene(190, 0.033, 1.0); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(4); + s.apply({ kind: "launch", id: "a" }); + const samples = []; + let launchedAt; + for (let i = 0; i < 60 * 8; i++) { + const events = s.step(DT); + const r = s.field.rockets.get("a"); + if (r?.mode === "launch") { + launchedAt ??= i * DT; + samples.push({ t: i * DT - launchedAt, radius: screenRadius(r.x, r.y), speed: Math.hypot(r.vx, r.vy) }); + } + if (events.some((e) => e.kind === "arrive")) break; + } + // After the engine burn the speed rises monotonically all the way in, with only numerical slack. + const coast = samples.filter((p) => p.t > 0.9); + for (let i = 1; i < coast.length; i++) assert.ok(coast[i].speed >= coast[i - 1].speed * 0.99, `slowed at t=${coast[i].t}`); + const far = samples.find((p) => p.radius < 130).speed; + const near = samples.find((p) => p.radius < 50).speed; + assert.ok(near > 1.6 * far, `speed ${far} far, ${near} near`); + assert.ok(Math.max(...samples.map((p) => p.speed)) > 4 * samples[0].speed); +}); + +test("light from a falling rocket is redshifted and dims to nothing by the shadow edge", () => { + let previous = infallLook(200); + assert.equal(previous.alpha, 1); + assert.equal(previous.stretch, 1); + for (let radius = 200; radius >= SHADOW_EDGE; radius -= 2) { + const look = infallLook(radius); + assert.ok(look.alpha <= previous.alpha + 1e-12 && look.stretch >= previous.stretch - 1e-12 && look.red >= previous.red - 1e-12); + previous = look; + } + assert.ok(infallLook(SHADOW_EDGE + 2).alpha < 0.01); + assert.ok(infallLook(SHADOW_EDGE + 2).stretch > 3); +}); + +test("a rocket circling its star stays close to it and spins up", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + let last = 0; + for (let i = 0; i < 60 * 30; i++) { + s.step(DT); + const r = s.field.rockets.get("a"); + const star = s.star(); + assert.ok(Math.hypot(r.x - star.x, r.y - star.y) <= 20); + if (i > 60) { + assert.ok(r.omega.value >= last - 0.02, "angular speed should not fall while circling"); + last = r.omega.value; + } + } + assert.ok(last > 4 && last < 5.5, `final spin ${last}`); +}); + +test("a queued rocket waits on the pad, docked on its star", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "pad" }); + s.step(2.5); + const r = s.field.rockets.get("a"); + const star = s.star(); + assert.ok(Math.hypot(r.x - star.x, r.y - star.y) < 1); + assert.ok(r.alpha.value > 0.95); +}); + +test("leaving the circle keeps the velocity the rocket had, so the departure is seamless", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3.3); + s.apply({ kind: "launch", id: "a" }); + const r = s.field.rockets.get("a"); + assert.equal(r.pendingLaunch, true, "it should wait for a launch window while circling"); + assert.equal(r.mode, "circle"); + let before; + for (let i = 0; i < 60 * 4 && r.mode === "circle"; i++) { + before = { vx: r.vx, vy: r.vy }; + s.step(DT); + } + assert.equal(r.mode, "launch"); + // The speed changes by what one frame of gravity and engine can give, with no jump at the switch. + assert.ok(Math.hypot(r.vx - before.vx, r.vy - before.vy) < 15, "velocity jumped when the rocket left the circle"); +}); + +test("a launch is released in a window where its own motion already carries it round the hole and a little inward", () => { + const s = scene(190, 0.033, 1.1); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "launch", id: "a" }); + const r = s.field.rockets.get("a"); + for (let i = 0; i < 60 * 4 && r.mode === "circle"; i++) s.step(DT); + const rr = Math.hypot(r.x, r.y); + const speed = Math.hypot(r.vx, r.vy); + const inward = -(r.x * r.vx + r.y * r.vy) / (rr * speed); + const prograde = (r.x * r.vy - r.y * r.vx) / (rr * speed); + assert.ok(prograde > 0.8, `prograde ${prograde}`); + assert.ok(inward > 0.05 && inward < 0.6, `inward ${inward}`); +}); + +test("a new run interrupts a flight and takes over exactly where the rocket is", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "launch", id: "a" }); + s.step(0.5); + const r = s.field.rockets.get("a"); + const before = { x: r.x, y: r.y, vx: r.vx, vy: r.vy }; + s.apply({ kind: "begin", id: "a", intent: "circle" }); + assert.equal(r.mode, "circle"); + // The circling controller reproduces the position and velocity the rocket had. + const star = s.star(); + const cos = Math.cos(r.phi); + const sin = Math.sin(r.phi); + const rho = r.radius.value; + assert.ok(Math.abs(star.x + rho * cos - before.x) < 1e-9 && Math.abs(star.y + rho * sin - before.y) < 1e-9); + assert.ok(Math.abs(star.vx + r.radius.velocity * cos - rho * r.omega.value * sin - before.vx) < 1e-6); + assert.ok(Math.abs(star.vy + r.radius.velocity * sin + rho * r.omega.value * cos - before.vy) < 1e-6); +}); + +test("adopting a circle from a stationary rocket on top of its star is safe", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "pad" }); + const r = s.field.rockets.get("a"); + adoptCircle(r, s.star()); + assert.equal(r.radius.value, 0); + assert.ok(Number.isFinite(r.phi)); +}); + +test("a failure before departure explodes in place and leaves debris that dies away", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + const events = []; + s.apply({ kind: "fail", id: "a", cause: "prepare" }); + assert.equal(s.field.rockets.has("a"), false); + assert.equal(s.field.debris.length, 12); + events.push(...s.step(DT)); + assert.ok(events.some((e) => e.kind === "boom" && e.id === "a")); + assert.ok(s.field.flares.get("a").value > 0.5); + s.step(2); + assert.equal(s.field.debris.length, 0); + assert.equal(s.field.flares.size, 0); + assert.equal(fieldActive(s.field), false); +}); + +test("a failure during transfer launches, loses power, and falls back to its star", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "fail", id: "a", cause: "transfer" }); + const events = []; + let farthest = 0; + const start = screenRadius(s.field.rockets.get("a").x, s.field.rockets.get("a").y); + for (let i = 0; i < 60 * 6; i++) { + events.push(...s.step(DT)); + const r = s.field.rockets.get("a"); + if (r) farthest = Math.max(farthest, Math.abs(screenRadius(r.x, r.y) - start)); + } + assert.ok(events.some((e) => e.kind === "impact"), "should come down on its star"); + assert.ok(events.some((e) => e.kind === "boom"), "the impact flares the star"); + assert.equal(events.some((e) => e.kind === "arrive"), false, "a failed backup never reaches the black hole"); + assert.ok(farthest > 8, `it should actually climb before failing, climbed ${farthest}`); + assert.equal(s.field.rockets.size, 0); +}); + +test("a rehearsal lands back on its star without reaching the black hole", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "ghost" }); + s.step(3); + assert.ok(s.field.rockets.get("a").alpha.value < 0.6, "a rehearsal rocket is a faint ghost"); + s.apply({ kind: "land", id: "a" }); + const events = s.step(4); + assert.ok(events.some((e) => e.kind === "landed")); + assert.equal(s.field.rockets.size, 0); +}); + +test("the black hole feeds while a rocket falls in and settles afterwards", () => { + const s = scene(190, 0.033, 1); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + s.apply({ kind: "launch", id: "a" }); + let peak = 0; + for (let i = 0; i < 60 * 2; i++) { + s.step(DT); + peak = Math.max(peak, s.field.absorption.value); + } + assert.ok(peak > 0.4, `absorption peaked at ${peak}`); + s.step(5); + assert.ok(s.field.absorption.value < 0.03); + assert.equal(fieldActive(s.field), false); +}); + +test("a star keeps looking busy while its outcome is still playing out", () => { + const s = scene(190, 0.033, 1); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + s.step(3); + assert.equal(holding(s.field, "a"), false); + s.apply({ kind: "launch", id: "a" }); + assert.equal(holding(s.field, "a"), true); + s.step(3); + assert.equal(holding(s.field, "a"), false); +}); + +test("at most ten rockets fly at once and an eleventh request is declined", () => { + const s = scene(190, 0.033, 0.4); + for (let i = 0; i < MAX_ROCKETS; i++) assert.equal(applyActivity(s.field, { kind: "begin", id: `o${i}`, intent: "circle" }, s.star(), i + 1), true); + assert.equal(applyActivity(s.field, { kind: "begin", id: "extra", intent: "circle" }, s.star(), 99), false); + assert.equal(s.field.rockets.size, MAX_ROCKETS); +}); + +test("an outcome for an orbit that was never seen working still plays from its star", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "launch", id: "a" }); + const events = s.step(3); + assert.ok(events.some((e) => e.kind === "arrive")); + const t = scene(190, 0.033, 0.4); + t.apply({ kind: "fail", id: "a", cause: "unknown" }); + assert.equal(t.field.debris.length, 12); +}); + +test("a rocket whose orbit has disappeared is removed", () => { + const s = scene(190, 0.033, 0.4); + s.apply({ kind: "begin", id: "a", intent: "circle" }); + stepField(s.field, DT, () => undefined); + assert.equal(s.field.rockets.size, 0); +}); diff --git a/web/scripts/trail.test.mjs b/web/scripts/trail.test.mjs new file mode 100644 index 0000000..71f6048 --- /dev/null +++ b/web/scripts/trail.test.mjs @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { TRAIL_JUMP, TRAIL_MAX_POINTS, TRAIL_SECONDS, advanceTrail, smoothPath, trailLength } from "../src/lib/trail.ts"; + +const DT = 1 / 60; + +function fly(path, seconds, start) { + let trail = start; + for (let i = 0; i < Math.round(seconds / DT); i++) { + const p = path(i * DT); + trail = advanceTrail(trail, "a", p.x, p.y, DT); + } + return trail; +} + +test("the trail is the path that was flown: points on a circle stay on that circle", () => { + const radius = 40; + const trail = fly((t) => ({ x: radius * Math.cos(2 * t), y: radius * Math.sin(2 * t) }), 3); + assert.ok(trail.points.length > 10); + for (const p of trail.points) assert.ok(Math.abs(Math.hypot(p.x, p.y) - radius) < 1e-6); +}); + +test("a curved path gives a curved trail, not a straight one", () => { + const trail = fly((t) => ({ x: 60 * Math.cos(1.6 * t), y: 60 * Math.sin(1.6 * t) }), 3); + const [first] = trail.points; + const last = trail.points.at(-1); + const chord = Math.hypot(last.x - first.x, last.y - first.y); + assert.ok(trailLength(trail.points) > chord * 1.01, "the trail must bend away from its chord"); + // The middle of the trail lies off the straight line between its ends. + const mid = trail.points[Math.floor(trail.points.length / 2)]; + const offLine = Math.abs((last.x - first.x) * (first.y - mid.y) - (first.x - mid.x) * (last.y - first.y)) / chord; + assert.ok(offLine > 1, `middle only ${offLine} off the chord`); +}); + +test("a faster rocket leaves a longer trail", () => { + const slow = fly((t) => ({ x: 30 * t, y: 0 }), 2); + const fast = fly((t) => ({ x: 150 * t, y: 0 }), 2); + assert.ok(trailLength(fast.points) > 3 * trailLength(slow.points)); +}); + +test("the trail forgets what is older than its window and never grows without bound", () => { + const trail = fly((t) => ({ x: 100 * t, y: 0 }), 5); + assert.ok(trail.clock - trail.points[0].t <= TRAIL_SECONDS + DT); + assert.ok(trail.points.length <= TRAIL_MAX_POINTS); +}); + +test("a rocket that is not moving leaves no trail to draw", () => { + const trail = fly(() => ({ x: 10, y: 10 }), 2); + assert.equal(trail.points.length, 1); + assert.equal(trailLength(trail.points), 0); +}); + +test("a new rocket, or a jump too big to be motion, starts a new trail", () => { + let trail = fly((t) => ({ x: 40 * t, y: 0 }), 1); + const before = trail.points.length; + assert.ok(before > 3); + trail = advanceTrail(trail, "b", 5, 5, DT); + assert.equal(trail.id, "b"); + assert.equal(trail.points.length, 1); + trail = fly((t) => ({ x: 40 * t, y: 0 }), 0.5, trail); + const jumped = advanceTrail(trail, "b", trail.points.at(-1).x + TRAIL_JUMP + 5, 0, DT); + assert.equal(jumped.points.length, 1); +}); + +test("the smooth path starts at the oldest point, ends at the newest, and rounds the corners between", () => { + assert.equal(smoothPath([]), ""); + assert.equal(smoothPath([{ x: 1, y: 2 }]), ""); + assert.equal(smoothPath([{ x: 0, y: 0 }, { x: 10, y: 0 }]), "M0.00 0.00L10.00 0.00"); + const d = smoothPath([{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }, { x: 20, y: 10 }]); + assert.ok(d.startsWith("M0.00 0.00") && d.endsWith("L20.00 10.00")); + assert.equal((d.match(/Q/g) ?? []).length, 2, "one quadratic segment per interior point"); +}); diff --git a/web/src/App.tsx b/web/src/App.tsx index 34b37f9..1111fda 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { AnimatePresence, useMotionValue } from "motion/react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { - abortReconstitute, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute, + abortReconstitute, fetchCaptureJobs, fetchHealth, fetchOrbits, fetchSnapshots, pollReconstitute, enqueueCapture, runOrbit, startReconstitute, type Orbit, } from "./api"; import { OrbitInspector, OrbitRegister, TelemetryStrip } from "./components/hud/DiegeticHUD"; @@ -21,6 +21,7 @@ import { SnapshotSheet } from "./components/vault/SnapshotSheet"; import { useReducedMotion } from "./hooks/useReducedMotion"; import { orbitStatus } from "./lib/format"; import { groupSnapshots } from "./lib/galaxyLayout"; +import type { FailureCause } from "./lib/orbitActivity"; import type { SearchResult } from "./lib/vaultSearch"; const panelTitles: Record = { @@ -134,6 +135,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 }); const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 }); const orbits = useQuery({ queryKey: ["orbits"], queryFn: fetchOrbits, refetchInterval: 8_000, retry: 1 }); + const [settled, setSettled] = useState<{ id: string; status: string; at: number }>(); const capture = useMutation({ mutationFn: async (target: Orbit) => { if (target.application_id) { @@ -142,7 +144,10 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis } return runOrbit(target.id); }, - onSettled: () => { + onSettled: (_data, error, target) => { + // Until the next poll arrives, show the verdict this click produced rather than the stale status the last poll + // had, so one backup is never animated twice and never flips through an old result. + setSettled({ id: target.id, status: error ? "failed" : target.application_id ? "queued" : target.dry_run ? "rehearsed" : "completed", at: Date.now() }); void qc.invalidateQueries({ queryKey: ["orbits"] }); void qc.invalidateQueries({ queryKey: ["snapshots"] }); void qc.invalidateQueries({ queryKey: ["capture-jobs"] }); @@ -150,10 +155,29 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis }); const online = health.isSuccess; - const activeId = capture.isPending ? capture.variables.id : undefined; + useEffect(() => { + if (!settled) return; + const timer = window.setTimeout(() => setSettled(undefined), 10_000); + return () => window.clearTimeout(timer); + }, [settled]); + // The orbit that was clicked shows what the click did: busy while pending, then its verdict, until a poll that began + // after the click has landed. An invalidating refetch cancels any poll already in flight, so that poll is fresh. + const override = capture.isPending + ? { id: capture.variables.id, status: capture.variables.application_id ? "queued" : capture.variables.dry_run ? "rehearsing" : "running" } + : settled && !(orbits.dataUpdatedAt > settled.at) ? settled : undefined; + const activeId = override?.id; + const overrideStatus = override?.status; const sceneOrbits = useMemo(() => (orbits.data ?? []).map((orbit) => - orbit.id === activeId ? { ...orbit, last_status: orbit.application_id ? "queued" : orbit.dry_run ? "rehearsing" : "running" } : orbit, - ), [orbits.data, activeId]); + orbit.id === activeId && overrideStatus ? { ...orbit, last_status: overrideStatus } : orbit, + ), [orbits.data, activeId, overrideStatus]); + const resolveFailure = useMemo(() => async (orbit: Orbit): Promise => { + try { + const phase = (await fetchCaptureJobs(orbit.application_id ?? "", "failed"))[0]?.phase; + return phase === "upload_failed" ? "transfer" : phase === "dump_failed" ? "prepare" : "unknown"; + } catch { + return "unknown"; + } + }, []); const register = useMemo(() => [...sceneOrbits].sort((a, b) => priority(a) - priority(b)), [sceneOrbits]); const grouped = useMemo(() => groupSnapshots(orbits.data ?? [], snaps.data ?? []), [orbits.data, snaps.data]); const totalBytes = useMemo(() => (snaps.data ?? []).reduce((sum, snap) => sum + snap.size_bytes, 0), [snaps.data]); @@ -277,7 +301,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis orbits={sceneOrbits} selectedOrbitId={selected?.id} recentSnapshots={history.slice(0, 3)} flowing={play && !reducedMotion} reducedMotion={reducedMotion} captureEffect={captureEffect} captureGlow={captureGlow} captureReady={captureReady} bigScreen={bigScreen} onToggleBigScreen={toggleBigScreen} - radar={radar} onToggleRadar={toggleRadar} + radar={radar} onToggleRadar={toggleRadar} resolveFailure={resolveFailure} onToggleFlow={() => setPlay((value) => !value)} onSelectOrbit={(id) => { selectOrbit(id); diff --git a/web/src/components/scene/BlackholeGalaxy.tsx b/web/src/components/scene/BlackholeGalaxy.tsx index 55ea7ef..13663ab 100644 --- a/web/src/components/scene/BlackholeGalaxy.tsx +++ b/web/src/components/scene/BlackholeGalaxy.tsx @@ -1,18 +1,21 @@ import { useId, useLayoutEffect, useMemo, useRef, useState } from "react"; -import { animate, motion, spring, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react"; +import { animate, motion, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react"; import type { Orbit, Snapshot } from "../../api"; import { orbitStatus } from "../../lib/format"; import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout"; import { - assignOrbitSlots, CAPTURE_HIGHLIGHT_START, capturePhases, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT, - SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, trailAngle, type Vec2, + assignOrbitSlots, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT, + SCENE_HEIGHT, SCENE_WIDTH, trailAngle, type Vec2, } from "../../lib/galaxyLayout"; import { useGalaxyMotion } from "../../hooks/useGalaxyMotion"; import { useScreenTransition } from "../../hooks/useScreenTransition"; -import { ambientSpring, gentleSpring, uiSpring } from "../../lib/motion"; +import { gentleSpring, uiSpring } from "../../lib/motion"; import { VaultCore } from "./VaultCore"; import type { CoreSignal } from "../../lib/blackhole/controller"; import { SCENE_UNITS_PER_M } from "../../lib/blackhole/layout"; +import { createActivity, observeStatuses, type FailureCause } from "../../lib/orbitActivity"; +import { applyActivity, createField, fieldActive, starPose, stepField, type FieldEvent } from "../../lib/rocket"; +import { RocketSprites, createSpriteRefs, paintSprites } from "./RocketSprites"; export type CaptureEffect = { orbitId: string; key: number; snapshotId?: string }; @@ -28,6 +31,8 @@ type Props = { signal: CoreSignal; svgCore: boolean; captureReady: boolean; + /** Why a backup failed, for orbits where the hub can tell. Picks between an explosion and a fall. */ + resolveFailure?: (orbit: Orbit) => Promise; onSelectOrbit: (id: string) => void; onSelectSnapshot: (id: string) => void; }; @@ -38,41 +43,51 @@ const labelFont = "500 11px ui-monospace, monospace"; const MAX_LABELS = 12; const clamp = (value: number) => Math.max(0, Math.min(1, value)); const ACCRETION_SECONDS = 6.4; -const TRAIL_WIDTHS = [0.8, 1.4, 2.3]; -/** Star colour by status: cool mint when healthy, amber while working, ember red when failed. */ /** Glow falloff, close to a gaussian so there is no visible edge. */ const GLOW_STOPS: [number, number][] = [[0, 0.9], [0.06, 0.6], [0.14, 0.34], [0.26, 0.14], [0.42, 0.045], [0.65, 0.01], [1, 0]]; +/** Star colour by status: cool mint when healthy, amber while working, ember red when failed. */ /** A diffraction spike: a thin diamond that tapers to nothing at both ends. */ const SPIKE = "M-14 0 L0 -.7 L14 0 L0 .7Z"; const STAR_TONES: [string, string][] = [["green", "#b4efd9"], ["amber", "#f2bc80"], ["red", "#ff9484"], ["grey", "#cdd3dc"]]; +type Body = { + id: string; index: number; x: number; y: number; look: number; kind: "calm" | "busy" | "failed"; + trail?: SVGGElement | null; life?: SVGGElement | null; +}; + +/** A stable number per orbit, so its rocket always scatters the same way. */ +function seedOf(id: string) { + let value = 7; + for (const char of id) value = (value * 31 + char.charCodeAt(0)) % 997; + return value + 1; +} + +/** How long a star keeps looking busy while waiting for its rocket's outcome, at most. */ +const HOLD_LIMIT_MS = 8000; + export function BlackholeGalaxy({ - orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, signal, svgCore, captureReady, onSelectOrbit, onSelectSnapshot, + orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, signal, svgCore, captureReady, resolveFailure, onSelectOrbit, onSelectSnapshot, }: Props) { const frame = useRef(null); - const bodyNodes = useRef(new Map()); + const bodyNodes = useRef(new Map()); + const bodyState = useRef(new WeakMap()); const ambient = useRef(0); const ringNodes = useRef(new Map()); const slotsBefore = useRef>(undefined); const elapsed = useRef(0); const entrance = useRef(0); const core = useRef(null); - const capture = useRef<{ event: CaptureEffect; time: number; source: Vec2; progress: ReturnType; done: boolean; waiting: boolean }>(undefined); - const skippedCapture = useRef(undefined); - const sourceFlare = useRef(null); + const field = useRef(createField()); + const activity = useRef(createActivity()); + const sprites = useRef(createSpriteRefs()); + const highlight = useRef<{ effect: CaptureEffect; armed: boolean; played: boolean }>(undefined); + const [held, setHeld] = useState>(new Set()); + const shownStatus = (orbit: Orbit) => (held.has(orbit.id) ? "running" : orbit.last_status); const busyAngle = useRef(0); const diskTime = useRef(0); - const hasRunning = orbits.some(orbit => orbitStatus(orbit.last_status).busy); - const trailId = useId(); + const hasRunning = orbits.some(orbit => orbitStatus(shownStatus(orbit)).busy); const knockoutId = useId(); const starId = useId(); - const trail = useRef(null); - const trailSegments = useRef<(SVGUseElement | null)[]>([]); - const head = useRef(null); - const effect = useRef(null); const [width, setWidth] = useState(0); const [coasting, setCoasting] = useState(false); const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0); @@ -142,7 +157,83 @@ export function BlackholeGalaxy({ } }, [moving, reducedMotion, selectedX, selectedY, selectionX, selectionY]); - useGalaxyMotion((delta) => { + // Holding a star's busy look until its outcome plays out means it turns red at the explosion and green on arrival, + // not the moment the status changes. + const movingNow = useRef(moving); + movingNow.current = moving; + const hold = (id: string) => { + setHeld((current) => (current.has(id) ? current : new Set(current).add(id))); + window.setTimeout(() => release(id), HOLD_LIMIT_MS); + }; + const release = (id: string) => { + setHeld((current) => { + if (!current.has(id)) return current; + const next = new Set(current); + next.delete(id); + return next; + }); + }; + const outcome = (event: FieldEvent) => { + if (event.kind === "arrive") { + release(event.id); + const light = highlight.current; + if (light && light.effect.orbitId === event.id) light.armed = true; + } else if (event.kind === "boom" || event.kind === "landed") { + release(event.id); + } + }; + + // What the backups are doing decides what the rockets do. This runs before the loop is (re)started below. + useLayoutEffect(() => { + if (reducedMotion) { + field.current = createField(); + activity.current = createActivity(); + setHeld((current) => (current.size ? new Set() : current)); + return; + } + const statuses = new Map(orbits.map((orbit) => [orbit.id, orbit.last_status])); + for (const event of observeStatuses(activity.current, statuses)) { + const slot = slots.get(event.id); + if (!slot) continue; + const orbit = orbits.find(({ id }) => id === event.id); + const now = () => starPose(slot, elapsed.current, movingNow.current ? Math.max(0, rate.get()) : 0); + if (event.kind === "fail" && orbit?.application_id && resolveFailure) { + // The hub can say whether the backup failed before it left or while it was transferring. Wait briefly for it. + hold(event.id); + void Promise.race([ + resolveFailure(orbit), + new Promise((done) => window.setTimeout(() => done("unknown"), 700)), + ]).catch((): FailureCause => "unknown").then((cause) => { + if (!applyActivity(field.current, { ...event, cause }, now(), seedOf(event.id))) release(event.id); + wake(); + }); + continue; + } + if (event.kind === "launch" || event.kind === "fail") hold(event.id); + if (!applyActivity(field.current, event, now(), seedOf(event.id))) release(event.id); + } + }, [orbits, slots, reducedMotion]); + + // A click-started capture arms its snapshot flash. It plays once the rocket arrives and the snapshot is listed, or + // after a few seconds if the rocket never flew, for example when there was no room for another one. + useLayoutEffect(() => { + captureGlow.stop(); + captureGlow.set(0); + if (!captureEffect?.snapshotId || reducedMotion) { + highlight.current = undefined; + return; + } + const entry = { effect: captureEffect, armed: false, played: false }; + highlight.current = entry; + const timer = window.setTimeout(() => { + if (highlight.current !== entry || entry.played) return; + entry.armed = true; + wake(); + }, 3500); + return () => window.clearTimeout(timer); + }, [captureEffect, captureGlow, reducedMotion]); + + const wake = useGalaxyMotion((delta) => { const speed = moving ? Math.max(0, rate.get()) : 0; elapsed.current += delta * speed; if (hasRunning && !reducedMotion && delta > 0) { @@ -184,7 +275,8 @@ export function BlackholeGalaxy({ const phase = body.index * 2.399; const wave = 0.6 * Math.sin(time * rate + phase) + 0.4 * Math.sin(time * rate * 2.3 + phase * 1.7); const depth = body.kind === "busy" ? 0.16 : body.kind === "failed" ? 0.12 : 0.07; - body.life.setAttribute("transform", `scale(${1 + depth * wave})`); + const swell = field.current.pulses.get(body.id)?.value ?? 0; + body.life.setAttribute("transform", `scale(${(1 + depth * wave) * (1 + 0.7 * swell)})`); body.life.setAttribute("opacity", String(1 - depth * 0.45 * (1 - wave))); } } @@ -193,62 +285,24 @@ export function BlackholeGalaxy({ selectionX.jump(point.x); selectionY.jump(point.y); } - if (reducedMotion) skippedCapture.current = captureEffect; - const event = captureEffect === skippedCapture.current ? undefined : captureEffect; - const slot = event && slots.get(event.orbitId); - if (event && slot && capture.current?.event !== event) { - captureGlow.set(0); - effect.current?.setAttribute("opacity", "0"); - const source = orbitPose(slot, elapsed.current); - capture.current = { - event, source, time: 0, done: false, waiting: false, - progress: spring({ ...ambientSpring, keyframes: [0, 1], restDelta: 0.002 }), - }; - if (event.snapshotId) { - const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35)); - trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" ")); - } - } - - const current = capture.current; + // Rockets. The field integrates each rocket's position and velocity, then the sprites are placed to match. + // Nothing is keyframed, so any outcome can interrupt any other and the motion stays continuous. let absorption = 0; - let capturing = false; - if (event && current?.event === event && !current.done) { - // The impact can finish while the snapshot list is still refreshing. - if (!current.waiting || captureReady) current.time += delta * 1000; - const { value, done } = current.progress.next(current.time); - const success = !!event.snapshotId; - current.waiting = success && !captureReady && value >= CAPTURE_HIGHLIGHT_START; - const progress = current.waiting ? CAPTURE_HIGHLIGHT_START : done ? 1 : value; - const phases = capturePhases(progress); - current.done = done && !current.waiting; - const source = slot ? orbitPose(slot, elapsed.current) : current.source; - const pulse = success ? phases.flare : phases.failure; - sourceFlare.current?.setAttribute("cx", String(source.x)); - sourceFlare.current?.setAttribute("cy", String(source.y)); - sourceFlare.current?.setAttribute("r", String(7 + 13 * clamp(value))); - sourceFlare.current?.setAttribute("stroke", success ? "#ffd3a5" : "#f59183"); - sourceFlare.current?.setAttribute("opacity", String(0.75 * pulse)); - - if (success) { - const { x, y } = spiralPoint(current.source, phases.flight); - head.current?.setAttribute("cx", String(x)); - head.current?.setAttribute("cy", String(y)); - head.current?.setAttribute("r", String(3.5 * (1 - phases.flight ** 4))); - const segmentLength = Math.min(phases.flight, 0.19) * (1 - phases.flight ** 6) / TRAIL_WIDTHS.length; - trailSegments.current.forEach((segment, index) => { - segment?.setAttribute("stroke-dasharray", `${segmentLength} 1`); - segment?.setAttribute("stroke-dashoffset", String((TRAIL_WIDTHS.length - index) * segmentLength - phases.flight)); - }); - effect.current?.setAttribute("opacity", String(clamp(phases.flight * 14) * (1 - phases.flight ** 8))); - absorption = phases.absorption; - captureGlow.set(phases.highlight); - } - capturing = !current.done && !current.waiting; - } else { - sourceFlare.current?.setAttribute("opacity", "0"); - effect.current?.setAttribute("opacity", "0"); - captureGlow.set(0); + if (!reducedMotion) { + const dt = Math.min(delta, 0.05); + const starOf = (id: string) => { + const slot = slots.get(id); + return slot ? starPose(slot, elapsed.current, speed) : undefined; + }; + if (dt > 0) for (const event of stepField(field.current, dt, starOf)) outcome(event); + paintSprites(sprites.current, field.current, { starOf, lookAt: signal.lookAt, time: ambient.current, dt }); + absorption = Math.max(0, field.current.absorption.value); + } + // The snapshot flash waits for the rocket to arrive and for the confirmed snapshot to show up in the list. + const light = highlight.current; + if (light?.armed && !light.played && captureReady) { + light.played = true; + animate(captureGlow, 1, { ...uiSpring, onComplete: () => { animate(captureGlow, 0, gentleSpring); } }); } if (delta > 0 && (speed || absorption)) { @@ -265,7 +319,7 @@ export function BlackholeGalaxy({ if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) { coreStyle.setProperty("--capture-absorption", String(absorption)); } - return moving || entering || capturing || (hasRunning && !reducedMotion); + return moving || entering || fieldActive(field.current) || (hasRunning && !reducedMotion); }); // The overlay follows the radar wave: each marker and ring takes the look at its own distance from the hole, so @@ -302,7 +356,7 @@ export function BlackholeGalaxy({ const visible = orbits.filter(({ id }) => slots.has(id)); const byPriority = (orbit: Orbit) => - orbit.id === selectedOrbitId ? 0 : orbit.last_status === "failed" ? 1 : orbitStatus(orbit.last_status).busy ? 2 : 3; + orbit.id === selectedOrbitId ? 0 : shownStatus(orbit) === "failed" ? 1 : orbitStatus(shownStatus(orbit)).busy ? 2 : 3; const labelCandidates = [...visible].sort((a, b) => byPriority(a) - byPriority(b)) .filter((orbit) => width >= 530 || orbit.id === selectedOrbitId) .slice(0, MAX_LABELS); @@ -330,14 +384,18 @@ export function BlackholeGalaxy({ const renderOrbits = visible.map((orbit, index) => { const selected = orbit.id === selectedOrbitId; - const status = orbitStatus(orbit.last_status); + const status = orbitStatus(shownStatus(orbit)); const radius = slots.get(orbit.id)?.radius; return ( { if (!node) return; - bodyNodes.current.set(node, { id: orbit.id, index, x: 0, y: 0, look: 0, kind: status.tone === "red" ? "failed" : status.busy ? "busy" : "calm" }); + // The per-node state outlives re-renders, so a marker keeps its position and look between them. + const body = bodyState.current.get(node) ?? { id: orbit.id, index, x: 0, y: 0, look: 0, kind: "calm" as const }; + Object.assign(body, { id: orbit.id, index, kind: status.tone === "red" ? "failed" : status.busy ? "busy" : "calm" }); + bodyState.current.set(node, body); + bodyNodes.current.set(node, body); return () => { bodyNodes.current.delete(node); }; }} initial={false} @@ -457,15 +515,7 @@ export function BlackholeGalaxy({ /> )} - - - - {TRAIL_WIDTHS.map((strokeWidth, index) => ( - { trailSegments.current[index] = node; }} - href={`#${trailId}`} fill="none" strokeWidth={strokeWidth} opacity={0.35 + index * 0.3} /> - ))} - - +