diff --git a/docs/UI.md b/docs/UI.md index 57bfbf4..1aee8f4 100644 --- a/docs/UI.md +++ b/docs/UI.md @@ -19,7 +19,23 @@ The persistent viewport maps backup jobs and recovery points. The black hole rep - The map preserves each orbit's assigned slot across polling updates. Layout and snapshot grouping live in `web/src/lib/galaxyLayout.ts`. - Snapshot summaries carry `orbit_id`. When connected to an older hub, the UI groups by name only if the name is unique. - Successful capture preserves HTTP 204 and supplies `X-Tessera-Snapshot-Id` when it retained a new snapshot. Automatic decay applies to that orbit's history. -- The scene uses SVG with static artwork and one animation clock. The clock pauses when the tab is hidden. Labels are laid out in screen coordinates. +- The orbits, markers, moons and selection are SVG on one animation clock. The black hole and the sky behind it are a single WebGL2 shader in `web/src/lib/blackhole/`. The clock pauses when the tab is hidden. Labels are laid out in screen coordinates. + +## Black hole renderer + +- Each pixel is a light ray traced through Schwarzschild spacetime (`geodesic.ts`, mirrored in the GLSL in `shaders.ts`). Rays that fall in are black, rays that cross the disk plane pick up Doppler-beamed disk light, and rays that escape sample the sky. The shadow, the arch of the far side of the disk, the second image and the Einstein ring all come from that, not from artwork. Far from the hole the integrator is skipped for the weak-field deflection. The thin ring hugging the shadow is real: it is light that skimmed the photon sphere. It stays on by default, and `rimCut` can fade it out. +- The proportions follow reference imagery of a thin disk seen from a low angle: the disk reaches about 26 M, roughly five times the shadow's radius, the camera sits 8° above the disk plane, the disk is optically thick near the hole and thins toward its rim, and its brightness falls steeply outward. In the app the shadow is 34 scene units across its radius, so the disk ends just past the first orbit ring. The disk plane is not the orbit plane: the orbits keep their own 0.68 tilt. +- The disk's texture is filtered by how many pixels each feature covers: noise octaves too fine to resolve collapse to their mean and melt into a smooth glow, so thin lines cannot alias into moire. Light bent a long way round the hole is squeezed onto fewer pixels, so it is filtered harder. The gas shears with differential rotation, and the whole pattern flows faster near the hole. +- The sky must never rival the orbit markers drawn over it. Point sources in the bake (stars and distant galaxies) are small, few, and capped in brightness (`POINT_CAP`), and every marker has a soft dark backing disc and a dark outline, so it stays readable over any haze. Treat both as a contract: a sky change that adds bright features near the orbits breaks clickability. +- The sky is baked once into a cubemap at load and sampled per pixel. It is a procedural galaxy with a bulge, dust lanes, nebulae, distant galaxies and stars. +- The canvas sits under the whole scene panel and follows `.galaxy-frame` through its bounding rectangle, so the hole stays centred on the orbits while the frame springs between the workspace and Big Screen. Drawing happens in Motion's post-render step so it never lags the frame's transform. +- The galaxy loop publishes its disk clock and the capture absorption to the renderer through a shared signal, so Flowing, coasting and capture spin-up drive the disk. A locked map renders once and sleeps. +- Quality adapts to the device. A few synchronised frames are timed at startup and after a resize, and the tier steps down until the median fits the frame budget: `high`, `medium`, `low`, `minimal`, then `still`, which freezes ambient motion. Ambient drawing is capped at 30 fps or lower. Tiers and the governor live in `quality.ts`. +- Without WebGL2, or after a lost context, the scene falls back to the SVG core and backdrop. +- **Radar view** in the map toolbar switches between the realistic and radar looks. The choice is remembered per browser. Without WebGL2 the button is hidden. The radar sweep runs on its own clock rather than the scene's, so it keeps turning on a locked map. Reduced motion switches looks at once and holds the sweep still and evenly lit, and the still quality tier does the same. A page that loads with the radar look applies it at once, with no wave. While the sweep runs the map redraws at the tier's frame-rate cap, so radar costs more battery than a locked realistic map, which draws nothing. +- The radar look draws range rings every 6 M, a bearing scale at 30 M just outside the disk, a crosshair and a rotating sweep head whose phosphor fades behind it. The lensed grid only shows outside about 20 M, so it never crowds the disk. The disk is drawn as contour bands equal in log brightness, and the long dim outer disk stays faint so the inner contours carry the weight. +- 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. + ## Animation guideline diff --git a/web/blackhole-proto.html b/web/blackhole-proto.html new file mode 100644 index 0000000..2909a1f --- /dev/null +++ b/web/blackhole-proto.html @@ -0,0 +1,39 @@ + + + + + + Black hole prototype + + + + +
WebGL2 is not available in this browser.
+
Shadow · 3√3 M
+
Accretion disk · 6–26 M
+

Black hole

+ + + diff --git a/web/scripts/blackhole-layout.test.mjs b/web/scripts/blackhole-layout.test.mjs new file mode 100644 index 0000000..ae3767a --- /dev/null +++ b/web/scripts/blackhole-layout.test.mjs @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { layoutFor } from "../src/lib/blackhole/layout.ts"; +import { SCENE_WIDTH } from "../src/lib/galaxyLayout.ts"; +import { CRITICAL_IMPACT } from "../src/lib/blackhole/geodesic.ts"; + +const panel = { left: 100, top: 50, width: 800, height: 600 }; + +test("the hole sits at the centre of the galaxy frame, relative to the panel", () => { + const frame = { left: 100 + 70, top: 50 + 60, width: 660, height: 480 }; + const { centerX, centerY } = layoutFor(frame, panel); + assert.ok(Math.abs(centerX - (70 + 330) / 800) < 1e-9); + assert.ok(Math.abs(centerY - (60 + 240) / 600) < 1e-9); +}); + +test("the shadow has a fixed radius in scene units and scales with the frame", () => { + const atNative = layoutFor({ left: 0, top: 0, width: SCENE_WIDTH, height: 480 }, panel); + assert.ok(Math.abs(atNative.pxPerM * CRITICAL_IMPACT - 34) < 1e-9); + const doubled = layoutFor({ left: 0, top: 0, width: SCENE_WIDTH * 2, height: 960 }, panel); + assert.ok(Math.abs(doubled.pxPerM - atNative.pxPerM * 2) < 1e-9); +}); + +test("a frame moving under a transition moves the hole with it", () => { + const before = layoutFor({ left: 200, top: 100, width: 600, height: 436 }, panel); + const after = layoutFor({ left: 240, top: 140, width: 600, height: 436 }, panel); + assert.ok(Math.abs(after.centerX - before.centerX - 40 / 800) < 1e-9); + assert.ok(Math.abs(after.centerY - before.centerY - 40 / 600) < 1e-9); + assert.equal(after.pxPerM, before.pxPerM); +}); diff --git a/web/scripts/geodesic.test.mjs b/web/scripts/geodesic.test.mjs new file mode 100644 index 0000000..9c9e6ff --- /dev/null +++ b/web/scripts/geodesic.test.mjs @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { CRITICAL_IMPACT, HORIZON, deflection, traceImpact, traceRay } from "../src/lib/blackhole/geodesic.ts"; + +test("a ray inside the critical impact parameter is captured and one outside escapes", () => { + assert.equal(traceImpact(CRITICAL_IMPACT * 0.94).outcome, "captured"); + assert.equal(traceImpact(CRITICAL_IMPACT * 1.06).outcome, "escaped"); +}); + +test("the shadow edge sits at the analytic 3√3 within the step error", () => { + let captured = 0; + let escaped = 10; + for (let i = 0; i < 24; i++) { + const mid = (captured + escaped) / 2; + const { outcome } = traceImpact(mid, 48, { maxSteps: 900 }); + if (outcome === "escaped") escaped = mid; + else captured = mid; + } + assert.ok(Math.abs(escaped - CRITICAL_IMPACT) / CRITICAL_IMPACT < 0.03, `edge at ${escaped}`); +}); + +test("weak-field deflection follows 4M/b plus the second-order term", () => { + const b = 20; + const expected = 4 / b + (15 * Math.PI) / 4 / (b * b); + const angle = deflection(traceImpact(b, 400, { maxSteps: 600 })); + assert.ok(Math.abs(angle - expected) / expected < 0.1, `${angle} vs ${expected}`); +}); + +test("a ray that falls radially is captured at the horizon", () => { + const trace = traceRay([0, 0, 30], [0, 0, -1]); + assert.equal(trace.outcome, "captured"); + assert.ok(trace.minRadius < HORIZON); +}); + +test("a ray in the disk plane never crosses it and a skewed ray crosses it once", () => { + assert.equal(traceImpact(9).crossings.length, 0); + const skew = traceRay([9, 14, 40], [0, -0.3, -0.95]); + assert.equal(skew.crossings.length, 1); + assert.equal(skew.crossings[0].point[1], 0); +}); diff --git a/web/scripts/look.test.mjs b/web/scripts/look.test.mjs new file mode 100644 index 0000000..434dd6b --- /dev/null +++ b/web/scripts/look.test.mjs @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createLook, jumpLook, requestLook, stepLook, styleAt, waveParams, WAVE_FEATHER } from "../src/lib/blackhole/look.ts"; +import { farthestCornerM } from "../src/lib/blackhole/layout.ts"; + +const run = (look, seconds, fps = 60) => { + const progress = []; + for (let i = 0; i < seconds * fps; i++) { + stepLook(look, 1 / fps); + progress.push(look.progress); + } + return progress; +}; + +test("the wave expands from the hole, never overshoots, and settles on the new look", () => { + const look = createLook(0); + requestLook(look, 1); + assert.equal(look.running, true); + assert.equal(look.progress, 0); + const progress = run(look, 3); + for (let i = 1; i < progress.length; i++) { + assert.ok(progress[i] >= progress[i - 1] - 1e-12, "progress never goes backwards"); + assert.ok(progress[i] <= 1, "progress never overshoots"); + } + assert.equal(look.running, false); + assert.equal(look.from, 1); + assert.equal(look.to, 1); + const finishedAt = progress.findIndex((value) => value === 1); + assert.ok(finishedAt > 20 && finishedAt < 150, `settled after ${finishedAt} frames`); +}); + +test("a request made mid-wave waits for the wave to finish instead of reversing it", () => { + const look = createLook(0); + requestLook(look, 1); + run(look, 0.3); + const before = look.progress; + requestLook(look, 0); + assert.equal(look.queued, 0); + assert.equal(look.to, 1, "the running wave keeps its target"); + assert.ok(look.progress >= before); + run(look, 4); + assert.equal(look.running, false); + assert.equal(look.to, 0, "the queued look ran afterwards"); +}); + +test("asking for the look that is already showing does nothing, and the queue follows the latest request", () => { + const look = createLook(1); + requestLook(look, 1); + assert.equal(look.running, false); + requestLook(look, 0); + assert.equal(look.running, true); + requestLook(look, 1); + assert.equal(look.queued, 1, "asking for the old look mid-wave queues it"); + requestLook(look, 0); + assert.equal(look.queued, undefined, "asking for the running target again cancels the queue"); + assert.equal(look.to, 0); +}); + +test("pixels inside the front show the new look and pixels outside keep the old one", () => { + const look = createLook(0); + requestLook(look, 1); + run(look, 0.4); + const wave = waveParams(look, 50); + assert.equal(styleAt(wave, 0), 1); + assert.equal(styleAt(wave, wave.waveRadius + 1), 0); + const middle = styleAt(wave, wave.waveRadius - WAVE_FEATHER / 2); + assert.ok(middle > 0 && middle < 1, "the front is soft"); +}); + +test("the front covers the whole picture by the time the wave finishes, and fades as it goes", () => { + const look = createLook(0); + requestLook(look, 1); + const fronts = []; + const radii = []; + for (let i = 0; i < 240 && look.running; i++) { + stepLook(look, 1 / 60); + const wave = waveParams(look, 50); + fronts.push(wave.waveFront); + radii.push(wave.waveRadius); + } + for (let i = 1; i < fronts.length; i++) { + assert.ok(fronts[i] <= fronts[i - 1] + 1e-12); + assert.ok(radii[i] >= radii[i - 1] - 1e-12); + } + const settled = waveParams(look, 50); + assert.equal(settled.waveFront, 0); + assert.equal(settled.styleFrom, 1); + assert.equal(styleAt(settled, 49), 1); +}); + +test("the wave has to travel as far as the farthest corner", () => { + const radius = farthestCornerM({ x: 300, y: 200 }, { width: 800, height: 600 }, 10); + assert.ok(Math.abs(radius - Math.hypot(500, 400) / 10) < 1e-9); +}); + +test("jumping to a look drops any wave and any queued request", () => { + const look = createLook(0); + requestLook(look, 1); + run(look, 0.2); + requestLook(look, 0); + jumpLook(look, 1); + assert.equal(look.running, false); + assert.equal(look.from, 1); + assert.equal(look.to, 1); + assert.equal(look.queued, undefined); + assert.equal(waveParams(look, 50).waveFront, 0); + assert.equal(styleAt(waveParams(look, 50), 40), 1); +}); diff --git a/web/scripts/quality.test.mjs b/web/scripts/quality.test.mjs new file mode 100644 index 0000000..faae31c --- /dev/null +++ b/web/scripts/quality.test.mjs @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { FRAME_BUDGET_MS, FREEZE_BUDGET_MS, QUALITY_TIERS, chooseTier, initialTier } from "../src/lib/blackhole/quality.ts"; + +const samples = (ms, count = 30) => Array.from({ length: count }, () => ms); + +test("the governor steps down one tier when the median render time exceeds the budget", () => { + assert.equal(chooseTier({ tier: 0, samples: samples(FRAME_BUDGET_MS + 4), sinceChangeMs: 5000 }), 1); + assert.equal(chooseTier({ tier: 0, samples: samples(FRAME_BUDGET_MS - 4), sinceChangeMs: 5000 }), 0); +}); + +test("the governor ignores a lone spike, too few samples and a tier that has not settled", () => { + const spiky = [...samples(4, 29), 90]; + assert.equal(chooseTier({ tier: 1, samples: spiky, sinceChangeMs: 5000 }), 1); + assert.equal(chooseTier({ tier: 1, samples: samples(40, 5), sinceChangeMs: 5000 }), 1); + assert.equal(chooseTier({ tier: 1, samples: samples(40), sinceChangeMs: 200 }), 1); +}); + +test("the governor stops at the lowest tier and never steps back up", () => { + const last = QUALITY_TIERS.length - 1; + assert.equal(chooseTier({ tier: last, samples: samples(80), sinceChangeMs: 5000 }), last); + assert.equal(chooseTier({ tier: 2, samples: samples(0.5), sinceChangeMs: 5000 }), 2); +}); + +test("motion only freezes when the lowest animated tier is clearly failing", () => { + const minimal = QUALITY_TIERS.findIndex(({ name }) => name === "minimal"); + assert.equal(chooseTier({ tier: minimal, samples: samples(FREEZE_BUDGET_MS - 4), sinceChangeMs: 5000 }), minimal); + assert.equal(chooseTier({ tier: minimal, samples: samples(FREEZE_BUDGET_MS + 4), sinceChangeMs: 5000 }), minimal + 1); + assert.equal(QUALITY_TIERS[minimal + 1].maxFps, 0); +}); + +test("tiers get strictly cheaper and software rendering starts at the bottom", () => { + for (let i = 1; i < QUALITY_TIERS.length; i++) { + assert.ok(QUALITY_TIERS[i].scale <= QUALITY_TIERS[i - 1].scale); + assert.ok(QUALITY_TIERS[i].steps <= QUALITY_TIERS[i - 1].steps); + assert.ok(QUALITY_TIERS[i].maxFps <= QUALITY_TIERS[i - 1].maxFps); + } + assert.equal(initialTier({ software: true, pixels: 1e6 }), QUALITY_TIERS.length - 1); + assert.equal(initialTier({ software: false, cores: 8, memoryGb: 16, pixels: 2e6 }), 0); + assert.equal(initialTier({ software: false, cores: 4, pixels: 2e6 }), 1); +}); diff --git a/web/src/App.tsx b/web/src/App.tsx index 278ef78..34b37f9 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -31,6 +31,17 @@ const panelTitles: Record = { snapshot: "Snapshot detail", }; +const LOOK_KEY = "tessera.look"; + +/** The look is a per-viewer preference. Storage can be blocked or empty, so every access is guarded. */ +function readRadar() { + try { + return window.localStorage.getItem(LOOK_KEY) === "radar"; + } catch { + return false; + } +} + function priority(orbit: Orbit) { if (orbit.last_status === "failed") return 0; return orbitStatus(orbit.last_status).busy ? 1 : 2; @@ -44,6 +55,7 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis const [logoutError, setLogoutError] = useState(false); const workspaceScroll = useRef(undefined); const [bigScreen, setBigScreen] = useState(false); + const [radar, setRadar] = useState(readRadar); const [mode, setMode] = useState("scene"); const [searchOpen, setSearchOpen] = useState(false); const searchTrigger = useRef(null); @@ -109,6 +121,15 @@ function VaultApp({ actor, onLogout }: { actor?: string; onLogout?: () => Promis if (!bigScreen) workspaceScroll.current = window.scrollY; setBigScreen(!bigScreen); } + function toggleRadar() { + const next = !radar; + setRadar(next); + try { + window.localStorage.setItem(LOOK_KEY, next ? "radar" : "realistic"); + } catch { + // The look still changes for this visit; it just will not be remembered. + } + } const health = useQuery({ queryKey: ["health"], queryFn: fetchHealth, refetchInterval: 15_000, retry: 1 }); const snaps = useQuery({ queryKey: ["snapshots"], queryFn: fetchSnapshots, refetchInterval: 8_000, retry: 1 }); @@ -256,6 +277,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} onToggleFlow={() => setPlay((value) => !value)} onSelectOrbit={(id) => { selectOrbit(id); diff --git a/web/src/components/scene/BlackholeBackdrop.tsx b/web/src/components/scene/BlackholeBackdrop.tsx new file mode 100644 index 0000000..3c66096 --- /dev/null +++ b/web/src/components/scene/BlackholeBackdrop.tsx @@ -0,0 +1,65 @@ +import { useLayoutEffect, useRef } from "react"; +import { createBlackholeController, type BlackholeController, type CoreSignal } from "../../lib/blackhole/controller"; + +/** + * The black hole and the sky behind it, drawn by one WebGL2 shader. It sits under the whole scene panel and follows + * the galaxy frame, which springs between the workspace and Big Screen. + */ +export function BlackholeBackdrop({ signal, bigScreen, radar, reducedMotion, onUnavailable }: { + signal: CoreSignal; + bigScreen: boolean; + radar: boolean; + reducedMotion: boolean; + onUnavailable: () => void; +}) { + const canvas = useRef(null); + const controller = useRef(undefined); + const unavailable = useRef(onUnavailable); + unavailable.current = onUnavailable; + + useLayoutEffect(() => { + const element = canvas.current; + const panel = element?.closest(".vault-scene"); + const created = element && panel && createBlackholeController({ + canvas: element, + panel, + frame: () => panel.querySelector(".galaxy-frame"), + signal, + onLost: () => unavailable.current(), + }); + if (!created) { + unavailable.current(); + return; + } + controller.current = created; + signal.wake = created.wake; + return () => { + signal.wake = undefined; + controller.current = undefined; + created.dispose(); + }; + }, [signal]); + + // The radar look arrives as a wave from the hole. The look the page loads with is applied at once, with no wave. + const styled = useRef(undefined); + useLayoutEffect(() => { + controller.current?.setReducedMotion(reducedMotion); + }, [reducedMotion]); + useLayoutEffect(() => { + // A new controller (first mount, or a StrictMode remount) takes the current look at once; later changes animate. + const fresh = styled.current !== controller.current; + styled.current = controller.current; + controller.current?.setLook(radar ? 1 : 0, fresh); + }, [radar]); + + // The frame moves under a spring when the mode changes, so keep drawing until it settles. + useLayoutEffect(() => { + controller.current?.track(2200); + }, [bigScreen]); + + return ( + + ); +} diff --git a/web/src/components/scene/BlackholeGalaxy.tsx b/web/src/components/scene/BlackholeGalaxy.tsx index 6bbfa67..dfa56bb 100644 --- a/web/src/components/scene/BlackholeGalaxy.tsx +++ b/web/src/components/scene/BlackholeGalaxy.tsx @@ -11,6 +11,7 @@ import { useGalaxyMotion } from "../../hooks/useGalaxyMotion"; import { useScreenTransition } from "../../hooks/useScreenTransition"; import { ambientSpring, gentleSpring, uiSpring } from "../../lib/motion"; import { VaultCore } from "./VaultCore"; +import type { CoreSignal } from "../../lib/blackhole/controller"; export type CaptureEffect = { orbitId: string; key: number; snapshotId?: string }; @@ -23,6 +24,8 @@ type Props = { bigScreen: boolean; captureEffect?: CaptureEffect; captureGlow: MotionValue; + signal: CoreSignal; + svgCore: boolean; captureReady: boolean; onSelectOrbit: (id: string) => void; onSelectSnapshot: (id: string) => void; @@ -37,7 +40,7 @@ const ACCRETION_SECONDS = 6.4; const TRAIL_WIDTHS = [0.8, 1.4, 2.3]; export function BlackholeGalaxy({ - orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, captureReady, onSelectOrbit, onSelectSnapshot, + orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, signal, svgCore, captureReady, onSelectOrbit, onSelectSnapshot, }: Props) { const frame = useRef(null); const bodyNodes = useRef(new Map()); @@ -52,6 +55,7 @@ export function BlackholeGalaxy({ const diskTime = useRef(0); const hasRunning = orbits.some(orbit => orbitStatus(orbit.last_status).busy); const trailId = useId(); + const knockoutId = useId(); const trail = useRef(null); const trailSegments = useRef<(SVGUseElement | null)[]>([]); const head = useRef(null); @@ -213,6 +217,11 @@ export function BlackholeGalaxy({ const phase = (diskTime.current % ACCRETION_SECONDS) / ACCRETION_SECONDS; core.current?.style.setProperty("--accretion-offset", String(-100 * phase)); } + if (signal.time !== diskTime.current || signal.absorption !== absorption) { + signal.time = diskTime.current; + signal.absorption = absorption; + signal.wake?.(); + } const coreStyle = core.current?.style; if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) { coreStyle.setProperty("--capture-absorption", String(absorption)); @@ -270,6 +279,7 @@ export function BlackholeGalaxy({ data-orbit-marker={orbit.id} className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`} > + {status.tone === "red" && } @@ -283,12 +293,19 @@ export function BlackholeGalaxy({ return (

Vault map

@@ -48,6 +58,24 @@ export function VaultScene({ {reducedMotion ? "Reduced motion" : flowing ? "Pause motion" : "Resume motion"} + {!svgCore && ( + + )}