ridge runtime: one owner of the rotation mode and the hold; the offset range and the speed bound per mode; the arc swept, not sampled at its ends; the heading kept bounded

- cameraState owns the mode; heading.ts keeps only where the view was at a
  clock and integrates under the choice, listening to it. A manual turn sets
  the mode to still, so a rebuild or a reload keeps the hold and choosing a
  mode again (the one the viewer had included) resumes it. The second copy of
  the mode in heading.ts and the sync that re-applied it at every scene build
  are deleted. Reduced motion is an override in heading.ts (freeze).
- offsetRange takes the mode (and the camera's angle): the forward bound
  camera.r_max_forward_m where the camera stays on its heading, the worst-case
  camera.r_max_m where it circles and for a backward offset, the nearest card's
  foot clamp on both sides where the circle takes the offset round to phi 180.
  The default +200 m is clamped by the range of the current mode.
- maxSpeed: the speed the baked resident count sustains, applied to the stored
  choice at the scene start and on every change.
- sweepArc: the arc of every pose of the next 30 s, sampled four times a
  second; the rig mounts and asks the loader for that, and lays out in the same
  tick as it issues a stretch.
- heading.normalize brings h and phi into [0, 360) before each stretch, so
  transforms and tile positions stay small however long the page is open.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-23 01:01:57 +01:00
commit 35c3f825a8
12 changed files with 619 additions and 145 deletions

View file

@ -9,7 +9,7 @@ The live noise ridge is nearly invisible on a phone (about 1.35:1 against the da
- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only the ring's residency, the camera's pose against its heading, blending and compositing. No ridge geometry is computed in the browser.
- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it.
- Phone cost is bounded: no per-frame script for the ridge, decoded size and fetched size gated in CI.
- The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps or wraps the heading but `ridge/ring.ts`.
- The ring is the bake and the heading is unbounded: the whole 360 degrees ships as azimuth tiles, the client holds only the arc it is about to need and fetches more as the view turns, and nothing caps the heading: it is unwrapped within a stretch of motion and `ridge/heading.ts` `normalize` brings it into [0, 360) before each one, so no angle or pixel position grows with uptime, while `ridge/ring.ts` is the one place that reasons about the wrap at 0 / 360.
- Motion is derived, not authored: a card's scale and shift come each second from the heading, the camera's angle on its circle, the viewer's offset and the card's distance (`ridge/view.ts` `cardPose`), and ride the compositor as one animation per card.
- The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause.
- A baked asset names its baker version, DEM source and licence in a validated manifest; the credits shown in the Sky menu come from the manifest.

View file

@ -31,7 +31,7 @@ behind a cell is the app's own, without clouds. Not shipped.
...ridgeSheet.html?views=214:0:200,0:0:200,214:90:98.2&sky=2 # one column per view heading:phi:offset (degrees, degrees, metres) at one sky (an index of SKIES)
A heading of 0 or 360 is across north; a phi other than 0 is the offset-only rotation mode (the camera circling the centre, the view direction staying); the offset is
clamped to the place's range as the app does.
clamped to the place's range as the app does (phi 0: `camera.r_max_forward_m`, another phi: `camera.r_max_m`).
npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/
http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies

View file

@ -1,7 +1,7 @@
// Look sheet for the lit ridge cards: a baked place lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas drawn by the app's own still path
// (`createRidgeScene` at tier 'still', the tiles of the arc round the heading, each card at `cardPose`). Not shipped.
// `?views=214:0:200,0:0:200,100:0:200,214:90:98.2` one column per view `heading:phi:offset` (degrees, degrees, metres) at one sky (`?sky=2`, an index of SKIES, noon by default); a heading
// of 360 or 0 is across north. The offset is clamped to the place's range as the app does, and a phi other than 0 is the offset-only rotation mode, the camera circling the centre.
// of 360 or 0 is across north. The offset is clamped to the place's range as the app does (phi 0: the bake's forward bound, any other phi: the worst-case bound), and a phi other than 0 is the offset-only rotation mode, the camera circling the centre.
// `?place=vienna` the baked place (index.json's default if absent)
// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=<JSON array, url-encoded or base64>` replaces the rows with
// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
@ -20,7 +20,7 @@ import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view
import { onScreen } from '../../src/app/features/scene/ridge/nightBodies';
import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop';
import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge';
import { anchor, hold, setMode, setRate } from '../../src/app/features/scene/ridge/heading';
import { anchor, hold } from '../../src/app/features/scene/ridge/heading';
import { setCamera } from '../../src/app/features/scene/cameraState';
import { sunAt } from '../../src/app/features/scene/ridge/sunAt';
import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue';
@ -244,12 +244,10 @@ async function main() {
tr[r].insertCell().append(host);
// The heading owner as the app leaves it: this view's heading, the camera on its circle at phi (offset-only rotation), the offset the viewer chose.
const t0 = performance.now();
anchor(`sheet-${manifest.bakeId}-${columns.indexOf(col)}-${r}`, v.h, t0 - 1); // a key of its own: every cell starts from phi 0
setMode('offset', t0 - 3_600_000);
setRate(1, t0 - 3_600_000);
hold(v.h, t0 - 3_600_000 + v.phi * 1000); // phi seconds of offset rotation, at 1 degree per second, then the view is held at h
setCamera({ offsetM: v.r, mode: 'still' });
const t0 = performance.now() - 3_600_000;
anchor(`sheet-${manifest.bakeId}-${columns.indexOf(col)}-${r}`, v.h, t0); // a key of its own: every cell starts from phi 0
setCamera({ mode: 'offset', speedDegPerS: 1, offsetM: v.r }, t0); // the offset-only rotation mode for phi seconds at 1 degree per second ...
hold(v.h, t0 + v.phi * 1000); // ... then the view is held at h: the mode is still, the camera stays at phi (phi 0 is the camera on its heading)
const backdrop = createBackdrop(manifest, physical, { lighter: (m, s) => createLighter(m, s, rows[r].look) });
await backdrop.ensure({ fromDeg: v.h - HFOV_MAX_DEG, toDeg: v.h + HFOV_MAX_DEG });

View file

@ -22,21 +22,22 @@ means "keep the CSS ground". Everything below this section describes the opt-in
unknown or absent: the index default), then the place's `manifest.json` (schema 3, written by `scripts/ridge-bake/export.py`; it is the one JSON
the backdrop reads): the whole 360 degree ring, K G-buffer cards nearest first, each cut into azimuth tiles (32 of 11.25 degrees) of a colour WebP (albedo,
straight alpha) and a geometry WebP (the normal as 'rt8', the log-distance, and the wall code R = G = 255 for the extruded face under a ridge), each tile
with the card's distance there; `camera.r_max_m` bounds the parallax offset. Schema 2 is refused with a message naming the stale deploy. `index.ts`
with the card's distance there; `camera.r_max_m` bounds the parallax offset over every angle of the camera on its circle and `camera.r_max_forward_m` with the camera on its heading alone. Schema 2 is refused with a message naming the stale deploy. `index.ts`
`prepare()` loads the manifest, anchors the heading (`ridge/heading.ts`) and, with the scene chunk, `ridge/Backdrop.ts` `createBackdrop`: `ensure(arc)`
fetches and decodes the tiles of an arc of azimuth it does not hold, one tile at a time (no premultiply, no colour management), and `ridge/lightCards.ts`
asks for the files of the tiles of an arc of azimuth it does not hold a few at a time (6 requests, each with a timeout) and decodes them one tile at a time (no premultiply, no colour management), and `ridge/lightCards.ts`
`createLighter` lights each card of a tile in WebGL2 for the sky of this build (sun and ambient from the atmosphere in absolute azimuth, aerial perspective from the
geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas of the tile's interior and one
overlap column each side. The backdrop holds the arc ahead and two tiles beyond and lets go of the rest; a tile that fails is absent and tried again. A sky change is a
overlap column each side. The backdrop holds the arc ahead and two tiles beyond and lets go of the rest; a tile that fails is absent and asked for again after a pause that doubles to a minute, and a file the server answers 404 is not asked for again (the tile is drawn with the cards that came). A sky change is a
rebuild, so it makes a new lighter; nothing is lit per frame, and the host canvas is only ever asked for 2d.
`createRidgeScene({ backdrop })` stays synchronous (`prepare()` awaits the first arc), and a rebuild keeps the old scene up until the new one is lit, then swaps; the
heading survives it. The rig is one div of K boxes, one per card (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's
parent), each holding that card's resident tiles at their unwrapped azimuth. A card's pose (scale and shift) is derived by `view.ts` `cardPose` from its distance at
the heading (`ring.ts`), the viewer's offset and the camera's angle on its circle, as a camera on a circle round the bake centre sees it (ruling ridge-camera-on-circle;
the offset is signed and clamped by `offsetRange`, the one clamp). `heading.ts` owns the view direction and the camera's angle (unwrapped degrees, module state, a manual
`hold` stops the rotation); `cameraState.ts` holds the viewer's mode, speed and offset in `ratatoskr.camera`. The motion is one `Element.animate` per card (transform only, a
the offset is signed and clamped by `offsetRange`, the one clamp, by the mode: the forward bound with the camera on its heading, the worst-case bound where it circles; the speed by `maxSpeed`,
what the baked resident count sustains, applied to the stored choice). `cameraState.ts` is the one owner of the viewer's mode, speed and offset in `ratatoskr.camera`; `heading.ts` owns the view direction and the camera's angle over it (module
state, normalized into [0, 360) before each stretch so nothing grows with uptime; a manual `hold` sets the mode to still, so a rebuild or a reload keeps it). The motion is one `Element.animate` per card (transform only, a
keyframe each second for 30 s, reissued at 80% and on any change; paused when the tab is hidden or motion is reduced, then constant); a 500 ms timer asks the backdrop for
the arc ahead and mounts the tiles it has made. A still draws the tiles of the arc into the host canvas at the heading now. The sky does not turn with the heading. A failure
the arc every pose of the next 30 s passes over (`view.ts` `sweepArc`, sampled four times a second, not its two ends) and mounts the tiles it has made. A still draws the tiles of the arc into the host canvas at the heading now. The sky does not turn with the heading. A failure
anywhere (404, a manifest that is not schema 3, no tile that will decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`,
told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale
or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`.

View file

@ -53,6 +53,13 @@ describe('the viewer camera', () => {
expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 2, offsetM: 50 });
});
it('tells listeners what the choice was and the clock it changed at, so the kinematics can be taken to that moment', () => {
const cb = vi.fn();
subscribe(cb);
setCamera({ mode: 'offset' }, 1234);
expect(cb).toHaveBeenCalledWith({ ...DEFAULT_CAMERA, mode: 'offset' }, DEFAULT_CAMERA, 1234);
});
it('ignores a stored value that is not a choice, and a change that is not one', () => {
store.set(CAMERA_KEY, '{"mode":"spin","speedDegPerS":1,"offsetM":0}');
expect(getCamera()).toEqual(DEFAULT_CAMERA);

View file

@ -1,6 +1,7 @@
// How the viewer wants the ridge camera to move: the rotation mode, the speed and the parallax offset, per viewer in localStorage. Intent only: the
// kinematics are `ridge/heading.ts`, the one clamp on the offset is `ridge/view.ts` `offsetRange`, and a scene applies this to both. Main-chunk safe
// (no ridge code is imported at runtime), as placeState and skyState are.
// How the viewer wants the ridge camera to move: the rotation mode, the speed and the parallax offset, per viewer in localStorage. The one owner of the
// mode (a manual turn sets it to 'still': `ridge/heading.ts` `hold`) and of the speed and offset as the viewer chose them; `ridge/heading.ts` integrates the
// view direction over it, the clamp on the offset is `ridge/view.ts` `offsetRange` and the bound on the speed `maxSpeed`, which a scene applies here when it
// knows the place. Main-chunk safe (no ridge code is imported at runtime), as placeState and skyState are.
import type { RotationMode } from './ridge/heading';
export const CAMERA_KEY = 'ratatoskr.camera';
@ -46,7 +47,9 @@ const reducedMotion = (): boolean => {
};
let current: CameraChoice | undefined;
const listeners = new Set<(c: CameraChoice) => void>();
type Listener = (next: CameraChoice, prev: CameraChoice, at: number) => void;
const listeners = new Set<Listener>();
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
function load(): CameraChoice {
try {
@ -64,8 +67,8 @@ export const getCamera = (): CameraChoice => {
return current;
};
/** Change any of the three; listeners hear it only when something moved. */
export function setCamera(change: Partial<CameraChoice>): void {
/** Change any of the three, at the clock `at` (ms, `performance.now()` by default); listeners hear it, with what it was and `at`, only when something moved. */
export function setCamera(change: Partial<CameraChoice>, at: number = clock()): void {
const next = parseCamera({ ...getCamera(), ...change });
if (!next) return;
const prev = getCamera();
@ -76,10 +79,10 @@ export function setCamera(change: Partial<CameraChoice>): void {
} catch {
// Storage is refused: the choice holds for this page load only.
}
[...listeners].forEach((cb) => cb(next));
[...listeners].forEach((cb) => cb(next, prev, at));
}
export function subscribe(cb: (c: CameraChoice) => void): () => void {
export function subscribe(cb: Listener): () => void {
listeners.add(cb);
return () => listeners.delete(cb);
}

View file

@ -12,8 +12,9 @@ import { parseManifest } from './manifest';
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
import type { Arc, Backdrop, LitTile } from './Backdrop';
import type { Mock } from 'vitest';
import { cardPose, FALLBACK_VIEW, offsetRange, windowFor } from './view';
import { anchor, getMode, headingAt, hold, phiAt, resetHeading } from './heading';
import { cardArc, cardPose, FALLBACK_VIEW, maxSpeed, offsetRange, windowFor } from './view';
import { residentTiles } from './ring';
import { anchor, headingAt, hold, phiAt, resetHeading } from './heading';
import { getCamera, resetCamera, setCamera } from '../cameraState';
describe('noise', () => {
@ -706,7 +707,7 @@ describe('the ridge cards in the scene', () => {
});
const clampOffset = () => {
const [lo, hi] = offsetRange(manifest, win);
const [lo, hi] = offsetRange(manifest, win, getCamera().mode, phiAt(T0));
return Math.min(hi, Math.max(lo, getCamera().offsetM));
};
@ -718,15 +719,21 @@ describe('the ridge cards in the scene', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const rig = rigOf(parent);
const out = { ids: mountedIds(rig), left: Number(rig.children[2].children[0].style.left.slice(0, -2)) };
const out = {
ids: mountedIds(rig),
left: Number(rig.children[2].children[0].style.left.slice(0, -2)),
heading: headingAt(T0),
};
s.dispose();
return out;
};
// Manual turns leave the rotation off; the default is 'both', which the scene applies over the hold, so the view keeps turning from the held angle.
// A manual turn leaves the rotation off, and a scene made over it keeps it off.
const a = at(40);
const b = at(400);
expect(b.ids).toEqual(a.ids);
expect(b.left - a.left).toBeCloseTo(360 * k, 4);
// The rig lays out from the heading brought into [0, 360): a revolution on is the same picture, with nothing grown.
expect(b.heading).toBeCloseTo(a.heading, 9);
expect(b.left).toBeCloseTo(a.left, 6);
});
it('asks the backdrop for the arc between now and the end of the stretch, at once and every half second, and mounts what it has made', async () => {
@ -804,7 +811,8 @@ describe('the ridge cards in the scene', () => {
motion.matches = true;
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
expect(getMode()).toBe('still');
expect(headingAt(T0 + 10_000)).toBe(headingAt(T0)); // nothing turns, whatever the viewer chose
expect(getCamera().mode).toBe('both'); // and the viewer's choice is not rewritten for it
rigOf(parent).children.forEach((box: any) => {
const { keyframes } = live(box)[0];
expect(keyframes.length).toBeGreaterThan(0);
@ -843,6 +851,160 @@ describe('the ridge cards in the scene', () => {
resumed.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
});
describe('after the viewer takes the view by hand, and for the long run', () => {
const fixtureRing = (camera: Record<string, number> = { r_max_m: 98.2, r_max_forward_m: 205.4 }) =>
parseManifest(wireManifest({ camera }, 3, 32), '/d/'); // the ring as the baker cuts it, with Vienna's two offset bounds
const ringBackdrop = (m: typeof manifest): Backdrop & { ensure: Mock<[Arc], Promise<void>> } => {
const lit = m.tiles.flatMap((row, tile) =>
row.flatMap((e, card) => {
if (!e) return [];
const canvas = fakeEl('canvas');
canvas.id = `t${tile}c${card}`;
return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }];
})
);
return {
manifest: m,
ensure: vi.fn(async (_arc: Arc): Promise<void> => undefined),
litTiles: () => lit,
dispose: vi.fn(),
};
};
const frame = (box: any, n: number) => live(box)[0].keyframes[n].transform as string;
const pending = () => {
vi.useFakeTimers();
(window as any).setTimeout = setTimeout;
(window as any).clearTimeout = clearTimeout;
};
it('a manual turn holds through a rebuild: a resize makes a new scene and the view stays where the viewer left it', () => {
pending();
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
hold(100, T0);
const at = headingAt(T0);
window.dispatchEvent(new Event('resize'));
vi.advanceTimersByTime(300); // the debounced rebuild: startRig runs again
expect(getCamera().mode).toBe('still');
expect(headingAt(T0 + 60_000)).toBe(at);
rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).toBe(frame(box, 0)));
s.dispose();
// And a scene made afterwards, as a sky change makes one.
const again = createRidgeScene({ canvas: host().canvas, tier: 'full', sky: night, backdrop: litCards() })!;
expect(headingAt(T0 + 60_000)).toBe(at);
again.dispose();
vi.useRealTimers();
});
it('picking the mode they already had after a hold resumes the turn, and the rig moves again', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
hold(100, T0);
rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).toBe(frame(box, 0)));
setCamera({ mode: 'both' }); // what the View's rotation picker sends: the mode the viewer had when they took the view
expect(headingAt(T0 + 10_000)).toBeCloseTo(106, 9);
rigOf(parent).children.forEach((box: any) => expect(frame(box, 30)).not.toBe(frame(box, 0)));
s.dispose();
});
it('mounts and asks for the tiles of every pose a stretch passes through, not those at its ends: offset-only turning swings the near card out and back', () => {
pending();
const ring = fixtureRing();
const bd = ringBackdrop(ring);
const w2 = windowFor(ring.view, 400, 800);
setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 98 });
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!;
vi.advanceTimersByTime(500);
const asked = bd.ensure.mock.calls[0][0];
const [, hi] = offsetRange(ring, w2, 'offset');
let from = Infinity;
let to = -Infinity;
let endFrom = Infinity;
let endTo = -Infinity;
for (let ms = 0; ms <= 30_000; ms += 100) {
for (let i = 0; i < 3; i += 1) {
const a = cardArc(ring.view, w2, 400, cardPose(ring, i, headingAt(T0 + ms), phiAt(T0 + ms), Math.min(hi, 98), w2));
from = Math.min(from, a.fromDeg);
to = Math.max(to, a.toDeg);
if (ms === 0 || ms === 30_000) {
endFrom = Math.min(endFrom, a.fromDeg);
endTo = Math.max(endTo, a.toDeg);
}
}
}
expect(endTo - endFrom).toBeLessThan(to - from - 5); // the ends alone miss degrees of it (a whole turn of the camera comes back to where it began)
expect(asked.fromDeg).toBeLessThanOrEqual(from + 0.01);
expect(asked.toDeg).toBeGreaterThanOrEqual(to - 0.01);
const need = new Set(residentTiles(ring.view, (from + to) / 2, (to - from) / 2 - 0.02).map((r) => r.tile));
const mounted = new Set(mountedIds(rigOf(parent)).map((id) => Number(/^t(\d+)c/.exec(id)?.[1])));
need.forEach((t) => expect(mounted.has(t), `tile ${t}`).toBe(true));
s.dispose();
vi.useRealTimers();
});
it('takes the default 200 m where the camera stays on its heading and the bake allows it, and the worst-case bound where the camera circles', () => {
const ring = fixtureRing();
const w2 = windowFor(ring.view, 400, 800);
const keyframe0 = (mode: 'both' | 'offset') => {
setCamera({ mode, speedDegPerS: 0.6, offsetM: 200 });
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
const got = frame(rigOf(parent).children[2], 0);
s.dispose();
return got;
};
const posed = (offset: number) => {
const p = cardPose(ring, 0, headingAt(T0), phiAt(T0), offset, w2);
return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
};
expect(keyframe0('both')).toBe(posed(200));
expect(keyframe0('offset')).toBe(posed(98.2));
});
it('bounds the speed to what the baked resident count sustains, in the stored choice itself, at the scene start and on every change', () => {
const ring = fixtureRing();
const slow = maxSpeed(ring, 'both');
expect(slow).toBeGreaterThan(0.6);
expect(slow).toBeLessThan(12);
setCamera({ mode: 'both', speedDegPerS: 50 }); // a stored or future-slider value
const { canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
expect(getCamera().speedDegPerS).toBe(slow);
setCamera({ speedDegPerS: -50 });
expect(getCamera().speedDegPerS).toBe(-slow);
setCamera({ mode: 'offset', speedDegPerS: 11 }); // the offset-only mode sweeps the circle the gate counts, whatever the speed
expect(getCamera().speedDegPerS).toBe(11);
setCamera({ mode: 'both' }); // and back to the view turning: the bound of that mode holds
expect(getCamera().speedDegPerS).toBe(slow);
expect(headingAt(T0 + 10_000) - headingAt(T0)).toBeCloseTo(10 * slow, 9);
s.dispose();
});
it('keeps the angles, the transforms and the tile positions bounded after days of uptime: the rig normalizes before each stretch', () => {
const now = vi.mocked(performance.now);
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const fiveDays = 5 * 86_400_000;
now.mockReturnValue(T0 + fiveDays);
setCamera({ offsetM: 20 }); // any change issues the next stretch from the clock now
const h = headingAt(T0 + fiveDays);
expect(h).toBeGreaterThanOrEqual(0);
expect(h).toBeLessThan(360 + 1);
expect(h).toBeCloseTo((214 + 0.6 * (fiveDays / 1000)) % 360, 4); // the view is where five days of turning put it
const rig = rigOf(parent);
const shifts = rig.children.flatMap((box: any) =>
live(box)[0].keyframes.map((f: any) => Math.abs(Number(/translate3d\((-?[\d.e+-]+)px/.exec(f.transform)?.[1])))
);
expect(Math.max(...shifts)).toBeLessThan(100_000); // days of turning would be millions of px
rig.children.forEach((box: any) =>
box.children.forEach((c: any) => expect(Math.abs(parseFloat(c.style.left))).toBeLessThan(100_000))
);
expect(mountedIds(rig).length).toBeGreaterThan(0); // the tiles the heading shows are mounted, not lost in the wrap
s.dispose();
});
});
it('a still draws the tiles of the arc in the host canvas, farthest card first, each card at its pose about the rig’s origin, at the heading now', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: litCards() });

View file

@ -3,12 +3,12 @@ import { overlayRequested } from '../debugOverlays';
import { FrameSampler, FrameStats } from './probe';
import { skyColours, SkyColours, Srgb } from './skyColour';
import { paintSky as paintPhysicalSky } from './physicalSky';
import { cardArc, cardPose, offsetRange, windowFor } from './view';
import { cardArc, cardPose, maxSpeed, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view';
import type { CardPose, View } from './view';
import type { TileCard } from './manifest';
import { residentTiles } from './ring';
import { headingAt, phiAt, setMode, setRate, subscribe as onHeading } from './heading';
import { getCamera, subscribe as onCamera } from '../cameraState';
import { freeze, headingAt, normalize, phiAt, subscribe as onHeading } from './heading';
import { getCamera, setCamera, subscribe as onCamera } from '../cameraState';
import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars';
import { nightBodies, paintNightBodies } from './nightBodies';
import type { NightBodies } from './nightBodies';
@ -126,10 +126,9 @@ interface Built {
const TWINKLE_FRAME_MS = 50;
/**
* A card's motion is issued as one animation of this many seconds, a keyframe each second sampled from the heading owner (`heading.ts`) and the
* A card's motion is issued as one animation of SEGMENT_S seconds (`view.ts`), a keyframe each second sampled from the heading owner (`heading.ts`) and the
* viewer's offset, and issued again once REISSUE_FRAC of it has run, so the compositor always has the next stretch before it needs it. Authored.
*/
const SEGMENT_S = 30;
const REISSUE_FRAC = 0.8;
/** How often the arc of tiles ahead is asked for and the mounted tiles are brought up to date. */
const RESIDENCY_MS = 500;
@ -248,20 +247,20 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
};
/**
* Hand the viewer's mode and speed to the heading owner: when the scene starts, when the viewer changes the camera and when reduced motion is switched. Not on
* every issue: a manual turn stops the rotation until the viewer chooses one again (ruling ridge-view-turn-handback), and a later issue must not undo that.
* Take the viewer's choice to what this place can show: the speed the baked resident count sustains in the mode (`view.ts` `maxSpeed`; the stored value is
* clamped, so the choice and what turns agree). Returns true when it changed the choice, which comes back to its listeners.
*/
const syncKinematics = () => {
const boundSpeed = (bd: Backdrop): boolean => {
const cam = getCamera();
const t = clock();
// Reduced motion turns nothing, whatever the viewer asked for.
setMode(reducedMotion?.matches ? 'still' : cam.mode, t);
setRate(cam.speedDegPerS, t);
const limit = maxSpeed(bd.manifest, cam.mode);
if (Math.abs(cam.speedDegPerS) <= limit) return false;
setCamera({ speedDegPerS: Math.sign(cam.speedDegPerS) * limit });
return true;
};
/** The viewer's offset, clamped to the range this place and viewport allow (`view.ts` `offsetRange`, the one clamp). */
/** The viewer's offset, clamped to the range this place, viewport, mode and camera angle allow (`view.ts` `offsetRange`, the one clamp). */
const offsetNow = (bd: Backdrop, win: ReturnType<typeof windowFor>): number => {
const [lo, hi] = offsetRange(bd.manifest, win);
const [lo, hi] = offsetRange(bd.manifest, win, getCamera().mode, phiAt(clock()));
return Math.min(hi, Math.max(lo, getCamera().offsetM));
};
@ -305,7 +304,8 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
boxes[i] = box;
}
const anims: (Animation | undefined)[] = new Array(k).fill(undefined);
syncKinematics();
freeze(reducedMotion?.matches === true, clock()); // reduced motion turns nothing, whatever the viewer chose
boundSpeed(bd);
let offset = offsetNow(bd, win);
const poseAt = (card: number, t: number): CardPose =>
cardPose(bd.manifest, card, headingAt(t), phiAt(t), offset, win);
@ -316,8 +316,9 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
/** The next stretch of every card's motion, from now: it replaces the one running, which agrees with it where they meet. */
const issue = () => {
if (!live) return;
offset = offsetNow(bd, win);
const t0 = clock();
normalize(t0); // the angles of this stretch start within a turn of zero, so the transforms stay small however long the page has been open
offset = offsetNow(bd, win);
issuedAt = t0;
const frozen = reducedMotion?.matches === true;
for (let i = 0; i < k; i += 1) {
@ -335,21 +336,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
});
if (!moving()) anims[i]?.pause();
}
mount(sweep(t0)); // laid out from the same angles as the keyframes, in the same tick
};
/** The arc of azimuth any card shows between two instants. */
const arcBetween = (t0: number, t1: number): Arc => {
let fromDeg = Infinity;
let toDeg = -Infinity;
for (const t of [t0, t1]) {
for (let i = 0; i < k; i += 1) {
const a = cardArc(view, win, w, poseAt(i, t));
fromDeg = Math.min(fromDeg, a.fromDeg);
toDeg = Math.max(toDeg, a.toDeg);
}
}
return { fromDeg, toDeg };
};
/** The arc of azimuth any card shows at any instant of the stretch from `t0`: every pose it passes through, not its ends. */
const sweep = (t0: number): Arc => sweepArc(view, win, w, k, poseAt, t0, SEGMENT_S);
const mounted = new Map<HTMLCanvasElement, number>();
/** Put the made tiles the arc shows into their card's box at their azimuth, and take the others out. */
@ -389,17 +380,16 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
if (!live) return;
const t = clock();
if (t - issuedAt >= SEGMENT_S * 1000 * REISSUE_FRAC && moving()) issue();
const arc = arcBetween(t, t + SEGMENT_S * 1000);
const arc = sweep(t);
mount(arc);
void bd.ensure(arc).then(() => live && mount(arc));
timer = win0.setTimeout(residency, RESIDENCY_MS);
};
parent.appendChild(el);
issue();
mount(arcBetween(issuedAt, issuedAt + SEGMENT_S * 1000));
const sync = () => {
syncKinematics();
issue();
freeze(reducedMotion?.matches === true, clock());
if (!boundSpeed(bd)) issue(); // a bounded speed is a change of the choice: it comes back here and issues once
};
const offHeading = onHeading(issue);
const offCamera = onCamera(sync);

View file

@ -1,13 +1,32 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { anchor, getMode, headingAt, hold, phiAt, resetHeading, setMode, setRate, subscribe } from './heading';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { anchor, freeze, headingAt, hold, normalize, phiAt, resetHeading, subscribe } from './heading';
import { getCamera, resetCamera, setCamera } from '../cameraState';
const S = 1000;
beforeEach(resetHeading);
/** The viewer's choice, at the clock `at` (ms): the one way the mode and the speed reach the view. */
const choose = (mode: 'still' | 'offset' | 'both', speedDegPerS: number, at: number) =>
setCamera({ mode, speedDegPerS }, at);
const store = new Map<string, string>();
beforeEach(() => {
store.clear();
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, v),
});
resetCamera();
resetHeading();
setCamera({ mode: 'still', speedDegPerS: 0 }, 0);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('the heading owner', () => {
it('starts still, facing nothing in particular until a place anchors it', () => {
expect(getMode()).toBe('still');
it('faces nothing in particular until a place anchors it, and turns nothing while the viewer chose nothing to turn', () => {
expect(headingAt(5 * S)).toBe(0);
expect(phiAt(5 * S)).toBe(0);
});
@ -15,8 +34,7 @@ describe('the heading owner', () => {
it('anchors a place at its rest azimuth once, and a later anchor of the same place changes nothing', () => {
anchor('vienna', 214, 0);
expect(headingAt(0)).toBe(214);
setMode('both', 0);
setRate(0.6, 0);
choose('both', 0.6, 0);
expect(headingAt(10 * S)).toBeCloseTo(220, 9);
anchor('vienna', 214, 10 * S); // a rebuild for a new sky: the view keeps the direction it has turned to
expect(headingAt(10 * S)).toBeCloseTo(220, 9);
@ -25,81 +43,135 @@ describe('the heading owner', () => {
expect(phiAt(10 * S)).toBe(0);
});
it('is unwrapped over several revolutions: nothing wraps or clamps it', () => {
it('is unwrapped over several revolutions between normalizations: nothing wraps or clamps it', () => {
anchor('p', 0, 0);
setMode('both', 0);
setRate(6, 0);
choose('both', 6, 0);
expect(headingAt(60 * S)).toBeCloseTo(360, 9);
expect(headingAt(210 * S)).toBeCloseTo(1260, 9);
setRate(-6, 210 * S);
choose('both', -6, 210 * S);
expect(headingAt(330 * S)).toBeCloseTo(540, 9);
expect(headingAt(500 * S)).toBeLessThan(0);
});
it('turns the view direction in both mode, the camera on its circle alone in offset mode, and nothing when still', () => {
anchor('p', 100, 0);
setRate(2, 0);
setMode('both', 0);
choose('both', 2, 0);
expect([headingAt(10 * S), phiAt(10 * S)]).toEqual([120, 0]);
setMode('offset', 10 * S); // nothing jumps at the change
choose('offset', 2, 10 * S); // nothing jumps at the change
expect([headingAt(10 * S), phiAt(10 * S)]).toEqual([120, 0]);
expect([headingAt(20 * S), phiAt(20 * S)]).toEqual([120, 20]);
setMode('still', 20 * S);
choose('still', 2, 20 * S);
expect([headingAt(99 * S), phiAt(99 * S)]).toEqual([120, 20]);
setMode('both', 99 * S); // the camera keeps the angle it stopped at
expect([headingAt(104 * S), phiAt(104 * S)]).toEqual([130, 20]);
choose('offset', 2, 99 * S); // the camera keeps the angle it stopped at, and goes on from there
expect([headingAt(104 * S), phiAt(104 * S)]).toEqual([120, 30]);
});
it('a rate change takes effect from now, without moving the view', () => {
it('puts the camera back on its heading when the view direction is made to turn with it', () => {
anchor('p', 100, 0);
choose('offset', 2, 0);
expect(phiAt(10 * S)).toBe(20);
choose('both', 2, 10 * S); // phi is 0 in every mode where the offset turns with the view: the range the baker ships for that relies on it
expect([headingAt(10 * S), phiAt(10 * S)]).toEqual([100, 0]);
expect([headingAt(20 * S), phiAt(20 * S)]).toEqual([120, 0]);
});
it('a speed change takes effect from now, without moving the view', () => {
anchor('p', 0, 0);
setMode('both', 0);
setRate(1, 0);
setRate(3, 10 * S);
choose('both', 1, 0);
choose('both', 3, 10 * S);
expect(headingAt(10 * S)).toBe(10);
expect(headingAt(20 * S)).toBe(40);
});
it('a manual turn sets the view direction in every mode, and stops the rotation where the viewer left it', () => {
it('a manual turn sets the view direction in every mode and stops the rotation: the mode is the viewer choice, still, the one fact', () => {
for (const mode of ['still', 'offset', 'both'] as const) {
resetHeading();
anchor('p', 0, 0);
setRate(1, 0);
setMode(mode, 0);
choose(mode, 1, 0);
hold(300, 10 * S);
expect(headingAt(10 * S)).toBe(300);
expect(getMode()).toBe('still');
expect(getCamera().mode).toBe('still');
expect(headingAt(500 * S)).toBe(300);
expect(phiAt(500 * S)).toBe(phiAt(10 * S));
setMode('both', 500 * S); // a rotation mode chosen again resumes it
choose('both', 1, 500 * S); // a rotation mode chosen again resumes it
expect(headingAt(510 * S)).toBe(310);
}
});
it('a hold outlives a rebuild and a reload: nothing re-applies the mode the viewer had before it', () => {
anchor('p', 0, 0);
choose('both', 1, 0);
hold(100, 10 * S);
anchor('p', 0, 20 * S); // what every scene build does
expect(headingAt(60 * S)).toBe(100);
const stored = getCamera();
resetCamera(); // a reload reads the stored choice
expect(getCamera()).toEqual(stored);
expect(getCamera().mode).toBe('still');
});
it('choosing the mode the viewer had before a hold resumes the view: the mode they had is not still any more, so the choice is a change', () => {
anchor('p', 0, 0);
choose('both', 1, 0);
hold(100, 10 * S);
setCamera({ mode: 'both' }, 20 * S);
expect(headingAt(30 * S)).toBe(110);
expect(getCamera().mode).toBe('both');
});
it('keeps the heading when the scene is rebuilt: the module outlives it', () => {
anchor('p', 50, 0);
setMode('both', 0);
setRate(1, 0);
// A rebuild is another scene reading the same module state: nothing here is per scene.
choose('both', 1, 0);
expect(headingAt(30 * S)).toBe(80);
anchor('p', 50, 30 * S);
expect(headingAt(30 * S)).toBe(80);
});
it('tells subscribers of every change and no change that changes nothing', () => {
it('freezes under reduced motion without moving the view, and goes on from where it stopped', () => {
anchor('p', 0, 0);
choose('both', 1, 0);
freeze(true, 10 * S);
expect(headingAt(10 * S)).toBe(10);
expect(headingAt(50 * S)).toBe(10);
expect(getCamera().mode).toBe('both'); // the viewer's choice is untouched
freeze(false, 50 * S);
expect(headingAt(60 * S)).toBe(20);
});
it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime', () => {
anchor('p', 0, 0);
choose('both', 6, 0);
const day = 24 * 3600 * S;
normalize(day);
const h = headingAt(day);
expect(h).toBeGreaterThanOrEqual(0);
expect(h).toBeLessThan(360);
expect(h).toBeCloseTo((6 * 86400) % 360, 6);
expect(headingAt(day + 30 * S)).toBeCloseTo(h + 180, 6);
choose('offset', 6, day + 30 * S);
normalize(day + 100 * S);
expect(phiAt(day + 100 * S)).toBeGreaterThanOrEqual(0);
expect(phiAt(day + 100 * S)).toBeLessThan(360);
setCamera({ speedDegPerS: -6 }, day + 100 * S);
normalize(day + 101 * S);
expect(phiAt(day + 101 * S)).toBeGreaterThanOrEqual(0); // a turn the other way is brought into range too
});
it('tells subscribers of a manual turn while still and of a new place, and of nothing that changes nothing; the viewer choice has its own channel', () => {
const cb = vi.fn();
const off = subscribe(cb);
anchor('p', 0, 0);
expect(cb).toHaveBeenCalledTimes(1);
anchor('p', 0, 1);
setMode('still', 1);
setRate(0, 1);
expect(cb).toHaveBeenCalledTimes(1);
setMode('both', 1);
setRate(1, 1);
hold(5, 2);
expect(cb).toHaveBeenCalledTimes(4);
hold(5, 2); // already still
expect(cb).toHaveBeenCalledTimes(2);
choose('both', 1, 3);
expect(cb).toHaveBeenCalledTimes(2); // the camera's listeners hear that
hold(6, 4); // takes the mode with it: told once, through the choice, not twice
expect(cb).toHaveBeenCalledTimes(2);
off();
setRate(2, 3);
expect(cb).toHaveBeenCalledTimes(4);
anchor('q', 0, 5);
expect(cb).toHaveBeenCalledTimes(2);
});
});

View file

@ -1,70 +1,105 @@
// The heading owner: which way the view faces (`h`) and where the camera stands on its circle against that (`phi`), as kinematics over a clock.
// Pure state and subscribe, module-level so it outlives scene rebuilds: a sky change makes a new scene and the view keeps its direction. Angles are
// unwrapped compass degrees, never wrapped by a consumer (`ring.ts` is the one place that reasons about 0 / 360). Nothing but this module advances
// `h` or `phi`; the viewer's intent (mode, speed, offset) is `cameraState.ts`, and a scene applies it here.
// Module-level state so it outlives scene rebuilds: a sky change makes a new scene and the view keeps its direction. Angles are unwrapped compass
// degrees between two `normalize` calls (the rig makes one before each stretch of motion, so they never grow with uptime); `ring.ts` is the one place
// that reasons about 0 / 360. Nothing but this module advances `h` or `phi`.
//
// The rotation mode and its speed are not held here: they are the viewer's choice, `cameraState.ts`, the one owner. This module keeps only where the view
// and the camera were at the clock `t0` and integrates them under the choice in force since, so it listens to the choice and takes the anchor to the moment
// of each change (a manual turn is a change of the choice to 'still', which a rebuild or a reload therefore keeps).
//
// The camera sits on its circle at angle `theta = h + phi`: with `phi` 0 it is pushed forward along its own heading (`view.ts` `cardPose`); rotating
// the offset alone moves `phi` and leaves the view direction where it is (ruling ridge-scene-view-submenus).
// the offset alone moves `phi` and leaves the view direction where it is (ruling ridge-scene-view-submenus). `phi` is 0 whenever the view direction turns
// with the camera ('both'): picking that mode returns the camera to its heading.
import { getCamera, setCamera, subscribe as onCamera } from '../cameraState';
import type { CameraChoice } from '../cameraState';
/** `still`: nothing turns. `offset`: the camera circles the centre, the view direction stays. `both`: the view direction turns and the camera with it. */
export type RotationMode = 'still' | 'offset' | 'both';
interface State {
mode: RotationMode;
/** Degrees per second, signed. */
rate: number;
h0: number;
phi0: number;
/** The clock (ms) at which `h0` and `phi0` held. */
t0: number;
/** What the heading was last anchored to: a baked place (its bake id), so a place change restarts at its rest azimuth and a sky change does not. */
anchor: string | undefined;
/** Nothing turns, whatever the viewer chose (the OS asks for reduced motion): an override of the environment, not a second copy of the choice. */
frozen: boolean;
}
const initial = (): State => ({ mode: 'still', rate: 0, h0: 0, phi0: 0, t0: 0, anchor: undefined });
const initial = (): State => ({ h0: 0, phi0: 0, t0: 0, anchor: undefined, frozen: false });
let state = initial();
const listeners = new Set<() => void>();
let unbind: (() => void) | undefined;
const advanced = (now: number): number => (state.rate * (now - state.t0)) / 1000;
const turning = (cam: CameraChoice, frozen: boolean): RotationMode => (frozen ? 'still' : cam.mode);
const advanced = (now: number, cam: CameraChoice): number => (cam.speedDegPerS * (now - state.t0)) / 1000;
const headingUnder = (now: number, cam: CameraChoice): number =>
state.h0 + (turning(cam, state.frozen) === 'both' ? advanced(now, cam) : 0);
const phiUnder = (now: number, cam: CameraChoice): number =>
state.phi0 + (turning(cam, state.frozen) === 'offset' ? advanced(now, cam) : 0);
/** The view direction at `now` (ms), unwrapped degrees. */
export const headingAt = (now: number): number => state.h0 + (state.mode === 'both' ? advanced(now) : 0);
/** The camera's angle on its circle against the heading at `now`, unwrapped degrees. */
export const phiAt = (now: number): number => state.phi0 + (state.mode === 'offset' ? advanced(now) : 0);
export const getMode = (): RotationMode => state.mode;
export const getRate = (): number => state.rate;
/** The view direction at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */
export const headingAt = (now: number): number => headingUnder(now, getCamera());
/** The camera's angle on its circle against the heading at `now`, degrees, as `headingAt`. */
export const phiAt = (now: number): number => phiUnder(now, getCamera());
const emit = () => [...listeners].forEach((cb) => cb());
/** Take `h`, `phi` and the clock to `now` and change what advances them: the one way a value is replaced, so no change makes the view jump. */
function rebase(now: number, over: Partial<State> = {}, h = headingAt(now), phi = phiAt(now)): void {
/** Take `h`, `phi` and the clock to `now` under the choice `cam` in force until now: the one way a value is replaced, so no change makes the view jump. */
function settle(now: number, cam: CameraChoice, over: Partial<State> = {}, h = headingUnder(now, cam), phi = phiUnder(now, cam)): void {
state = { ...state, ...over, h0: h, phi0: phi, t0: now };
emit();
}
/** Listen to the viewer's choice from now on (again, if a test cleared the listeners): a change of mode or speed lands on the anchor at the moment it is made. */
function bind(): void {
unbind?.();
unbind = onCamera((next, prev, at) => {
settle(at, prev, {}, undefined, next.mode === 'both' ? 0 : undefined);
});
}
/**
* Point the view at a place: the first time it is shown, or when it is not the place the heading was last anchored to, the view faces its rest azimuth
* with the camera on its heading. The same place again changes nothing (a rebuild for a sky keeps the heading).
* with the camera on its heading. The same place again changes nothing (a rebuild for a sky keeps the heading). Also starts listening to the viewer's choice.
*/
export function anchor(key: string, restDeg: number, now: number): void {
bind();
if (state.anchor === key) return;
rebase(now, { anchor: key }, restDeg, 0);
settle(now, getCamera(), { anchor: key }, restDeg, 0);
emit();
}
/** A manual turn: the view direction becomes `h` now, in every mode, and the rotation stops where the viewer left it (ruling ridge-view-turn-handback); a mode chosen again resumes it. */
/**
* A manual turn: the view direction becomes `h` now, in every mode, and the rotation stops where the viewer left it (ruling ridge-view-turn-handback): the
* viewer's mode becomes 'still', the one owner of it, so a rebuild or a reload keeps the hold and choosing a rotation mode again, the one already shown
* included, resumes it.
*/
export function hold(h: number, now: number): void {
rebase(now, { mode: 'still' }, h);
const wasStill = getCamera().mode === 'still';
settle(now, getCamera(), {}, h);
if (wasStill) emit();
else setCamera({ mode: 'still' }, now); // the camera's listeners tell everyone, once
}
export function setMode(mode: RotationMode, now: number): void {
if (mode !== state.mode) rebase(now, { mode });
/** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view stays where it is. */
export function freeze(on: boolean, now: number): void {
if (on === state.frozen) return;
settle(now, getCamera());
state = { ...state, frozen: on };
}
export function setRate(rate: number, now: number): void {
if (rate !== state.rate) rebase(now, { rate });
/**
* Bring `h` and `phi` into [0, 360) and the clock to `now`, changing nothing the view shows but the whole turns the unwrapped angles had gathered; tiles
* are laid out from them, so their positions and the transforms stay small however long the page has been open. Silent: the caller lays out again.
*/
export function normalize(now: number): void {
const cam = getCamera();
const wrap = (x: number): number => x - 360 * Math.floor(x / 360);
settle(now, cam, {}, wrap(headingUnder(now, cam)), wrap(phiUnder(now, cam)));
}
/** Hear every change of the kinematics (a manual turn, a mode, a rate, a new place); returns the way to stop. */
/** Hear every change of the kinematics that the viewer's choice does not announce (a manual turn while still, a new place); returns the way to stop. */
export function subscribe(cb: () => void): () => void {
listeners.add(cb);
return () => listeners.delete(cb);
@ -72,6 +107,8 @@ export function subscribe(cb: () => void): () => void {
/** For tests: the state of a fresh page. */
export function resetHeading(): void {
unbind?.();
unbind = undefined;
state = initial();
listeners.clear();
}

View file

@ -5,10 +5,15 @@ import {
FALLBACK_VIEW,
HFOV_MAX_DEG,
HORIZON_AT,
maxSpeed,
offsetRange,
RIDGE_BAND_FRAC,
SEGMENT_S,
SPEED_CEILING_DEG_S,
sweepArc,
windowFor,
} from './view';
import { KEEP_MARGIN_TILES, residentTiles, runTiles } from './ring';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { View } from './view';
@ -149,26 +154,152 @@ describe('cardArc', () => {
});
describe('offsetRange', () => {
it('never exceeds the bake, and is symmetric while the nearest card keeps its foot under the viewport bottom', () => {
it('is the bake worst-case bound either way round in the offset-only mode, whose camera circles the whole ring of angles', () => {
for (const [w, h] of VIEWPORTS) {
const [lo, hi] = offsetRange(manifest, windowFor(manifest.view, w, h));
expect(hi).toBe(manifest.camera.rMaxM);
expect(lo).toBe(-manifest.camera.rMaxM);
const win = windowFor(manifest.view, w, h);
expect(offsetRange(manifest, win, 'offset')).toEqual([-manifest.camera.rMaxM, manifest.camera.rMaxM]);
// The angle the camera stands at does not matter there: it is going to all of them.
expect(offsetRange(manifest, win, 'offset', 0)).toEqual(offsetRange(manifest, win, 'offset', 123));
}
});
it('lets a forward offset go as far as the bake phi 0 bound where the offset turns with the view, and a backward one only as far as the worst case', () => {
for (const [w, h] of VIEWPORTS) {
const win = windowFor(manifest.view, w, h);
for (const mode of ['both', 'still'] as const) {
const [lo, hi] = offsetRange(manifest, win, mode);
expect(hi).toBe(manifest.camera.rMaxForwardM);
expect(lo).toBe(-manifest.camera.rMaxM);
}
}
expect(manifest.camera.rMaxForwardM).toBeGreaterThan(manifest.camera.rMaxM);
});
it('a camera held at an angle of its circle is bounded as the circle is: the bound follows where the camera stands, not only the mode', () => {
const win = windowFor(manifest.view, 1920, 1080);
expect(offsetRange(manifest, win, 'still', 0)[1]).toBe(manifest.camera.rMaxForwardM);
expect(offsetRange(manifest, win, 'still', 360)[1]).toBe(manifest.camera.rMaxForwardM);
expect(offsetRange(manifest, win, 'still', 137)).toEqual([-manifest.camera.rMaxM, manifest.camera.rMaxM]);
});
it('keeps a default +200 m where phi stays 0 and the bake allows it, and takes it to the worst-case bound where the camera circles', () => {
const vienna = parseManifest(
wireManifest({ camera: { r_max_m: 98.2, r_max_forward_m: 205.4 } }),
'/d/'
);
const win = windowFor(vienna.view, 1920, 1080);
const clamp = (mode: 'both' | 'offset' | 'still') => {
const [lo, hi] = offsetRange(vienna, win, mode);
return Math.min(hi, Math.max(lo, 200));
};
expect(clamp('both')).toBe(200);
expect(clamp('still')).toBe(200);
expect(clamp('offset')).toBe(98.2);
});
it('gives up part of its backward half where the nearest card shrunk by R / (R + r) would lift its foot above the viewport bottom, and all of it past that', () => {
// 1920 x 1080: keep = (1 - HORIZON_AT) 1080 / (scale (planeH - horizonRow)). Put the horizon row so that keep is 0.95, and the nearest card is 1000 m away.
const scale = windowFor(manifest.view, 1920, 1080).plane.scale;
const near = withView({ horizon_row: 600 - (0.15 * 1080) / 0.95 / scale });
const win = windowFor(near.view, 1920, 1080);
const [lo, hi] = offsetRange(near, win);
expect(hi).toBe(100);
const [lo, hi] = offsetRange(near, win, 'both');
expect(hi).toBe(180);
expect(lo).toBeCloseTo(-1000 * (1 / 0.95 - 1), 6);
// At that offset the card's foot is exactly at the viewport bottom.
const s = 1000 / (1000 - lo);
expect(s * win.plane.scale * (near.view.planeH - near.view.horizonRow)).toBeCloseTo(0.15 * 1080, 6);
const none = withView({ horizon_row: 599 });
expect(offsetRange(none, windowFor(none.view, 1920, 1080))).toEqual([-0, 100]);
expect(offsetRange(none, windowFor(none.view, 1920, 1080), 'both')).toEqual([-0, 180]);
});
it('gives up the same part of its forward half in the offset-only mode: the camera circles round to phi 180 and the nearest card shrinks as it does for a backward offset', () => {
const scale = windowFor(manifest.view, 1920, 1080).plane.scale;
const near = withView({ horizon_row: 600 - (0.15 * 1080) / 0.95 / scale });
const win = windowFor(near.view, 1920, 1080);
const [lo, hi] = offsetRange(near, win, 'offset');
expect(hi).toBeCloseTo(1000 * (1 / 0.95 - 1), 6);
expect(lo).toBe(-hi);
// The camera at phi 180 and offset hi puts the nearest card at the scale that leaves its foot on the bottom edge.
const R = 1000;
const p = cardPose(near, 0, near.view.lookAzDeg, 180, hi, win);
expect(Math.abs(p.scale - R / (R + hi))).toBeLessThan(0.02); // the fitted line is within a hair of the tangent the clamp uses
const none = withView({ horizon_row: 599 });
expect(offsetRange(none, windowFor(none.view, 1920, 1080), 'offset')).toEqual([-0, 0]);
});
});
describe('maxSpeed', () => {
const ring = parseManifest(wireManifest({}, 3, 32), '/d/'); // the ring as the baker cuts it: 32 tiles of 11.25 degrees, rmin 1000 m, r_max 100, forward 180
const win = windowFor(ring.view, 1920, 1080);
const poses = (v: number, h: number, off: number) => (card: number, ms: number) =>
cardPose(ring, card, h + (v * ms) / 1000, 0, off, win);
/** The most tiles the loader would hold for a view turning at v, over a sweep of headings and the offsets the mode allows. */
const mostHeld = (v: number): number => {
const [lo, hi] = offsetRange(ring, win, 'both');
let most = 0;
for (const off of [lo, 0, hi]) {
for (let h = 0; h < 360; h += 3.7) {
const arc = sweepArc(ring.view, win, 1920, 3, poses(v, h, off), 0);
const keep = residentTiles(
ring.view,
(arc.fromDeg + arc.toDeg) / 2,
(arc.toDeg - arc.fromDeg) / 2 + KEEP_MARGIN_TILES * 11.25
);
most = Math.max(most, keep.length);
}
}
return most;
};
const N = runTiles(ring.view, HFOV_MAX_DEG, ring.camera.rMaxForwardM, 1000);
it('is what the baked resident count leaves in the mode where the view turns, and the ceiling where it does not', () => {
const v = maxSpeed(ring, 'both');
expect(v).toBeGreaterThan(0);
expect(v).toBeLessThan(SPEED_CEILING_DEG_S);
expect(maxSpeed(ring, 'offset')).toBe(SPEED_CEILING_DEG_S);
expect(maxSpeed(ring, 'still')).toBe(SPEED_CEILING_DEG_S);
// Held to N by the sweep of SEGMENT_S seconds at the bound, and over it a little above.
expect(mostHeld(v)).toBeLessThanOrEqual(N);
expect(mostHeld(v * 1.6)).toBeGreaterThan(N);
expect(SEGMENT_S).toBe(30);
});
it('is never above the ceiling, whatever room the ring has, and never below 0', () => {
const open = parseManifest(wireManifest({ camera: { r_max_m: 0.1, r_max_forward_m: 0.1 } }, 3, 32), '/d/');
expect(maxSpeed(open, 'both')).toBeLessThanOrEqual(SPEED_CEILING_DEG_S);
const tight = parseManifest(wireManifest({ camera: { r_max_m: 100, r_max_forward_m: 100 } }, 3, 32), '/d/');
expect(maxSpeed(tight, 'both')).toBeGreaterThanOrEqual(0);
});
});
describe('sweepArc', () => {
const ring = parseManifest(wireManifest({}, 3, 32), '/d/');
const win = windowFor(ring.view, 1920, 1080);
// The offset-only mode at 12 degrees a second and the offset own bound: the nearest card swings out and back over the stretch.
const v = 12;
const [, hi] = offsetRange(ring, win, 'offset');
const poseAt = (card: number, ms: number) => cardPose(ring, card, 100, 30 + (v * ms) / 1000, hi, win);
it('covers every pose the stretch passes through, not the two it begins and ends with', () => {
const swept = sweepArc(ring.view, win, 1920, 3, poseAt, 0);
let from = Infinity;
let to = -Infinity;
for (let ms = 0; ms <= SEGMENT_S * 1000; ms += 50) {
for (let i = 0; i < 3; i += 1) {
const a = cardArc(ring.view, win, 1920, poseAt(i, ms));
from = Math.min(from, a.fromDeg);
to = Math.max(to, a.toDeg);
}
}
// Within a hundredth of a degree of the dense answer, either side: it covers the swing and is not the whole ring.
expect(Math.abs(swept.fromDeg - from)).toBeLessThan(0.01);
expect(Math.abs(swept.toDeg - to)).toBeLessThan(0.01);
// The two ends alone fall short of the dense answer by whole degrees.
const ends = [0, SEGMENT_S * 1000].flatMap((ms) =>
[0, 1, 2].map((i) => cardArc(ring.view, win, 1920, poseAt(i, ms)))
);
const endFrom = Math.min(...ends.map((a) => a.fromDeg));
const endTo = Math.max(...ends.map((a) => a.toDeg));
expect(endFrom - from > 1 || to - endTo > 1).toBe(true);
});
});

View file

@ -3,8 +3,9 @@
// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. `offsetRange` is the one
// clamp on the camera's offset and `cardPose` the one place a card's scale and shift are derived (ruling ridge-camera-on-circle). Nothing
// else chooses a field of view, a horizon row, an azimuth, a scale or a shift.
import { distanceAt } from './ring';
import { distanceAt, KEEP_MARGIN_TILES, norm, runTiles } from './ring';
import type { RidgeManifest } from './manifest';
import type { RotationMode } from './heading';
/** Where the observer stands. `id` names the baked place (it keys a rebuild); `altitudeKm` is the ground height, eye height excluded. */
export interface Place {
@ -104,19 +105,60 @@ export function windowFor(view: View, viewportW: number, viewportH: number): Win
};
}
/** Nearest card's nearest tile distance, metres: where the camera first meets a card. */
const nearestM = (manifest: RidgeManifest): number =>
Math.min(...manifest.tiles.map((row) => row[0]?.distanceM ?? Infinity));
/** Whether the camera stands on its heading (phi 0, a whole turn off it included): a mode where the offset turns with the view puts it there. */
const onHeading = (mode: RotationMode, phiDeg: number): boolean =>
mode !== 'offset' && Math.abs(norm(phiDeg + 180) - 180) < 1e-6;
/**
* The offsets the camera may take on its circle, metres, forward positive: the one clamp (ruling ridge-offset-range-fit). Forward is the bake's
* `rMaxM`, the largest offset every card's linear slide fits. Backward is the same, until the nearest card, shrunk by R / (R + r) about the horizon,
* would lift its foot above the viewport bottom and show the sky under it: the baker's nearest-card-off-the-bottom refusal as a clamp.
* The offsets the camera may take on its circle, metres, forward positive: the one clamp (ruling ridge-offset-range-fit, "the slider stops where the linear
* map holds"). How well a card's linear slide fits depends on the camera's angle `phiDeg` on its circle, so the bound depends on where the mode keeps it. With
* the camera on its heading (modes 'still' and 'both', `phi` 0) a forward offset goes to the bake's `rMaxForwardM`, the largest every card fits at phi 0;
* everywhere else (the offset-only mode swings the camera round the whole circle, and a backward offset at phi 0 is the camera at phi 180) the bound is
* `rMaxM`, the worst over every phi. The nearest card, shrunk by R / (R + r) about the horizon, would lift its foot above the viewport bottom and show the
* sky under it past the point where `1 / keep - 1` of its distance is the offset: the baker's nearest-card-off-the-bottom refusal as a clamp, applied to
* every position the camera can reach at the offset's sign (backward always, forward too where the circle takes it round to phi 180).
*/
export function offsetRange(manifest: RidgeManifest, win: Window): [number, number] {
const { rMaxM } = manifest.camera;
export function offsetRange(
manifest: RidgeManifest,
win: Window,
mode: RotationMode,
phiDeg = 0
): [number, number] {
const { rMaxM, rMaxForwardM } = manifest.camera;
const { planeH, horizonRow } = manifest.view;
const below = win.plane.scale * (planeH - horizonRow);
const keep = 1 + win.plane.bottom / below; // the smallest scale at which the foot stays under the viewport bottom
const nearest = Math.min(...manifest.tiles.map((row) => row[0]?.distanceM ?? Infinity));
const back = keep >= 1 ? 0 : Math.min(rMaxM, nearest * (1 / keep - 1));
return [-back, rMaxM];
const foot = keep >= 1 ? 0 : nearestM(manifest) * (1 / keep - 1);
const back = Math.min(rMaxM, foot);
return onHeading(mode, phiDeg) ? [-back, rMaxForwardM] : [-back, back];
}
/** The longest stretch of motion the rig issues at once, seconds: the loader holds the tiles it passes over, so it also bounds how far a turn may sweep. */
export const SEGMENT_S = 30;
/** The fastest the view or the camera may turn, degrees per second, whatever the loader holds: a keyframe a second must not skip a whole tile (11.25 degrees at 32 tiles). */
export const SPEED_CEILING_DEG_S = 12;
/**
* The largest speed (degrees per second, either direction) the baked resident count sustains in `mode`: the loader holds the tiles of the arc a card shows
* over the next SEGMENT_S seconds and two tiles beyond it each side, and the bake's gate (`ring.ts` `runTiles`, `export.py`) priced N of them. Turning the view
* widens that arc by speed x SEGMENT_S, so in 'both' the speed is what N leaves after the widest card arc (the viewport over the smallest slide rate, at the
* backward offset `rMaxM`) and the margin tiles. The offset-only mode sweeps the camera over a circle the gate already counts whatever the speed, and a still
* view has none: those take the ceiling, as does a ring the gate priced whole.
*/
export function maxSpeed(manifest: RidgeManifest, mode: RotationMode): number {
if (mode !== 'both') return SPEED_CEILING_DEG_S;
const { view, camera } = manifest;
const tileDeg = 360 / view.tiles;
const rmin = nearestM(manifest);
const n = runTiles(view, HFOV_MAX_DEG, camera.rMaxForwardM, rmin);
if (n >= view.tiles) return SPEED_CEILING_DEG_S; // the gate counted the whole ring: nothing the loader holds can exceed it
const sMin = rmin / (rmin + camera.rMaxM);
const room = (n - 1 - 2 * KEEP_MARGIN_TILES) * tileDeg - HFOV_MAX_DEG / sMin;
return Math.min(SPEED_CEILING_DEG_S, Math.max(0, room / SEGMENT_S));
}
/** What a card does on screen: its scale about the horizon and how far it is shifted sideways, viewport px, at a heading and camera angle. */
@ -185,3 +227,34 @@ export function cardArc(
toDeg: view.lookAzDeg + (viewportW / 2 - pose.shiftPx) / per,
};
}
/** How often the pose is sampled to find the arc a stretch of motion passes over, seconds: finer than the rig's keyframe a second, so no swing between two keyframes is missed. */
const SWEEP_STEP_S = 0.25;
/**
* The arc of azimuth any of `cards` cards shows at any instant of the `seconds` after `t0` (ms), by `poseAt(card, ms)`: the union of `cardArc` over the whole
* stretch, not its ends. A pose is not monotone in time (offset-only rotation carries the nearest card out and back as the camera circles), so a card's reach
* peaks mid-stretch, and the tiles it needs there are the ones to mount and to ask the loader for.
*/
export function sweepArc(
view: View,
win: Window,
viewportW: number,
cards: number,
poseAt: (card: number, ms: number) => CardPose,
t0: number,
seconds: number = SEGMENT_S
): { fromDeg: number; toDeg: number } {
let fromDeg = Infinity;
let toDeg = -Infinity;
const steps = Math.ceil(seconds / SWEEP_STEP_S);
for (let n = 0; n <= steps; n += 1) {
const t = t0 + Math.min(seconds, n * SWEEP_STEP_S) * 1000;
for (let i = 0; i < cards; i += 1) {
const a = cardArc(view, win, viewportW, poseAt(i, t));
fromDeg = Math.min(fromDeg, a.fromDeg);
toDeg = Math.max(toDeg, a.toDeg);
}
}
return { fromDeg, toDeg };
}