diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 8fa17001..9679079f 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -6,10 +6,10 @@ means "keep the CSS ground". Everything below this section describes the opt-in - `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) into a sky plate (`ridge/skyTurn.ts`): one element over the host - canvas, the viewport's width plus 20 degrees of sky each side, centred on the heading `heading.ts` owns, holding the sky with the real stars, the moon and the lines baked into it and a + 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 14 degrees of the plate's edge and swaps it in the same tick - (the same sky at the same screen place, so nothing moves; the plate's backing store is capped at 3 Mpx, the pixel ratio lowering before the plate shrinks). Then come the lit ridge + 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 diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 1671a01e..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,7 +15,7 @@ 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 { plateCamera, plateSize } from './skyTurn'; +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'; @@ -167,6 +167,9 @@ 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() }), @@ -195,6 +198,7 @@ function ctx() { }), putImageData(img: { data: Uint8ClampedArray }) { painted.push(img.data); + onPaint?.(); }, beginPath() {}, moveTo() {}, @@ -215,6 +219,7 @@ function ctx() { 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: () => { @@ -246,6 +251,8 @@ beforeEach(() => { 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(), { @@ -321,7 +328,7 @@ describe('createRidgeScene', () => { const s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!; // 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).cssW, 800, plateCamera(win, ELSEWHERE_VIEW.lookAzDeg)); + 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(); @@ -428,7 +435,7 @@ describe('the starfield in the scene', () => { const N = nightBodies(physical, paintPhysicalSky(physical, 400, 800, view400.camera), false).stars.length; const NPLATE = nightBodies( physical, - paintPhysicalSky(physical, plateSize(view400, 400, 800, 2).cssW, 800, plateCamera(view400, FALLBACK_VIEW.lookAzDeg)), + 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) => { @@ -451,8 +458,8 @@ describe('the starfield in the scene', () => { 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(); }); @@ -780,11 +787,11 @@ describe('the ridge cards in the scene', () => { 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).cssW, 800, plateCamera(wn, 100)); + 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).cssW) / 2, 9); // centred on the viewport + 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(); }); @@ -819,7 +826,7 @@ describe('the ridge cards in the scene', () => { }; const plateX = (device: number) => { const wn = windowFor(view, W, 800); - const size = plateSize(wn, W, 800, 2); + 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]); @@ -863,6 +870,122 @@ describe('the ridge cards in the scene', () => { 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); @@ -930,7 +1053,7 @@ describe('the ridge cards in the scene', () => { 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); + 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); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index acbe73d8..b6f5d729 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -7,10 +7,11 @@ import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, wind 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 { alignTurns, panPx, plateCamera, plateSize, recentre } from './skyTurn'; +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'; @@ -118,18 +119,25 @@ interface Plate { el: HTMLElement; /** The twinkle canvas of this plate, over its sky; absent in a day sky. */ twinkle?: HTMLCanvasElement; - /** The stars this plate was painted with, which the twinkle schedule indexes. */ - field: Star[]; + /** 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; - /** Key the slide from `t0` (ms) after the heading owner's pose, painting a new plate first when the heading is near this one's edge; `play`: the motion runs. */ - issue: (t0: number, frozen: boolean, play: boolean) => void; - /** The residency tick: paint a new plate and key it from now when the heading is near the edge. */ - tend: (t: number) => void; + /** + * 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; } @@ -197,6 +205,8 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { let built: Built | undefined; 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; @@ -347,8 +357,9 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { /** The next stretch of every card's motion, from now: it replaces the one running, which agrees with it where they meet. */ const issue = () => { if (!live) return; + 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; const play = moving(); @@ -363,7 +374,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { }); if (!play) anims[i]?.pause(); } - plate?.issue(t0, frozen, play); // the sky turns on the same keyframes, from the same poses + 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 }; @@ -403,13 +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 (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(t); + 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 @@ -491,8 +507,11 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { */ const startPlate = (physical: NonNullable, w: number, h: number, dpr: number): Plate | undefined => { const win = windowFor(physical.view, w, h); - const { cssW, ratio, pxPerDeg } = plateSize(win, w, h, dpr); - const paint = (centre: number) => { + 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, { @@ -514,15 +533,30 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { return c; }; const skyEl = layer(); - const painted = paintSky(skyEl, sky, plateCamera(win, centre), cssW, h, makeCanvas); + 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); - return { el, twinkle: bodies.stars.length ? layer() : undefined, field: bodies.stars }; + 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); + 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. */ @@ -533,29 +567,31 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { if (!play) anim?.pause(); return anim; }; - /** A plate about `centre` in the place of `old`: the same sky at the same place on the screen, so nothing moves. Undefined (the old one stays) if it cannot be painted. */ - const renew = (old: Plate, centre: number) => { - const next = paint(centre); - if (!next) return undefined; - parent.insertBefore(next.el, old.el); - old.anim?.cancel(); - old.el.remove(); - return next; - }; const plate: Plate = { ...first, - ratio, centre: facing, - issue: (t0, frozen, play) => { - const at = headingPose(t0).h; + refit: (periodMs) => { + const at = headingPose(clock()).h; plate.centre = alignTurns(plate.centre, at); - const next = recentre(at, plate.centre) ? renew(plate, at) : undefined; - if (next) Object.assign(plate, next, { centre: at, anim: undefined }); + 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: (t) => { - if (recentre(headingPose(t).h, plate.centre)) plate.issue(t, false, true); // ticks run only while moving + tend: (periodMs) => { + if (plate.refit(periodMs)) plate.key(clock(), false, true); // ticks run only while moving }, stop: () => { plate.anim?.cancel(); @@ -601,14 +637,9 @@ 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 plate = built?.plate; - const el = plate?.twinkle; - const ctx = el && context2d(el); - if (!plate || !el || !ctx) return; - const active = t === undefined ? [] : activeAt(plate.field.length, t); - paintTwinkle(ctx, plate.field, active, el.width, el.height, plate.ratio); + if (built?.plate) paintTwinkleOf(built.plate, t); }; // The same guard as the drift: not still, not disposed, not reduced motion, tab visible. Not moving 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 index 4d58c11c..bd6e4bec 100644 --- a/src/app/features/scene/ridge/skyTurn.test.ts +++ b/src/app/features/scene/ridge/skyTurn.test.ts @@ -1,5 +1,18 @@ import { describe, expect, it } from 'vitest'; -import { alignTurns, panPx, plateCamera, plateSize, PLATE_MAX_PX, RECENTRE_MARGIN_DEG, recentre, SLACK_DEG } from './skyTurn'; +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'; @@ -7,44 +20,83 @@ 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); + const cam = plateCamera(win, 100, SLACK_MIN_DEG); expect(cam.azimuthDeg).toBe(100); - expect(cam.hfovDeg).toBeCloseTo(win.camera.hfovDeg + 2 * SLACK_DEG, 12); - expect(SLACK_DEG).toBe(20); + 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); + 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).azimuthDeg).toBe(30); - expect(plateCamera(win, -10).azimuthDeg).toBe(350); + 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', () => { - it('fires 14 degrees from the centre, not 5, and not for a heading that stays', () => { - expect(RECENTRE_MARGIN_DEG).toBe(6); - expect(recentre(100, 100)).toBe(false); - expect(recentre(105, 100)).toBe(false); - expect(recentre(113.9, 100)).toBe(false); - expect(recentre(114.1, 100)).toBe(true); - expect(recentre(85.9, 100)).toBe(true); + 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(recentre(10 + 360, 10)).toBe(false); - expect(recentre(350, 5)).toBe(true); // 15 degrees off, the short way - expect(recentre(358, 5)).toBe(false); + 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); }); +}); - it('is decided before the plate can run out between two residency ticks of the fastest turn', () => { - expect(SPEED_CEILING_DEG_S * (RESIDENCY_MS / 1000)).toBeLessThanOrEqual(RECENTRE_MARGIN_DEG); +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); + } + } }); }); @@ -58,13 +110,13 @@ describe('plateSize', () => { [800, 600, 1], ].forEach(([w, h, dpr]) => { const wn = windowFor(FALLBACK_VIEW, w, h); - const p = plateSize(wn, w, h, dpr); + 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_DEG)) / wn.camera.hfovDeg, 9); + 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).ratio).toBe(2); + expect(plateSize(windowFor(FALLBACK_VIEW, 300, 500), 300, 500, 2, SLACK_MIN_DEG).ratio).toBe(2); }); }); diff --git a/src/app/features/scene/ridge/skyTurn.ts b/src/app/features/scene/ridge/skyTurn.ts index a976f49c..15654778 100644 --- a/src/app/features/scene/ridge/skyTurn.ts +++ b/src/app/features/scene/ridge/skyTurn.ts @@ -1,30 +1,47 @@ // 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 SLACK_DEG each side, +// `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 lets the heading wander before the plate runs out; the scene paints a new plate about the heading it has reached, in the same +// `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'; -/** Degrees of sky painted beyond the viewport on each side of it. Authored: a tick of the fastest turn (`SPEED_CEILING_DEG_S`) is 6 degrees. */ -export const SLACK_DEG = 20; -/** A plate is replaced once the heading is within this many degrees of its edge: one residency tick (500 ms) of the fastest turn, so it is never run out between two ticks. */ -export const RECENTRE_MARGIN_DEG = 6; +/** 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 = SLACK_DEG): Camera { +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: its CSS width (the viewport's px per degree is the plate's), and the pixel ratio of its backing store. */ +/** 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 = SLACK_DEG + slackDeg: number ): { cssW: number; ratio: number; pxPerDeg: number } { const pxPerDeg = w / win.camera.hfovDeg; const cssW = pxPerDeg * (win.camera.hfovDeg + 2 * slackDeg); @@ -36,14 +53,13 @@ export function plateSize( export const alignTurns = (centreDeg: number, headingDeg: number): number => centreDeg + 360 * Math.round((headingDeg - centreDeg) / 360); -/** Whether a plate centred on `centreDeg` should be replaced now: the heading is nearer its edge than the margin. A still heading never is. */ -export function recentre( - headingDeg: number, - centreDeg: number, - slackDeg: number = SLACK_DEG, - marginDeg: number = RECENTRE_MARGIN_DEG -): boolean { - return Math.abs(headingDeg - alignTurns(centreDeg, headingDeg)) > slackDeg - marginDeg; +/** + * 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. */ 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();