diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 646fab95..39b93421 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -3,7 +3,8 @@ import { createRidgeScene } from './Ridge'; import { valueNoise, hash2 } from './noise'; import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe'; import type { SkyColours } from './skyColour'; -import { makeStars } from './stars'; +import { nightBodies } from './nightBodies'; +import { sunAt } from './sunAt'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { startBackgroundScene } from '../index'; import { parseManifest } from './manifest'; @@ -158,6 +159,8 @@ function ctx() { }, rect() {}, clip() {}, + rotate() {}, + ellipse() {}, createImageData: (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, @@ -377,13 +380,15 @@ describe('the door', () => { describe('the starfield in the scene', () => { const count = (kind: string) => draws.filter((d) => d === kind).length; - const night = { - ...DAY, - top: [10, 14, 40], - mid: [30, 34, 80], - horizon: [60, 50, 90], - } as SkyColours; - const N = makeStars(night, 400, 800).length; + // A moonless-horizon night over Vienna (the moon is 17 degrees below it): the real stars of that moment, and no moon to count as an arc. + const t = new Date('2026-12-04T00:00:00Z'); + const physical = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t)); + const night: SkyColours = { ...DAY, physical }; + const N = nightBodies( + physical, + paintPhysicalSky(physical, 400, 800, windowFor(FALLBACK_VIEW, 400, 800).camera), + false + ).stars.length; const hear = (name: string) => { const calls = motion.addEventListener.mock.calls.filter((c: any[]) => c[0] === name); return calls[calls.length - 1][1] as () => void; @@ -395,7 +400,7 @@ describe('the starfield in the scene', () => { const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: night })!; expect(count('star')).toBe(N); - expect(count('sky')).toBe(1); + expect(painted).toHaveLength(1); // the physical sky's one grid expect(parent.children[1].anims).toHaveLength(0); // the overlay, above the sky expect(parent.children).toHaveLength(2); const before = baked(); @@ -403,8 +408,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 - expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 32); + // each pass paints at most SLOTS stars, each as its cover and the star again + expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64); expect(count('twinkle')).toBeGreaterThan(0); s.dispose(); }); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index 5cbc0cfd..639c4df1 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -4,7 +4,9 @@ import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; import { cardMotion, windowFor } from './view'; -import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars'; +import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars'; +import { nightBodies, paintNightBodies } from './nightBodies'; +import type { NightBodies } from './nightBodies'; import { drawRainTile, RAIN_TILES } from './rain'; import type { Backdrop } from './Backdrop'; @@ -19,6 +21,8 @@ export type RidgeOptions = Pick & { sky?: SkyColours; /** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */ backdrop?: Backdrop; + /** Draw the constellation lines over the stars (a hidden extra, `skyState.ts`); only a night sky shows them. */ + lines?: boolean; }; const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`; @@ -55,9 +59,9 @@ function paintSky( cssW: number, cssH: number, makeCanvas: () => HTMLCanvasElement -): boolean { +): { ok: boolean; px?: ReturnType } { const ctx = context2d(canvas); - if (!ctx) return false; + if (!ctx) return { ok: false }; if (sky.physical) { const px = paintPhysicalSky( sky.physical, @@ -77,7 +81,7 @@ function paintSky( ctx.imageSmoothingQuality = 'high'; ctx.drawImage(small, 0, 0, canvas.width, canvas.height); if (px.sunDisc) drawSun(ctx, px.sunDisc, canvas.width, canvas.height); - return true; + return { ok: true, px }; } } const g = ctx.createLinearGradient(0, 0, 0, canvas.height); @@ -87,7 +91,7 @@ function paintSky( g.addColorStop(1, css(sky.horizon)); ctx.fillStyle = g; ctx.fillRect(0, 0, canvas.width, canvas.height); - return true; + return { ok: true }; } const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); @@ -293,12 +297,17 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const { w, h, scale } = viewSize(); canvas.width = Math.round(w * scale); canvas.height = Math.round(h * scale); - if (!paintSky(canvas, sky, w, h, () => document.createElement('canvas'))) return false; - // Every star is baked into the sky; the twinkling ones get their own canvas, which a per-frame - // pass clears and paints over. 'still' has no overlay. - const stars = makeStars(sky, w, h); + 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) drawStars(skyCtx, stars, canvas.width, canvas.height, scale); + if (skyCtx) paintNightBodies(skyCtx, bodies, canvas.width, canvas.height, scale); let twinkle: HTMLCanvasElement | undefined; if (stars.length && tier !== 'still') { twinkle = document.createElement('canvas'); diff --git a/src/app/features/scene/ridge/nightBodies.test.ts b/src/app/features/scene/ridge/nightBodies.test.ts new file mode 100644 index 00000000..0daab8c2 --- /dev/null +++ b/src/app/features/scene/ridge/nightBodies.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; +import { limbAngle, nightBodies, onScreen, paintNightBodies } from './nightBodies'; +import { makePhysicalSky, paintSky } from './physicalSky'; +import { sunAt } from './sunAt'; +import { FALLBACK_VIEW } from './view'; +import type { Camera } from './view'; +import { MAG_LIMIT, starsAt } from './starCatalogue'; +import { moonAt } from './nightSky'; + +const P = FALLBACK_VIEW.place; +// A camera that sees most of the sky, so the moon of any hour is in it (the app's own window looks 72 degrees wide over the south-west). +const camera: Camera = { azimuthDeg: 180, hfovDeg: 340, vfovDeg: 170, horizonAt: 0.92 }; + +const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => { + const t = new Date(iso); + return makePhysicalSky(state, t, 0, FALLBACK_VIEW, sunAt(P, t)); +}; +const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => { + const p = sky(iso, state); + return { p, nb: nightBodies(p, paintSky(p, 640, 360, camera), lines) }; +}; + +// 2026-11-24 22:00 UTC: full moon high in the south over Vienna. 2026-12-09 20:00 UTC: new moon. 2026-12-04 00:00 UTC: no moon up. +const FULL = '2026-11-24T22:00:00Z'; +const NEW = '2026-12-09T20:00:00Z'; +const MOONLESS = '2026-12-04T00:00:00Z'; + +describe('the stars of a night sky', () => { + it('are the catalogue stars of the sky\'s own moment inside the camera, brightest drawn largest', () => { + const { nb } = bodies(MOONLESS); + expect(nb.stars.length).toBeGreaterThan(300); + const inView = starsAt(new Date(MOONLESS), P.lat, P.lon, MAG_LIMIT, -0.5).filter((s) => { + const a = onScreen(camera, s.azimuth, s.elevation); + return a.x > -0.02 && a.x < 1.02 && a.y > -0.02 && a.y < 1.02; + }); + expect(nb.stars.length).toBeLessThanOrEqual(inView.length); + const radii = nb.stars.map((s) => s.r); + expect(Math.max(...radii)).toBeGreaterThan(1.2 * Math.min(...radii)); + }); + + it('are hidden by the twilight that exposes the sky: none at dusk, none by day, more on a moonless night than a full-moon one', () => { + expect(bodies('2026-06-21T10:40:00Z', 'day').nb.stars).toHaveLength(0); + expect(bodies('2026-12-04T15:20:00Z', 'dusk').nb.stars.length).toBeLessThan(5); + expect(bodies(MOONLESS).nb.stars.length).toBeGreaterThan(bodies(FULL).nb.stars.length); + }); + + it('move with the clock: three hours later the field is a different one, rotated by 45 degrees about the pole', () => { + const a = bodies('2026-12-04T00:00:00Z').nb.stars.slice(0, 20).map((s) => s.x.toFixed(3)).join(); + const b = bodies('2026-12-04T03:00:00Z').nb.stars.slice(0, 20).map((s) => s.x.toFixed(3)).join(); + expect(a).not.toBe(b); + }); + + it('twinkle by flux: a star dimmed by its gain is closer to the sky behind it, brightened is lighter, base is its fill', () => { + const { nb } = bodies(MOONLESS); + const s = nb.stars[0]; + const lum = (c: string) => c.match(/\d+/g)!.map(Number).reduce((a, b) => a + b, 0); + expect(s.shade(1)).toBe(s.fill); + expect(lum(s.shade(0.35))).toBeLessThanOrEqual(lum(s.fill)); + expect(lum(s.shade(1.15))).toBeGreaterThanOrEqual(lum(s.fill)); + expect(lum(s.cover)).toBeLessThan(lum(s.fill)); + }); +}); + +describe('the moon of a night sky', () => { + it('is drawn where the ephemeris puts it, with the real phase', () => { + const { p, nb } = bodies(FULL); + expect(nb.moon).toBeDefined(); + expect(nb.moon!.illuminated).toBeGreaterThan(0.99); + const at = onScreen(camera, p.moon.azimuth, p.moon.elevation); + expect(nb.moon!.x).toBeCloseTo(at.x, 9); + expect(nb.moon!.y).toBeCloseTo(at.y, 9); + // 0.52 degrees across, vertical field of view a few tens of degrees + expect(nb.moon!.radius * camera.vfovDeg).toBeCloseTo((p.moon.radius * 180) / Math.PI, 6); + }); + + it('is a thin sliver near new moon and not drawn when it is below the horizon', () => { + expect(moonAt(P, new Date(NEW)).illuminated).toBeLessThan(0.05); + expect(bodies(MOONLESS).nb.moon).toBeUndefined(); + }); + + it('points its bright limb at the sun: down and toward the sun at moonrise after sunset, up at moonset in the morning', () => { + // A moon due south at 30 degrees with the sun at the horizon due west: the limb leans to the right (east is left on screen looking south, west right). + const a = limbAngle({ azimuth: 180, elevation: 30 }, { azimuth: 270, elevation: 0 }); + expect(Math.cos(a)).toBeGreaterThan(0.5); + expect(Math.sin(a)).toBeLessThan(0); + // Sun straight below the moon: the limb points down the screen. + expect(Math.sin(limbAngle({ azimuth: 180, elevation: 30 }, { azimuth: 180, elevation: -30 }))).toBeLessThan(-0.99); + }); + + it('is lighter than the sky around it, and its dark side lighter than the sky', () => { + const { nb } = bodies(FULL); + const lum = (c: string) => c.match(/\d+/g)!.map(Number).reduce((a, b) => a + b, 0); + expect(lum(nb.moon!.lit)).toBeGreaterThan(lum(nb.moon!.dark)); + expect(lum(nb.moon!.lit)).toBeGreaterThan(450); + }); +}); + +describe('the constellation lines', () => { + it('are absent unless asked for, and present for a night sky when they are', () => { + expect(bodies(MOONLESS, 'night', false).nb.lines).toHaveLength(0); + const on = bodies(MOONLESS, 'night', true).nb.lines; + expect(on.length).toBeGreaterThan(20); + expect(on.every((l) => l.points.length > 1)).toBe(true); + }); + + it('are not drawn in a day or dusk sky even when asked for', () => { + expect(bodies('2026-06-21T10:40:00Z', 'day', true).nb.lines).toHaveLength(0); + expect(bodies('2026-12-04T15:20:00Z', 'dusk', true).nb.lines).toHaveLength(0); + }); +}); + +describe('painting', () => { + it('draws lines, stars and the moon in that order and builds the terminator from an ellipse', () => { + const calls: string[] = []; + const ctx = new Proxy( + {}, + { + get: (_t, k) => (k === 'save' ? () => 0 : () => calls.push(String(k))), + set: () => true, + } + ) as unknown as CanvasRenderingContext2D; + const { nb } = bodies(FULL, 'night', true); + paintNightBodies(ctx, nb, 1280, 720, 2); + expect(calls.indexOf('stroke')).toBeGreaterThanOrEqual(0); + expect(calls.indexOf('stroke')).toBeLessThan(calls.indexOf('arc')); + expect(calls).toContain('ellipse'); + expect(calls.filter((c) => c === 'arc').length).toBeGreaterThanOrEqual(nb.stars.length + 2); + }); +}); diff --git a/src/app/features/scene/ridge/nightBodies.ts b/src/app/features/scene/ridge/nightBodies.ts new file mode 100644 index 00000000..a4b482ca --- /dev/null +++ b/src/app/features/scene/ridge/nightBodies.ts @@ -0,0 +1,266 @@ +// The night's bodies on the sky canvas: the real stars (`starCatalogue.ts`, for the place and the moment the sky state draws, `sun.time`), +// the moon with its phase, and the constellation lines. Each body's radiance (`nightSky.ts`) is added to the sky's own radiance behind it +// (the dome's grid, `skyDome.ts`) and goes through the sky's display (exposure, scotopic grade, ACES, curve), so the twilight that brightens the sky +// hides them, as a camera's exposure would, and the cards share the display. A body's contrast is compressed (`NIGHT_LOOK`): see there. +import { display8 } from './toneMap'; +import { blackbodyRgb, compressed, extinguished, NIGHT_LOOK, moonSurface, starRadiance, temperatureOfBV } from './nightSky'; +import type { Dome } from './skyDome'; +import type { PhysicalSky, SkyPixels } from './physicalSky'; +import { linesAt, MAG_LIMIT, starsAt } from './starCatalogue'; +import type { Star } from './stars'; + +const RAD = Math.PI / 180; +const luma = (c: ArrayLike): number => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; +const css = (c: ArrayLike): string => `rgb(${c[0]},${c[1]},${c[2]})`; +const wrap180 = (d: number): number => ((((d + 180) % 360) + 360) % 360) - 180; + +/** Where a direction is on the image (the camera's angle-linear mapping, `view.ts`), as fractions of its width and height (y down). */ +export function onScreen( + camera: SkyPixels['camera'], + azimuth: number, + elevation: number +): { x: number; y: number } { + return { + x: 0.5 + wrap180(azimuth - camera.azimuthDeg) / camera.hfovDeg, + y: camera.horizonAt - elevation / camera.vfovDeg, + }; +} + +/** The dome's radiance behind a point of the image (fractions), bilinear between texel centres. */ +export function domeAt(dome: Dome, x: number, y: number, out: number[]): void { + const fx = Math.min(dome.w - 1, Math.max(0, x * dome.w - 0.5)); + const fy = Math.min(dome.h - 1, Math.max(0, y * dome.h - 0.5)); + const i0 = Math.floor(fx); + const j0 = Math.floor(fy); + const i1 = Math.min(dome.w - 1, i0 + 1); + const j1 = Math.min(dome.h - 1, j0 + 1); + const tx = fx - i0; + const ty = fy - j0; + for (let k = 0; k < 3; k += 1) { + const at = (i: number, j: number) => dome.hdr[(j * dome.w + i) * 3 + k]; + out[k] = + (at(i0, j0) * (1 - tx) + at(i1, j0) * tx) * (1 - ty) + (at(i0, j1) * (1 - tx) + at(i1, j1) * tx) * ty; + } +} + +/** `bg` plus a body of radiance `add` on it, the contrast compressed to the power `exp` (1 physical), as linear rgb into `out`. */ +function composite(bg: number[], add: number[], exp: number, out: number[]): void { + const total = luma(bg) + luma(add); + const k = total > 0 ? compressed(luma(bg), luma(add), exp) / total : 1; + for (let i = 0; i < 3; i += 1) out[i] = (bg[i] + add[i]) * k; +} + +export interface MoonDraw { + x: number; + y: number; + /** Radius as a fraction of the image height. */ + radius: number; + /** Lit fraction of the disc and the phase angle (0 full) in radians. */ + illuminated: number; + phaseAngle: number; + /** Direction of the bright limb on the image, radians counter-clockwise from the right. */ + limb: number; + lit: string; + dark: string; +} + +export interface LineDraw { + /** Polyline in image fractions. */ + points: { x: number; y: number }[]; +} + +export interface NightBodies { + stars: Star[]; + moon?: MoonDraw; + lines: LineDraw[]; +} + +/** Unit vector (east, north, up) of a direction. */ +const vec = (az: number, el: number): [number, number, number] => [ + Math.cos(el * RAD) * Math.sin(az * RAD), + Math.cos(el * RAD) * Math.cos(az * RAD), + Math.sin(el * RAD), +]; + +/** The screen direction (radians, counter-clockwise from the right) from the moon toward `toward`, by the tangent of the great circle at the moon. */ +export function limbAngle(moon: { azimuth: number; elevation: number }, toward: { azimuth: number; elevation: number }): number { + const m = vec(moon.azimuth, moon.elevation); + const s = vec(toward.azimuth, toward.elevation); + const d = m[0] * s[0] + m[1] * s[1] + m[2] * s[2]; + const t = [s[0] - d * m[0], s[1] - d * m[1], s[2] - d * m[2]]; + const az = moon.azimuth * RAD; + const el = moon.elevation * RAD; + const east = [Math.cos(az), -Math.sin(az), 0]; + const up = [-Math.sin(el) * Math.sin(az), -Math.sin(el) * Math.cos(az), Math.cos(el)]; + return Math.atan2(t[0] * up[0] + t[1] * up[1] + t[2] * up[2], t[0] * east[0] + t[1] * east[1] + t[2] * east[2]); +} + +/** Great-circle subdivision of a chain's legs, as az/el. */ +function slerp(a: { azimuth: number; elevation: number }, b: { azimuth: number; elevation: number }, n: number) { + const u = vec(a.azimuth, a.elevation); + const v = vec(b.azimuth, b.elevation); + const w = Math.acos(Math.min(1, Math.max(-1, u[0] * v[0] + u[1] * v[1] + u[2] * v[2]))); + if (w < 1e-6) return [a]; + return Array.from({ length: n + 1 }, (_, i) => { + const t = i / n; + const s0 = Math.sin((1 - t) * w) / Math.sin(w); + const s1 = Math.sin(t * w) / Math.sin(w); + const p = [0, 1, 2].map((k) => s0 * u[k] + s1 * v[k]); + return { + azimuth: ((Math.atan2(p[0], p[1]) / RAD) % 360 + 360) % 360, + elevation: Math.asin(Math.min(1, Math.max(-1, p[2]))) / RAD, + }; + }); +} + +/** + * The stars, moon and (when asked, and only in the night state) constellation lines of a physical sky as seen through the camera of `px` + * (`paintSky`'s grid and the dome behind it). The moment is the sky's own, `p.sun.time`, so the bodies agree with the light. + */ +export function nightBodies(p: PhysicalSky, px: SkyPixels, withLines: boolean): NightBodies { + const { place } = p.view; + const { camera, dome } = px; + const display = p.fit.display; + const bg = [0, 0, 0]; + const add = [0, 0, 0]; + const tot = [0, 0, 0]; + const out = [0, 0, 0]; + const stars: Star[] = []; + for (const s of starsAt(p.sun.time, place.lat, place.lon, MAG_LIMIT, -0.5)) { + const at = onScreen(camera, s.azimuth, s.elevation); + if (at.x < -0.02 || at.x > 1.02 || at.y < -0.02 || at.y > 1.02) continue; + const back = [0, 0, 0]; + domeAt(dome, at.x, at.y, back); + const m = extinguished(s.mag, s.elevation); + const rgb = blackbodyRgb(temperatureOfBV(s.bv)); + const lum = starRadiance(m); + // Each star owns its own scratch: `shade` outlives this loop. + const hdr = (gain: number, o: number[]) => { + const a = [rgb[0] * lum * gain, rgb[1] * lum * gain, rgb[2] * lum * gain]; + const t = [0, 0, 0]; + composite(back, a, NIGHT_LOOK.starContrastExp, t); + display8(t[0], t[1], t[2], display, o); + }; + const base = [0, 0, 0]; + hdr(1, base); + display8(back[0], back[1], back[2], display, out); + // A star the sky hides (within three 8-bit steps of it in every channel) is not drawn. + 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({ + x: at.x, + y: at.y, + r: r0 + perMag * Math.max(0, MAG_LIMIT - m), + fill: css(base), + cover: css(out), + shade: (gain) => { + const o = [0, 0, 0]; + hdr(gain, o); + return css(o); + }, + }); + } + + let moon: MoonDraw | undefined; + const mo = p.moon; + const mAt = onScreen(camera, mo.azimuth, mo.elevation); + if (mo.elevation > -1 && mAt.x > -0.05 && mAt.x < 1.05 && mAt.y > -0.05 && mAt.y < 1.05) { + domeAt(dome, mAt.x, mAt.y, bg); + const trans = [0, 0, 0]; + p.atm.transmittanceToSpace(Math.max(Math.sin(mo.elevation * RAD), 0), trans); + const top = Math.max(...trans, 1e-9); + const tint = [1, 0.96, 0.88]; + const surface = moonSurface(mo); + for (let i = 0; i < 3; i += 1) add[i] = surface * tint[i] * (trans[i] / top) ** 0.6; + composite(bg, add, NIGHT_LOOK.moonContrastExp, tot); + display8(tot[0], tot[1], tot[2], display, out); + const lit = css(out); + // Earthshine: a fraction of the full moon's surface, the more the thinner the crescent. + const full = moonSurface({ ...mo, ratio: mo.ratio / Math.max(mo.illuminated, 0.02), illuminated: 1 }); + for (let i = 0; i < 3; i += 1) add[i] = NIGHT_LOOK.earthshine * full * (1.1 - mo.illuminated) * [0.9, 1, 1.15][i]; + composite(bg, add, NIGHT_LOOK.moonContrastExp, tot); + display8(tot[0], tot[1], tot[2], display, out); + moon = { + x: mAt.x, + y: mAt.y, + radius: ((mo.radius / RAD) * NIGHT_LOOK.moonScale) / camera.vfovDeg, + illuminated: mo.illuminated, + phaseAngle: mo.phaseAngleDeg * RAD, + limb: limbAngle(mo, p.sun), + lit, + dark: css(out), + }; + } + + const lines: LineDraw[] = []; + if (withLines && p.state === 'night') { + for (const chain of linesAt(p.sun.time, place.lat, place.lon)) { + const points: { x: number; y: number }[] = []; + const flush = () => { + if (points.length > 1) lines.push({ points: points.slice() }); + points.length = 0; + }; + chain.forEach((v, i) => { + const legs = i === 0 ? [v] : slerp(chain[i - 1], v, 6).slice(1); + legs.forEach((q) => { + const a = onScreen(camera, q.azimuth, q.elevation); + const prev = points[points.length - 1]; + if (prev && Math.abs(a.x - prev.x) > 0.5) flush(); + points.push(a); + }); + }); + flush(); + } + } + return { stars, moon, lines }; +} + +/** Paint the lines, the stars and the moon onto the canvas (`w` x `h` device px, `scale` device px per CSS px), in that order. */ +export function paintNightBodies( + ctx: CanvasRenderingContext2D, + nb: NightBodies, + w: number, + h: number, + scale: number +): void { + if (nb.lines.length) { + const [r, g, b] = NIGHT_LOOK.lines.rgb; + ctx.save(); + ctx.strokeStyle = `rgba(${r},${g},${b},${NIGHT_LOOK.lines.alpha})`; + ctx.lineWidth = NIGHT_LOOK.lines.widthPx * scale; + ctx.lineJoin = 'round'; + nb.lines.forEach((l) => { + ctx.beginPath(); + l.points.forEach((q, i) => (i ? ctx.lineTo(q.x * w, q.y * h) : ctx.moveTo(q.x * w, q.y * h))); + ctx.stroke(); + }); + ctx.restore(); + } + nb.stars.forEach((s) => { + ctx.fillStyle = s.fill; + ctx.beginPath(); + ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI); + ctx.fill(); + }); + const m = nb.moon; + if (!m) return; + const R = Math.max(2 * scale, m.radius * h); + ctx.save(); + ctx.translate(m.x * w, m.y * h); + ctx.rotate(-m.limb); // the bright limb to +x; canvas rotation is clockwise, `limb` counter-clockwise + ctx.fillStyle = m.dark; + ctx.beginPath(); + ctx.arc(0, 0, R, 0, 2 * Math.PI); + ctx.fill(); + if (m.illuminated > 0.004) { + // Lit: the half toward the sun, plus or minus the half-ellipse of the terminator, whose semi-axis along x is R |cos i|. + const cosI = Math.cos(m.phaseAngle); + ctx.fillStyle = m.lit; + ctx.beginPath(); + ctx.arc(0, 0, R, -Math.PI / 2, Math.PI / 2, false); + ctx.ellipse(0, 0, Math.max(R * Math.abs(cosI), 1e-3), R, 0, Math.PI / 2, cosI > 0 ? (3 * Math.PI) / 2 : -Math.PI / 2, cosI <= 0); + ctx.closePath(); + ctx.fill(); + } + ctx.restore(); +} diff --git a/src/app/features/scene/ridge/stars.test.ts b/src/app/features/scene/ridge/stars.test.ts index e14f2a7c..f036a7ee 100644 --- a/src/app/features/scene/ridge/stars.test.ts +++ b/src/app/features/scene/ridge/stars.test.ts @@ -1,88 +1,23 @@ /* eslint-disable no-restricted-syntax, no-continue -- test loops over sample times */ import { describe, expect, it } from 'vitest'; -import { skyColours } from './skyColour'; import { - MAX_STARS, - NIGHT_LUMA, SLOTS, TWINKLE_GAIN, TWINKLE_PERIOD, activeAt, - makeStars, - skyLuma, slotCount, slotOffset, slotPeriod, - starCount, twinkleGain, } from './stars'; -const DAY = { - ...skyColours(), - top: [96, 150, 220], - mid: [150, 190, 235], - horizon: [240, 215, 190], -} as const; -const NIGHT = { - ...skyColours(), - top: [10, 14, 40], - mid: [30, 34, 80], - horizon: [60, 50, 90], -} as const; -const N = makeStars(NIGHT, 390, 844).length; +/** A field the size of a night's visible stars. */ +const N = 1200; function hash2(a: number, b: number) { return ((a * 7919 + b * 104729) % 1000) / 1000; } -describe('star placement', () => { - it('is deterministic: the same sky and size give the identical field', () => { - expect(makeStars(NIGHT, 390, 844)).toEqual(makeStars(NIGHT, 390, 844)); - expect(makeStars(skyColours(), 390, 844)).toEqual(makeStars(skyColours(), 390, 844)); - }); - - it('draws none in a day sky or the lavender dusk, and some in a night one', () => { - expect(makeStars(DAY, 390, 844)).toHaveLength(0); - expect(makeStars(skyColours(), 390, 844)).toHaveLength(0); - expect(makeStars(NIGHT, 390, 844).length).toBeGreaterThan(50); - }); - - it('is a few hundred at most: bounded by MAX_STARS and by the viewport', () => { - for (const [w, h] of [ - [390, 844], - [1920, 1080], - [100, 100], - ] as const) { - expect(makeStars(NIGHT, w, h).length).toBeLessThanOrEqual(starCount(w, h)); - expect(starCount(w, h)).toBeLessThanOrEqual(MAX_STARS); - } - expect(N).toBeGreaterThan(150); - }); - - it('thins toward the horizon: more than twice the stars in the top third than the bottom third of the sky', () => { - const all = makeStars(NIGHT, 390, 844); - expect(all.filter((s) => s.y < 0.26).length).toBeGreaterThan( - 2 * all.filter((s) => s.y > 0.52).length - ); - }); - - it('fades with the sky: every star sits where the sky is dark, alpha within bounds', () => { - for (const s of makeStars(NIGHT, 390, 844)) { - expect(skyLuma(NIGHT, s.y)).toBeLessThan(NIGHT_LUMA); - expect(s.alpha).toBeLessThanOrEqual(0.9); - expect(s.alpha).toBeGreaterThanOrEqual(0.05); - } - }); - - it('varies in size and brightness', () => { - const all = makeStars(NIGHT, 390, 844); - expect(new Set(all.map((s) => s.r.toFixed(2))).size).toBeGreaterThan(50); - expect( - Math.max(...all.map((s) => s.alpha)) - Math.min(...all.map((s) => s.alpha)) - ).toBeGreaterThan(0.3); - }); -}); - 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 0e6d2628..68568ad7 100644 --- a/src/app/features/scene/ridge/stars.ts +++ b/src/app/features/scene/ridge/stars.ts @@ -1,22 +1,11 @@ -// The Midnight starfield: placed once from a seeded PRNG and baked once into the sky canvas. A -// rolling window of them twinkles on an overlay canvas: SLOTS slots, each running back-to-back -// twinkles of one star at a time, so the active set is always SLOTS stars and every star gets its turn. -// The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs -// after the field is built, so any instant maps straight to the active set and its brightnesses. +// The twinkle of the real stars (`nightBodies.ts` places them from the catalogue for the place and moment). A rolling window of them twinkles +// on an overlay canvas: SLOTS slots, each running back-to-back twinkles of one star at a time, so the active set is always SLOTS stars and every +// star gets its turn. The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs, so any instant maps +// straight to the active set and its gains. A gain multiplies the star's radiance before the display (scintillation is flux), so a star +// the twilight hides stays hidden whatever it does. -/* eslint-disable no-bitwise -- the seeded PRNG and hash are 32-bit integer arithmetic */ -import type { SkyColours, Srgb } from './skyColour'; +/* eslint-disable no-bitwise -- the seeded hash is 32-bit integer arithmetic */ -/** - * Stars show when the sky behind them is darker than this sRGB luma (0..255). The ridge scene has - * no night flag (the sky theme's Midnight/Noonday is a body class chosen by the app, not seen here), - * so night is the sky's own darkness: a star's alpha is 1 - luma/NIGHT_LUMA at its height in the - * gradient, and a sky whose zenith is lighter than this gets no stars at all. - */ -export const NIGHT_LUMA = 110; -/** The sky gradient runs from the top (0) through mid (0.5) to the horizon glow (0.78 and below). */ -export const SKY_STOPS = { mid: 0.5, horizon: 0.78 }; -export const MAX_STARS = 400; /** Twinkling stars at any instant (fewer only if the field has fewer stars). */ export const SLOTS = 32; export const TWINKLE_PERIOD = { min: 2, max: 7 } as const; @@ -30,43 +19,12 @@ export interface Star { y: number; /** Radius in CSS px. */ r: number; - /** Base alpha 0..0.9 (brightness times how dark the sky is there). */ - alpha: number; - /** CSS colour, white tinted blue or warm. */ + /** CSS colour of the star's centre at base brightness: the display of the sky behind it plus the star, through the sky's own display. */ fill: string; - /** The sky gradient's colour at this height: dimming paints it over the baked star. */ + /** CSS colour of the sky behind it, through the same display: twinkling paints it over the baked star first. */ cover: string; -} - -const luma = (c: Srgb) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; -const lerp = (a: number, b: number, t: number) => a + (b - a) * t; - -/** The baked gradient's colour at fraction t of the canvas height (the canvas interpolates in sRGB). */ -function skyAt(sky: SkyColours, t: number): Srgb { - const mix = (a: Srgb, b: Srgb, k: number): Srgb => [ - Math.round(lerp(a[0], b[0], k)), - Math.round(lerp(a[1], b[1], k)), - Math.round(lerp(a[2], b[2], k)), - ]; - if (t <= SKY_STOPS.mid) return mix(sky.top, sky.mid, t / SKY_STOPS.mid); - if (t <= SKY_STOPS.horizon) - return mix(sky.mid, sky.horizon, (t - SKY_STOPS.mid) / (SKY_STOPS.horizon - SKY_STOPS.mid)); - return sky.horizon; -} - -export const skyLuma = (sky: SkyColours, t: number): number => luma(skyAt(sky, t)); -export const isNight = (sky: SkyColours): boolean => luma(sky.top) < NIGHT_LUMA; - -/** mulberry32: 32-bit seeded PRNG, one float in [0, 1) per call. */ -function prng(seed: number) { - let a = seed >>> 0; - return () => { - a = (a + 0x6d2b79f5) >>> 0; - let t = a; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; + /** The star's centre colour with its radiance multiplied by `gain` (scintillation). */ + shade: (gain: number) => string; } /** Stateless seeded hash of up to three integers to [0, 1). */ @@ -78,49 +36,6 @@ export function hash(a: number, b = 0, c = 0): number { return (h >>> 0) / 4294967296; } -/** How many stars a viewport carries: about one per 1100 CSS px squared, 150..MAX_STARS. */ -export const starCount = (cssW: number, cssH: number): number => - Math.min(MAX_STARS, Math.max(150, Math.round((cssW * cssH) / 1100))); - -/** - * Seeded placement. Each candidate draws all its random numbers whether it is kept or not, so a - * given seed and sky always give the same field and the prefix does not shift with the count. - * Heights are squeezed toward the zenith (y = 0.78 u^1.7) and alpha falls with the sky's luma, so - * the stars thin out and fade into the horizon glow. None for a day sky. - */ -export function makeStars(sky: SkyColours, cssW: number, cssH: number): Star[] { - if (!isNight(sky)) return []; - const rnd = prng(SEED); - const n = starCount(cssW, cssH); - // Every candidate draws all its numbers, kept or not, so the prefix is stable. - const candidates = Array.from({ length: MAX_STARS }, () => ({ - x: rnd(), - y: SKY_STOPS.horizon * rnd() ** 1.7, - r: 0.35 + 1.0 * rnd() ** 4, - bright: 0.35 + 0.65 * rnd() ** 1.5, - tint: rnd(), - })).slice(0, n); - return candidates.flatMap(({ x, y, r, bright, tint }) => { - const alpha = Math.min(0.9, bright * Math.max(0, 1 - skyLuma(sky, y) / NIGHT_LUMA)); - if (alpha < 0.05) return []; - // White, pulled toward blue or toward warm by the tint draw. - const to: Srgb = tint < 0.5 ? [165, 195, 255] : [255, 222, 185]; - const k = 0.55 * Math.abs(tint - 0.5) * 2; - const c = [255, 255, 255].map((v, j) => Math.round(lerp(v, to[j], k))); - const s = skyAt(sky, y); - return [ - { - x, - y, - r, - alpha, - fill: `rgb(${c[0]},${c[1]},${c[2]})`, - cover: `rgb(${s[0]},${s[1]},${s[2]})`, - }, - ]; - }); -} - // ---- The schedule --------------------------------------------------------------------------- export const slotCount = (stars: number): number => Math.min(SLOTS, stars); @@ -199,7 +114,7 @@ export function activeAt(stars: number, t: number): Twinkling[] { // ---- Drawing -------------------------------------------------------------------------------- -/** Bake `stars` into `ctx` (canvas `w` x `h` device px, `scale` device px per CSS px) at base alpha. */ +/** Bake `stars` into `ctx` (canvas `w` x `h` device px, `scale` device px per CSS px) at base brightness. */ export function drawStars( ctx: CanvasRenderingContext2D, stars: readonly Star[], @@ -208,19 +123,16 @@ export function drawStars( scale: number ) { stars.forEach((s) => { - ctx.globalAlpha = s.alpha; ctx.fillStyle = s.fill; ctx.beginPath(); ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI); ctx.fill(); }); - ctx.globalAlpha = 1; } /** - * The overlay pass: clear, then for each active star whose gain is off base, paint over the baked - * star. Dimming covers it with the sky's own colour at (1 - gain), which leaves exactly - * alpha * gain of the star; brightening adds a second star on top. A star at base draws nothing. + * 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 + * at the gain. A star at base draws nothing. */ export function drawTwinkle( ctx: CanvasRenderingContext2D, @@ -234,16 +146,13 @@ export function drawTwinkle( active.forEach((a) => { const s = stars[a.star]; if (!s || Math.abs(a.gain - 1) < 0.01) return; - if (a.gain < 1) { - ctx.globalAlpha = 1 - a.gain; - ctx.fillStyle = s.cover; - } else { - ctx.globalAlpha = Math.min(1, ((a.gain - 1) * s.alpha) / (1 - s.alpha)); - ctx.fillStyle = s.fill; - } + ctx.fillStyle = s.cover; ctx.beginPath(); - ctx.arc(s.x * w, s.y * h, s.r * scale + (a.gain < 1 ? 1 : 0), 0, 2 * Math.PI); + ctx.arc(s.x * w, s.y * h, s.r * scale + 1, 0, 2 * Math.PI); + ctx.fill(); + ctx.fillStyle = s.shade(a.gain); + ctx.beginPath(); + ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI); ctx.fill(); }); - ctx.globalAlpha = 1; }