ridge runtime: one box per card posed from the heading owner; tiles mounted by arc

The rig is a box per card holding that card's resident tiles, carried by one
animation of cardPose sampled each second over 30 s from heading.ts and the
viewer's offset, reissued at 80% and on any change; a 500 ms timer asks the
backdrop for the arc ahead and mounts what it has made. The reach animation,
DRIFT_LEG_S and the drift's easing are gone. prepare() anchors the heading and
awaits the first arc; a stale or failed build disposes its backdrop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-22 23:39:20 +01:00
commit 19d49cbd46
4 changed files with 569 additions and 155 deletions

View file

@ -8,19 +8,20 @@ import type { SkyChoice } from './ridge/skyMoment';
import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
import { FALLBACK_VIEW } from './ridge/view';
import { FALLBACK_VIEW, HFOV_MAX_DEG } from './ridge/view';
import { hold, resetHeading } from './ridge/heading';
import { sunAt } from './ridge/sunAt';
import { ridgeWeather } from './ridge/weather';
import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed';
const { createRidgeScene, createScene, loadBackdrop } = vi.hoisted(() => ({
const { createRidgeScene, createScene, createBackdrop } = vi.hoisted(() => ({
createRidgeScene: vi.fn(),
createScene: vi.fn(),
loadBackdrop: vi.fn(),
createBackdrop: vi.fn(),
}));
vi.mock('./ridge/Ridge', () => ({ createRidgeScene }));
// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a loader it can hold, fail and count.
vi.mock('./ridge/Backdrop', () => ({ loadBackdrop }));
// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a backdrop whose first arc it can hold, fail and count.
vi.mock('./ridge/Backdrop', () => ({ createBackdrop }));
vi.mock('./Scene', () => ({ createScene }));
// The physical sky is baked per call (tens of ms: atmosphere LUTs) and the clock here is fixed, so a state always
// draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is
@ -58,26 +59,38 @@ const microtasks = (n: number) =>
(p) => p.then(() => undefined),
Promise.resolve()
);
/** A loader for `loadBackdrop` that waits on `ctl.hold` (queueing its settle in `ctl.pending`), then resolves a backdrop or, with `ctl.fail` as it stood when asked, null. `ctl.calls` is the sky each call was lit for. */
/** A `createBackdrop` whose first `ensure` waits on `ctl.hold` (queueing its settle in `ctl.pending`), then makes tiles or, with `ctl.fail` as it stood when asked, none. `ctl.calls` is the sky each backdrop was lit for; `ctl.made` the backdrops. */
const loader = () => {
const ctl = {
pending: [] as Array<() => void>,
hold: false,
fail: false,
calls: [] as any[],
made: [] as any[],
};
loadBackdrop.mockImplementation(
(manifest: unknown, physical: unknown) =>
new Promise((resolve) => {
const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
const settle = () => {
ctl.calls.push(physical);
resolve(fails ? null : { manifest, cards: [] });
};
if (ctl.hold) ctl.pending.push(settle);
else settle();
})
);
createBackdrop.mockImplementation((manifest: unknown, physical: unknown) => {
const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
let made = false;
const bd = {
manifest,
dispose: vi.fn(),
litTiles: () => (made && !fails ? [{ tile: 0, card: 0, canvas: {} }] : []),
ensure: vi.fn(
() =>
new Promise<void>((resolve) => {
const settle = () => {
made = true;
ctl.calls.push(physical);
resolve();
};
if (ctl.hold) ctl.pending.push(settle);
else settle();
})
),
};
ctl.made.push(bd);
return bd;
});
return {
ctl,
release: async () => {
@ -102,7 +115,7 @@ beforeEach(() => {
setSkyPlace(FALLBACK_VIEW.place);
createRidgeScene.mockReset();
createScene.mockReset();
loadBackdrop.mockReset();
createBackdrop.mockReset();
});
afterEach(() => {
setSkyClock();
@ -384,6 +397,61 @@ describe('the ridge planes', () => {
scene?.dispose();
});
it('awaits the first arc of tiles round the heading before the scene is made, and anchors a new place at its rest azimuth', async () => {
served();
resetHeading();
const d = loader();
createRidgeScene.mockReturnValue(fakeScene());
d.ctl.hold = true;
const started = startBackgroundScene(config, caps, { canvas });
await flush();
expect(createRidgeScene).not.toHaveBeenCalled(); // the tiles are not made yet
expect(d.ctl.made).toHaveLength(1);
const arc = d.ctl.made[0].ensure.mock.calls[0][0];
expect((arc.fromDeg + arc.toDeg) / 2).toBeCloseTo(214, 0); // the Vienna rest azimuth, nothing having turned the view
expect(arc.toDeg - arc.fromDeg).toBeCloseTo(HFOV_MAX_DEG, 6);
await d.release();
(await started)?.dispose();
expect(createRidgeScene).toHaveBeenCalledOnce();
// A rebuild for a new sky keeps the heading the view has turned to.
hold(100, performance.now());
forgetManifests();
(await startBackgroundScene(config, caps, { canvas }))?.dispose();
const second = d.ctl.made[1].ensure.mock.calls[0][0];
expect((second.fromDeg + second.toDeg) / 2).toBeCloseTo(100, 0);
});
it('a build that goes stale disposes the backdrop it made, and a scene that fails to be made does too', async () => {
served();
const d = loader();
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
d.ctl.hold = true;
setSkyChoice(NOON); // stale once the next choice lands
await flush();
const day = d.ctl.pending.splice(0);
setSkyChoice(DUSK);
await flush();
const dusk = d.ctl.pending.splice(0);
dusk.forEach((s) => s());
await flush();
day.forEach((s) => s());
await flush();
const [, dayBackdrop, duskBackdrop] = d.ctl.made;
expect(dayBackdrop.dispose).toHaveBeenCalledOnce();
expect(duskBackdrop.dispose).not.toHaveBeenCalled(); // it is the live scene's
scene?.dispose();
createRidgeScene.mockImplementationOnce(() => {
throw new Error('boom');
});
d.ctl.hold = false;
const onCompileFail = vi.fn();
forgetManifests();
await startBackgroundScene(config, caps, { canvas, onCompileFail });
expect(onCompileFail).toHaveBeenCalled();
expect(d.ctl.made[d.ctl.made.length - 1].dispose).toHaveBeenCalledOnce();
});
it('config place picks the index entry; an unknown id falls back to the default', async () => {
served();
loader();
@ -594,7 +662,9 @@ describe('the ridge cards and the live scene', () => {
it('a lighting pass that throws (no WebGL2) is the sky alone, one onPlanesFail and never onCompileFail', async () => {
serve();
loadBackdrop.mockRejectedValue(new Error('ridge: no WebGL2'));
createBackdrop.mockImplementation(() => {
throw new Error('ridge: no WebGL2');
});
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
const onCompileFail = vi.fn();

View file

@ -6,7 +6,7 @@ import type { SkyChoice } from './ridge/skyMoment';
import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop';
import { FALLBACK_VIEW } from './ridge/view';
import { FALLBACK_VIEW, HFOV_MAX_DEG } from './ridge/view';
export type { Scene, SceneStats } from './Scene';
export type { SceneStyle, SceneTier } from './tier';
@ -30,6 +30,8 @@ const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}
/** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */
interface Prepared {
make: () => Scene | null;
/** Let go of what was made for a scene that will never be made (a build that went stale): the backdrop's lighting context. */
discard: () => void;
/** Why this scene is the sky alone, when the baked planes did not load; null when it has planes or none are asked for. */
planesFail: Error | null;
}
@ -40,12 +42,15 @@ async function prepare(
choice: SkyChoice
): Promise<Prepared> {
// Whatever throws in making the scene is a compile failure, as whatever throws in loading it.
let backdrop: Backdrop | null = null;
const guarded = (make: () => Scene | null): Prepared => ({
planesFail: null,
discard: () => backdrop?.dispose(),
make: () => {
try {
return make();
} catch (e) {
backdrop?.dispose();
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
return null;
}
@ -61,22 +66,29 @@ async function prepare(
const { createRidgeScene } = await import('./ridge/Ridge');
const { manifest, fail } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place);
// The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per
// frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone, over the view the store is told of.
let backdrop: Backdrop | null = null;
// The tiles around the heading load with the scene chunk and the weather, and are lit here for this sky (a sky change comes through a rebuild), so
// createRidgeScene stays synchronous and the scene's first frame has its ridge; it asks for the tiles ahead as the view turns. Any failure, a missing
// WebGL2 included, is the sky alone, over the view the store is told of.
let lit: SkyColours | undefined;
let planesFail: Error | null = fail;
if (manifest) {
try {
const manifestSky = ridgeSkyFor(choice, manifest.view);
const { loadBackdrop } = await import('./ridge/Backdrop');
backdrop = await loadBackdrop(
const { createBackdrop } = await import('./ridge/Backdrop');
const heading = await import('./ridge/heading');
backdrop = createBackdrop(
manifest,
manifestSky.physical as NonNullable<typeof manifestSky.physical>
);
if (!backdrop) throw new Error('ridge cards did not load');
// A place not shown before faces its rest azimuth; a rebuild for a sky keeps the heading the view has turned to.
const now = performance.now();
heading.anchor(manifest.view.place.id, manifest.view.lookAzDeg, now);
const h = heading.headingAt(now);
await backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 });
if (backdrop.litTiles().length === 0) throw new Error('ridge cards did not load');
lit = manifestSky;
} catch (e) {
backdrop?.dispose();
backdrop = null;
planesFail = e instanceof Error ? e : new Error(String(e));
}
@ -95,7 +107,7 @@ async function prepare(
return { ...made, planesFail };
} catch (e) {
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
return { make: () => null, planesFail: null };
return { make: () => null, discard: () => undefined, planesFail: null };
}
}
@ -171,7 +183,10 @@ export async function startBackgroundScene(
built = key;
// The old scene stays up while the next one loads; a build that is stale or after dispose is never made, so it never speaks.
const ready = await prepared(next);
if (disposed || mine !== generation) return;
if (disposed || mine !== generation) {
ready.discard();
return;
}
inner?.dispose();
inner = null;
const scene = ready.make();

View file

@ -10,8 +10,10 @@ import { sunOfBand } from './skyTestkit';
import { startBackgroundScene } from '../index';
import { parseManifest } from './manifest';
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
import type { Backdrop } from './Backdrop';
import { cardMotion, FALLBACK_VIEW, windowFor } from './view';
import type { Backdrop, LitTile } from './Backdrop';
import { cardPose, FALLBACK_VIEW, offsetRange, windowFor } from './view';
import { anchor, getMode, headingAt, hold, phiAt, resetHeading } from './heading';
import { getCamera, resetCamera, setCamera } from '../cameraState';
describe('noise', () => {
it('is deterministic and in [0, 1)', () => {
@ -228,6 +230,7 @@ beforeEach(() => {
innerWidth: 400,
innerHeight: 800,
matchMedia: () => motion,
clearTimeout,
location: {
get search() {
return search;
@ -545,15 +548,27 @@ describe('rain in the scene', () => {
});
describe('the ridge cards in the scene', () => {
const manifest = parseManifest(wireManifest(), '/d/'); // three cards, scales 1.2, 1.0167, 1.005, nearest first
const litCards = (): Backdrop => ({
manifest,
cards: manifest.cards.map((c, k) => {
const canvas = fakeEl('canvas');
canvas.id = `card-${k}`;
return { canvas: canvas as unknown as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale };
}),
});
const manifest = parseManifest(wireManifest(), '/d/'); // four tiles of 90 degrees, three cards (card 2 absent in tile 2); rest azimuth 214
const { view } = manifest;
const tilesOf = (): LitTile[] =>
manifest.tiles.flatMap((row, tile) =>
row.flatMap((e, card) => {
if (!e) return [];
const canvas = fakeEl('canvas');
canvas.id = `t${tile}c${card}`;
canvas.width = 1602;
return [{ tile, card, canvas: canvas as unknown as HTMLCanvasElement }];
})
);
const litCards = (): Backdrop & { ensure: ReturnType<typeof vi.fn>; dispose: ReturnType<typeof vi.fn> } => {
const lit = tilesOf();
return {
manifest,
ensure: vi.fn(async () => undefined),
litTiles: () => lit,
dispose: vi.fn(),
};
};
const night: SkyColours = {
...DAY,
top: [10, 14, 40],
@ -564,7 +579,22 @@ describe('the ridge cards in the scene', () => {
const rigOf = (parent: any) =>
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));
const win = windowFor(manifest.view, 400, 800);
const motion400 = cardMotion(manifest, win);
const planeTop = 800 - win.plane.bottom - win.plane.h;
const horizonY = planeTop + view.horizonRow * win.plane.scale;
const k = win.plane.scale * view.pxPerDegH;
/** The animations of a box that are still running: a reissue cancels the one before it. */
const live = (box: any): any[] => box.anims.filter((a: any) => a.cancel.mock.calls.length === 0);
const mountedIds = (rig: any): string[] =>
rig.children.flatMap((box: any) => box.children.map((c: any) => c.id)).sort();
const T0 = 5_000;
beforeEach(() => {
resetHeading();
resetCamera();
vi.spyOn(performance, 'now').mockReturnValue(T0);
anchor(view.place.id, view.lookAzDeg, T0); // what index.ts prepare does before the scene is made
});
afterEach(() => vi.restoreAllMocks());
it('lays the night bodies (lines, stars, moon) in the sky before any card, so the cards occlude them', () => {
const { canvas } = host();
@ -579,8 +609,8 @@ describe('the ridge cards in the scene', () => {
const images = draws.map((d, i) => (d === 'image' ? i : -1)).filter((i) => i >= 0);
expect(bodies.length).toBeGreaterThan(0);
expect(draws).toContain('line'); // the lines are drawn (the sky is a night one)
const cards = images.slice(-3); // the sky's upscale first, then the three cards, farthest first
expect(cards).toHaveLength(3);
const cards = images.slice(1); // the sky's upscale first, then the cards' tiles
expect(cards.length).toBeGreaterThan(0);
expect(Math.max(...bodies)).toBeLessThan(Math.min(...cards));
});
@ -594,9 +624,10 @@ describe('the ridge cards in the scene', () => {
expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the sky's own upscale is in the host canvas: the cards are DOM above it
});
it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => {
it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position, and disposes the backdrop with itself', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!;
const bd = litCards();
const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: bd })!;
const kinds = parent.children.map((c: any) => c.tag);
expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']);
expect(parent.children[2].children).toHaveLength(3);
@ -604,112 +635,241 @@ describe('the ridge cards in the scene', () => {
expect(c.style.zIndex).toBeUndefined();
expect(c.style.position).not.toBe('fixed');
});
expect(bd.dispose).not.toHaveBeenCalled();
s.dispose();
expect(parent.children).toEqual([canvas]);
expect(bd.dispose).toHaveBeenCalledOnce();
});
it('is one element per card, farthest first, each at its rows of the plane and its origin on the horizon centre', () => {
it('is one box per card, farthest first, spanning the viewport with its origin on the horizon centre, holding that card’s tiles', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const rig = rigOf(parent);
expect(rig.children.map((c: any) => c.id)).toEqual(['card-2', 'card-1', 'card-0']);
const planeTop = 800 - win.plane.bottom - win.plane.h;
rig.children.forEach((el: any, j: number) => {
const card = manifest.cards[2 - j];
expect(el.style.left).toBe(`${(400 - win.plane.w) / 2}px`);
expect(el.style.width).toBe(`${win.plane.w}px`);
expect(el.style.top).toBe(`${planeTop + card.top * win.plane.scale}px`);
expect(el.style.height).toBe(`${card.h * win.plane.scale}px`);
expect(el.style.transformOrigin).toBe(
`${win.plane.w / 2}px ${(manifest.view.horizonRow - card.top) * win.plane.scale}px`
);
rig.children.forEach((el: any) => {
expect(el.style.left).toBe('0');
expect(el.style.width).toBe('400px');
expect(el.style.height).toBe('800px');
expect(el.style.transformOrigin).toBe(`200px ${horizonY}px`);
});
// Each card's tiles are its own: the box of card 0 holds only c0 canvases.
rig.children.forEach((el: any) => {
const card = Number(el.id.slice(-1));
el.children.forEach((c: any) => expect(c.id.endsWith(`c${card}`)).toBe(true));
});
s.dispose();
});
it('pans card i by scale_i x heading and scales it by scale_i, to and fro on the compositor', () => {
it('mounts the tiles of the arc about to be seen at their unwrapped azimuth, at their own rows of the plane, one overlap column before the interior', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
rigOf(parent).children.forEach((el: any, j: number) => {
const k = 2 - j;
const { scale, reachPx } = motion400.cards[k];
const { keyframes, options } = el.anims[0];
expect(scale).toBe(manifest.cards[k].scale);
expect(keyframes).toEqual([
{ transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
{ transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
]);
expect(options).toMatchObject({
duration: 75000,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out',
});
});
// The nearer the card, the further it travels.
const reach = (j: number) => motion400.cards[2 - j].reachPx;
expect(reach(2)).toBeGreaterThan(reach(1));
expect(reach(1)).toBeGreaterThan(reach(0));
const rig = rigOf(parent);
// Rest azimuth 214: tile 2 (180..270). Tile 1 and tile 3 are out of sight for the next 30 s at 0.6 degrees per second.
expect(mountedIds(rig)).toEqual(['t2c0', 't2c1']);
const c0 = rig.children[2].children[0];
const e = manifest.tiles[2][0]!;
const colDeg = 360 / view.ringW;
const px = (v: string) => parseFloat(v);
expect(px(c0.style.left)).toBeCloseTo(200 + (180 - colDeg - 214) * k, 6);
expect(px(c0.style.top)).toBeCloseTo(horizonY + (e.top - view.horizonRow) * win.plane.scale, 6);
expect(px(c0.style.width)).toBeCloseTo((view.tileW + 2) * win.plane.scale, 6);
expect(px(c0.style.height)).toBeCloseTo(e.h * win.plane.scale, 6);
s.dispose();
});
it('adds no rAF or timer callback of its own: the drift is Element.animate, the stars alone loop', () => {
it('is one animation per card, not per tile, carrying the pose the heading owner gives each second for 30 seconds', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const rig = rigOf(parent);
rig.children.forEach((box: any) => expect(live(box)).toHaveLength(1));
rig.children.forEach((box: any) => {
const card = Number(box.id.slice(-1));
const { keyframes, options } = live(box)[0];
expect(options).toEqual({ duration: 30000, easing: 'linear', fill: 'forwards' });
expect(keyframes).toHaveLength(31);
const pose = (t: number) =>
cardPose(manifest, card, headingAt(t), phiAt(t), clampOffset(), win);
[0, 1, 17, 30].forEach((n) => {
const p = pose(T0 + n * 1000);
expect(keyframes[n]).toEqual({ transform: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})` });
});
// The view turns at the viewer's 0.6 degrees per second: the container moves one pan per second, a nearer card faster.
});
const near = live(rig.children[2])[0].keyframes;
const far = live(rig.children[0])[0].keyframes;
const shift = (kf: any) => Number(/translate3d\((-?[\d.e-]+)px/.exec(kf.transform)?.[1]);
expect(Math.abs(shift(near[30]) - shift(near[0]))).toBeGreaterThan(Math.abs(shift(far[30]) - shift(far[0])));
s.dispose();
});
const clampOffset = () => {
const [lo, hi] = offsetRange(manifest, win);
return Math.min(hi, Math.max(lo, getCamera().offsetM));
};
it('a heading of 400 degrees places the tiles a heading of 40 does, a revolution on', () => {
const at = (h: number) => {
resetHeading();
anchor(view.place.id, view.lookAzDeg, T0);
hold(h, T0);
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)) };
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.
const a = at(40);
const b = at(400);
expect(b.ids).toEqual(a.ids);
expect(b.left - a.left).toBeCloseTo(360 * k, 4);
});
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 () => {
vi.useFakeTimers();
(window as any).setTimeout = setTimeout;
(window as any).clearTimeout = clearTimeout;
const { parent, canvas } = host();
const bd = litCards();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: bd })!;
expect(bd.ensure).not.toHaveBeenCalled(); // the first arc was made before the scene (index.ts prepare)
vi.advanceTimersByTime(500);
expect(bd.ensure).toHaveBeenCalledTimes(1);
const arc = bd.ensure.mock.calls[0][0];
// The heading is 214 and turns 0.6 degrees per second to 232 in 30 s; on a 400 x 800 viewport a card shows about 28 degrees of itself.
expect(arc.fromDeg).toBeLessThan(214 - 10);
expect(arc.toDeg).toBeGreaterThan(232 + 10);
vi.advanceTimersByTime(1500);
expect(bd.ensure).toHaveBeenCalledTimes(4);
// The view is turned by hand to the north: the next tick holds the tiles there.
const before = mountedIds(rigOf(parent));
hold(300, T0);
vi.advanceTimersByTime(500);
const after = mountedIds(rigOf(parent));
expect(before).toEqual(['t2c0', 't2c1']);
expect(after).not.toContain('t2c0');
expect(after.some((id) => id.startsWith('t3'))).toBe(true);
s.dispose();
vi.useRealTimers();
});
it('issues the next stretch of motion once 80% of the last has run, on any change of heading, mode or offset, and not otherwise', () => {
vi.useFakeTimers();
(window as any).setTimeout = setTimeout;
(window as any).clearTimeout = clearTimeout;
const now = vi.mocked(performance.now);
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const rig = rigOf(parent);
const issued = () => rig.children.map((b: any) => b.anims.length);
const base = issued()[0];
now.mockReturnValue(T0 + 20_000);
vi.advanceTimersByTime(20_000);
expect(issued()[0]).toBe(base); // 20 s of 30: not yet
now.mockReturnValue(T0 + 24_500);
vi.advanceTimersByTime(4_500);
expect(issued()[0]).toBe(base + 1);
expect(rig.children[0].anims[base - 1].cancel).toHaveBeenCalled();
const afterReissue = issued()[0];
setCamera({ offsetM: 20 });
expect(issued()[0]).toBe(afterReissue + 1);
setCamera({ offsetM: 20 }); // nothing changed
expect(issued()[0]).toBe(afterReissue + 1);
hold(10, T0 + 24_500);
expect(issued()[0]).toBe(afterReissue + 2);
s.dispose();
setCamera({ offsetM: 30 });
expect(issued()[0]).toBe(afterReissue + 2); // a disposed scene is deaf
vi.useRealTimers();
});
it('adds no rAF of its own over ten idle seconds: the drift is Element.animate, the stars alone loop', () => {
vi.useFakeTimers();
(window as any).setTimeout = setTimeout;
(window as any).clearTimeout = clearTimeout;
const { canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards
vi.advanceTimersByTime(10_000);
expect(rafQueue).toHaveLength(1);
s.dispose();
vi.useRealTimers();
});
it('runs constant keyframes under reduced motion, and the view turns nothing whatever the viewer asked for', () => {
motion.matches = true;
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
expect(getMode()).toBe('still');
rigOf(parent).children.forEach((box: any) => {
const { keyframes } = live(box)[0];
expect(keyframes.length).toBeGreaterThan(0);
keyframes.forEach((f: any) => expect(f).toEqual(keyframes[0]));
});
s.dispose();
});
it('pauses the drift under reduced motion, in a hidden tab, and plays it again', () => {
it('pauses the motion in a hidden tab and when motion is reduced, plays it again from where the clock is, and cancels it on dispose', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const anims = rigOf(parent).children.map((g: any) => g.anims[0]);
anims.forEach((a: any) => expect(a.play).toHaveBeenCalled());
anims.forEach((a: any) => a.pause.mockClear());
const rig = rigOf(parent);
const anims = () => rig.children.map((g: any) => g.anims[g.anims.length - 1]);
anims().forEach((a: any) => expect(a.play).toHaveBeenCalled());
const first = anims();
first.forEach((a: any) => a.pause.mockClear());
motion.matches = true;
motion.addEventListener.mock.calls
.filter((c: any[]) => c[0] === 'change')
.forEach((c: any[]) => c[1]());
anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
anims().forEach((a: any) => expect(a.pause).toHaveBeenCalled());
motion.matches = false;
anims.forEach((a: any) => a.pause.mockClear());
doc.visibilityState = 'hidden';
doc.dispatchEvent(new Event('visibilitychange'));
anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
anims().forEach((a: any) => expect(a.pause).toHaveBeenCalled());
doc.visibilityState = 'visible';
(performance.now as any).mockReturnValue(T0 + 60_000);
doc.dispatchEvent(new Event('visibilitychange'));
const resumed = anims();
resumed.forEach((a: any) => expect(a.play).toHaveBeenCalled());
// Back in view the motion starts from the clock now, not from where it stopped.
const frame0 = (box: any) => box.anims[box.anims.length - 1].keyframes[0].transform;
const p = cardPose(manifest, 0, headingAt(T0 + 60_000), phiAt(T0 + 60_000), clampOffset(), win);
expect(frame0(rig.children[2])).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`);
s.dispose();
anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
resumed.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
});
it("a still draws every card, farthest first, scaled by its own scale about the rig's origin, at heading 0", () => {
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() });
const drawn = images.filter((a) => (a[0] as any).id) as any[];
expect(drawn.map((a) => a[0].id)).toEqual(['card-2', 'card-1', 'card-0']);
expect(drawn.map((a) => a[0].id)).toEqual(['t2c1', 't2c0']);
expect(drawn[0][0].id.endsWith('c1')).toBe(true);
const dpr = 2;
const s = win.plane.scale * dpr;
const x0 = (800 - win.plane.w * dpr) / 2;
const planeTop = 1600 - (win.plane.h + win.plane.bottom) * dpr;
const origin = [x0 + (win.plane.w * dpr) / 2, planeTop + manifest.view.horizonRow * s];
drawn.forEach((a, j) => {
const card = manifest.cards[2 - j];
expect(a.k).toBe(card.scale);
expect(a.t).toEqual(origin);
drawn.forEach((a) => {
const card = Number(a[0].id.slice(-1));
const p = cardPose(manifest, card, headingAt(T0), phiAt(T0), clampOffset(), win);
expect(a.k).toBe(p.scale);
expect(a.t).toEqual([(200 + p.shiftPx) * dpr, horizonY * dpr]);
const e = manifest.tiles[2][card]!;
const colDeg = 360 / view.ringW;
expect([a[1], a[2], a[3], a[4]]).toEqual([
x0 - origin[0],
planeTop + card.top * s - origin[1],
win.plane.w * dpr,
card.h * s,
(180 - colDeg - 214) * k * dpr,
(e.top - view.horizonRow) * win.plane.scale * dpr,
(view.tileW + 2) * win.plane.scale * dpr,
e.h * win.plane.scale * dpr,
]);
expect([a.alpha, a.op]).toEqual([1, 'source-over']);
});
expect(parent.children).toEqual([canvas]);
});
it('settles to a still with the cards painted when the frame rate is poor', () => {
it('settles to a still with the tiles painted when the frame rate is poor', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() });
runFrames(100, 400);
expect(images.filter((a) => (a[0] as any).id)).toHaveLength(3);
expect(images.filter((a) => (a[0] as any).id).length).toBeGreaterThan(0);
expect(parent.children).toEqual([canvas]);
});
@ -720,7 +880,7 @@ describe('the ridge cards in the scene', () => {
expect(images.filter((a) => (a[0] as any).id)).toHaveLength(0);
});
it('asks the host canvas, and every canvas it makes, only for 2d: the cards arrive lit', () => {
it('asks the host canvas, and every canvas it makes, only for 2d: the tiles arrive lit', () => {
const { canvas } = host();
const kinds: string[] = [];
const ask = (el: any) => {

View file

@ -3,12 +3,17 @@ import { overlayRequested } from '../debugOverlays';
import { FrameSampler, FrameStats } from './probe';
import { skyColours, SkyColours, Srgb } from './skyColour';
import { paintSky as paintPhysicalSky } from './physicalSky';
import { cardMotion, windowFor } from './view';
import { cardArc, cardPose, offsetRange, 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 { activeAt, drawTwinkle as paintTwinkle, Star } from './stars';
import { nightBodies, paintNightBodies } from './nightBodies';
import type { NightBodies } from './nightBodies';
import { drawRainTile, RAIN_TILES } from './rain';
import type { Backdrop } from './Backdrop';
import type { Arc, Backdrop, LitTile } from './Backdrop';
export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */
@ -19,7 +24,7 @@ export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
onProbe?: (s: FrameStats & { still: boolean }) => void;
/** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */
sky?: SkyColours;
/** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */
/** The baked ridge cards by tile, lit for `sky` (`Backdrop.ts`), the arc around the heading already made; none is the sky-only scene (`view.ts` FALLBACK_VIEW). The scene owns it from here and disposes it with itself. */
backdrop?: Backdrop;
/** Draw the constellation lines over the stars (a hidden extra, `skyState.ts`); only a night sky shows them. */
lines?: boolean;
@ -96,11 +101,23 @@ function paintSky(
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
/** The rig: one box per card, each holding that card's resident tiles and carried by one animation of its pose. */
interface Rig {
el: HTMLElement;
anims: (Animation | undefined)[];
/** Issue the next stretch of every card's motion from the heading owner's clock now (a tab shown again). */
reissue: () => void;
/** Take the viewer's mode and speed to the heading owner again, then reissue (reduced motion switched). */
sync: () => void;
/** Stop the residency timer and the subscriptions. */
stop: () => void;
}
interface Built {
/** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */
twinkle?: HTMLCanvasElement;
/** The ridge cards' rig, over the twinkle canvas and under the rain; absent in 'still' (the cards are drawn into the host canvas). */
rig?: { el: HTMLElement; anims: (Animation | undefined)[] };
rig?: Rig;
/** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */
rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] };
}
@ -108,8 +125,14 @@ interface Built {
/** The twinkle overlay redraws at most this often: the swings are 2 to 7 s, no need for 60 fps. */
const TWINKLE_FRAME_MS = 50;
/** One leg of the back-and-forth drift, a turn of the heading from one end of its range to the other, takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */
const DRIFT_LEG_S = 75;
/**
* 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
* 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;
/**
* The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS
@ -146,6 +169,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
const teardown = () => {
built?.twinkle?.remove();
built?.rig?.stop();
built?.rig?.anims.forEach((a) => a?.cancel());
built?.rig?.el.remove();
built?.rain?.anims.forEach((a) => a?.cancel());
@ -211,15 +235,47 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
return { els, anims };
};
/** Where a tile sits in a card's box, in viewport px from the centre column and the horizon: its left edge (one overlap column before its interior) and its band. */
const tileBox = (view: View, scale: number, lt: LitTile, turn: number, entry: TileCard) => {
const colDeg = 360 / view.ringW;
const az = turn * 360 + (lt.tile * 360) / view.tiles - colDeg;
return {
left: (az - view.lookAzDeg) * view.pxPerDegH * scale,
top: (entry.top - view.horizonRow) * scale,
w: (view.tileW + 2) * scale,
h: entry.h * scale,
};
};
/**
* The ridge over the sky: one element per lit card, farthest first (DOM order is paint order, stacking is by order alone), placed at the card's rows
* of the plane and scaled about the horizon's centre by the baker's `scale` (`view.ts` `cardMotion` owns every offset and scale). The camera
* turns through its heading range and back on the compositor: card i pans `scale` x heading, so a nearer card leads the far range.
* 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.
*/
const startRig = (bd: Backdrop, w: number, h: number): NonNullable<Built['rig']> => {
const syncKinematics = () => {
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);
};
/** The viewer's offset, clamped to the range this place and viewport allow (`view.ts` `offsetRange`, the one clamp). */
const offsetNow = (bd: Backdrop, win: ReturnType<typeof windowFor>): number => {
const [lo, hi] = offsetRange(bd.manifest, win);
return Math.min(hi, Math.max(lo, getCamera().offsetM));
};
/**
* The ridge over the sky: one box per card, farthest first (DOM order is paint order, stacking is by order alone). A box spans the viewport with its
* transform origin on the horizon centre and holds the resident tiles of its card at their azimuth; one animation per box carries its pose
* (`view.ts` `cardPose`) over SEGMENT_S seconds of the heading owner's clock. A timer asks the backdrop for the arc ahead and mounts what it has made.
*/
const startRig = (bd: Backdrop, w: number, h: number): Rig => {
const { view } = bd.manifest;
const win = windowFor(view, w, h);
const motion = cardMotion(bd.manifest, win);
const planeTop = h - win.plane.bottom - win.plane.h;
const horizonY = planeTop + view.horizonRow * win.plane.scale;
const k = bd.manifest.cards.length;
const el = document.createElement('div');
el.setAttribute('aria-hidden', 'true');
Object.assign(el.style, {
@ -231,60 +287,167 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
overflow: 'hidden',
pointerEvents: 'none',
});
const anims: (Animation | undefined)[] = [];
const planeTop = h - win.plane.bottom - win.plane.h;
for (let k = bd.cards.length - 1; k >= 0; k -= 1) {
const card = bd.cards[k];
const { scale, reachPx } = motion.cards[k];
const node = card.canvas;
Object.assign(node.style, {
const boxes: HTMLElement[] = [];
for (let i = k - 1; i >= 0; i -= 1) {
const box = document.createElement('div');
box.id = `card-${i}`;
Object.assign(box.style, {
position: 'absolute',
left: `${(w - win.plane.w) / 2}px`,
top: `${planeTop + card.top * win.plane.scale}px`,
width: `${win.plane.w}px`,
height: `${card.h * win.plane.scale}px`,
transformOrigin: `${win.plane.w / 2}px ${(view.horizonRow - card.top) * win.plane.scale}px`,
left: '0',
top: '0',
width: `${w}px`,
height: `${h}px`,
transformOrigin: `${w / 2}px ${horizonY}px`,
willChange: 'transform',
pointerEvents: 'none',
});
el.appendChild(node);
anims.push(
node.animate?.(
[
{ transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
{ transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
],
{
duration: DRIFT_LEG_S * 1000,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out',
}
)
);
el.appendChild(box);
boxes[i] = box;
}
const anims: (Animation | undefined)[] = new Array(k).fill(undefined);
syncKinematics();
let offset = offsetNow(bd, win);
const poseAt = (card: number, t: number): CardPose =>
cardPose(bd.manifest, card, headingAt(t), phiAt(t), offset, win);
const transform = (p: CardPose) => `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
let issuedAt = 0;
let live = true;
/** 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();
issuedAt = t0;
const frozen = reducedMotion?.matches === true;
for (let i = 0; i < k; i += 1) {
const frames = frozen
? [{ transform: transform(poseAt(i, t0)) }, { transform: transform(poseAt(i, t0)) }]
: Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({
transform: transform(poseAt(i, t0 + n * 1000)),
}));
boxes[i].style.transform = frames[0].transform;
anims[i]?.cancel();
anims[i] = boxes[i].animate?.(frames, {
duration: SEGMENT_S * 1000,
easing: 'linear',
fill: 'forwards',
});
if (!moving()) anims[i]?.pause();
}
};
/** 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 };
};
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. */
const mount = (arc: Arc) => {
const refs = residentTiles(view, (arc.fromDeg + arc.toDeg) / 2, (arc.toDeg - arc.fromDeg) / 2);
const turnOf = new Map(refs.map((r) => [r.tile, r.turn]));
const keep = new Set<HTMLCanvasElement>();
for (const lt of bd.litTiles()) {
const turn = turnOf.get(lt.tile);
const entry = bd.manifest.tiles[lt.tile][lt.card];
if (turn === undefined || !entry) continue;
keep.add(lt.canvas);
if (mounted.get(lt.canvas) === turn && lt.canvas.parentElement === boxes[lt.card]) continue;
const b = tileBox(view, win.plane.scale, lt, turn, entry);
Object.assign(lt.canvas.style, {
position: 'absolute',
left: `${w / 2 + b.left}px`,
top: `${horizonY + b.top}px`,
width: `${b.w}px`,
height: `${b.h}px`,
});
mounted.set(lt.canvas, turn);
boxes[lt.card].appendChild(lt.canvas);
}
for (const c of [...mounted.keys()]) {
if (keep.has(c)) continue;
c.remove();
mounted.delete(c);
}
};
// The one timer: ask for the arc ahead, mount what is made, and issue the next stretch once this one is mostly spent.
const win0 = window;
let timer = 0;
const residency = () => {
timer = 0;
if (!live) return;
const t = clock();
if (t - issuedAt >= SEGMENT_S * 1000 * REISSUE_FRAC && moving()) issue();
const arc = arcBetween(t, t + SEGMENT_S * 1000);
mount(arc);
void bd.ensure(arc).then(() => live && mount(arc));
timer = win0.setTimeout(residency, RESIDENCY_MS);
};
parent.appendChild(el);
return { el, anims };
issue();
mount(arcBetween(issuedAt, issuedAt + SEGMENT_S * 1000));
const sync = () => {
syncKinematics();
issue();
};
const offHeading = onHeading(issue);
const offCamera = onCamera(sync);
timer = win0.setTimeout(residency, RESIDENCY_MS);
return {
el,
anims,
reissue: issue,
sync,
stop: () => {
live = false;
win0.clearTimeout(timer);
offHeading();
offCamera();
},
};
};
/** Paint the lit cards into the host canvas, farthest first, each at its scale about the same origin as the rig, at heading 0: the still scene's one image. */
/** Paint the lit tiles of every card into the host canvas, farthest first, each card at its pose about the rig's origin, at the heading now: the still scene's one image. */
const paintCards = (bd: Backdrop) => {
const ctx = context2d(canvas);
if (!ctx) return;
const { view } = bd.manifest;
const { w, h, scale } = viewSize();
const { w, h, scale: dpr } = viewSize();
const win = windowFor(view, w, h);
const s = win.plane.scale * scale;
const dw = win.plane.w * scale;
const x0 = (canvas.width - dw) / 2;
const planeTop = canvas.height - (win.plane.h + win.plane.bottom) * scale;
const ox = x0 + dw / 2;
const oy = planeTop + view.horizonRow * s;
for (let k = bd.cards.length - 1; k >= 0; k -= 1) {
const card = bd.cards[k];
const offset = offsetNow(bd, win);
const t = clock();
const planeTop = h - win.plane.bottom - win.plane.h;
const horizonY = planeTop + view.horizonRow * win.plane.scale;
const poses = bd.manifest.cards.map((_, i) =>
cardPose(bd.manifest, i, headingAt(t), phiAt(t), offset, win)
);
const arcs = poses.map((p) => cardArc(view, win, w, p));
const from = Math.min(...arcs.map((a) => a.fromDeg));
const to = Math.max(...arcs.map((a) => a.toDeg));
const turnOf = new Map(residentTiles(view, (from + to) / 2, (to - from) / 2).map((r) => [r.tile, r.turn]));
const lit = bd.litTiles();
for (let i = poses.length - 1; i >= 0; i -= 1) {
ctx.save();
ctx.translate(ox, oy);
ctx.scale(card.scale, card.scale);
ctx.drawImage(card.canvas, x0 - ox, planeTop + card.top * s - oy, dw, card.h * s);
ctx.translate((w / 2 + poses[i].shiftPx) * dpr, horizonY * dpr);
ctx.scale(poses[i].scale, poses[i].scale);
for (const lt of lit.filter((x) => x.card === i)) {
const turn = turnOf.get(lt.tile);
const entry = bd.manifest.tiles[lt.tile][i];
if (turn === undefined || !entry) continue;
const b = tileBox(view, win.plane.scale, lt, turn, entry);
ctx.drawImage(lt.canvas, b.left * dpr, b.top * dpr, b.w * dpr, b.h * dpr);
}
ctx.restore();
}
};
@ -361,6 +524,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
};
function syncPlayState() {
if (moving()) built?.rig?.reissue();
const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? [])];
anims.forEach((a) => (moving() ? a?.play() : a?.pause()));
if (!built?.twinkle) return;
@ -458,7 +622,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
};
document.addEventListener('visibilitychange', onVisibility);
window.addEventListener('resize', onResize);
reducedMotion?.addEventListener?.('change', syncPlayState);
const onMotionChange = () => {
built?.rig?.sync();
syncPlayState();
};
reducedMotion?.addEventListener?.('change', onMotionChange);
return {
login() {
@ -468,10 +636,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
if (disposed) return;
disposed = true;
cancelAnimationFrame(raf);
opts.backdrop?.dispose();
clearTimeout(resizeTimer);
document.removeEventListener('visibilitychange', onVisibility);
window.removeEventListener('resize', onResize);
reducedMotion?.removeEventListener?.('change', syncPlayState);
reducedMotion?.removeEventListener?.('change', onMotionChange);
teardown();
readout?.remove();
},