feat: show what each backup is doing as a light that moves like a rocket

Replace the single-shot meteor with a per-orbit activity system. A backup's state
is read from how a small glowing triangle moves, not from a drawing of a rocket.

- Events come from status changes between polls, so scheduled backups animate
  too. A click shows its own verdict until a poll that began after it has landed,
  which keeps one backup from being animated twice or flipping through a stale
  status. Loading the page only sets a baseline and never replays history.
- Queued waits on its star. Running circles it, climbing and spinning up.
- Success waits for a launch window, where the light's own motion already carries
  it round the black hole, then departs with that velocity. It falls under a
  pseudo-Newtonian pull after a burn that trims angular momentum to just under
  the capture limit, so the path spirals with the orbits, always arrives, and
  never slows on the way in. Near the shadow it reddens, dims and stretches, and
  the disk spins up as it feeds.
- Failure explodes in place or, when the hub says the transfer failed, launches,
  loses power and falls back. The star keeps its busy look until the outcome and
  then turns red. Rehearsal is a faint dashed light that lands on its star.
- Position and velocity are integrated and a mode change only swaps forces, so
  every transition is continuous and interruptible. Parameters use the shared
  spring tokens. Trails follow the path actually flown.
- At most ten lights are drawn; reduced motion draws none and shows outcomes at once.
- Pure modules with tests for activity, physics and trails. The Playwright capture
  script now checks lights by data-orbit. The animation guideline in docs/UI.md
  describes the simulation approach in place of the old single progress value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 23:04:25 +07:00
parent d0f22c4ad0
commit 8b6efe1eaa
16 changed files with 1571 additions and 143 deletions

View File

@@ -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<HUDMode, string> = {
@@ -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<FailureCause> => {
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);

View File

@@ -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<FailureCause>;
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<HTMLDivElement>(null);
const bodyNodes = useRef(new Map<SVGGElement, {
id: string; index: number; x: number; y: number; look: number; kind: "calm" | "busy" | "failed";
trail?: SVGGElement | null; life?: SVGGElement | null;
}>());
const bodyNodes = useRef(new Map<SVGGElement, Body>());
const bodyState = useRef(new WeakMap<SVGGElement, Body>());
const ambient = useRef(0);
const ringNodes = useRef(new Map<number, SVGEllipseElement>());
const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
const elapsed = useRef(0);
const entrance = useRef(0);
const core = useRef<SVGGElement>(null);
const capture = useRef<{ event: CaptureEffect; time: number; source: Vec2; progress: ReturnType<typeof spring>; done: boolean; waiting: boolean }>(undefined);
const skippedCapture = useRef<CaptureEffect>(undefined);
const sourceFlare = useRef<SVGCircleElement>(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<ReadonlySet<string>>(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<SVGPathElement>(null);
const trailSegments = useRef<(SVGUseElement | null)[]>([]);
const head = useRef<SVGCircleElement>(null);
const effect = useRef<SVGGElement>(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<FailureCause>((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 (
<motion.g
key={orbit.id}
ref={(node) => {
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({
/>
)}
</g>
<circle ref={sourceFlare} className="capture-flare" opacity="0" pointerEvents="none" fill="none" />
<g ref={effect} className="capture-arrival" opacity="0" pointerEvents="none">
<defs><path id={trailId} ref={trail} pathLength="1" /></defs>
{TRAIL_WIDTHS.map((strokeWidth, index) => (
<use key={strokeWidth} ref={node => { trailSegments.current[index] = node; }}
href={`#${trailId}`} fill="none" strokeWidth={strokeWidth} opacity={0.35 + index * 0.3} />
))}
<circle ref={head} r="3.5" />
</g>
<RocketSprites refs={sprites.current} />
</svg>
<div aria-hidden="true" className="scene-labels" style={{ font: labelFont }}>
{labels.map(({ id, x, y, width: labelWidth }, index) => (

View File

@@ -0,0 +1,225 @@
import { useId } from "react";
import { MAX_ROCKETS, infallLook, screenRadius, type Field, type Rocket, type StarPose } from "../../lib/rocket";
import { ORBIT_TILT } from "../../lib/galaxyLayout";
import { SCENE_UNITS_PER_M } from "../../lib/blackhole/layout";
import { advanceTrail, smoothPath, trailLength, type Trail } from "../../lib/trail";
const DEBRIS_POOL = 24;
const FLARE_POOL = 6;
export type SpriteRefs = {
rockets: (SVGGElement | null)[];
trails: (SVGPathElement | null)[];
trailStops: ([SVGStopElement | null, SVGStopElement | null])[];
trailGradients: (SVGLinearGradientElement | null)[];
debris: (SVGCircleElement | null)[];
flares: (SVGCircleElement | null)[];
};
export function createSpriteRefs(): SpriteRefs {
return {
rockets: Array(MAX_ROCKETS).fill(null),
trails: Array(MAX_ROCKETS).fill(null),
trailStops: Array.from({ length: MAX_ROCKETS }, () => [null, null] as [SVGStopElement | null, SVGStopElement | null]),
trailGradients: Array(MAX_ROCKETS).fill(null),
debris: Array(DEBRIS_POOL).fill(null),
flares: Array(FLARE_POOL).fill(null),
};
}
// A rocket is not drawn as a rocket: its motion says what it is. It is a small glowing triangle that points where it is
// going, with a trail that follows the path it actually flew. It speaks the same language as the stars it leaves.
const TRIANGLE = "M4.6 0 L-3.2 -2.8 L-3.2 2.8Z";
/** Small: the motion is what says rocket, so the mark itself stays quiet next to the stars. */
const SIZE = 0.95;
/** The glow is the same triangle, bigger and fainter, stacked: no blur filter, so it is cheap to animate. */
const HALOS = [{ scale: 2.3, alpha: 0.07 }, { scale: 1.7, alpha: 0.13 }, { scale: 1.3, alpha: 0.24 }];
/**
* Pooled sprites for every rocket, trail, piece of debris and explosion flash. React renders them once; the scene loop
* moves them with setAttribute, so flying a rocket never re-renders anything.
*/
export function RocketSprites({ refs }: { refs: SpriteRefs }) {
const id = useId();
return (
<g className="rocket-layer" pointerEvents="none">
<defs>
<filter id={`${id}-soft`} x="-150%" y="-150%" width="400%" height="400%">
<feGaussianBlur stdDeviation="0.9" />
</filter>
{Array.from({ length: MAX_ROCKETS }, (_, index) => (
<linearGradient key={index} id={`${id}-trail-${index}`} gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"
ref={(node) => { refs.trailGradients[index] = node; }}>
<stop ref={(node) => { refs.trailStops[index][0] = node; }} offset="0" stopColor="#ffb870" stopOpacity="0" />
<stop ref={(node) => { refs.trailStops[index][1] = node; }} offset="1" stopColor="#ffe9cc" stopOpacity=".9" />
</linearGradient>
))}
</defs>
{Array.from({ length: MAX_ROCKETS }, (_, index) => (
<path key={index} ref={(node) => { refs.trails[index] = node; }} className="rocket-trail"
stroke={`url(#${id}-trail-${index})`} opacity="0" />
))}
{Array.from({ length: MAX_ROCKETS }, (_, index) => (
<g key={index} ref={(node) => { refs.rockets[index] = node; }} className="rocket" opacity="0">
<g className="rocket-real">
<g filter={`url(#${id}-soft)`}>
{HALOS.map(({ scale }) => (
<path key={scale} className="rocket-halo" d={TRIANGLE} transform={`translate(-0.5 0) scale(${scale}) translate(0.5 0)`} />
))}
</g>
<path className="rocket-tri" d={TRIANGLE} />
</g>
<g className="rocket-radar" opacity="0">
<path d={TRIANGLE} />
</g>
</g>
))}
{Array.from({ length: DEBRIS_POOL }, (_, index) => (
<circle key={index} ref={(node) => { refs.debris[index] = node; }} className="rocket-debris" r="1" opacity="0" />
))}
{Array.from({ length: FLARE_POOL }, (_, index) => (
<circle key={index} ref={(node) => { refs.flares[index] = node; }}
className="rocket-flare" r="8" opacity="0" />
))}
</g>
);
}
const headings = new WeakMap<SVGGElement, number>();
const trails = new WeakMap<SVGPathElement, Trail>();
const mix = (a: number, b: number, t: number) => a + (b - a) * t;
const hex = (r: number, g: number, b: number) =>
`#${[r, g, b].map((v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, "0")).join("")}`;
export type PaintContext = {
starOf: (id: string) => StarPose | undefined;
/** 0 realistic .. 1 radar, at a distance from the hole in gravitational radii. */
lookAt: ((radiusM: number) => number) | undefined;
/** Seconds, for the engine flicker. */
time: number;
dt: number;
};
/** Move every sprite to match the field. Called once per frame by the scene loop. */
export function paintSprites(refs: SpriteRefs, field: Field, context: PaintContext) {
let slot = 0;
for (const rocket of field.rockets.values()) {
const node = refs.rockets[slot];
if (!node || slot >= MAX_ROCKETS) break;
paintRocket(refs, slot, node, rocket, context);
slot++;
}
for (; slot < MAX_ROCKETS; slot++) {
const node = refs.rockets[slot];
if (node && node.getAttribute("opacity") !== "0") node.setAttribute("opacity", "0");
const path = refs.trails[slot];
if (path) {
if (path.getAttribute("opacity") !== "0") path.setAttribute("opacity", "0");
trails.delete(path);
}
}
field.debris.forEach((piece, index) => {
const node = refs.debris[index];
if (!node) return;
const fade = Math.max(0, 1 - piece.age / piece.life);
node.setAttribute("cx", String(piece.x));
node.setAttribute("cy", String(piece.y * ORBIT_TILT));
node.setAttribute("r", String(piece.size * (0.6 + 0.4 * fade)));
node.setAttribute("opacity", String(fade ** 1.4));
});
for (let index = field.debris.length; index < refs.debris.length; index++) {
const node = refs.debris[index];
if (node && node.getAttribute("opacity") !== "0") node.setAttribute("opacity", "0");
}
let flare = 0;
for (const [id, spring] of field.flares) {
const node = refs.flares[flare];
const star = context.starOf(id);
if (!node || !star || flare >= refs.flares.length) continue;
flare++;
const value = Math.max(0, spring.value);
node.setAttribute("cx", String(star.x));
node.setAttribute("cy", String(star.y * ORBIT_TILT));
node.setAttribute("r", String(7 + 22 * (1 - value)));
node.setAttribute("opacity", String(0.85 * value));
}
for (; flare < refs.flares.length; flare++) {
const node = refs.flares[flare];
if (node && node.getAttribute("opacity") !== "0") node.setAttribute("opacity", "0");
}
}
function paintTrail(refs: SpriteRefs, slot: number, rocket: Rocket, sx: number, sy: number, alpha: number, radar: number, dt: number) {
const path = refs.trails[slot];
if (!path) return;
const trail = advanceTrail(trails.get(path), rocket.id, sx, sy, dt);
trails.set(path, trail);
const points = trail.points;
const first = points[0];
if (points.length < 2 || trailLength(points) < 2) {
if (path.getAttribute("opacity") !== "0") path.setAttribute("opacity", "0");
return;
}
path.setAttribute("d", smoothPath(points));
const gradient = refs.trailGradients[slot];
gradient?.setAttribute("x1", String(first.x));
gradient?.setAttribute("y1", String(first.y));
gradient?.setAttribute("x2", String(sx));
gradient?.setAttribute("y2", String(sy));
const [tail, head] = refs.trailStops[slot];
// Warm in the realistic look, mint on the radar.
tail?.setAttribute("stop-color", hex(mix(255, 139, radar), mix(184, 203, radar), mix(112, 179, radar)));
head?.setAttribute("stop-color", hex(mix(255, 160, radar), mix(233, 230, radar), mix(204, 205, radar)));
path.setAttribute("opacity", String(alpha * (rocket.mode === "ghost" ? 0.55 : 1)));
path.classList.toggle("rocket-trail--ghost", rocket.mode === "ghost");
}
function paintRocket(refs: SpriteRefs, slot: number, node: SVGGElement, rocket: Rocket, { lookAt, time, dt }: PaintContext) {
if (node.dataset.orbit !== rocket.id) node.dataset.orbit = rocket.id;
const sx = rocket.x;
const sy = rocket.y * ORBIT_TILT;
// Heading follows the screen-space velocity, smoothed so an interruption turns the rocket instead of snapping it.
const vx = rocket.vx;
const vy = rocket.vy * ORBIT_TILT;
const previous = headings.get(node) ?? Math.atan2(vy, vx);
let heading = previous;
if (Math.hypot(vx, vy) > 4) {
const target = Math.atan2(vy, vx);
const delta = Math.atan2(Math.sin(target - previous), Math.cos(target - previous));
heading = previous + delta * (1 - Math.exp(-14 * dt));
}
headings.set(node, heading);
const flying = rocket.mode === "launch";
const look = flying ? infallLook(screenRadius(rocket.x, rocket.y)) : { alpha: 1, stretch: 1, red: 0 };
const radar = lookAt ? lookAt(Math.hypot(sx, sy) / SCENE_UNITS_PER_M) : 0;
const along = look.stretch;
const across = 1 / Math.sqrt(look.stretch);
const alpha = Math.max(0, rocket.alpha.value) * look.alpha;
node.setAttribute("transform", `translate(${sx} ${sy}) rotate(${(heading * 180) / Math.PI}) scale(${along * SIZE} ${across * SIZE})`);
node.setAttribute("opacity", String(alpha));
paintTrail(refs, slot, rocket, sx, sy, alpha, radar, dt);
const real = node.firstElementChild as SVGGElement | null;
const outline = real?.nextElementSibling as SVGGElement | null;
real?.setAttribute("opacity", String(1 - radar));
outline?.setAttribute("opacity", String(radar));
if (real) {
// The glow follows the engine's thrust, which is itself a spring, so it swells and dies smoothly, with a flicker.
const flicker = 1 + 0.14 * Math.sin(time * 41 + rocket.seed * 5) + 0.07 * Math.sin(time * 67 + rocket.seed);
const halos = real.querySelectorAll(".rocket-halo");
halos.forEach((halo, index) => {
halo.setAttribute("opacity", String(Math.min(1, (0.45 + 0.9 * rocket.thrust.value) * flicker * (rocket.mode === "ghost" ? 0.4 : 1))));
halo.setAttribute("fill-opacity", String(HALOS[index].alpha / 0.24 * 0.9));
});
// Redshift: the light goes from warm white toward ember red as it nears the shadow.
const tri = real.querySelector(".rocket-tri");
tri?.setAttribute("fill", rocket.mode === "ghost" ? "none" : hex(255, mix(236, 96, look.red), mix(208, 64, look.red)));
for (const halo of halos) halo.setAttribute("fill", hex(255, mix(196, 90, look.red), mix(138, 60, look.red)));
}
node.classList.toggle("rocket--ghost", rocket.mode === "ghost");
}

View File

@@ -3,12 +3,13 @@ import { useCallback, useState } from "react";
import { BlackholeBackdrop } from "./BlackholeBackdrop";
import { SpaceBackdrop } from "./SpaceBackdrop";
import type { CoreSignal } from "../../lib/blackhole/controller";
import type { FailureCause } from "../../lib/orbitActivity";
import { motion, type MotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
export function VaultScene({
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, captureEffect, captureGlow, captureReady,
bigScreen, radar, onToggleBigScreen, onToggleRadar, onToggleFlow, onSelectOrbit, onSelectSnapshot,
bigScreen, radar, resolveFailure, onToggleBigScreen, onToggleRadar, onToggleFlow, onSelectOrbit, onSelectSnapshot,
}: {
orbits: Orbit[];
selectedOrbitId?: string;
@@ -20,6 +21,7 @@ export function VaultScene({
captureReady: boolean;
bigScreen: boolean;
radar: boolean;
resolveFailure?: (orbit: Orbit) => Promise<FailureCause>;
onToggleBigScreen: () => void;
onToggleRadar: () => void;
onToggleFlow: () => void;
@@ -105,6 +107,7 @@ export function VaultScene({
signal={signal}
svgCore={svgCore}
captureReady={captureReady}
resolveFailure={resolveFailure}
onSelectOrbit={onSelectOrbit}
onSelectSnapshot={onSelectSnapshot}
/>

View File

@@ -1,4 +1,4 @@
import { useLayoutEffect, useRef } from "react";
import { useCallback, useLayoutEffect, useRef } from "react";
export function useGalaxyMotion(draw: (elapsed: number) => boolean) {
const latest = useRef(draw);
@@ -37,4 +37,7 @@ export function useGalaxyMotion(draw: (elapsed: number) => boolean) {
latest.current = draw;
if (draw(0)) wake.current?.();
});
/** Start the loop from outside a render, for example when something arrives asynchronously. */
return useCallback(() => wake.current?.(), []);
}

View File

@@ -364,10 +364,14 @@ button:disabled { cursor: default; }
.accretion-flow { stroke-dashoffset: var(--accretion-offset, 0); }
.accretion-flow--inner { stroke-dashoffset: calc(32 + 2 * var(--accretion-offset, 0)); }
.core-absorption { opacity: var(--capture-absorption, 0); }
.capture-flare, .snapshot-flash { stroke-width: 1.5; }
.snapshot-flash { fill: none; stroke: #ffce9b; pointer-events: none; }
.capture-arrival use { stroke: #ffce9b; stroke-linecap: round; }
.capture-arrival circle { fill: #fff0d9; }
.snapshot-flash { stroke-width: 1.5; fill: none; stroke: #ffce9b; pointer-events: none; }
.rocket-radar path { fill: none; stroke: #8bcbb3; stroke-width: 1.2; stroke-linejoin: round; }
.rocket-tri { stroke: none; }
.rocket--ghost .rocket-tri { stroke: #cfe6ff; stroke-width: .8; stroke-dasharray: 1.6 1.2; stroke-linejoin: round; }
.rocket-trail { fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
.rocket-trail--ghost { stroke-dasharray: 1.6 2.6; }
.rocket-debris { fill: #ffb87a; }
.rocket-flare { fill: none; stroke: #ff8a70; stroke-width: 1.6; }
.scene-labels { position: absolute; inset: 0; pointer-events: none; }
.scene-labels span { display: block; position: absolute; height: 24px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; line-height: 22px; color: #dde0e6; background: #111519ed; border: 1px solid #353c46; border-radius: 4px; padding-inline: 7px; }
.scene-labels span.is-selected { color: #ffe5cb; border-color: #8b6349; }

View File

@@ -102,23 +102,3 @@ export function groupSnapshots(orbits: Orbit[], snapshots: Snapshot[]): Map<stri
}
return groups;
}
export function spiralPoint(source: Vec2, progress: number): Vec2 {
const u = Math.min(1, Math.max(0, progress));
const angle = Math.atan2(source.y, source.x) + u * Math.PI * 1.15;
const radius = Math.hypot(source.x, source.y) * (1 - u ** 1.4);
return { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
}
export const CAPTURE_HIGHLIGHT_START = 0.94;
export function capturePhases(progress: number) {
const stage = (start: number, end: number) => Math.min(1, Math.max(0, (progress - start) / (end - start)));
return {
flare: stage(0, 0.06) * (1 - stage(0.08, 0.24)),
flight: stage(0.09, 0.79),
absorption: stage(0.76, 0.84) * (1 - stage(0.85, CAPTURE_HIGHLIGHT_START)),
highlight: stage(CAPTURE_HIGHLIGHT_START, 0.97) * (1 - stage(0.97, 0.998)),
failure: stage(0, 0.15) * (1 - stage(0.17, 0.9)),
};
}

View File

@@ -0,0 +1,92 @@
// What each orbit is doing, derived from backup statuses. This module has no DOM and no animation: it turns a stream
// of polled statuses into intents ("this orbit should have a rocket circling it") and one-shot events ("the backup
// just succeeded"), which the rocket simulation then plays out.
export type Intent = "none" | "pad" | "circle" | "ghost";
/** Why a backup failed, when the hub can tell: before the rocket could leave, or while it carried the payload. */
export type FailureCause = "prepare" | "transfer" | "unknown";
export type ActivityEvent =
| { kind: "begin"; id: string; intent: Exclude<Intent, "none"> }
| { kind: "launch"; id: string }
| { kind: "fail"; id: string; cause: FailureCause }
| { kind: "land"; id: string }
| { kind: "dismiss"; id: string };
export type ActivityState = {
/** Last status seen for each orbit. Absent until the first observation. */
seen: Map<string, string>;
intents: Map<string, Intent>;
baselined: boolean;
};
export function createActivity(): ActivityState {
return { seen: new Map(), intents: new Map(), baselined: false };
}
/** The intent a status asks for while the backup is still going. */
export function intentFor(status: string): Intent {
switch (status) {
case "queued": return "pad";
case "running": return "circle";
case "rehearsing": return "ghost";
default: return "none";
}
}
const busy = (status: string | undefined) => !!status && intentFor(status) !== "none";
/**
* Compare the latest statuses with the previous ones and report what happened.
*
* The first call only records a baseline: an orbit that is already running starts out circling, and one that has
* already finished starts out settled, so opening the page never replays history. An orbit that appears later is
* treated the same way. A backup that finished between two polls (idle to completed, or failed to completed) still
* gets its outcome, because the change itself is the evidence.
*/
export function observeStatuses(
state: ActivityState,
statuses: ReadonlyMap<string, string>,
causes: ReadonlyMap<string, FailureCause> = new Map(),
): ActivityEvent[] {
const events: ActivityEvent[] = [];
for (const [id, next] of statuses) {
const previous = state.seen.get(id);
const nextIntent = intentFor(next);
state.seen.set(id, next);
state.intents.set(id, nextIntent);
if (!state.baselined || previous === undefined) {
if (nextIntent !== "none") events.push({ kind: "begin", id, intent: nextIntent });
continue;
}
if (previous === next) continue;
if (nextIntent !== "none") {
// Queued to running is the same rocket changing pace; anything else is a fresh start.
events.push({ kind: "begin", id, intent: nextIntent });
} else if (next === "completed") {
events.push({ kind: "launch", id });
} else if (next === "failed") {
events.push({ kind: "fail", id, cause: causes.get(id) ?? "unknown" });
} else if (next === "rehearsed") {
events.push({ kind: "land", id });
} else if (busy(previous)) {
// The backup stopped without a verdict, for example the orbit was reset: let the rocket go quietly.
events.push({ kind: "dismiss", id });
}
}
for (const id of [...state.seen.keys()]) {
if (statuses.has(id)) continue;
// The orbit was deleted.
if (busy(state.seen.get(id))) events.push({ kind: "dismiss", id });
state.seen.delete(id);
state.intents.delete(id);
}
state.baselined = true;
return events;
}

494
web/src/lib/rocket.ts Normal file
View File

@@ -0,0 +1,494 @@
// Rockets for the orbit map. A rocket is a small physical body: its position and velocity are integrated, and the
// mode it is in (circling, launching, falling) only decides which forces act on it. A mode change never resets
// velocity, so every transition is continuous and any of them can be interrupted by another.
//
// Everything is in orbit-plane coordinates: the plane the orbits lie in, with the black hole at the origin. The
// screen position is (x, y * ORBIT_TILT). Distances that decide what the viewer sees (when a rocket fades into the
// black disk) are measured on the screen, because the shadow is round there.
import { ORBIT_TILT } from "./galaxyLayout.ts";
import { ambientSpring, gentleSpring, uiSpring } from "./motion.ts";
import type { ActivityEvent, FailureCause, Intent } from "./orbitActivity.ts";
/** Screen radius of the shadow, in scene units. A rocket is gone by the time it reaches it. */
export const SHADOW_EDGE = 34;
/** Screen radius where gravitational redshift and tidal stretching begin to show. */
export const FADE_START = 80;
/** Strength of the black hole's pull, in scene units cubed per second squared. */
/** Pull at the reference launch radius. It scales with the cube of the launch radius so every shell takes the same time. */
export const GRAVITY = 2.4e6;
export const REFERENCE_RADIUS = 190;
/**
* Schwarzschild radius in scene units (2 M, with M the shadow radius over 3 root 3). The pull follows the
* Paczynski-Wiita potential, mu / (r - r_s)^2: it grows sharply toward the horizon the way general relativity's does, so
* a body with plenty of sideways momentum still falls in, and it keeps speeding up all the way, with no friction.
*/
export const HORIZON_RADIUS = 13;
/** Keeps the pull finite if a rocket ever strays this close to the horizon. */
export const MIN_GAP = 6;
export const MAX_ROCKETS = 10;
const SUBSTEP = 1 / 240;
export type Spring = { value: number; velocity: number };
type Tokens = { stiffness: number; damping: number; mass?: number };
export const makeSpring = (value = 0): Spring => ({ value, velocity: 0 });
/** Advance a spring toward a target, with the same physics as the app's shared spring tokens. */
export function stepSpring(spring: Spring, target: number, tokens: Tokens, dt: number) {
const steps = Math.max(1, Math.ceil(dt / SUBSTEP));
const h = dt / steps;
const mass = tokens.mass ?? 1;
for (let i = 0; i < steps; i++) {
spring.velocity += ((tokens.stiffness * (target - spring.value) - tokens.damping * spring.velocity) / mass) * h;
spring.value += spring.velocity * h;
}
}
export type StarPose = { x: number; y: number; vx: number; vy: number };
/** A star's pose in the orbit plane, from its slot angle. `rate` is how fast the map is moving right now, 0 to 1. */
export function starPose(slot: { radius: number; angle: number; speed: number }, time: number, rate: number): StarPose {
const angle = slot.angle + time * slot.speed;
const omega = slot.speed * rate;
return {
x: Math.cos(angle) * slot.radius,
y: Math.sin(angle) * slot.radius,
vx: -Math.sin(angle) * slot.radius * omega,
vy: Math.cos(angle) * slot.radius * omega,
};
}
export type RocketMode = "pad" | "circle" | "ghost" | "land" | "launch" | "fall" | "gone";
export type Rocket = {
id: string;
mode: RocketMode;
age: number;
modeAge: number;
x: number;
y: number;
vx: number;
vy: number;
/** Circling controller, relative to the star: angle, angular speed and radius. */
phi: number;
omega: Spring;
radius: Spring;
thrust: Spring;
alpha: Spring;
/** A launch that will lose power partway and fall back. */
failing: boolean;
/** Waiting for a good launch window while still circling. */
pendingLaunch: boolean;
waitAge: number;
/** Distance from the black hole when the rocket left its circle: the engine works harder from farther out. */
launchRadius: number;
/** Angular momentum the launch burn aims for. */
targetMomentum: number;
arrived: boolean;
seed: number;
};
export type Debris = { x: number; y: number; vx: number; vy: number; age: number; life: number; size: number };
export type FieldEvent = { kind: "arrive" | "impact" | "boom" | "landed"; id: string };
export type Field = {
rockets: Map<string, Rocket>;
debris: Debris[];
/** Flash at the spot of an explosion, per orbit. */
flares: Map<string, Spring>;
/** A brief swell of a star when its backup resolves. */
pulses: Map<string, Spring>;
/** How much the black hole is feeding: drives the disk's spin-up. */
absorption: Spring;
events: FieldEvent[];
};
export function createField(): Field {
return { rockets: new Map(), debris: [], flares: new Map(), pulses: new Map(), absorption: makeSpring(), events: [] };
}
const smoothstep = (edge0: number, edge1: number, x: number) => {
const t = Math.min(1, Math.max(0, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
};
export const screenRadius = (x: number, y: number) => Math.hypot(x, y * ORBIT_TILT);
/**
* How a falling rocket looks from far away. Near the black hole its light is redshifted and dims, and tidal forces
* stretch it along its fall, so it fades out by the edge of the shadow instead of popping out of existence.
*/
export function infallLook(radius: number) {
// 0 far away, 1 at the shadow edge.
const near = 1 - smoothstep(SHADOW_EDGE + 2, FADE_START, radius);
return { alpha: 1 - near ** 1.3, stretch: 1 + 2.4 * near, red: near };
}
export function spawnRocket(id: string, star: StarPose, intent: Exclude<Intent, "none">, seed = 1): Rocket {
const rocket: Rocket = {
id, mode: intent, age: 0, modeAge: 0,
x: star.x, y: star.y, vx: star.vx, vy: star.vy,
phi: (seed * 2.399) % (Math.PI * 2),
omega: makeSpring(0), radius: makeSpring(0), thrust: makeSpring(0), alpha: makeSpring(0),
failing: false, pendingLaunch: false, waitAge: 0, launchRadius: Math.hypot(star.x, star.y), targetMomentum: 0, arrived: false, seed,
};
return rocket;
}
/** Recover the circling controller's state from a rocket's position and velocity, so a body that was flying can circle. */
export function adoptCircle(rocket: Rocket, star: StarPose) {
const ox = rocket.x - star.x;
const oy = rocket.y - star.y;
const rho = Math.hypot(ox, oy);
const rvx = rocket.vx - star.vx;
const rvy = rocket.vy - star.vy;
if (rho < 1e-6) {
rocket.radius.value = 0;
rocket.radius.velocity = 0;
rocket.omega.velocity = 0;
return;
}
rocket.phi = Math.atan2(oy, ox);
rocket.radius.value = rho;
rocket.radius.velocity = (rvx * ox + rvy * oy) / rho;
rocket.omega.value = (ox * rvy - oy * rvx) / (rho * rho);
rocket.omega.velocity = 0;
}
export function setMode(rocket: Rocket, mode: RocketMode, star: StarPose) {
if (rocket.mode === mode) return;
const circling = (m: RocketMode) => m === "pad" || m === "circle" || m === "ghost" || m === "land";
if (circling(mode) && !circling(rocket.mode)) adoptCircle(rocket, star);
rocket.mode = mode;
rocket.modeAge = 0;
}
/** Leave the circle. The rocket keeps exactly the velocity it had, so the departure is seamless. */
export function startLaunch(rocket: Rocket, failing = false) {
rocket.mode = "launch";
rocket.modeAge = 0;
rocket.failing = failing;
rocket.pendingLaunch = false;
rocket.launchRadius = Math.hypot(rocket.x, rocket.y);
// The capture limit for a body falling from rest, in this launch's own scale of time: 4 sqrt(mu M).
const pull = GRAVITY * Math.pow(rocket.launchRadius / REFERENCE_RADIUS, 3);
rocket.targetMomentum = MOMENTUM_FRACTION * 4 * Math.sqrt(pull * (HORIZON_RADIUS / 2));
}
/**
* Ask a circling rocket to leave. It does not leave at once: like a real transfer burn it waits for the point on its
* circle where its own motion already carries it the right way round the black hole and a little inward, then departs
* with the velocity it has. The curved path is momentum and gravity, not steering.
*/
export function requestLaunch(rocket: Rocket, failing = false) {
rocket.pendingLaunch = true;
rocket.failing = failing;
rocket.waitAge = 0;
}
/** Is the rocket moving prograde around the hole and a little inward, so releasing it now makes a good spiral? */
export function inLaunchWindow(rocket: Rocket) {
const rr = Math.hypot(rocket.x, rocket.y);
const speed = Math.hypot(rocket.vx, rocket.vy);
if (rr < 1e-6 || speed < 1e-6) return true;
const inward = -(rocket.x * rocket.vx + rocket.y * rocket.vy) / (rr * speed);
const prograde = (rocket.x * rocket.vy - rocket.y * rocket.vx) / (rr * speed);
// Mostly tangential, a little inward: between roughly 5 and 33 degrees inward of the prograde tangent.
return prograde > 0.8 && inward > 0.09 && inward < 0.55;
}
const CIRCLE = {
pad: { radius: 0, omega: 0.5, thrust: 0.12, alpha: 1 },
ghost: { radius: 12, omega: 2.4, thrust: 0.18, alpha: 0.5 },
land: { radius: 0, omega: 5, thrust: 0, alpha: 0 },
};
/** Where the circling controller is heading. A working rocket climbs and spins up the longer it has been preparing. */
function circleTargets(rocket: Rocket) {
if (rocket.mode === "circle") {
const spin = 1 - Math.exp(-rocket.modeAge / 7);
// Waiting to depart, the engine lights and the lap quickens.
if (rocket.pendingLaunch) return { radius: 12, omega: 4.2, thrust: 1, alpha: 1 };
return { radius: 9 + 6 * spin, omega: 2 + 3 * spin, thrust: 0.3 + 0.35 * spin, alpha: 1 };
}
return CIRCLE[rocket.mode as keyof typeof CIRCLE] ?? CIRCLE.pad;
}
function stepCircling(rocket: Rocket, star: StarPose, dt: number) {
const target = circleTargets(rocket);
stepSpring(rocket.radius, target.radius, gentleSpring, dt);
stepSpring(rocket.omega, target.omega, ambientSpring, dt);
stepSpring(rocket.thrust, target.thrust, uiSpring, dt);
stepSpring(rocket.alpha, target.alpha, gentleSpring, dt);
rocket.phi += rocket.omega.value * dt;
const rho = Math.max(0, rocket.radius.value);
const cos = Math.cos(rocket.phi);
const sin = Math.sin(rocket.phi);
rocket.x = star.x + rho * cos;
rocket.y = star.y + rho * sin;
rocket.vx = star.vx + rocket.radius.velocity * cos - rho * rocket.omega.value * sin;
rocket.vy = star.vy + rocket.radius.velocity * sin + rho * rocket.omega.value * cos;
}
const LAUNCH_BURN = 0.6;
/** How hard the burn pulls angular momentum toward its target, per second. */
const BURN_GAIN = 5;
/** The fraction of the capture limit the burn aims for: close enough to sweep a long curve, far enough to fall in. */
const MOMENTUM_FRACTION = 0.97;
/** The longest a rocket waits for a good launch window: about one lap of its circle. */
const MAX_WAIT = 3;
const FAILING_CUT = 0.55;
const FALL_STIFFNESS = 90;
const FALL_DAMPING = 8;
function stepLaunch(rocket: Rocket, dt: number) {
const steps = Math.max(1, Math.ceil(dt / SUBSTEP));
const h = dt / steps;
for (let i = 0; i < steps; i++) {
const r2 = rocket.x * rocket.x + rocket.y * rocket.y;
const rr = Math.sqrt(r2);
const gap = Math.max(rr - HORIZON_RADIUS, MIN_GAP);
const pull = (GRAVITY * Math.pow(rocket.launchRadius / REFERENCE_RADIUS, 3)) / (gap * gap * Math.max(rr, 1e-6));
let ax = -pull * rocket.x;
let ay = -pull * rocket.y;
// The engine burn trims the rocket's angular momentum toward a fixed target just under the capture limit, with a
// prograde or retrograde push along the circle's own direction. Every launch then spirals the same way round, as far
// as its momentum carries it, and still falls in. After the burn it coasts and gravity does the rest.
const burn = Math.exp(-rocket.modeAge / LAUNCH_BURN);
if (rr > 1e-6 && burn > 1e-3) {
const momentum = rocket.x * rocket.vy - rocket.y * rocket.vx;
const push = (BURN_GAIN * (rocket.targetMomentum - momentum) * burn) / rr;
ax += (-rocket.y / rr) * push;
ay += (rocket.x / rr) * push;
}
// A backstop so no launch can orbit forever: after a few seconds the pull gets a nudge.
if (rocket.modeAge > 6 && rr > 1e-6) {
ax -= (rocket.x / rr) * 500;
ay -= (rocket.y / rr) * 500;
}
rocket.vx += ax * h;
rocket.vy += ay * h;
rocket.x += rocket.vx * h;
rocket.y += rocket.vy * h;
rocket.modeAge += h;
}
stepSpring(rocket.thrust, rocket.failing && rocket.modeAge > FAILING_CUT ? 0 : rocket.modeAge < LAUNCH_BURN ? 1 : 0.25, uiSpring, dt);
stepSpring(rocket.alpha, 1, gentleSpring, dt);
}
function stepFall(rocket: Rocket, star: StarPose, dt: number) {
const steps = Math.max(1, Math.ceil(dt / SUBSTEP));
const h = dt / steps;
for (let i = 0; i < steps; i++) {
const ax = -FALL_STIFFNESS * (rocket.x - star.x) - FALL_DAMPING * (rocket.vx - star.vx);
const ay = -FALL_STIFFNESS * (rocket.y - star.y) - FALL_DAMPING * (rocket.vy - star.vy);
rocket.vx += ax * h;
rocket.vy += ay * h;
rocket.x += rocket.vx * h;
rocket.y += rocket.vy * h;
rocket.modeAge += h;
}
stepSpring(rocket.thrust, 0, uiSpring, dt);
stepSpring(rocket.alpha, 1, gentleSpring, dt);
}
export function stepRocket(rocket: Rocket, star: StarPose, dt: number): FieldEvent | undefined {
rocket.age += dt;
if (rocket.mode === "launch") {
stepLaunch(rocket, dt);
if (rocket.failing && rocket.modeAge > FAILING_CUT) setMode(rocket, "fall", star);
else if (screenRadius(rocket.x, rocket.y) <= SHADOW_EDGE) {
rocket.mode = "gone";
rocket.arrived = true;
return { kind: "arrive", id: rocket.id };
}
return undefined;
}
if (rocket.mode === "fall") {
stepFall(rocket, star, dt);
const gap = Math.hypot(rocket.x - star.x, rocket.y - star.y);
const closing = Math.hypot(rocket.vx - star.vx, rocket.vy - star.vy);
if (rocket.modeAge > 0.4 && gap < 2.5 && closing < 20) {
rocket.mode = "gone";
return { kind: "impact", id: rocket.id };
}
return undefined;
}
rocket.modeAge += dt;
stepCircling(rocket, star, dt);
if (rocket.pendingLaunch) {
rocket.waitAge += dt;
if (inLaunchWindow(rocket) || rocket.waitAge > MAX_WAIT) startLaunch(rocket, rocket.failing);
}
if (rocket.mode === "land" && rocket.alpha.value < 0.03 && rocket.radius.value < 1.5) {
rocket.mode = "gone";
return { kind: "landed", id: rocket.id };
}
return undefined;
}
/** A deterministic scatter, so an explosion looks the same in a test and on screen. */
function scatter(seed: number, index: number) {
const value = Math.sin(seed * 127.1 + index * 311.7) * 43758.5453;
return value - Math.floor(value);
}
export function explode(rocket: Rocket): Debris[] {
const pieces: Debris[] = [];
for (let i = 0; i < 12; i++) {
const angle = scatter(rocket.seed, i) * Math.PI * 2;
const speed = 28 + 70 * scatter(rocket.seed, i + 40);
pieces.push({
x: rocket.x, y: rocket.y,
vx: rocket.vx * 0.35 + Math.cos(angle) * speed,
vy: rocket.vy * 0.35 + Math.sin(angle) * speed,
age: 0, life: 0.7 + 0.6 * scatter(rocket.seed, i + 80), size: 0.8 + 1.3 * scatter(rocket.seed, i + 120),
});
}
return pieces;
}
const DEBRIS_DRAG = 2.6;
function stepDebris(debris: Debris[], dt: number) {
const slow = Math.exp(-DEBRIS_DRAG * dt);
for (const piece of debris) {
piece.age += dt;
piece.vx *= slow;
piece.vy *= slow;
piece.x += piece.vx * dt;
piece.y += piece.vy * dt;
}
return debris.filter((piece) => piece.age < piece.life);
}
function pulse(field: Field, id: string) {
const swell = makeSpring(1);
swell.velocity = 0;
field.pulses.set(id, swell);
}
function burst(field: Field, rocket: Rocket) {
field.debris.push(...explode(rocket));
field.flares.set(rocket.id, makeSpring(1));
field.events.push({ kind: "boom", id: rocket.id });
pulse(field, rocket.id);
}
/** Apply something that happened to an orbit's backup. Returns false when there is no room for another rocket. */
export function applyActivity(field: Field, event: ActivityEvent, star: StarPose, seed = 1): boolean {
const existing = field.rockets.get(event.id);
if (event.kind === "dismiss") {
if (existing && existing.mode !== "launch") setMode(existing, "land", star);
return true;
}
const ensure = (intent: Exclude<Intent, "none">) => {
if (existing && existing.mode !== "gone") return existing;
if (field.rockets.size >= MAX_ROCKETS) return undefined;
const rocket = spawnRocket(event.id, star, intent, seed);
field.rockets.set(event.id, rocket);
return rocket;
};
if (event.kind === "begin") {
const rocket = ensure(event.intent);
if (!rocket) return false;
// A new run on an orbit whose rocket is still falling or flying takes over from where the rocket is.
rocket.pendingLaunch = false;
setMode(rocket, event.intent, star);
return true;
}
if (event.kind === "launch") {
const rocket = ensure("circle");
if (!rocket) return false;
if (rocket.mode === "pad" || rocket.mode === "ghost" || rocket.mode === "land") setMode(rocket, "circle", star);
if (rocket.mode === "circle" && rocket.alpha.value < 0.4) rocket.alpha.value = 1;
if (rocket.mode === "circle") requestLaunch(rocket);
else startLaunch(rocket);
return true;
}
if (event.kind === "land") {
if (existing) setMode(existing, "land", star);
return true;
}
// fail
const cause: FailureCause = event.cause;
const rocket = ensure("circle");
if (!rocket) {
field.flares.set(event.id, makeSpring(1));
field.events.push({ kind: "boom", id: event.id });
return false;
}
if (cause === "transfer") {
if (rocket.mode === "pad" || rocket.mode === "ghost" || rocket.mode === "land") setMode(rocket, "circle", star);
if (rocket.mode === "circle") {
rocket.alpha.value = 1;
requestLaunch(rocket, true);
} else startLaunch(rocket, true);
return true;
}
burst(field, rocket);
field.rockets.delete(event.id);
return true;
}
export function stepField(field: Field, dt: number, starOf: (id: string) => StarPose | undefined): FieldEvent[] {
const out: FieldEvent[] = field.events.splice(0);
let feeding = 0;
for (const [id, rocket] of field.rockets) {
const star = starOf(id);
if (!star) {
field.rockets.delete(id);
continue;
}
const event = stepRocket(rocket, star, dt);
if (rocket.mode === "launch") feeding = Math.max(feeding, smoothstep(140, SHADOW_EDGE, screenRadius(rocket.x, rocket.y)));
if (event) {
out.push(event);
if (event.kind === "arrive") pulse(field, id);
if (event.kind === "impact") {
// The rocket comes down hard: the star flares and the failure is final.
field.flares.set(id, makeSpring(0.6));
pulse(field, id);
out.push({ kind: "boom", id });
}
field.rockets.delete(id);
}
}
stepSpring(field.absorption, feeding, ambientSpring, dt);
field.debris = stepDebris(field.debris, dt);
for (const [id, flare] of field.flares) {
stepSpring(flare, 0, gentleSpring, dt);
if (flare.value < 0.01 && Math.abs(flare.velocity) < 0.05) field.flares.delete(id);
}
for (const [id, swell] of field.pulses) {
stepSpring(swell, 0, gentleSpring, dt);
if (swell.value < 0.01 && Math.abs(swell.velocity) < 0.05) field.pulses.delete(id);
}
return out;
}
/** Whether anything in the field still needs frames. */
export function fieldActive(field: Field): boolean {
return field.rockets.size > 0 || field.debris.length > 0 || field.flares.size > 0 || field.pulses.size > 0
|| Math.abs(field.absorption.value) > 0.004 || Math.abs(field.absorption.velocity) > 0.004;
}
/** True while an orbit's outcome is still playing out, so its star keeps looking busy until the moment of truth. */
export function holding(field: Field, id: string): boolean {
const rocket = field.rockets.get(id);
return !!rocket && (rocket.pendingLaunch || rocket.mode === "launch" || rocket.mode === "fall");
}

57
web/src/lib/trail.ts Normal file
View File

@@ -0,0 +1,57 @@
// A trail is the path a thing actually flew: its recent positions, drawn as a smooth curve. Because it is built from
// where the rocket has been rather than from where it is pointing, it curves when the path curves, loops when the rocket
// circles, and lengthens as the rocket speeds up.
export type TrailPoint = { x: number; y: number; t: number };
export type Trail = { id: string; clock: number; points: TrailPoint[] };
/** How much of its recent path a rocket remembers, in seconds of scene time. */
export const TRAIL_SECONDS = 0.65;
export const TRAIL_MAX_POINTS = 48;
/** Points closer together than this add nothing to the curve. */
export const TRAIL_MIN_SPACING = 0.7;
/** A move bigger than this in one frame is a teleport, not motion: the old path no longer applies. */
export const TRAIL_JUMP = 60;
export function createTrail(id: string): Trail {
return { id, clock: 0, points: [] };
}
/** Record the rocket's position for this frame. Returns the same trail, or a fresh one if the path was broken. */
export function advanceTrail(trail: Trail | undefined, id: string, x: number, y: number, dt: number): Trail {
const tail = trail?.points.at(-1);
let current = trail;
if (!current || current.id !== id || (tail && Math.hypot(x - tail.x, y - tail.y) > TRAIL_JUMP)) current = createTrail(id);
current.clock += dt;
const last = current.points.at(-1);
if (!last || Math.hypot(x - last.x, y - last.y) >= TRAIL_MIN_SPACING) current.points.push({ x, y, t: current.clock });
else last.t = current.clock;
while (
current.points.length > TRAIL_MAX_POINTS
|| (current.points.length > 2 && current.clock - current.points[0].t > TRAIL_SECONDS)
) current.points.shift();
return current;
}
/** Length of the trail along the path it was flown. */
export function trailLength(points: readonly { x: number; y: number }[]) {
let length = 0;
for (let i = 1; i < points.length; i++) length += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
return length;
}
/**
* A smooth path through a trail: quadratic segments that run through the midpoints of the polyline, so the corners
* between frames are rounded off while the curve stays within the path that was flown.
*/
export function smoothPath(points: readonly { x: number; y: number }[]) {
if (points.length < 2) return "";
let d = `M${points[0].x.toFixed(2)} ${points[0].y.toFixed(2)}`;
for (let i = 1; i < points.length - 1; i++) {
const mx = (points[i].x + points[i + 1].x) / 2;
const my = (points[i].y + points[i + 1].y) / 2;
d += `Q${points[i].x.toFixed(2)} ${points[i].y.toFixed(2)} ${mx.toFixed(2)} ${my.toFixed(2)}`;
}
const last = points[points.length - 1];
return `${d}L${last.x.toFixed(2)} ${last.y.toFixed(2)}`;
}