diff --git a/harness/scene/README.md b/harness/scene/README.md index d3981fa6..217e2241 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -21,6 +21,12 @@ directory whose ancestors hold no empty `package.json` (esbuild reads them). Timings from SwiftShader are CPU time: use them for the split between passes and for before and after of one change, never as a phone frame time. +## Ridge live scene + +`ridgeLive.html` is one live scene (tier 'full', the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot: `?h=214&sun=232:22&speed=6` (start heading, the sun's azimuth and elevation, degrees a second of rotation), +`?sky=night&lines=1`. `window.live` offers `hold(h)`, `pose()`, `plate()`, `left()` (the plate's left edge on the page) and `plateCost()` (ms of main thread to paint one plate here); `window.longTasks` lists the tasks over 50 ms. +A held heading's sun lands within a tenth of a pixel of the column the heading owner says, across re-centres of the plate. + ## Ridge look sheet Renders a baked place (`?place=`, the index default otherwise) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun) @@ -30,6 +36,8 @@ 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) +`&sun=100:6` puts the sun of that sky at compass azimuth 100, 6 degrees up (the stars are those of the moment the sheet is opened): a sun at the heading's side shows where the turned sky puts it, `&sky=5&lines=1` is the night. + 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 (phi 0: `camera.r_max_forward_m`, another phi: `camera.r_max_m`). diff --git a/harness/scene/ridgeLive.html b/harness/scene/ridgeLive.html new file mode 100644 index 00000000..fba96a06 --- /dev/null +++ b/harness/scene/ridgeLive.html @@ -0,0 +1,8 @@ + + + +Ridge live scene + +
+ + diff --git a/harness/scene/ridgeLive.ts b/harness/scene/ridgeLive.ts new file mode 100644 index 00000000..fcab4092 --- /dev/null +++ b/harness/scene/ridgeLive.ts @@ -0,0 +1,71 @@ +// One live ridge scene (tier 'full': the sky plate and the cards on the compositor) filling the window, for a driver to turn and screenshot. Not shipped. +// `?h=214` the heading the scene starts at; `?sun=232:22` the sun's compass azimuth and elevation (degrees); `?sky=night` the stars of now (sun below the horizon); `?lines=1` the constellation lines. +// `?speed=6` degrees a second the view turns (rotation mode 'both'); 0 holds it. The page offers `window.live`: `hold(h)` turns the view by hand, `pose()` is the heading owner's pose now, +// `plate()` the sky plate's element and `left()` its left edge and width on the page. +import { parseManifest } from '../../src/app/features/scene/ridge/manifest'; +import { makePhysicalSky } from '../../src/app/features/scene/ridge/physicalSky'; +import { createBackdrop } from '../../src/app/features/scene/ridge/Backdrop'; +import { createRidgeScene } from '../../src/app/features/scene/ridge/Ridge'; +import { anchor, hold, poseAt } from '../../src/app/features/scene/ridge/heading'; +import { setCamera } from '../../src/app/features/scene/cameraState'; +import { HFOV_MAX_DEG, windowFor } from '../../src/app/features/scene/ridge/view'; +import { paintSky } from '../../src/app/features/scene/ridge/physicalSky'; +import { nightBodies } from '../../src/app/features/scene/ridge/nightBodies'; +import { plateCamera, plateSize, SLACK_MIN_DEG } from '../../src/app/features/scene/ridge/skyTurn'; + +const q = new URLSearchParams(location.search); +/** The main-thread tasks over 50 ms the page saw, ms: `window.longTasks`. */ +const longTasks: number[] = []; +(window as unknown as { longTasks: number[] }).longTasks = longTasks; +try { + new PerformanceObserver((l) => l.getEntries().forEach((e) => longTasks.push(e.duration))).observe({ entryTypes: ['longtask'] }); +} catch { + // No long-task entries in this browser. +} + +async function main() { + const index = await (await fetch('/public/ridge/index.json')).json(); + const dir = `/public/ridge/${index.places[q.get('place') ?? index.default]}/`; + const manifest = parseManifest(await (await fetch(`${dir}manifest.json`)).json(), dir); + const { view } = manifest; + const [az, el] = (q.get('sun') ?? '232:22').split(':').map(Number); + const time = new Date(); + const sun = q.get('sky') === 'night' ? { azimuth: 0, elevation: -30, time } : { azimuth: az, elevation: el, time }; + const physical = makePhysicalSky(sun, 0, view); + const h0 = Number(q.get('h') ?? view.lookAzDeg); + anchor(view.place.id, h0, performance.now()); + setCamera({ mode: 'both', speedDegPerS: Number(q.get('speed') ?? 0), offsetM: 200 }); + const backdrop = createBackdrop(manifest, physical); + await backdrop.ensure({ fromDeg: h0 - HFOV_MAX_DEG, toDeg: h0 + HFOV_MAX_DEG }); + const canvas = document.getElementById('c') as HTMLCanvasElement; + const scene = createRidgeScene({ canvas, tier: 'full', sky: { ...physical.stops, physical }, backdrop, lines: q.get('lines') === '1' }); + const host = document.getElementById('host') as HTMLElement; + // The plate is the host's div whose first child is a canvas (the rig's first child is a div, the rain's has none). + const plate = () => [...host.children].find((c) => c.tagName === 'DIV' && c.firstElementChild?.tagName === 'CANVAS'); + (window as unknown as { live: unknown }).live = { + scene, + hold: (h: number) => hold(h, performance.now()), + pose: () => poseAt(performance.now()), + plate, + /** Mean ms of the main-thread part of painting one plate here (the dome, its pixels and the bodies, not the canvas upscale), over `n` runs. */ + plateCost: (n = 10) => { + const w = innerWidth; + const h = innerHeight; + const win = windowFor(view, w, h); + const { cssW } = plateSize(win, w, h, devicePixelRatio >= 2 ? 2 : 1, SLACK_MIN_DEG); + const t0 = performance.now(); + for (let i = 0; i < n; i += 1) nightBodies(physical, paintSky(physical, cssW, h, plateCamera(win, 214 + i, SLACK_MIN_DEG)), true); + return (performance.now() - t0) / n; + }, + left: () => { + const r = plate()?.getBoundingClientRect(); + return r && { left: r.left, width: r.width }; + }, + }; + document.title = 'ridge live: done'; +} + +main().catch((e) => { + console.error(e); + document.title = `ridge live: failed ${e}`; +}); diff --git a/harness/scene/ridgeSheet.ts b/harness/scene/ridgeSheet.ts index 79671f38..440a3a57 100644 --- a/harness/scene/ridgeSheet.ts +++ b/harness/scene/ridgeSheet.ts @@ -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 (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. +// of 360 or 0 is across north. `&sun=100:6` puts the sun of that sky at azimuth 100, 6 degrees up (the stars are always those of the moment the sheet is opened). 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=` 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). @@ -171,11 +171,12 @@ function momentsFrom(params: URLSearchParams, place: Parameters[0] }); return cols; } -/** `?views=h:phi:r,...`: one column per view, all at the sky `?sky=` (default noon). */ +/** `?views=h:phi:r,...`: one column per view, all at the sky `?sky=` (default noon), whose sun `?sun=az:el` may put elsewhere (compass degrees, degrees above the horizon). */ function viewsFrom(params: URLSearchParams): Column[] | undefined { const list = params.get('views'); if (!list) return undefined; - const sky = SKIES[Number(params.get('sky') ?? 2)]; + const [az, el] = (params.get('sun') ?? '').split(':').map(Number); + const sky = { ...SKIES[Number(params.get('sky') ?? 2)], ...(Number.isFinite(az) && Number.isFinite(el) ? { azimuth: az, elevation: el } : {}) }; return list.split(',').map((v) => { const [h, phi, r] = v.split(':').map(Number); return { ...sky, label: `h ${h} phi ${phi} r ${r}`, view: { h, phi, r } }; diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 8fc215bd..9679079f 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -5,14 +5,17 @@ config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene. - `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ login, dispose }` or - null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) on the host - canvas at the viewport's size in canvas pixels, then the stars baked into it, a twinkle overlay canvas for the swinging ones - (`ridge/stars.ts`), the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). - With no cards (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms. - The host canvas and its parent must be positioned and the canvas should fill the parent. A resize rebuilds it; so does a sky change + null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) into a sky plate (`ridge/skyTurn.ts`): one element over the host + canvas, the viewport's width plus its slack of sky each side (20 degrees, more as the turn speeds up: the margin of the speed in force over a tick and 2 s of lateness, and 14 degrees of travel), centred on the heading `heading.ts` owns, holding the sky with the real stars, the moon and the lines baked into it and a + twinkle canvas for the swinging stars (`ridge/stars.ts`) over it. The sky is at infinity, so one animation slides the plate by the heading's turn at the cards' px per degree, on the + same keyframes as the cards; a residency tick or a reissue paints a new plate about the heading once it is within that margin of the plate's edge (or the speed asks for more slack) and swaps it in the same tick, + keyed from the clock after the paint (the same sky at the same screen place, so nothing moves; the twinkle schedule runs over the catalogue, so a swap keeps which stars swing; the plate's backing store is capped at 3 Mpx, the pixel ratio lowering before the plate shrinks). Then come the lit ridge + cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). A sky with no physical model is a gradient in the host canvas. + With no cards (the load failed) the scene shows the sky, stars and weather only, the plate facing the place's rest azimuth and staying. No script runs per frame except the twinkle, at most every 50 ms. + The host canvas and its parent must be positioned and the parent must clip (the plate is wider than the viewport); the canvas should fill the parent. A resize rebuilds it; so does a sky change (`index.ts`). - Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness. - `tier: 'still'` paints the sky and stars and adds no overlay, no rain and no loop. + `tier: 'still'` paints the sky (facing the heading its pose froze at) and stars into the host canvas and adds no plate, no rain and no loop. - Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over 33 ms the scene settles to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling and shows `n / median / p95` in a corner readout. @@ -37,7 +40,7 @@ means "keep the CSS ground". Everything below this section describes the opt-in 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's pose, the direction, the camera's angle over it and its offset, as one segment (module state: the pose at a clock, the mode and speed in force and the ease to the pose the choices owe; any change of a choice, a hold, a bound or reduced motion starts a new segment from the pose it has at that clock, `poseAt(t)` is a pure function of it, and a mode pick eases the angle and the offset one after the other, 300 ms each, in the order that keeps every pose inside the bound; `cameraState.ts` hands it each change synchronously before its listeners and keeps no log; `view.ts` `offsetRange`, given to it by the scene, is the one clamp; angles are 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 and every 50 ms while an ease runs, 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 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 + 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 sky and the tiles of the arc into the host canvas at the heading now. 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/`. diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 1b43c855..1f462a5e 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { createRidgeScene } from './Ridge'; +import { createRidgeScene, RESIDENCY_MS } from './Ridge'; import { valueNoise, hash2 } from './noise'; import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; import type { SkyColours } from './skyColour'; @@ -15,6 +15,8 @@ import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; import type { Arc, Backdrop, LitTile } from './Backdrop'; import type { Mock } from 'vitest'; import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view'; +import { LATENESS_S, plateCamera, plateSize, SLACK_MIN_DEG, slackFor } from './skyTurn'; +import { ringAzimuth, sunColumns, sunInColumn } from './lightCards'; import { norm, residentTiles } from './ring'; import { anchor, hold, poseAt, resetHeading, settledAt, STAGE_MS } from './heading'; import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; @@ -122,6 +124,11 @@ function fakeEl(tag = 'div') { this.children.push(c); return c; }, + insertBefore(c: any, before: any) { + c.parentElement = this; + this.children.splice(this.children.indexOf(before), 0, c); + return c; + }, animate: vi.fn((keyframes: any[], options: any) => { const a: any = { currentTime: 0, @@ -157,6 +164,12 @@ const draws: string[] = []; const images: unknown[][] = []; /** Every RGBA grid the host canvas was painted from (the small canvas's putImageData). */ const painted: Uint8ClampedArray[] = []; +/** Where each sun disc (its gradient's centre) and each body (an arc) was drawn into a sky canvas, in that canvas's device px, in paint order. */ +const suns: number[][] = []; +const arcs: number[][] = []; +/** Where each star of the twinkle overlay was drawn (its canvas's device px), in draw order; and what happens while a sky is painted (a paint takes time). */ +const twinks: number[][] = []; +let onPaint: (() => void) | undefined; function ctx() { const c: any = { createLinearGradient: () => ({ addColorStop: vi.fn() }), @@ -185,13 +198,17 @@ function ctx() { }), putImageData(img: { data: Uint8ClampedArray }) { painted.push(img.data); + onPaint?.(); }, beginPath() {}, moveTo() {}, stroke() { draws.push('line'); }, - createRadialGradient: () => ({ addColorStop: vi.fn() }), + createRadialGradient: (x: number, y: number) => { + suns.push([x, y]); + return { addColorStop: vi.fn() }; + }, lineTo() {}, closePath() {}, // Stars: arc+fill is one draw. A context that has cleared a rect is the twinkle overlay's. @@ -199,8 +216,10 @@ function ctx() { c.overlay = true; draws.push('clear'); }, - arc() { + arc(x: number, y: number) { draws.push(c.overlay ? 'twinkle' : 'star'); + if (!c.overlay) arcs.push([x, y]); + else twinks.push([x, y]); c.arcing = true; }, fill: () => { @@ -230,6 +249,10 @@ beforeEach(() => { draws.length = 0; images.length = 0; painted.length = 0; + suns.length = 0; + arcs.length = 0; + twinks.length = 0; + onPaint = undefined; search = ''; motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }; doc = Object.assign(new EventTarget(), { @@ -303,7 +326,9 @@ describe('createRidgeScene', () => { const { canvas } = host(); const physical = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), 0, ELSEWHERE_VIEW); const s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!; - const want = paintPhysicalSky(physical, 400, 800, windowFor(ELSEWHERE_VIEW, 400, 800).camera); + // a live sky is a plate about the heading, which with no ridge is the View's rest azimuth + const win = windowFor(ELSEWHERE_VIEW, 400, 800); + const want = paintPhysicalSky(physical, plateSize(win, 400, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(win, ELSEWHERE_VIEW.lookAzDeg, SLACK_MIN_DEG)); expect(painted).toHaveLength(1); expect(Array.from(painted[0])).toEqual(Array.from(want.data)); s.dispose(); @@ -405,9 +430,12 @@ describe('the starfield in the scene', () => { const t = new Date('2026-12-04T00:00:00Z'); const physical = makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW); const night: SkyColours = { ...DAY, physical }; - const N = nightBodies( + const view400 = windowFor(FALLBACK_VIEW, 400, 800); + /** The stars of a still, painted through the viewport's own camera, and of a live plate, painted through the viewport's plus the slack each side. */ + const N = nightBodies(physical, paintPhysicalSky(physical, 400, 800, view400.camera), false).stars.length; + const NPLATE = nightBodies( physical, - paintPhysicalSky(physical, 400, 800, windowFor(FALLBACK_VIEW, 400, 800).camera), + paintPhysicalSky(physical, plateSize(view400, 400, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(view400, FALLBACK_VIEW.lookAzDeg, SLACK_MIN_DEG)), false ).stars.length; const hear = (name: string) => { @@ -420,17 +448,18 @@ describe('the starfield in the scene', () => { it('bakes every star once into the sky; per frame only the overlay is touched', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; - expect(count('star')).toBe(N); + expect(count('star')).toBe(NPLATE); expect(painted).toHaveLength(1); // the physical sky's one grid - expect(parent.children[1].anims).toHaveLength(0); // the overlay, above the sky + const plate = parent.children[1]; // one element over the host canvas: the sky and, above it, the twinkle canvas + expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); expect(parent.children).toHaveLength(2); const before = baked(); runFrames(16.7, 300); // 5 s at 60 fps; the overlay repaints at 20 fps expect(baked()).toBe(before); expect(count('clear')).toBeGreaterThan(60); expect(count('clear')).toBeLessThanOrEqual(101); - // each pass paints at most SLOTS stars, each as its cover and the star again - expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64); + // the schedule runs over the catalogue and the plate has a share of it: SLOTS of the plate's stars twinkle on average, each drawn as its cover and the star again + expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64 * 2); expect(count('twinkle')).toBeGreaterThan(0); s.dispose(); }); @@ -504,7 +533,7 @@ describe('the starfield in the scene', () => { const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; runFrames(100, 100); expect(parent.children).toEqual([canvas]); - expect(count('star')).toBe(N); + expect(count('star')).toBe(NPLATE + N); // the plate's, then the still's own in the host canvas expect(rafQueue).toHaveLength(0); s.dispose(); }); @@ -523,7 +552,7 @@ describe('rain in the scene', () => { ...DAY, physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), w, FALLBACK_VIEW), }); - const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div'); + const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div' && c.style.backgroundImage); it('lays one falling tile per rain layer over the sky when it rains, each slid by its own height on the compositor', () => { const { parent, canvas } = host(); @@ -631,14 +660,15 @@ describe('the ridge cards in the scene', () => { expect(Math.max(...bodies)).toBeLessThan(Math.min(...cards)); }); - it('keeps the live sky canvas, with every body baked into it, under the twinkle canvas and the rig', () => { + it('keeps the live sky, with every body baked into it, and the twinkle canvas in one plate under the rig; the host canvas is not painted', () => { const { parent, canvas } = host(); createRidgeScene({ canvas, tier: 'full', sky: { ...night }, backdrop: litCards(), lines: true }); const rig = rigOf(parent); - const twinkle = parent.children.findIndex((c: any) => c.tag === 'canvas'); - expect(twinkle).toBeGreaterThanOrEqual(0); - expect(parent.children.indexOf(rig)).toBeGreaterThan(twinkle); - 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 + const plate = parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas')); + expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); // the sky, then the twinkle canvas over it + expect(parent.children.indexOf(rig)).toBeGreaterThan(parent.children.indexOf(plate)); + expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the plate's sky upscale: nothing in the host canvas, the cards are DOM above the plate + expect(live(plate)).toHaveLength(1); // one animation slides it }); 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', () => { @@ -646,7 +676,7 @@ describe('the ridge cards in the scene', () => { 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(kinds).toEqual(['canvas', 'div', 'div', 'div', 'div']); // the host canvas, the sky plate, the rig, the rain expect(parent.children[2].children).toHaveLength(3); parent.children.forEach((c: any) => { expect(c.style.zIndex).toBeUndefined(); @@ -719,6 +749,325 @@ describe('the ridge cards in the scene', () => { s.dispose(); }); + describe('the sky turns with the heading', () => { + const W = 400; + const SUN_ABOVE_REST = 5; // the sun stands this many degrees clockwise of the rest azimuth, 15 degrees up + const sunSky = (): SkyColours => ({ + ...DAY, + physical: makePhysicalSky({ azimuth: view.lookAzDeg + SUN_ABOVE_REST, elevation: 15, time: new Date('2026-06-21T10:40:00Z') }, 0, view), + }); + const nightSky = (): SkyColours => ({ + ...DAY, + physical: makePhysicalSky(sunOfBand(view.place, 'night', new Date('2026-12-04T00:00:00Z')), 0, view), + }); + const px = (v: string) => parseFloat(v); + const plateOf = (parent: any) => parent.children.find((c: any) => c.children.some((g: any) => g.tag === 'canvas')); + /** The plate's pan (px) at the clock `t`, read from its running animation: its keyframes are a second apart. */ + const panAt = (plate: any, t: number): number => { + const a = live(plate)[0]; + const at = (n: number) => px(/translate3d\((-?[\d.e+-]+)px/.exec(a.keyframes[n].transform)![1]); + const s = Math.max(0, (t - a.at) / 1000); + const i = Math.min(Math.floor(s), a.keyframes.length - 2); + return at(i) * (1 - (s - i)) + at(i + 1) * (s - i); + }; + /** Where a point drawn at `x` device px of the plate's sky canvas is on the viewport at `t`, CSS px from its left edge. */ + const onViewport = (plate: any, x: number, t: number): number => { + const ratio = plate.children[0].width / px(plate.style.width); + return px(plate.style.left) + x / ratio + panAt(plate, t); + }; + const ticking = () => { + vi.useFakeTimers(); + (window as any).setTimeout = setTimeout; + (window as any).clearTimeout = clearTimeout; + }; + + it('paints the plate about the heading the view has, not the rest azimuth, and holds it still there', () => { + hold(100, T0); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const sky = sunSky().physical!; + const wn = windowFor(view, W, 800); + const want = paintPhysicalSky(sky, plateSize(wn, W, 800, 2, SLACK_MIN_DEG).cssW, 800, plateCamera(wn, 100, SLACK_MIN_DEG)); + expect(Array.from(painted[0])).toEqual(Array.from(want.data)); + expect(painted).toHaveLength(1); // the host canvas has none: the plate is the sky + const plate = plateOf(parent); + expect(px(plate.style.left)).toBeCloseTo((W - plateSize(wn, W, 800, 2, SLACK_MIN_DEG).cssW) / 2, 9); // centred on the viewport + expect(panAt(plate, T0)).toBeCloseTo(0, 9); + s.dispose(); + }); + + it('moves the sun and a catalogue star by exactly the turn times the px per degree between a plate centred on h and one centred on h + delta', () => { + const first = host(); + const a = createRidgeScene({ canvas: first.canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const sunA = [...suns[0]]; + const plateA = plateOf(first.parent); + const xA = onViewport(plateA, sunA[0], T0); + expect(xA).toBeCloseTo(W / 2 + SUN_ABOVE_REST * k, 0); // the sun at its true azimuth against the heading + a.dispose(); + suns.length = 0; + hold(view.lookAzDeg + 10, T0); + const second = host(); + const b = createRidgeScene({ canvas: second.canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const xB = onViewport(plateOf(second.parent), suns[0][0], T0); + expect(xA - xB).toBeCloseTo(10 * k, 0); + expect(suns[0][1]).toBe(sunA[1]); // the sun does not climb: only the azimuth turns + b.dispose(); + + }); + + it('moves a catalogue star by exactly the turn times the px per degree too, and the stars that stay in sight are the same ones', () => { + const starsAt = (heading: number) => { + resetHeading(); + anchor(view.place.id, heading, T0); + arcs.length = 0; + const h = host(); + createRidgeScene({ canvas: h.canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!.dispose(); + return arcs.map((p) => [p[0], p[1]]); + }; + const plateX = (device: number) => { + const wn = windowFor(view, W, 800); + const size = plateSize(wn, W, 800, 2, SLACK_MIN_DEG); + return (device / Math.floor(size.cssW * size.ratio)) * size.cssW + (W - size.cssW) / 2; + }; + const here = starsAt(view.lookAzDeg).map(([x, y]) => [plateX(x), y]); + const turned = starsAt(view.lookAzDeg + 10).map(([x, y]) => [plateX(x), y]); + const inSight = here.filter(([x]) => x - 10 * k > 0 && x - 10 * k < W && x > 0 && x < W); + expect(inSight.length).toBeGreaterThan(3); + inSight.forEach(([x, y]) => { + // pan 0 in both: the viewport position is the plate's, and it moved left by ten degrees of pixels + const found = turned.find(([tx, ty]) => ty === y && Math.abs(tx - (x - 10 * k)) < 0.75); + expect(found).toBeDefined(); + }); + }); + + it('keeps the sun and every star where the view faces them across a re-centre: the old plate goes, a new one stands in its place, the sun moves by less than a pixel', () => { + ticking(); + const now = vi.mocked(performance.now); + setCamera({ speedDegPerS: 4 }); // the view turns 4 degrees a second: the plate runs to 14 degrees off its centre in 3.5 s + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const first = plateOf(parent); + const kinds = parent.children.map((c: any) => c.tag); + const seen = new Set([first]); + let last = onViewport(first, suns[suns.length - 1][0], T0); + for (let ms = 500; ms <= 9_000; ms += 500) { + now.mockReturnValue(T0 + ms); + vi.advanceTimersByTime(500); + const plate = plateOf(parent); + seen.add(plate); + const x = onViewport(plate, suns[suns.length - 1][0], T0 + ms); + const want = W / 2 + (view.lookAzDeg + SUN_ABOVE_REST - poseAt(T0 + ms).h) * k; // the sun's true place on the viewport + expect(Math.abs(x - want)).toBeLessThan(1); + expect(Math.abs(x - last + 4 * 0.5 * k)).toBeLessThan(1); // it moved only as the view turned (half a second of it) + last = x; + expect(parent.children.map((c: any) => c.tag)).toEqual(kinds); // the plate is replaced in its place: nothing stacks up + } + expect(seen.size).toBe(3); // 36 degrees of turn: replaced at 16 and at 32 degrees + expect([...seen].filter((p) => p.parentElement).length).toBe(1); + expect(live(plateOf(parent))).toHaveLength(1); + s.dispose(); + expect(parent.children).toEqual([canvas]); + vi.useRealTimers(); + }); + + it('keys a swapped plate from the clock after it is painted, so a paint, however long, is not lag behind the heading', () => { + ticking(); + const now = vi.mocked(performance.now); + setCamera({ speedDegPerS: 4 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const first = plateOf(parent); + const PAINT_MS = 250; // a phone: the clock runs on while the sky is painted + let swapped: any; + for (let ms = 500; ms <= 9_000 && !swapped; ms += 500) { + now.mockReturnValue(T0 + ms); + onPaint = () => now.mockReturnValue(T0 + ms + PAINT_MS); + vi.advanceTimersByTime(500); + onPaint = undefined; + if (plateOf(parent) !== first) swapped = plateOf(parent); + } + expect(swapped).toBeDefined(); + const a = live(swapped)[0]; + expect(a.at % 500).toBe(PAINT_MS); // keyed after the paint: from the clock the paint ended at + // the sun is where the view faces it at the instant the slide begins, to the pixel + const x = onViewport(swapped, suns[suns.length - 1][0], a.at); + expect(Math.abs(x - (W / 2 + (view.lookAzDeg + SUN_ABOVE_REST - poseAt(a.at).h) * k))).toBeLessThan(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('never runs a plate out at the speed in force, whichever phase a late tick falls in, and sizes the slack to that speed', () => { + ticking(); + const now = vi.mocked(performance.now); + const SPEED = 12; + setCamera({ speedDegPerS: SPEED }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const hfov = win.camera.hfovDeg; + expect(px(plateOf(parent).style.width) / k).toBeCloseTo(hfov + 2 * slackFor(SPEED, RESIDENCY_MS), 6); // the slack of 12 degrees a second, not of 0.6 + // Ticks every half second, one in four two seconds late: at no instant may the viewport's edge pass the plate's. + let t = 0; + let widest = 0; + for (let n = 0; t < 24_000; n += 1) { + const gap = n % 4 === 3 ? 500 + LATENESS_S * 1000 : 500; + for (let at = t; at < t + gap; at += 50) { + const plate = plateOf(parent); + const edge = (px(plate.style.width) - W) / 2; // px the plate reaches past the viewport each side + widest = Math.max(widest, Math.abs(panAt(plate, T0 + at)) - edge); + } + t += gap; + now.mockReturnValue(T0 + t); + vi.advanceTimersByTime(500); + } + expect(widest).toBeLessThanOrEqual(1e-6); // the viewport's edge never got past the plate's + s.dispose(); + vi.useRealTimers(); + }); + + it('slides a slow turn on the least slack, and sizes the plate again when the speed asks for more', () => { + ticking(); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const hfov = win.camera.hfovDeg; + expect(px(plateOf(parent).style.width) / k).toBeCloseTo(hfov + 2 * SLACK_MIN_DEG, 6); + const slow = plateOf(parent); + setCamera({ speedDegPerS: 12 }); // the viewer speeds the turn up: a plate with the slack of a slow one would be run out + const fast = plateOf(parent); + expect(fast).not.toBe(slow); + expect(px(fast.style.width) / k).toBeCloseTo(hfov + 2 * slackFor(12, RESIDENCY_MS), 6); + expect(panAt(fast, T0)).toBeCloseTo(0, 6); + s.dispose(); + vi.useRealTimers(); + }); + + it('keeps which stars twinkle, and their phase, across a swap, and shows the new plate with its twinkles already drawn', () => { + ticking(); + const now = vi.mocked(performance.now); + setCamera({ speedDegPerS: 4 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!; + /** One display frame of the twinkle loop alone, at the clock now. */ + const frame = () => { + const cbs = rafQueue.filter((c) => c.name === 'twTick'); + rafQueue = rafQueue.filter((c) => c.name !== 'twTick'); + cbs.forEach((c) => c(now())); + }; + /** The stars drawn since `twinks` was cleared, as where they are on the viewport and how high, once each. */ + const seen = (plate: any): string[] => + [...new Set(twinks.map(([x, y]) => `${Math.round(onViewport(plate, x, now()))},${Math.round(y)}`))].filter((p) => { + const x = Number(p.split(',')[0]); + return x > 2 && x < W - 2; + }); + let compared = 0; + for (let ms = 500; ms <= 9_000 && compared === 0; ms += 500) { + now.mockReturnValue(T0 + ms); + const before = plateOf(parent); + twinks.length = 0; + frame(); // the loop's frame at this clock: the stars the plate that is up has swinging + const old = seen(before); + twinks.length = 0; + vi.advanceTimersByTime(500); // the tick, at the same clock, which swaps the plate when the heading is near its edge + const after = plateOf(parent); + if (after === before) continue; + const next = seen(after); + expect(old.length).toBeGreaterThan(0); + const near = (a: string, list: string[]) => + list.some((b) => { + const [ax, ay] = a.split(',').map(Number); + const [bx, by] = b.split(',').map(Number); + return Math.abs(ax - bx) <= 1 && ay === by; + }); + old.forEach((p) => expect(near(p, next)).toBe(true)); // each star swinging a moment ago is swinging now, at the same place + next.forEach((p) => expect(near(p, old)).toBe(true)); // and no other + compared += 1; + } + expect(compared).toBe(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('does not repaint a plate for a view that stays or turns within its slack', () => { + ticking(); + const now = vi.mocked(performance.now); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; // 0.6 degrees a second + const first = plateOf(parent); + for (let ms = 500; ms <= 20_000; ms += 500) { + now.mockReturnValue(T0 + ms); + vi.advanceTimersByTime(500); + } + expect(plateOf(parent)).toBe(first); // 12 degrees of turn: inside the 14 + expect(painted).toHaveLength(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('re-centres on a reissue too: a turn by hand past the edge paints a plate about where the view now faces', () => { + ticking(); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const first = plateOf(parent); + hold(view.lookAzDeg + 60, T0); + const plate = plateOf(parent); + expect(plate).not.toBe(first); + expect(panAt(plate, T0)).toBeCloseTo(0, 6); + expect(live(plate)).toHaveLength(1); + s.dispose(); + vi.useRealTimers(); + }); + + it('puts the twinkle canvas in the plate, over the sky, and nothing animates but the plate', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: nightSky(), backdrop: litCards() })!; + const plate = plateOf(parent); + expect(plate.children.map((c: any) => c.tag)).toEqual(['canvas', 'canvas']); + expect([plate.children[1].width, plate.children[1].height]).toEqual([plate.children[0].width, plate.children[0].height]); + plate.children.forEach((c: any) => expect(c.anims).toHaveLength(0)); // they ride the plate + expect(parent.children.filter((c: any) => c.tag === 'canvas')).toEqual([canvas]); // no twinkle canvas of the page's own + s.dispose(); + }); + + it('paints a plate that stays under the pixel cap and pans by the same px per degree as the cards', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: sunSky(), backdrop: litCards() })!; + const plate = plateOf(parent); + expect(plate.children[0].width * plate.children[0].height).toBeLessThanOrEqual(3_000_000); + expect(px(plate.style.width) / (win.camera.hfovDeg + 40)).toBeCloseTo(k, 9); + hold(view.lookAzDeg + 10, T0); // a turn by hand inside the slack: the same plate slides ten degrees of pixels + expect(panAt(plateOf(parent), T0)).toBeCloseTo(-10 * k, 6); + s.dispose(); + }); + + it('shows the sun at the azimuth the ridge is lit from: facing it the sky puts it on the centre column and the ridge faces it; facing away it is off the plate and the ridge is in shade', () => { + const sun = { azimuth: view.lookAzDeg + 17, elevation: 12 }; + const lit = { ...DAY, physical: makePhysicalSky({ ...sun, time: new Date('2026-06-21T10:40:00Z') }, 0, view) }; + // The ridge's own: the column whose face looks at the sun is the one the lit table gives most to. + const cols = sunColumns(view, sun); + let best = 0; + for (let c = 0; c < view.ringW; c += 1) if (cols[c * 4] > cols[best * 4]) best = c; + expect(Math.abs(ringAzimuth(best, view.ringW) - sun.azimuth)).toBeLessThanOrEqual(360 / view.ringW); + + resetHeading(); + anchor(view.place.id, sun.azimuth, T0); + const facing = host(); + createRidgeScene({ canvas: facing.canvas, tier: 'full', sky: lit, backdrop: litCards() })!.dispose(); + expect(suns).toHaveLength(1); + const wn = windowFor(view, W, 800); + const size = plateSize(wn, W, 800, 2, SLACK_MIN_DEG); + const centreCol = (suns[0][0] / Math.floor(size.cssW * size.ratio)) * size.cssW + (W - size.cssW) / 2; + expect(Math.abs(centreCol - W / 2)).toBeLessThan(1); // the sky's sun is on the column the view centres, whose face the ridge lights fullest + expect(sunInColumn(sun, sun.azimuth)[0]).toBeCloseTo(Math.cos((sun.elevation * Math.PI) / 180), 12); + + suns.length = 0; + resetHeading(); + anchor(view.place.id, sun.azimuth + 180, T0); + const away = host(); + createRidgeScene({ canvas: away.canvas, tier: 'full', sky: lit, backdrop: litCards() })!.dispose(); + expect(suns).toHaveLength(0); // the sun is behind the camera: no disc anywhere on the plate + expect(sunInColumn(sun, sun.azimuth + 180)[0]).toBeLessThan(0); // and the ridge faces it away + }); + }); + it('a heading of 400 degrees places the tiles a heading of 40 does, a revolution on', () => { const at = (h: number) => { resetHeading(); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index 4d34d1d1..b6f5d729 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -4,12 +4,14 @@ import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view'; -import type { CardPose, View } from './view'; +import type { Camera, CardPose, View } from './view'; import type { TileCard } from './manifest'; import { residentTiles } from './ring'; -import { freeze, normalize, poseAt as headingPose, setRange, settledAt, subscribe as onHeading } from './heading'; +import { freeze, normalize, poseAt as headingPose, setRange, settledAt, subscribe as onHeading, turnRate } from './heading'; import type { Pose } from './heading'; -import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars'; +import { activeAt, drawTwinkle as paintTwinkle, slotsFor, Star } from './stars'; +import { STAR_COUNT } from './nightSkyData'; +import { alignTurns, panPx, plateCamera, plateSize, recentre, slackFor } from './skyTurn'; import { nightBodies, paintNightBodies } from './nightBodies'; import type { NightBodies } from './nightBodies'; import { drawRainTile, RAIN_TILES } from './rain'; @@ -55,25 +57,21 @@ function drawSun( } /** - * The host canvas's sky: the physical sky (`physicalSky.ts`) as a small grid of display pixels, scaled up smoothly (it is a soft - * field); without one, the three-stop gradient. + * A canvas's sky: the physical sky (`physicalSky.ts`) seen through `camera` as a small grid of display pixels, scaled up smoothly (it is a soft + * field); without one, the three-stop gradient. `cssW` and `cssH` are the canvas's size in CSS px, which `camera`'s field of view spans. */ function paintSky( canvas: HTMLCanvasElement, sky: SkyColours, + camera: Camera | undefined, cssW: number, cssH: number, makeCanvas: () => HTMLCanvasElement ): { ok: boolean; px?: ReturnType } { const ctx = context2d(canvas); if (!ctx) return { ok: false }; - if (sky.physical) { - const px = paintPhysicalSky( - sky.physical, - cssW, - cssH, - windowFor(sky.physical.view, cssW, cssH).camera - ); + if (sky.physical && camera) { + const px = paintPhysicalSky(sky.physical, cssW, cssH, camera); const small = makeCanvas(); small.width = px.w; small.height = px.h; @@ -113,10 +111,40 @@ interface Rig { stop: () => void; } -interface Built { - /** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */ +/** + * The sky of a live scene: one element, wider than the viewport, holding the painted sky (every real body baked into it) and, with stars, the twinkling + * stars' canvas over it. One animation slides it with the heading (`skyTurn.ts`). Replaced, element and all, when the heading nears its edge. + */ +interface Plate { + el: HTMLElement; + /** The twinkle canvas of this plate, over its sky; absent in a day sky. */ 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). */ + /** The stars this plate was painted with, by catalogue index: the identity the twinkle schedule is keyed by. */ + stars: ReadonlyMap; + /** Device pixels per CSS px of the plate's canvases (capped by `PLATE_MAX_PX`). */ + ratio: number; + /** Degrees of sky it holds beyond the viewport each side (`skyTurn.ts` `slackFor`, at the speed it was painted for). */ + slack: number; + /** The compass azimuth the plate is centred on, unwrapped to the heading owner's turn. */ + centre: number; + /** The one animation that slides it. */ + anim?: Animation; + /** + * Paint a new plate about the heading in this one's place when the heading is near its edge, or the speed in force needs more slack than it has; `periodMs`: + * the real period of the residency tick. True when it did, and then the slide is not keyed yet: `key` it, from a clock read after this. + */ + refit: (periodMs: number) => boolean; + /** Key the slide from `t0` (ms), the heading owner's clock read after the plate was last painted; `play`: the motion runs. */ + key: (t0: number, frozen: boolean, play: boolean) => void; + /** The residency tick: refit, and key from the clock after the paint if it painted. */ + tend: (periodMs: number) => void; + stop: () => void; +} + +interface Built { + /** The sky and its twinkling stars, under the rig; absent in 'still' (the sky is painted into the host canvas) and in a sky with no physical model (a gradient in the host canvas). */ + plate?: Plate; + /** The ridge cards' rig, over the plate and under the rain; absent in 'still' (the cards are drawn into the host canvas). */ rig?: Rig; /** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */ rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] }; @@ -131,7 +159,7 @@ const TWINKLE_FRAME_MS = 50; */ 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; +export const RESIDENCY_MS = 500; /** Keyframe spacing while an ease runs, ms: fine enough that the straight lines between them are the smoothstep to a pixel. */ const EASE_KEY_MS = 50; @@ -144,6 +172,20 @@ const easeTimes = (easeMs: number): number[] => { return times; }; +/** + * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, finely + * keyed while an ease of the heading owner runs, constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together. + */ +const stretch = (t0: number, frozen: boolean, transformAt: (t: number) => string): Keyframe[] => { + if (frozen) { + const at = transformAt(t0); + return [{ transform: at }, { transform: at }]; + } + const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, settledAt() - t0)); + if (easeMs > 0) return easeTimes(easeMs).map((ms) => ({ transform: transformAt(t0 + ms), offset: ms / (SEGMENT_S * 1000) })); + return Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({ transform: transformAt(t0 + n * 1000) })); +}; + /** * The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS * ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` (none: the sky alone) and the rain. The scene itself @@ -161,9 +203,10 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); let built: Built | undefined; - let field: Star[] = []; let twRaf = 0; let twLast = 0; + /** Paint a plate's twinkle canvas at t seconds, or clear it (set by the plate the scene is up with). */ + let paintTwinkleOf: (of: Pick, t?: number) => void = () => undefined; let still = tier === 'still'; let disposed = false; let raf = 0; @@ -179,8 +222,10 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { return { w, h, scale: (window.devicePixelRatio || 1) >= 2 ? 2 : 1 }; }; + const makeCanvas = () => document.createElement('canvas'); + const teardown = () => { - built?.twinkle?.remove(); + built?.plate?.stop(); built?.rig?.stop(); built?.rig?.anims.forEach((a) => a?.cancel()); built?.rig?.el.remove(); @@ -264,7 +309,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { * 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 startRig = (bd: Backdrop, w: number, h: number, plate?: Plate): Rig => { const { view } = bd.manifest; const win = windowFor(view, w, h); const planeTop = h - win.plane.bottom - win.plane.h; @@ -312,21 +357,14 @@ 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; + normalize(clock()); // the angles of this stretch start within a turn of zero, so the transforms stay small however long the page has been open + plate?.refit(tickMs); // a new plate costs a paint: whatever it costs, the cards and the sky are keyed from the clock after it, so none of it is lag 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 issuedAt = t0; const frozen = reducedMotion?.matches === true; - // A stretch with an ease in it is keyed finely while the ease runs (its keyframes at explicit offsets of the stretch), a second apart after. - const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, settledAt() - t0)); - const times = easeMs > 0 && !frozen ? easeTimes(easeMs) : null; + const play = moving(); for (let i = 0; i < k; i += 1) { - const frames: Keyframe[] = frozen - ? [{ transform: transform(poseAt(i, t0)) }, { transform: transform(poseAt(i, t0)) }] - : times - ? times.map((ms) => ({ transform: transform(poseAt(i, t0 + ms)), offset: ms / (SEGMENT_S * 1000) })) - : Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({ - transform: transform(poseAt(i, t0 + n * 1000)), - })); + const frames = stretch(t0, frozen, (t) => transform(poseAt(i, t))); boxes[i].style.transform = frames[0].transform as string; anims[i]?.cancel(); anims[i] = boxes[i].animate?.(frames, { @@ -334,8 +372,9 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { easing: 'linear', fill: 'forwards', }); - if (!moving()) anims[i]?.pause(); + if (!play) anims[i]?.pause(); } + plate?.key(t0, frozen, play); // the sky turns on the same keyframes, from the same poses mount(sweep(t0)); // laid out from the same angles as the keyframes, in the same tick }; @@ -375,11 +414,18 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { // 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; + let lastTick: number | undefined; + /** The real period of the tick, ms: what the last two began apart (a tick is a timeout chain, so its work and its lateness are in it), never less than RESIDENCY_MS. */ + let tickMs = RESIDENCY_MS; const residency = () => { timer = 0; if (!live) return; const t = clock(); - if (t - issuedAt >= SEGMENT_S * 1000 * REISSUE_FRAC && moving()) issue(); + if (lastTick !== undefined) tickMs = Math.max(RESIDENCY_MS, t - lastTick); + lastTick = t; + const play = moving(); + if (play && t - issuedAt >= SEGMENT_S * 1000 * REISSUE_FRAC) issue(); + else if (play) plate?.tend(tickMs); const arc = sweep(t); mount(arc); void bd.ensure(arc, sweepArc(view, win, w, k, poseAt, t, 0)).then(() => live && mount(arc)); // the view now first, then along the sweep @@ -440,7 +486,122 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } }; - /** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */ + /** A still's one image in the host canvas: the sky facing the pose it froze at, its bodies, and the cards of that pose over them. */ + const paintStill = () => { + const { w, h, scale } = viewSize(); + const physical = sky.physical; + if (opts.backdrop) stillPose ??= headingPose(clock()); + const facing = stillPose?.h ?? physical?.view.lookAzDeg ?? 0; // with no ridge there is no heading: the place's rest azimuth + const camera = physical && plateCamera(windowFor(physical.view, w, h), facing, 0); + const painted = paintSky(canvas, sky, camera, w, h, makeCanvas); + const ctx = context2d(canvas); + if (ctx && physical && painted.px) + paintNightBodies(ctx, nightBodies(physical, painted.px, opts.lines === true), canvas.width, canvas.height, scale); + if (opts.backdrop) paintCards(opts.backdrop); + }; + + /** + * The sky of a live scene (`skyTurn.ts`): a plate painted about the heading the view has, under a stretch of the heading owner's keyframes. The real stars, + * the moon and (when asked) the constellation lines are baked into the plate's sky; the twinkling stars get their own canvas on it, which a per-frame pass + * clears and paints over. A sky-only scene has no rig to issue it: its plate faces the place's rest azimuth and stays. + */ + const startPlate = (physical: NonNullable, w: number, h: number, dpr: number): Plate | undefined => { + const win = windowFor(physical.view, w, h); + const pxPerDeg = w / win.camera.hfovDeg; + /** Slots of the twinkle schedule, fixed by the first plate: the schedule runs over the catalogue, so every plate of this sky twinkles the same stars in the same phase. */ + let slots = 0; + const paint = (centre: number, slack: number) => { + const { cssW, ratio } = plateSize(win, w, h, dpr, slack); + const el = document.createElement('div'); + el.setAttribute('aria-hidden', 'true'); + Object.assign(el.style, { + position: 'absolute', + left: `${(w - cssW) / 2}px`, + top: '0', + width: `${cssW}px`, + height: `${h}px`, + willChange: 'transform', + pointerEvents: 'none', + }); + const layer = (): HTMLCanvasElement => { + const c = document.createElement('canvas'); + c.width = Math.floor(cssW * ratio); + c.height = Math.floor(h * ratio); + c.setAttribute('aria-hidden', 'true'); + Object.assign(c.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%', pointerEvents: 'none' }); + el.appendChild(c); + return c; + }; + const skyEl = layer(); + const painted = paintSky(skyEl, sky, plateCamera(win, centre, slack), cssW, h, makeCanvas); + const skyCtx = context2d(skyEl); + if (!painted.ok || !painted.px || !skyCtx) return undefined; + const bodies: NightBodies = nightBodies(physical, painted.px, opts.lines === true); + paintNightBodies(skyCtx, bodies, skyEl.width, skyEl.height, ratio); + slots ||= slotsFor(STAR_COUNT, bodies.stars.length); + return { + el, + twinkle: bodies.stars.length ? layer() : undefined, + stars: new Map(bodies.stars.map((star) => [star.id, star])), + ratio, + slack, + }; + }; + /** The overlay of `of` at `t` seconds: the stars of the catalogue that twinkle then, those of them this plate has. */ + paintTwinkleOf = (of, t) => { + const el = of.twinkle; + const ctx = el && context2d(el); + if (!el || !ctx) return; + const active = t === undefined ? [] : activeAt(STAR_COUNT, t, slots); + paintTwinkle(ctx, of.stars, active, el.width, el.height, of.ratio); + }; + const facing = opts.backdrop ? headingPose(clock()).h : physical.view.lookAzDeg; // with no ridge there is no heading: the place's rest azimuth + const first = paint(facing, slackFor(turnRate(), RESIDENCY_MS)); + if (!first) return undefined; + parent.appendChild(first.el); + /** The slide from `t0` of a plate centred on `centre`: its pan at every instant of the stretch is the heading owner's `h` there against that centre. */ + const key = (el: HTMLElement, centre: number, t0: number, frozen: boolean, play: boolean): Animation | undefined => { + const frames = stretch(t0, frozen, (t) => `translate3d(${panPx(headingPose(t).h, centre, pxPerDeg)}px,0,0)`); + el.style.transform = frames[0].transform as string; + const anim = el.animate?.(frames, { duration: SEGMENT_S * 1000, easing: 'linear', fill: 'forwards' }); + if (!play) anim?.pause(); + return anim; + }; + const plate: Plate = { + ...first, + centre: facing, + refit: (periodMs) => { + const at = headingPose(clock()).h; + plate.centre = alignTurns(plate.centre, at); + const rate = turnRate(); + const slack = slackFor(rate, RESIDENCY_MS); + if (slack <= plate.slack && !recentre(at, plate.centre, plate.slack, rate, periodMs)) return false; + // A plate about the heading, in the place of this one: the same sky at the same place on the screen, so nothing moves. Undefined (this one stays) if it cannot be painted. + const next = paint(at, slack); + if (!next) return false; + if (moving()) paintTwinkleOf(next, clock() / 1000); // its twinkles as the old one's are now: shown with the stars already swinging + parent.insertBefore(next.el, plate.el); + plate.anim?.cancel(); + plate.el.remove(); + Object.assign(plate, next, { centre: at, anim: undefined }); + return true; + }, + key: (t0, frozen, play) => { + plate.anim?.cancel(); + plate.anim = key(plate.el, plate.centre, t0, frozen, play); + }, + tend: (periodMs) => { + if (plate.refit(periodMs)) plate.key(clock(), false, true); // ticks run only while moving + }, + stop: () => { + plate.anim?.cancel(); + plate.el.remove(); + }, + }; + return plate; + }; + + /** Paint the cards' rig, the sky and the rain. Returns false when a 2D context is missing or there is no area yet. */ const build = (): boolean => { teardown(); // A zero-size canvas throws on drawImage; wait for the first resize that gives the host an area. @@ -448,41 +609,21 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const { w, h, scale } = viewSize(); canvas.width = Math.round(w * scale); canvas.height = Math.round(h * scale); - const painted = paintSky(canvas, sky, w, h, () => document.createElement('canvas')); - if (!painted.ok) return false; - // The real stars, the moon and (when asked) the constellation lines are baked into the sky; the twinkling stars get their own - // canvas, which a per-frame pass clears and paints over. 'still' has no overlay. A sky with no physical model has no bodies. - const bodies: NightBodies = - painted.px && sky.physical - ? nightBodies(sky.physical, painted.px, opts.lines === true) - : { stars: [], lines: [] }; - const stars = bodies.stars; - const skyCtx = context2d(canvas); - if (skyCtx) paintNightBodies(skyCtx, bodies, canvas.width, canvas.height, scale); - let twinkle: HTMLCanvasElement | undefined; - if (stars.length && tier !== 'still') { - twinkle = document.createElement('canvas'); - twinkle.width = canvas.width; - twinkle.height = canvas.height; - twinkle.setAttribute('aria-hidden', 'true'); - Object.assign(twinkle.style, { - position: 'absolute', - left: '0', - top: '0', - width: '100%', - height: '100%', - pointerEvents: 'none', - }); - parent.appendChild(twinkle); + if (!context2d(canvas)) return false; + built = {}; + if (!still) { + // The host canvas keeps a still's sky (`paintStill`); a live scene's physical sky is a plate over it, and one with none is a gradient in the host canvas. + if (sky.physical) { + built.plate = startPlate(sky.physical, w, h, scale); + if (!built.plate) return false; + } else if (!paintSky(canvas, sky, undefined, w, h, makeCanvas).ok) return false; } - field = stars; - built = { twinkle }; if (opts.backdrop) { // The offsets this place and viewport allow, to the one owner of the pose: a rebuild at another size is a new bound, and the view eases from the pose it has. const { manifest } = opts.backdrop; const win = windowFor(manifest.view, w, h); setRange((mode, phi) => offsetRange(manifest, win, mode, phi), clock()); - if (!still) built.rig = startRig(opts.backdrop, w, h); + if (!still) built.rig = startRig(opts.backdrop, w, h, built.plate); } if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0) built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale); @@ -496,20 +637,16 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { !(reducedMotion?.matches ?? false) && document.visibilityState === 'visible'; - /** Paint the overlay at t seconds (stars away from base), or just clear it with no t (all at base). */ + /** Paint the overlay of the plate that is up at t seconds (stars away from base), or just clear it with no t (all at base). */ const drawTwinkle = (t?: number) => { - const el = built?.twinkle; - const ctx = el && context2d(el); - if (!el || !ctx) return; - const active = t === undefined ? [] : activeAt(field.length, t); - paintTwinkle(ctx, field, active, el.width, el.height, viewSize().scale); + if (built?.plate) paintTwinkleOf(built.plate, t); }; // The same guard as the drift: not still, not disposed, not reduced motion, tab visible. Not moving // stops the loop and leaves the stars steady at base brightness. const twTick = (now: number) => { twRaf = 0; - if (!moving() || !built?.twinkle) return; + if (!moving() || !built?.plate?.twinkle) return; if (now - twLast >= TWINKLE_FRAME_MS) { twLast = now; drawTwinkle(now / 1000); @@ -519,9 +656,9 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { function syncPlayState() { if (moving()) built?.rig?.reissue(); - const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? [])]; + const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? []), built?.plate?.anim]; anims.forEach((a) => (moving() ? a?.play() : a?.pause())); - if (!built?.twinkle) return; + if (!built?.plate?.twinkle) return; if (moving()) { if (!twRaf) twRaf = requestAnimationFrame(twTick); } else { @@ -539,7 +676,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { teardown(); cancelAnimationFrame(raf); raf = 0; - if (opts.backdrop) paintCards(opts.backdrop); + paintStill(); report(true); }; diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts index 4cdb0d66..4019bc70 100644 --- a/src/app/features/scene/ridge/heading.test.ts +++ b/src/app/features/scene/ridge/heading.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, settledAt, STAGE_MS, subscribe } from './heading'; +import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, settledAt, STAGE_MS, subscribe, turnRate } from './heading'; import type { RotationMode } from './heading'; import * as camera from '../cameraState'; import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState'; @@ -37,6 +37,25 @@ afterEach(() => { vi.unstubAllGlobals(); }); +describe('turnRate', () => { + it('is the speed the view direction turns at: the viewer sets, bounded by the place, and nothing while it does not turn', () => { + anchor('p', 0, 0, (mode) => (mode === 'both' ? 5 : 12)); + expect(turnRate()).toBe(0); // still + choose('both', 3, 0); + expect(turnRate()).toBe(3); + choose('both', -12, 0); + expect(turnRate()).toBe(5); // the place sustains 5, not the ceiling + choose('offset', 12, 0); + expect(turnRate()).toBe(0); // the camera circles: the view direction stays + choose('both', 3, 0); + freeze(true, 0); + expect(turnRate()).toBe(0); + freeze(false, 0); + hold(40, 0); + expect(turnRate()).toBe(0); // held by hand + }); +}); + describe('the heading owner', () => { it('faces nothing in particular until a place anchors it, and turns nothing while the viewer chose nothing to turn', () => { expect(poseAt(5 * S)).toEqual({ h: 0, phi: 0, r: 0 }); diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts index 6a52c878..880caa59 100644 --- a/src/app/features/scene/ridge/heading.ts +++ b/src/app/features/scene/ridge/heading.ts @@ -130,6 +130,13 @@ function restart(now: number, over: Partial = {}, snap = false): void { emit(); } +/** + * Degrees per second the view direction turns at under the inputs in force: the viewer's speed bounded by what the place sustains in the mode picked (`anchor`'s + * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). Every change of any of these starts a + * segment and is heard by `subscribe`, so a reader that sizes something to this speed learns when it must size again. + */ +export const turnRate = (): number => (seg?.turns === 'h' ? Math.abs(seg.rate) : 0); + /** The clock (ms) at which what the last change eased is home. */ export const settledAt = (): number => seg?.endAt ?? 0; diff --git a/src/app/features/scene/ridge/nightBodies.ts b/src/app/features/scene/ridge/nightBodies.ts index 40fde6e2..bf313a4a 100644 --- a/src/app/features/scene/ridge/nightBodies.ts +++ b/src/app/features/scene/ridge/nightBodies.ts @@ -181,6 +181,7 @@ export function nightBodies(p: PhysicalSky, px: SkyPixels, withLines: boolean): if (Math.max(Math.abs(base[0] - out[0]), Math.abs(base[1] - out[1]), Math.abs(base[2] - out[2])) < 3) continue; const { base: r0, perMag } = NIGHT_LOOK.starRadius; stars.push({ + id: s.index, x: at.x, y: at.y, r: r0 + perMag * Math.max(0, MAG_LIMIT - m), diff --git a/src/app/features/scene/ridge/skyTurn.test.ts b/src/app/features/scene/ridge/skyTurn.test.ts new file mode 100644 index 00000000..bd6e4bec --- /dev/null +++ b/src/app/features/scene/ridge/skyTurn.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest'; +import { + alignTurns, + LATENESS_S, + marginFor, + MIN_TRAVEL_DEG, + panPx, + plateCamera, + plateSize, + PLATE_MAX_PX, + recentre, + SLACK_MIN_DEG, + slackFor, + TRAVEL_DEG, +} from './skyTurn'; +import { FALLBACK_VIEW, SPEED_CEILING_DEG_S, windowFor } from './view'; +import { RESIDENCY_MS } from './Ridge'; + +const win = windowFor(FALLBACK_VIEW, 1280, 720); + +describe('plateCamera', () => { + it('spans the viewport plus the slack each side about its centre, at the viewport angles per pixel', () => { + const cam = plateCamera(win, 100, SLACK_MIN_DEG); + expect(cam.azimuthDeg).toBe(100); + expect(cam.hfovDeg).toBeCloseTo(win.camera.hfovDeg + 2 * SLACK_MIN_DEG, 12); + expect(cam.vfovDeg).toBe(win.camera.vfovDeg); + expect(cam.horizonAt).toBe(win.camera.horizonAt); + // a plate is `plateSize` wide and shows the same degrees per pixel as the viewport + const { cssW } = plateSize(win, 1280, 720, 1, SLACK_MIN_DEG); + expect(cssW / cam.hfovDeg).toBeCloseTo(1280 / win.camera.hfovDeg, 9); + }); + + it('names its centre within one turn, whatever turn the heading owner is on', () => { + expect(plateCamera(win, 750, SLACK_MIN_DEG).azimuthDeg).toBe(30); + expect(plateCamera(win, -10, SLACK_MIN_DEG).azimuthDeg).toBe(350); + expect(plateCamera(win, 214, 0).hfovDeg).toBe(win.camera.hfovDeg); // no slack: the viewport's own camera, as a still paints + }); +}); + +describe('recentre', () => { + const still = (heading: number, centre: number, slack = SLACK_MIN_DEG) => recentre(heading, centre, slack, 0, RESIDENCY_MS); + + it('fires at the slack for a heading that does not turn, and not for one that stays', () => { + expect(still(100, 100)).toBe(false); + expect(still(119.9, 100)).toBe(false); + expect(still(120.1, 100)).toBe(true); + expect(still(80.1, 100)).toBe(false); + expect(still(79.9, 100)).toBe(true); + }); + + it('takes the margin from the speed in force and the tick: a faster turn is replaced sooner, a slower tick sooner too', () => { + const slack = slackFor(4, RESIDENCY_MS); // 4 degrees a second: margin 10 in 2.5 s + expect(marginFor(4, RESIDENCY_MS)).toBeCloseTo(4 * (LATENESS_S + 0.5), 12); + expect(recentre(100 + slack - 10.1, 100, slack, 4, RESIDENCY_MS)).toBe(false); + expect(recentre(100 + slack - 9.9, 100, slack, 4, RESIDENCY_MS)).toBe(true); + expect(recentre(100 + slack - 10.1, 100, slack, 4, 1500)).toBe(true); // a tick that really took 1.5 s: margin 14 + expect(recentre(100 + slack - 10.1, 100, slack, 0, RESIDENCY_MS)).toBe(false); + }); + + it('never takes the whole slack: a plate just painted is not due again whatever the tick', () => { + expect(recentre(100, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(false); + expect(recentre(100 + MIN_TRAVEL_DEG - 0.1, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(false); + expect(recentre(100 + MIN_TRAVEL_DEG + 0.1, 100, SLACK_MIN_DEG, 12, 60_000)).toBe(true); + }); + + it('reads the heading on the turn of the centre', () => { + expect(still(10 + 360, 10)).toBe(false); + expect(still(350, 5, 14)).toBe(true); // 15 degrees off, the short way + expect(still(358, 5)).toBe(false); + expect(alignTurns(10, 725)).toBe(730); + expect(alignTurns(370, 5)).toBe(10); + }); +}); + +describe('the slack at the speed in force', () => { + const speeds = [0, 0.6, 4, 6, SPEED_CEILING_DEG_S]; + + it('holds the margin and the travel between replacements, at every speed, and is the floor when the view barely turns', () => { + for (const v of speeds) { + const slack = slackFor(v, RESIDENCY_MS); + expect(slack).toBeGreaterThanOrEqual(SLACK_MIN_DEG); + expect(slack).toBeGreaterThanOrEqual(marginFor(v, RESIDENCY_MS) + TRAVEL_DEG); + } + expect(slackFor(0, RESIDENCY_MS)).toBe(SLACK_MIN_DEG); + expect(slackFor(SPEED_CEILING_DEG_S, RESIDENCY_MS)).toBe(TRAVEL_DEG + SPEED_CEILING_DEG_S * (LATENESS_S + RESIDENCY_MS / 1000)); + }); + + it('is never run out between two ticks, in the worst phase, with a late tick, at every speed: a tick that finds the plate whole is followed by one that does too', () => { + for (const v of speeds) { + for (const periodMs of [RESIDENCY_MS, 700]) { + const slack = slackFor(v, RESIDENCY_MS); + // The farthest from its centre a heading can be at a tick that leaves the plate alone, found by walking out from the centre. + let edge = 0; + while (!recentre(100 + edge + 0.001, 100, slack, v, periodMs)) edge += 0.001; + // The next tick comes a period later and as late as the budget lets it be. + const worst = edge + v * (periodMs / 1000 + LATENESS_S); + expect(worst).toBeLessThanOrEqual(slack + 1e-6); + } + } + }); +}); + +describe('plateSize', () => { + it('never has more backing store than PLATE_MAX_PX: the pixel ratio lowers, the plate does not shrink', () => { + [ + [1280, 720, 2], + [1920, 1080, 2], + [3840, 2160, 1], + [390, 844, 3], + [800, 600, 1], + ].forEach(([w, h, dpr]) => { + const wn = windowFor(FALLBACK_VIEW, w, h); + const p = plateSize(wn, w, h, dpr, SLACK_MIN_DEG); + expect(Math.floor(p.cssW * p.ratio) * Math.floor(h * p.ratio)).toBeLessThanOrEqual(PLATE_MAX_PX); + expect(p.ratio).toBeLessThanOrEqual(dpr); + expect(p.cssW).toBeCloseTo((w * (wn.camera.hfovDeg + 2 * SLACK_MIN_DEG)) / wn.camera.hfovDeg, 9); + }); + // a small viewport keeps the whole device ratio, a phone-sized one at 2x loses a little of it + expect(plateSize(windowFor(FALLBACK_VIEW, 300, 500), 300, 500, 2, SLACK_MIN_DEG).ratio).toBe(2); + }); +}); + +describe('panPx', () => { + it('slides the plate one for one with the heading, opposite to it', () => { + const ppd = 1280 / win.camera.hfovDeg; + expect(panPx(214, 214, ppd)).toBeCloseTo(0, 12); + expect(panPx(224, 214, ppd)).toBeCloseTo(-10 * ppd, 9); + expect(panPx(204, 214, ppd)).toBeCloseTo(10 * ppd, 9); + }); +}); diff --git a/src/app/features/scene/ridge/skyTurn.ts b/src/app/features/scene/ridge/skyTurn.ts new file mode 100644 index 00000000..15654778 --- /dev/null +++ b/src/app/features/scene/ridge/skyTurn.ts @@ -0,0 +1,66 @@ +// The sky that turns with the view. The sky is at infinity: it pans one for one with the view direction and ignores the camera's offset (`view.ts` +// `cardPose` is where the near cards differ). So the live scene paints it once into a PLATE, a canvas wider than the viewport by its slack each side, +// centred on a heading, and the compositor slides the plate by `(heading - centre)` degrees of pixels on the same keyframes as the cards (`heading.ts` +// `poseAt`). The slack, sized to the speed of the turn (`slackFor`), lets the heading wander before the plate runs out; the scene paints a new plate about the heading it has reached, in the same +// tick it takes the old one away. Both plates are the same sky, so nothing moves. This file owns which arc of sky a plate holds and when it is replaced. +import { norm } from './ring'; +import type { Camera, Window } from './view'; + +/** The least sky painted beyond the viewport on each side of it, degrees: what a slow turn gets. Authored. */ +export const SLACK_MIN_DEG = 20; +/** Degrees the heading may wander from a fresh plate's centre before it is due a new one, however fast it turns: a plate is not repainted more often than this. Authored. */ +export const TRAVEL_DEG = 14; +/** + * How late a residency tick may run, seconds, beyond its own period, before the plate can run out: a tile mount, a paint, a collection or a busy phone each cost + * a tick a few hundred milliseconds; this is a budget for several of them. Authored. + */ +export const LATENESS_S = 2; +/** The margin never takes more than this much of the slack, degrees, so a plate that has just been painted is not due again at once. */ +export const MIN_TRAVEL_DEG = 1; +/** The most backing store a plate may have, pixels: the pixel ratio lowers before the plate shrinks. */ +export const PLATE_MAX_PX = 3_000_000; + +/** + * Degrees a heading turning at `rateDegPerS` covers between a residency tick that finds the plate good and the next one: a tick's period (`periodMs`, the real + * one, work included) and the lateness budget. A plate is replaced once the heading is nearer its edge than this, so the next tick, however late, finds it whole. + */ +export const marginFor = (rateDegPerS: number, periodMs: number): number => Math.abs(rateDegPerS) * (LATENESS_S + periodMs / 1000); + +/** The slack a plate needs at `rateDegPerS`, the speed in force (`heading.ts` `turnRate`): its margin at the nominal tick `tickMs` and the travel between replacements. */ +export const slackFor = (rateDegPerS: number, tickMs: number): number => + Math.max(SLACK_MIN_DEG, TRAVEL_DEG + marginFor(rateDegPerS, tickMs)); + +/** The camera of a plate: the viewport's, with `slackDeg` more field each side, centred on the compass azimuth `centreDeg` (any turn of it). Angles per pixel are the viewport's. */ +export function plateCamera(win: Window, centreDeg: number, slackDeg: number): Camera { + return { ...win.camera, azimuthDeg: norm(centreDeg), hfovDeg: win.camera.hfovDeg + 2 * slackDeg }; +} + +/** The plate for a viewport `w` x `h` CSS px at `dpr` device pixels per CSS px with `slackDeg` of slack: its CSS width (the viewport's px per degree is the plate's), and the pixel ratio of its backing store. */ +export function plateSize( + win: Window, + w: number, + h: number, + dpr: number, + slackDeg: number +): { cssW: number; ratio: number; pxPerDeg: number } { + const pxPerDeg = w / win.camera.hfovDeg; + const cssW = pxPerDeg * (win.camera.hfovDeg + 2 * slackDeg); + const ratio = Math.min(dpr, Math.sqrt(PLATE_MAX_PX / (cssW * h))); + return { cssW, ratio, pxPerDeg }; +} + +/** `centreDeg` shifted by whole turns to the one nearest `headingDeg` (the heading owner keeps its angles within a turn of zero, so the plate's centre follows). */ +export const alignTurns = (centreDeg: number, headingDeg: number): number => + centreDeg + 360 * Math.round((headingDeg - centreDeg) / 360); + +/** + * Whether a plate with `slackDeg` of slack centred on `centreDeg` should be replaced now: the heading is nearer its edge than the margin, which the speed in + * force and the tick's real period set (`marginFor`) and which never takes more than the slack less MIN_TRAVEL_DEG. A still heading never is. + */ +export function recentre(headingDeg: number, centreDeg: number, slackDeg: number, rateDegPerS: number, periodMs: number): boolean { + const margin = Math.min(marginFor(rateDegPerS, periodMs), slackDeg - MIN_TRAVEL_DEG); + return Math.abs(headingDeg - alignTurns(centreDeg, headingDeg)) > slackDeg - margin; +} + +/** How far the plate is slid, px, when the view faces `headingDeg` and the plate is centred on `centreDeg` (both in the same turn, `alignTurns`): negative once the view has turned clockwise. */ +export const panPx = (headingDeg: number, centreDeg: number, pxPerDeg: number): number => -(headingDeg - centreDeg) * pxPerDeg; diff --git a/src/app/features/scene/ridge/stars.test.ts b/src/app/features/scene/ridge/stars.test.ts index f036a7ee..87a1244f 100644 --- a/src/app/features/scene/ridge/stars.test.ts +++ b/src/app/features/scene/ridge/stars.test.ts @@ -6,6 +6,7 @@ import { TWINKLE_PERIOD, activeAt, slotCount, + slotsFor, slotOffset, slotPeriod, twinkleGain, @@ -18,6 +19,28 @@ function hash2(a: number, b: number) { return ((a * 7919 + b * 104729) % 1000) / 1000; } +describe('the schedule over a universe of which a plate shows a share', () => { + const U = 2887; + const shown = 90; // stars on the plate: the first of the universe's, as any plate's are some of them + + it('twinkles SLOTS of the shown stars on average, and is the same schedule whichever plate asks', () => { + const slots = slotsFor(U, shown); + let on = 0; + const ts = Array.from({ length: 300 }, (_, i) => i * 0.53); + for (const t of ts) on += activeAt(U, t, slots).filter((a) => a.star < shown).length; + expect(on / ts.length).toBeGreaterThan(SLOTS * 0.7); + expect(on / ts.length).toBeLessThan(SLOTS * 1.3); + // a star's twinkle is keyed by its identity: asked again, by another plate, the same star has the same phase and gain + expect(activeAt(U, 41.3, slots)).toEqual(activeAt(U, 41.3, slots)); + }); + + it('never has more slots than half the universe, nor fewer than one', () => { + expect(slotsFor(U, 1)).toBe(Math.floor(U / 2)); + expect(slotsFor(U, 0)).toBe(Math.floor(U / 2)); + expect(slotsFor(2, 5)).toBe(1); + }); +}); + describe('twinkle schedule', () => { const times = Array.from({ length: 400 }, (_, i) => i * 0.37); diff --git a/src/app/features/scene/ridge/stars.ts b/src/app/features/scene/ridge/stars.ts index cbdc9a7a..d91a6f6c 100644 --- a/src/app/features/scene/ridge/stars.ts +++ b/src/app/features/scene/ridge/stars.ts @@ -14,6 +14,8 @@ export const TWINKLE_GAIN = { dim: 0.35, bright: 1.15 } as const; const SEED = 0x57a45eed; export interface Star { + /** The star's index in the catalogue (`starCatalogue.ts`): the identity the twinkle schedule is keyed by, the same on every plate of a sky. */ + id: number; /** Position as fractions of the sky canvas width and height. */ x: number; y: number; @@ -39,6 +41,13 @@ export function hash(a: number, b = 0, c = 0): number { // ---- The schedule --------------------------------------------------------------------------- export const slotCount = (stars: number): number => Math.min(SLOTS, stars); +/** + * The slots for a schedule over `universe` stars of which `shown` are on the plate that is up: enough that SLOTS of the ones shown twinkle at any instant on + * average, though the schedule runs over the whole universe (the catalogue), so that the same stars twinkle whichever plate shows them. Never more than half + * the universe, so each slot has a star to turn to. + */ +export const slotsFor = (universe: number, shown: number): number => + Math.max(1, Math.min(Math.floor(universe / 2), Math.round((SLOTS * universe) / Math.max(1, shown)), universe)); /** A slot's twinkle period in seconds: its own, in TWINKLE_PERIOD. */ export const slotPeriod = (j: number): number => TWINKLE_PERIOD.min + (TWINKLE_PERIOD.max - TWINKLE_PERIOD.min) * hash(j, 1); @@ -89,9 +98,8 @@ export interface Twinkling { gain: number; } -/** The active set at time `t` seconds for a field of `stars` stars, in slot order. */ -export function activeAt(stars: number, t: number): Twinkling[] { - const slots = slotCount(stars); +/** The active set at time `t` seconds for a universe of `stars` stars, in slot order, in `slots` slots (`slotCount` of them, or `slotsFor`). `star` is an index into the universe. */ +export function activeAt(stars: number, t: number, slots: number = slotCount(stars)): Twinkling[] { return Array.from({ length: slots }, (_, j) => { const period = slotPeriod(j); const off = slotOffset(j); @@ -115,12 +123,12 @@ export function activeAt(stars: number, t: number): Twinkling[] { // ---- Drawing -------------------------------------------------------------------------------- /** - * The overlay pass: clear, then for each active star whose gain is off base, cover the baked star with the sky behind it and draw it again + * The overlay pass over the plate's stars by identity: clear, then for each active star on this plate whose gain is off base, cover the baked star with the sky behind it and draw it again * at the gain. A star at base draws nothing. */ export function drawTwinkle( ctx: CanvasRenderingContext2D, - stars: readonly Star[], + stars: ReadonlyMap, active: readonly Twinkling[], w: number, h: number, @@ -128,7 +136,7 @@ export function drawTwinkle( ) { ctx.clearRect(0, 0, w, h); active.forEach((a) => { - const s = stars[a.star]; + const s = stars.get(a.star); if (!s || Math.abs(a.gain - 1) < 0.01) return; ctx.fillStyle = s.cover; ctx.beginPath();