Compare commits

..
Author SHA1 Message Date
Meta Vens
069df981f9 ridge-bake tests: r_max at R = d, the 0.1 seam-prior pin back where it holds, tighter albedo bounds
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m34s
The 0.1 pin is back on the 3-12, 4-15/10 and 6-14 km fixtures; 0.04 stays on 4-15/6, 5-30 and 8-40 (closing the seam on the ring tears them above it). Albedo: mean 0.021, p99 0.081 (measured maxima 0.0202, 0.0806).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 22:48:46 +01:00
Meta Vens
30e4ee549a ridge-bake: r_max_m fits each card tile's linear map at its own distance (R = d)
The per-column median distances inside a tile are no longer part of the fit: the card sits at the tile's distance_m, as ruling ridge-offset-range-fit has it. Vienna's r_max_m is 98.2 m (was 56.1).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 22:48:46 +01:00
Meta Vens
920e37e385 ridge-bake tests: pin the tile cut, the ring anchors and the apron against mutants; mutate.py takes name filters
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 22:10:31 +01:00
Meta Vens
dbef945493 ridge-bake: README and places.json for the ring, tiles and r_max_m
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 21:25:12 +01:00
Meta Vens
65db62c986 ridge-bake: the ring is the bake, 32 azimuth tiles per card (schema 3)
The 72 degree window and the baked camera are deleted. The march's 6400 columns are the bake: seams run periodic round the ring (DP over three laps, middle kept), ridge.cards runs per tile on 204 columns with the matching normals, and the vertical anchors read the skyline of the whole ring. Each card tile carries its own distance_m; camera.r_max_m is the largest offset the per-card linear slide fits within 24 card px (and the resident gate allows). Tile, place and resident budgets replace the window's. Manifest schema 3, baker version 4. Tests and mutants rewritten for the ring.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 21:25:09 +01:00
d851a5fca9 Merge pull request 'Sky menu: Auto, six named moments and a free moment, in the place's local time' (#176) from void/sky-menu-moments into dev
All checks were successful
Rat dev preview / Build dev preview (push) Successful in 3m55s
2026-11-20 23:12:54 +00:00
Meta Vens
cd81f85d05 Sky menu fixes: one owner of the drawn place, Night is tonight's, named moments roll
All checks were successful
Build pull request / Build pull request (pull_request) Successful in 3m32s
- skyPlace.ts is the only writer of the sky's place: the manifest's when the cards load, FALLBACK_VIEW's
  when the manifest or cards fail; the scene draws the view it told the store, so sky, weather, ink and
  Auto agree on every drawn state (Auto ticks on the fallback).
- useSkyPlace removed: only a scene start fetches the manifest.
- Old-key migration writes the new key first; a refused write keeps the pick for the page load.
- A named moment re-resolves when the place-local day rolls over (the one timer); Night is the nearest
  solar midnight (before the day's noon the one just passed or coming), keyed by the instant drawn.
- Baker validate/schema check place.tz as load_preset does; Vienna manifest baker_version 3 (it carries tz).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 00:07:01 +01:00
Meta Vens
3269250d19 Scene README: the sky choice, the moment authority and place.tz
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:42:49 +01:00
Meta Vens
e948f99f9e Sky menu: Auto, six named moments and a free moment picker
Seven radio items plus Pick a moment, which opens a date input and a 5-minute time slider that show the
place-local time and zone and commit on the native change event (slider release), never per input tick.
The picker opens from the moment being drawn, in the place zone (seedFree).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:42:48 +01:00
Meta Vens
4597539976 Tests and look sheet follow the moment authority
Tests move to SkyChoice and the sun-taking makePhysicalSky; the harness sheet takes the six named moments
on both solstices (?named=1).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:36:08 +01:00
Meta Vens
ca77bacb4a Sky choice store: Auto, named or free moment resolved at the loaded place
skyState.ts holds the choice, the place and the lines and resolves the band through momentFor and skyBand;
resolveSkyState, LAT and the page-zone clock approximation are deleted. skyPlace.ts shares the manifest with
the scene; hooks, theme and ink take an undefined sky until a place is known. Old 'ratatoskr.skyState' is read
once and removed; the choice persists as 'ratatoskr.skyChoice'.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:36:06 +01:00
Meta Vens
8e44479792 Place carries its time zone: baker writes place.tz, manifest parses it
places.json tz per preset, load_preset refuses a missing or unknown zone, schema regenerated,
BAKER_VERSION 3; runtime rejects a zone Intl does not know; Vienna manifest gains the one line.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:23:26 +01:00
Meta Vens
fbe9c9a930 Sky moment authority: skyMoment.ts decides the drawn instant; sunForState deleted
momentFor(choice, place, now) and skyBand are the one owner of the instant and the band.
sunAt.ts loses STATE_ELEVATION, solarNoon and sunForState; makePhysicalSky takes the sun it is given.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 23:23:24 +01:00
43 changed files with 2453 additions and 901 deletions

View file

@ -46,4 +46,4 @@ Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named
| painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 |
| painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 |
Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).
Named moments (`ridgeSheet.html?named=1`): the six moments of the Sky menu (dawn, morning, noon, golden hour, dusk, night) at the baked place on the December and June solstices, drawn from `momentFor` as the app draws them (`SKY_MOMENTS` in `ridge/skyMoment.ts` is the table tuned by eye from this sheet). Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation).

View file

@ -17,8 +17,7 @@ import { nightBodies, onScreen, paintNightBodies } from '../../src/app/features/
import { sunAt } from '../../src/app/features/scene/ridge/sunAt';
import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue';
import { moonPhase } from '../../src/sky/moon.js';
import { DAY_FROM } from '../../src/app/features/scene/skyState';
import type { FixedSkyState } from '../../src/app/features/scene/skyState';
import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment';
const DIR = '/public/ridge/vienna-6815bb9dca99/';
@ -38,7 +37,7 @@ interface Column {
time?: Date;
}
/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. Elevation picks the display budget (day from DAY_FROM, night below its negative). */
/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. The band of the elevation (`skyBand`) picks the display budget. */
const SKIES: Column[] = [
{ label: 'dawn 2 deg', elevation: 2, azimuth: 100 },
{ label: 'morning 15 deg', elevation: 15, azimuth: 135 },
@ -138,6 +137,14 @@ function momentsFrom(params: URLSearchParams, place: Parameters<typeof sunAt>[0]
if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`);
return { label: fmt(time), time };
});
// `named=1`: the six named moments of the sky menu (`momentFor`, as the app draws them) on both solstices at the place: the look sheet the elevation table is tuned from.
if (params.get('named'))
return ['2026-12-21', '2026-06-21'].flatMap((day) =>
MOMENT_IDS.map((id) => {
const time = momentFor({ kind: 'named', id }, place, new Date(`${day}T12:00:00Z`));
return { label: `${id} ${day.slice(5)} ${fmt(time)}`, time };
})
);
if (!params.get('night')) return undefined;
const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date();
const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number);
@ -176,9 +183,6 @@ const W = Number(q.get('w') ?? 480);
const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16);
const root = document.getElementById('sheet') as HTMLElement;
const stateOf = (el: number): FixedSkyState =>
el >= DAY_FROM ? 'day' : el <= -DAY_FROM ? 'night' : 'dusk';
async function main() {
const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR);
const blobs = await Promise.all(
@ -213,7 +217,7 @@ async function main() {
col.time !== undefined
? sunAt(view.place, col.time)
: { elevation: col.elevation as number, azimuth: col.azimuth as number, time };
const physical = makePhysicalSky(stateOf(sun.elevation), time, 0, view, sun);
const physical = makePhysicalSky(sun, 0, view);
const px = paintSky(physical, W, H, win.camera);
const bodies = nightBodies(physical, px, withLines);
const small = document.createElement('canvas');

View file

@ -1,6 +1,6 @@
{
"schema": 2,
"baker_version": 2,
"baker_version": 3,
"bake_id": "6815bb9dca99",
"place": {
"id": "vienna",
@ -8,7 +8,8 @@
"lat": 48.1929826,
"lon": 16.3534237,
"altitude_km": 0.18330000000000002,
"eye_m": 213.3
"eye_m": 213.3,
"tz": "Europe/Vienna"
},
"view": {
"look_az_deg": 214.0,

View file

@ -1,6 +1,6 @@
# ridge-bake
Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams, plus a `manifest.json` (schema 2) and an `index.json` that the runtime reads. Each card is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked.
Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams and cut into 32 azimuth tiles round the whole 360 degree ring, plus a `manifest.json` (schema 3) and an `index.json` that the runtime reads. Each card tile is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked.
## Run
@ -8,7 +8,7 @@ Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffe
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
```
Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet (the composite, every card alone and the depth image with every seam, lit by one fixed light). `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet at 1/4 of the ring's width (the ring composite, every card's strip alone and the depth image with every seam, the 32 tile boundaries drawn, lit by one fixed light). The bake prints `r_max_m`, the resident run and the worst fit error per card. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
Tests: `RIDGE_PY=<python> RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py]` (`mutate.py` re-introduces each rule's failure into a copy of the baker and fails if a test does not notice).
@ -31,13 +31,16 @@ Files are `Copernicus_DSM_COG_10_<N|S>dd_00_<E|W>ddd_00_DEM.tif`; the list below
1. **March.** `stage0` marches 6400 azimuth columns of rays over the DEM with Earth curvature and refraction (`ridge.elev`), cached by a key of its inputs.
2. **Low-pass.** `prefilter` blurs the sampled heights with a Gaussian of `prefilter_m` metres along each ray and across rays at equal distance (sigma = `prefilter_m` / (distance x column width) columns), then recomputes the angles. Roofs go, hills stay.
3. **View.** `set_view` maps angle to row linearly: the highest skyline angle in the window sits at 4% of the frame height, the lowest at 66%, clamped to 1x to 10x vertical exaggeration.
4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1.
5. **Cards.** `cards` makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall` (card 0 has none: its rows there are the ground). The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a bake that differs by more than 0.02.
6. **Camera.** `CAMERA_R_M` (+200 m, signed: + forward, - backward; `camera_r_m` in `places.json` per place) and `HEADING_MAX_DEG` (23) are the camera on a circle round the bake centre (ruling `ridge-camera-on-circle`). `pack` gives each card `distance_m` (the median distance of its solid pixels that are not wall; `median_m` is the same number) and `scale = distance_m / (distance_m - r)`, the card's pan rate per unit of heading and its static size. It refuses `|r|` at or above half the nearest card's distance, a card with no solid terrain apart from its wall, and (in `write_bake`) a camera that lifts the nearest card off the frame bottom (every backward `r`: the bake is not wider and taller yet) or shrinks a card below what a 16:9 viewport needs at rest.
7. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
3. **View.** `set_view` maps angle to row linearly: the highest skyline angle of the whole ring sits at 4% of the frame height, the lowest at 66%, clamped to 1x to 10x vertical exaggeration (ruling `ridge-ring-vertical-anchors`: every azimuth sits inside one frame).
4. **Seams.** `coverage` counts the visible rows of the opaque view per log-distance bin and column. `seams` finds one seam per authored split per column by dynamic programming (seam carving, forward energy): it sits in a gap between depths, moving it costs 2 per bin plus the visible rows it sweeps (so it never hops across a ridge between two columns and splits it side by side), a seam inside visible terrain is cheap to cross-fade, the authored depth only breaks ties. Seam k stays 0.4 nat beyond seam k-1. The DP runs over the ring three times side by side and keeps the middle lap, so a seam is continuous across the wrap (column 6399 to 0) and a tile boundary is only a crop.
5. **Cards.** `cards` runs per tile, on that tile's columns and the matching normals (it is column-independent: a tile is a crop of per-column results, so no seam appears at a tile boundary). It makes card i from the first visible hit at or beyond seam i-1 (layered depth: a farther card keeps the terrain a nearer ridge hides), alpha 1 minus a smoothstep over seam i in log-distance (the cross-fade), crest rows with fractional coverage, distance and normal interpolated between samples by angle, albedo from a small height and slope material, cropped to the rows where alpha is not zero. The rows of card i > 0 below the angle of its first sample (hit and first sample of the card) are its **wall**: the extruded face of the ridge the card starts at, which keeps that sample's distance, wears the ground material at its height with the face up, and is flagged `wall` (card 0 has none: its rows there are the ground). The alpha-over composite of the cards equals the opaque view; `check_cover` refuses a tile that differs by more than 0.02.
6. **Tiles.** The ring is absolute compass, column 0 = north, column c at azimuth (c + 0.5) / 6400 x 360; `places.json`'s `az_deg` / `look_at` is only the rest azimuth (`view.look_az_deg`). Tile t owns columns [200 t, 200 t + 200) (11.25 degrees) and its files hold [200 t - 2, 200 t + 202): two columns of real neighbour data each side (the client's ink pass and lighting read one texel each way; the client crops it), taken periodically by `ridge.ring_cols`. Per card and tile the file is cropped to the rows where that tile's 8-bit alpha is not zero (`top`, `h`); a card that holds nothing in a tile is `null` there (the client interpolates its distance from the neighbours); a card with no solid pixel in any tile is refused.
7. **Distance and the offset range.** The bake holds no camera (ruling `ridge-camera-full-ring`). `pack` gives each card tile `distance_m` = exp(median ln d) over the tile's solid pixels that are not wall (its interior 200 columns); the client derives each card's slide from that and the viewer's offset r and heading. `camera.r_max_m` is the largest |r| (never above half the nearest card's smallest tile distance) at which, for every tile, card and phi (24 steps of the camera's angle on the circle against its heading), the least-squares line `a + s beta` fitted to the exact view angle `atan2(R sin beta - r sin phi, R cos beta - r cos phi)` over the widest viewport (`HFOV_MAX_DEG` = 72 / 1.1) errs by at most `FIT_PX_MAX` = 24 card px; the card sits at the tile's `distance_m` (R = d) and the line is fitted for that same distance, and the resident gate (below) must hold at r_max_m too. `FIT_PX_MAX` is provisional, tuned by eye (ruling `ridge-offset-range-fit`). A bake whose `r_max_m` is below `R_MAX_FLOOR_M` = 25 m is refused, naming the card and tile.
8. **Normals.** `normals` takes the along-ray slope and the across-ray slope at equal distance (neighbouring columns, same sample), both times the vertical exaggeration.
Files per card `i`: `card-<i>-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card-<i>-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches). The manifest lists the cards nearest first with their row band (`top`, `h`), median seam depths, `distance_m`, `scale` and files, and the `camera` {`r_m`, `heading_max_deg`}; the runtime paints the list last to first. `check_budget` refuses more than `MAX_CARDS` cards, more than 1.5 MB of card files, or more than 20 MB decoded (2 textures x width x band rows x 4 bytes per card); a cap is never raised to fit a bake.
Files per card `i` and tile `t`: `card-<i>-t<tt>-colour.webp` (lossy RGB albedo, lossless straight alpha) and `card-<i>-t<tt>-geometry.webp` (lossless: R, G = (n + 1) / 2 for the normal's along and across components, B = log-distance normalised between `encoding.log_d_min` and `log_d_max`; wall pixels write R = G = 255, a code outside the unit disc that no real normal reaches), each 204 columns wide. The manifest lists the cards nearest first (`near_m`, `far_m`: the median seam depths over the ring) and `tiles[t][i]` = `{ top, h, distance_m, colour, geometry }` or `null`; the runtime paints the cards last to first. The `bake_id` is the sha256 of the files, tile-major, then card, colour then geometry.
Budgets (`check_budget`; a cap is never raised to fit a bake, the lever is `TILES` = 64): every file of one tile at most 235 kB (1.5 MB per 72 degrees), every file of the place at most 7.5 MB, at most 6 cards, and the lit canvases (4 bytes x 202 columns x band rows, per card) of the worst run of N consecutive tiles, cyclic, at most 20 MB, where N = ceil(arc_max / 11.25) + 5 and arc_max = `HFOV_MAX_DEG` / s_min + 2 (r_max / Rmin) 57.3 degrees with Rmin the nearest card's smallest tile distance and s_min = Rmin / (Rmin + r_max). The loader decodes one tile at a time, so the decode transient is not gated.
## Licence

View file

@ -1,28 +1,34 @@
"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards (colour + geometry WebP each), a manifest v2 and the index.
"""Ridge backdrop export: bake a place with ridge.py and write its K+1 G-buffer cards as 32 azimuth tiles each (colour + geometry WebP per card per tile), a manifest v3 and the index.
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
python3 -I scripts/ridge-bake/export.py --write-schema (rewrites ridge-bake.schema.json from SCHEMA below)
The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake; the camera (ruling ridge-camera-on-circle) is the baker's, so per-card scale and the heading range ride the manifest; it lights the cards itself (ruling ridge-cards-runtime-lit). The pure parts (budget, bake_id, manifest, index, schema check)
import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work)."""
The runtime reads manifest.json (SCHEMA is its contract) and nothing else about the bake. The ring is the whole 360 degrees (ruling ridge-camera-full-ring), absolute compass, column 0 = north, cut into TILES tiles of TILE_W columns plus an APRON of real neighbour
columns each side; the bake holds no camera: it ships each card tile's distance_m and camera.r_max_m, the largest offset the per-card linear slide can take (ruling ridge-offset-range-fit); the client lights the cards itself (ruling ridge-cards-runtime-lit).
The pure parts (budget, bake_id, manifest, index, schema check) import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work)."""
import os, sys, json, math, shutil, hashlib, argparse, tempfile
from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import numpy as np, imagecodecs
BAKER_VERSION = 2
WINDOW_DEG = 72
PLANE_W = 1280 # every card is the whole 72 deg window wide
PLANE_W_MAX = 4096
MAX_CARDS = 6 # per place; a full-frame card decodes to 2 textures x 1280 x 600 x 4 B = 6.1 MB, the decode budget below holds 3 of them and cropping to the row band is what lets a livelier place have more
TOTAL_BYTES_MAX = 1_500_000 # every card file of a place together
DECODE_BYTES_MAX = 20_000_000 # the cards decoded: sum over cards of 2 textures x w x band h x 4 bytes
COVER_TOL = 0.02 # the composite of the cards may differ from the opaque view by this much of a pixel, nowhere more
CAMERA_R_M = 200.0 # ruling ridge-camera-on-circle: the camera sits on a circle of this radius round the bake centre, signed, + forward along its heading and - backward; places.json may set camera_r_m per place. The steward's calibration for feel, tuned in the art pass
HEADING_MAX_DEG = 23.0 # the drift's heading range each side of look_az: today's phone sweep, 409 card px (the runtime caps it by what a viewport can cover)
R_FRAC_MAX = 0.5 # |r| stays under this share of the nearest card's distance: the offset must stay well inside the nearest cylinder
REST_SCALE_MIN = 1 / 1.1 # a 16:9 viewport is width-bound and the runtime's plane is 1.1 viewport widths wide (view.ts windowFor, DRIFT_FRAC 0.05 a side): a card scaled below this leaves the viewport's edge bare at rest
BAKER_VERSION = 4
RING_W = 6400 # the ring's columns (ridge.W, asserted in bake_place): column c is at azimuth (c + 0.5) / RING_W x 360, column 0 = north
TILES = 32 # azimuth tiles of the ring, each card cut into TILES files per kind (ruling ridge-camera-full-ring: the client loads the arc near its heading)
TILE_W = RING_W // TILES # 200 columns = 11.25 degrees owned by a tile
APRON = 2 # real neighbour columns each side in a tile's file: the client's ink pass and lighting read +-1 texel; the client crops it
LIT_W = TILE_W + 2 # a lit canvas keeps one apron texel each side
TILE_DEG = 360.0 / TILES
MAX_CARDS = 6 # per place; a card is cropped to its row band in every tile, which is what lets a livelier place have more
TILE_BYTES_MAX = 235_000 # every file of one tile (1.5 MB per 72 degrees, scaled to 11.25)
PLACE_BYTES_MAX = 7_500_000 # every file of the place
RESIDENT_BYTES_MAX = 20_000_000 # the lit canvases (4 B x LIT_W x band h per card) of the worst run of consecutive tiles, cyclic; the loader decodes one tile at a time, so the decode transient is not gated
HFOV_MAX_DEG = 72 / 1.1 # the widest viewport: a 16:9 viewport with 1.1 widths of plane (view.ts windowFor)
FIT_PX_MAX = 24.0 # the per-card linear slide may err by this many card pixels over the viewport (provisional, tuned by eye: ruling ridge-offset-range-fit)
R_MAX_FLOOR_M = 25.0 # a bake whose cards cannot take this offset is refused
PHI_STEPS = 24 # the camera's angle on its circle against its heading, sampled by the r_max search
COVER_TOL = 0.02 # the composite of a tile's cards may differ from the opaque view by this much of a pixel, nowhere more
WEBP_QUALITY = 80
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
SHEET_LIGHT = (-0.35, 0.55, 0.76) # the fixed light of the contact sheet in (along ray, across ray, up); the sheet is a look at the cards, the client lights the real thing
@ -35,26 +41,34 @@ ATTRIBUTION = dict(
# ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from)
_num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'}
_numnull = {'type': ['number', 'null']}
_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
def _objnull(**props): return dict(_obj(**props), type=['object', 'null'])
_file = _obj(file=_str, bytes=_int)
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v2 and index v1', '$defs': {
'manifest': _obj(schema={'const': 2}, baker_version=_int, bake_id=_str,
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num),
view=_obj(look_az_deg=_num, window_deg={'const': WINDOW_DEG}, plane_w={'type': 'integer', 'maximum': PLANE_W_MAX}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v3 and index v1', '$defs': {
'manifest': _obj(schema={'const': 3}, baker_version=_int, bake_id=_str,
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz),
view=_obj(look_az_deg=_num, ring_w={'const': RING_W}, tile_w={'const': TILE_W}, tiles={'const': TILES}, apron={'const': APRON}, plane_h=_int, px_per_deg_h=_num, px_per_deg_v=_num, exaggeration=_num, horizon_row=_num, sky_row=_num, near_row=_num),
curvature=_obj(r_earth_m=_num, k_ref=_num),
encoding=_obj(log_d_min=_num, log_d_max=_num, normal={'const': 'rt8'}),
camera=_obj(r_m=_num, heading_max_deg=_num),
cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': dict(_obj(top=_int, h=_int, near_m=_numnull, far_m=_numnull, median_m=_num, distance_m=_num, scale=_num, colour=_file, geometry=_file),
description="nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size.")},
w=_int, h=_int, bytes=_int,
camera=_obj(r_max_m=_num),
cards={'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _obj(near_m=_numnull, far_m=_numnull),
'description': "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."},
tiles={'type': 'array', 'minItems': TILES, 'maxItems': TILES, 'items': {'type': 'array', 'minItems': 1, 'maxItems': MAX_CARDS, 'items': _objnull(top=_int, h=_int, distance_m=_num, colour=_file, geometry=_file)},
'description': "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are not wall (the interior tile_w columns)."},
bytes=_int,
attribution=_obj(credit_line=_str, licence=_str, dem_source=_str, url=_str)),
'index': _obj(schema={'const': 1}, default=_str, places={'type': 'object', 'additionalProperties': _str})}}
def tile_file(i, t, kind): return f'card-{i}-t{t:02d}-{kind}.webp'
def validate(x, s, path='$'):
"""The subset of JSON Schema SCHEMA uses; raises ValueError naming the path."""
if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path)
tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)}
if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}')
if s.get('format') == 'iana-tz':
try: ZoneInfo(x)
except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f'{path}: {x!r} is not a time zone the system knows')
if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}")
if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}')
if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}')
@ -70,6 +84,18 @@ def validate(x, s, path='$'):
elif extra is False: raise ValueError(f'{path}: extra key {k}')
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
def validate_manifest(m):
"""The schema plus what it cannot say: every tile lists one entry per card, every card holds something in some tile, each file is named for its card and tile, bytes is the sum of the files."""
validate(m, SCHEMA['$defs']['manifest']); k = len(m['cards'])
for t, row in enumerate(m['tiles']):
if len(row) != k: raise ValueError(f'$.tiles[{t}]: {len(row)} entries for {k} cards')
for i, e in enumerate(row):
for kind in (('colour', 'geometry') if e else ()):
if e[kind]['file'] != tile_file(i, t, kind): raise ValueError(f'$.tiles[{t}][{i}].{kind}: file {e[kind]["file"]!r} is not {tile_file(i, t, kind)!r}')
for i in range(k):
if all(row[i] is None for row in m['tiles']): raise ValueError(f'card {i} is null in every tile')
if m['bytes'] != sum(e[kind]['bytes'] for row in m['tiles'] for e in row if e for kind in ('colour', 'geometry')): raise ValueError('bytes is not the sum of the files')
# ------------------------------------------------------------------------------------ cards -> bytes
def u8(a): return np.clip(np.rint(np.asarray(a) * 255.0), 0, 255).astype(np.uint8)
def encode_colour(albedo, alpha):
@ -96,47 +122,92 @@ def check_cover(cards, opaque, tol=COVER_TOL):
err = np.abs(composite_alpha(cards, *opaque.shape) - opaque); bad = err > tol
if bad.any(): y, x = np.unravel_index(int(np.argmax(err)), err.shape); raise ValueError(f'the cards do not composite to the opaque view within {tol}: {int(bad.sum())} pixels differ, worst {err.max():.3f} at x={x} row {y}')
def check_budget(card_bytes, w, bands):
"""Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a card wider than PLANE_W_MAX, every card file together above TOTAL_BYTES_MAX, or the cards decoding (2 textures x w x band rows x 4 bytes each) above DECODE_BYTES_MAX."""
if len(card_bytes) > MAX_CARDS: raise ValueError(f'{len(card_bytes)} cards, above {MAX_CARDS}')
if w > PLANE_W_MAX: raise ValueError(f'card width {w} above {PLANE_W_MAX}')
if sum(card_bytes) > TOTAL_BYTES_MAX: raise ValueError(f'the cards are {sum(card_bytes)} bytes, above {TOTAL_BYTES_MAX}')
decoded = sum(2 * w * h * 4 for h in bands)
if decoded > DECODE_BYTES_MAX: raise ValueError(f'the cards decode to {decoded} bytes, above {DECODE_BYTES_MAX}')
def run_tiles(r_max_m, rmin_m):
"""N, the consecutive tiles the loader keeps resident: the viewport arc at the smallest slide rate plus the offset's own swing (arc_max = HFOV_MAX_DEG / s_min + 2 (r_max / Rmin) 57.3 degrees, s_min = Rmin / (Rmin + r_max)), one straddled tile and two tiles of margin each side."""
s_min = rmin_m / (rmin_m + r_max_m); arc = HFOV_MAX_DEG / s_min + 2 * (r_max_m / rmin_m) * 57.3
return min(TILES, math.ceil(arc / TILE_DEG) + 1 + 4)
def resident_bytes(bands, n):
"""The lit canvases (4 bytes x LIT_W x band rows, per card) of the worst run of n consecutive tiles of the ring, wrapping. bands[t]: the row counts of the cards that tile holds."""
per = [sum(4 * LIT_W * h for h in b) for b in bands]; n = min(n, TILES)
return max(sum(per[(t + k) % TILES] for k in range(n)) for t in range(TILES))
def check_budget(n_cards, tile_bytes, bands, r_max_m, rmin_m):
"""Refuse a bake the runtime could not hold: more than MAX_CARDS cards, a tile whose files together are above TILE_BYTES_MAX, every file of the place above PLACE_BYTES_MAX, or the worst run of run_tiles(r_max_m, rmin_m) consecutive tiles lit above RESIDENT_BYTES_MAX."""
if n_cards > MAX_CARDS: raise ValueError(f'{n_cards} cards, above {MAX_CARDS}')
for t, b in enumerate(tile_bytes):
if b > TILE_BYTES_MAX: raise ValueError(f'tile {t} is {b} bytes, above {TILE_BYTES_MAX}')
if sum(tile_bytes) > PLACE_BYTES_MAX: raise ValueError(f'the place is {sum(tile_bytes)} bytes, above {PLACE_BYTES_MAX}')
n = run_tiles(r_max_m, rmin_m); res = resident_bytes(bands, n)
if res > RESIDENT_BYTES_MAX: raise ValueError(f'{n} consecutive tiles light to {res} bytes, above {RESIDENT_BYTES_MAX}')
def card_scales(distances, r_m):
"""scale_i = d_i / (d_i - r) for the cards' distances (m), nearest first: the card's pan rate per unit of heading and its static size seen from a camera r metres along its heading (ruling ridge-camera-on-circle; + forward, - backward). Refuses |r| >= R_FRAC_MAX x the nearest distance."""
if abs(r_m) >= R_FRAC_MAX * min(distances): raise ValueError(f"the camera offset {r_m:g} m is not under {R_FRAC_MAX} x the nearest card's distance {min(distances):g} m")
return [d / (d - r_m) for d in distances]
def check_camera(scales, tops, bands, view):
"""Refuse a camera whose scaled cards leave the frame uncovered: the nearest card, scaled about the horizon row, must still reach the frame bottom (a backward camera shrinks it away), and no card may be smaller than REST_SCALE_MIN (a 16:9 viewport's edge)."""
hr = view['horizon_row']; bottom = hr + (tops[0] + bands[0] - hr) * scales[0]
if bottom < view['plane_h'] - 1e-6: raise ValueError(f"the camera lifts the nearest card to row {bottom:.1f}, off the frame bottom (row {view['plane_h']})")
if min(scales) < REST_SCALE_MIN: raise ValueError(f'a card scaled {min(scales):.3f} cannot cover a 16:9 viewport at rest (below {REST_SCALE_MIN:.3f})')
def fit_px(d, r, px_per_deg):
"""The worst error, in card pixels, of a card tile's linear slide at offset r (m): over the camera's angle phi on its circle against its heading (PHI_STEPS) and the viewport (beta in +-HFOV_MAX_DEG / 2), the exact view angle of a cylinder point at the tile's
distance d, alpha = atan2(d sin beta - r sin phi, d cos beta - r cos phi), against the least-squares line a + s beta fitted to it (ruling ridge-offset-range-fit)."""
b = np.radians(np.linspace(-HFOV_MAX_DEG / 2, HFOV_MAX_DEG / 2, 33))[None, :]; p = np.linspace(0, 2 * math.pi, PHI_STEPS, endpoint=False)[:, None]
A = np.arctan2(d * np.sin(b) - r * np.sin(p), d * np.cos(b) - r * np.cos(p)); bc = b - b.mean(); s = (A * bc).sum(-1, keepdims=True) / (bc * bc).sum(); line = A.mean(-1, keepdims=True) + s * bc
return math.degrees(float(np.abs(A - line).max())) * px_per_deg
def fit_table(dist, r, px_per_deg):
"""(tiles, cards) fit_px of every card tile at offset r; nan where the card is null in that tile."""
return np.array([[np.nan if d is None else fit_px(d, r, px_per_deg) for d in row] for row in dist])
def solve_r_max(dist, bands, px_per_deg):
"""The largest offset r (m, down to 0.1 m) at which every card tile fits within FIT_PX_MAX and the resident gate holds: never above half the nearest card's smallest tile distance. Scans r upward from 0 on 128 steps to the first failure, then bisects that step.
Refuses (naming the card and tile that bind) a bake whose r_max_m is below R_MAX_FLOOR_M."""
near = min((row[0], t) for t, row in enumerate(dist) if row[0] is not None); rmin = near[0]; cap = 0.5 * rmin
ok = lambda r: bool(np.nanmax(fit_table(dist, r, px_per_deg)) <= FIT_PX_MAX) and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX
lo, hi = 0.0, None
for r in np.linspace(0, cap, 129)[1:]:
if ok(r): lo = float(r)
else: hi = float(r); break
if hi is None: lo = cap
else:
for _ in range(24):
mid = 0.5 * (lo + hi)
if ok(mid): lo = mid
else: hi = mid
r_max = math.floor(lo * 10) / 10
if r_max < R_MAX_FLOOR_M:
if cap < R_MAX_FLOOR_M: raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card 0 stands {rmin:.0f} m away in tile {near[1]} and the offset stays under half of that')
tb = fit_table(dist, R_MAX_FLOOR_M, px_per_deg); t, i = np.unravel_index(int(np.nanargmax(tb)), tb.shape)
if tb[t, i] > FIT_PX_MAX: raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: card {i} in tile {t} errs {tb[t, i]:.1f} card px at {R_MAX_FLOOR_M:g} m (the bound is {FIT_PX_MAX:g})')
n = run_tiles(R_MAX_FLOOR_M, rmin); raise ValueError(f'r_max_m {r_max:g} is below {R_MAX_FLOOR_M:g} m: at {R_MAX_FLOOR_M:g} m, {n} consecutive tiles light to {resident_bytes(bands, n)} bytes, above {RESIDENT_BYTES_MAX}')
return r_max
def bake_id(cards):
"""First 12 hex of sha256 over the card files in index order, colour then geometry. cards: [(colour bytes, geometry bytes)]."""
def bake_id(files):
"""First 12 hex of sha256 over the tile files, tile-major then card, colour then geometry (a null card tile writes none). files: [(colour bytes, geometry bytes)] in that order."""
h = hashlib.sha256()
for colour, geometry in cards: h.update(colour); h.update(geometry)
for colour, geometry in files: h.update(colour); h.update(geometry)
return h.hexdigest()[:12]
def write_bake(out, place, view, meta, cards, opaque, default=None):
"""Write out/<place>-<bake_id>/ (card WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. cards: [dict(top, colour bytes, geometry bytes, near_m, far_m, median_m, distance_m, scale)], nearest first; opaque (h, w) is
the opaque view's coverage. Refuses before writing a bake whose files decode to different sizes, leave the frame or the view's plane_h, break the budget or composite away from the opaque view. meta: dict(curvature, encoding, camera dict(r_m, heading_max_deg)). Returns the directory."""
dec = [(decode(c['colour']), decode(c['geometry'])) for c in cards]; shapes = {a.shape[:2] for pair in dec for a in pair}; bands = [a.shape[0] for a, _ in dec]
if any(c.shape[:2] != g.shape[:2] for c, g in dec): raise ValueError('a card colour and geometry are not one size')
if len({a.shape[1] for pair in dec for a in pair}) != 1: raise ValueError(f'the cards are not one width: {sorted(shapes)}')
w = dec[0][0].shape[1]; h = view['plane_h']
if any(band < 1 or c['top'] < 0 or c['top'] + band > h for c, band in zip(cards, bands)): raise ValueError(f'a card leaves the {h} rows of the frame')
if opaque.shape != (h, w): raise ValueError(f'the opaque view is {opaque.shape}, the frame {(h, w)}')
sizes = [len(c['colour']) + len(c['geometry']) for c in cards]; check_budget(sizes, w, bands)
check_cover([(c['top'], col[..., 3] / 255.0) for c, (col, _) in zip(cards, dec)], opaque); check_camera([c['scale'] for c in cards], [c['top'] for c in cards], bands, view)
bid = bake_id([(c['colour'], c['geometry']) for c in cards]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name
manifest = dict(schema=2, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_m=meta['camera']['r_m'], heading_max_deg=meta['camera']['heading_max_deg']),
cards=[dict(top=c['top'], h=band, near_m=c['near_m'], far_m=c['far_m'], median_m=c['median_m'], distance_m=c['distance_m'], scale=c['scale'], colour=dict(file=f'card-{i}-colour.webp', bytes=len(c['colour'])), geometry=dict(file=f'card-{i}-geometry.webp', bytes=len(c['geometry'])))
for i, (c, band) in enumerate(zip(cards, bands))], w=w, h=h, bytes=sum(sizes), attribution=ATTRIBUTION)
validate(manifest, SCHEMA['$defs']['manifest']); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
for i, c in enumerate(cards): (tmp / f'card-{i}-colour.webp').write_bytes(c['colour']); (tmp / f'card-{i}-geometry.webp').write_bytes(c['geometry'])
def write_bake(out, place, view, meta, packed, opaque, default=None):
"""Write out/<place>-<bake_id>/ (tile WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. packed: dict(cards [dict(near_m, far_m)], tiles [TILES][cards] of dict(top, colour bytes, geometry bytes, distance_m) or None,
camera dict(r_max_m)); opaque: TILES arrays (plane_h, TILE_W + 2 APRON), each the opaque view's coverage over a tile's columns. Refuses before writing a bake whose files decode to the wrong size, leave the frame, break a budget (the resident gate at r_max_m) or composite
away from the opaque view in any tile. meta: dict(curvature, encoding). Returns the directory."""
cards, tiles, camera = packed['cards'], packed['tiles'], packed['camera']; k = len(cards); h = view['plane_h']; w = TILE_W + 2 * APRON
if len(tiles) != TILES or len(opaque) != TILES or any(len(row) != k for row in tiles): raise ValueError(f'the bake needs {TILES} tiles of {k} cards each')
for i in range(k):
if all(row[i] is None for row in tiles): raise ValueError(f'card {i} is null in every tile')
dec = [[None if e is None else (decode(e['colour']), decode(e['geometry'])) for e in row] for row in tiles]; bands = [[pair[0].shape[0] for pair in row if pair] for row in dec]; tile_bytes = []
for t, (row, drow) in enumerate(zip(tiles, dec)):
tile_bytes.append(sum(len(e['colour']) + len(e['geometry']) for e in row if e))
for i, (e, pair) in enumerate(zip(row, drow)):
if e is None: continue
c, g = pair
if c.shape[:2] != g.shape[:2]: raise ValueError(f'tile {t} card {i}: colour and geometry are not one size')
if c.shape[1] != w: raise ValueError(f'tile {t} card {i} is {c.shape[1]} columns wide, not {w} (tile {TILE_W} + 2 apron {APRON})')
if c.shape[0] < 1 or e['top'] < 0 or e['top'] + c.shape[0] > h: raise ValueError(f'tile {t} card {i} leaves the {h} rows of the frame')
if opaque[t].shape != (h, w): raise ValueError(f'tile {t}: the opaque view is {opaque[t].shape}, the frame {(h, w)}')
rmin = min(row[0]['distance_m'] for row in tiles if row[0]); check_budget(k, tile_bytes, bands, camera['r_max_m'], rmin)
for t, (row, drow) in enumerate(zip(tiles, dec)):
try: check_cover([(e['top'], pair[0][..., 3] / 255.0) for e, pair in zip(row, drow) if e], opaque[t])
except ValueError as ex: raise ValueError(f'tile {t}: {ex}')
bid = bake_id([(e['colour'], e['geometry']) for row in tiles for e in row if e]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name
manifest = dict(schema=3, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, ring_w=RING_W, tile_w=TILE_W, tiles=TILES, apron=APRON), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_max_m=camera['r_max_m']),
cards=[dict(near_m=c['near_m'], far_m=c['far_m']) for c in cards],
tiles=[[None if e is None else dict(top=e['top'], h=pair[0].shape[0], distance_m=e['distance_m'], colour=dict(file=tile_file(i, t, 'colour'), bytes=len(e['colour'])), geometry=dict(file=tile_file(i, t, 'geometry'), bytes=len(e['geometry'])))
for i, (e, pair) in enumerate(zip(row, drow))] for t, (row, drow) in enumerate(zip(tiles, dec))], bytes=sum(tile_bytes), attribution=ATTRIBUTION)
validate_manifest(manifest); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
for t, row in enumerate(tiles):
for i, e in enumerate(row):
if e: (tmp / tile_file(i, t, 'colour')).write_bytes(e['colour']); (tmp / tile_file(i, t, 'geometry')).write_bytes(e['geometry'])
(tmp / 'manifest.json').write_text(json.dumps(manifest, indent=1) + '\n')
idx_path = out / 'index.json'; idx = json.loads(idx_path.read_text()) if idx_path.exists() else dict(schema=1, default=place['id'], places={})
old = idx['places'].get(place['id']); idx['places'][place['id']] = name; idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])
@ -147,33 +218,46 @@ def write_bake(out, place, view, meta, cards, opaque, default=None):
return dest
# ------------------------------------------------------------------------------------ the bake
def bake_place(pid):
"""stage 0, prefilter, set_view, coverage, seams, cards: dict(place, view, meta, cards (ridge.cards arrays), seams (K, w) in m, cov (bins, w), opaque (h, w) coverage). Needs RIDGE_TILES / RIDGE_WORK."""
def cut_ring(d, a, h, splits_km):
"""The ring cut of a prefiltered march (set_view done): normals, coverage, the periodic seams on all RING_W columns, then ridge.cards per tile on its TILE_W + 2 APRON columns with the matching normals. Returns dict(cards [TILES][cards] (ridge.cards arrays),
splits_km, seams (K, ring) in m, cov (bins, ring), opaque [TILES] (rows, TILE_W + 2 APRON) coverage, edges)."""
import ridge
assert ridge.WIN == PLANE_W and ridge.H > 0
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0))
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d)
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'])
nrm = ridge.normals(d, h); cov = ridge.coverage(d, a); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], d); op = ridge.opaque(a); cols = lambda x, t: ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON); tiles = []
for t in range(TILES): tiles.append(ridge.cards(d, cols(a, t), cols(h, t), cols(sm, t), tuple(cols(x, t) for x in nrm))); print(f'tile {t + 1}/{TILES}', file=sys.stderr, flush=True)
return dict(cards=tiles, splits_km=list(splits_km), seams=sm, cov=cov, opaque=[cols(op, t) for t in range(TILES)], edges=ridge.log_edges(d))
def bake_place(pid):
"""stage 0, prefilter, set_view on the whole ring, cut_ring: dict(place, view, meta, v, and cut_ring's cards, splits_km, seams, cov, opaque, edges). Needs RIDGE_TILES / RIDGE_WORK."""
import ridge
assert ridge.W == RING_W and ridge.H > 0
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0)); ring = cut_ring(d, a, h, p['card_split_km'])
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'], tz=p['tz'])
view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG))
return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d))
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])))
return dict(place=place, view=view, meta=meta, v=v, **ring)
def pack(bake):
"""The cards of a bake as bytes plus their manifest facts: median seam depths either side, the median distance of the card's solid pixels that are not wall (median_m = distance_m), and scale = distance_m / (distance_m - camera r). Refuses a card
with no solid terrain apart from its wall rows, and a camera offset the cards cannot take (card_scales)."""
enc = bake['meta']['encoding']; sm = bake['seams']; out = []; sp = bake['splits_km']; cs = bake['cards']
for i, c in enumerate(cs):
if c['alpha'].shape[0] == 0: raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split")
dist = []
for i, c in enumerate(cs):
ground = (c['alpha'] >= 0.5) & ~c['wall']
if not ground.any(): raise ValueError(f'card {i} holds no solid terrain apart from its wall rows')
dist.append(float(np.exp(np.median(c['logd'][ground]))))
scales = card_scales(dist, bake['meta']['camera']['r_m'])
for i, c in enumerate(cs):
out.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']),
near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None, median_m=dist[i], distance_m=dist[i], scale=scales[i]))
return out
"""The tiles of a bake as bytes plus their manifest facts. Per card tile: distance_m = exp(median ln d) over the solid (alpha >= 0.5) pixels that are not wall of the interior TILE_W columns (a tile with none falls back to its non-wall, then any, lit pixels);
a card with no rows in a tile is null there. Per card: the median seam depths over the ring. camera.r_max_m: solve_r_max over the card tiles' distances. Refuses a card empty in every tile (naming the splits) and a card with
no solid terrain apart from its wall in any tile. Returns dict(cards, tiles, camera, report) (report is printed, not written)."""
sm = bake['seams']; sp = bake['splits_km']; k = len(sp) + 1; ppd = bake['view']['px_per_deg_h']; inner = slice(APRON, APRON + TILE_W); enc = bake['meta']['encoding']
for i in range(k):
if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise ValueError(f"card {i} is empty: it lies between the splits {' and '.join(f'{sp[j]:g} km' for j in (i - 1, i) if 0 <= j < len(sp))} (card_split_km {sp}) and holds no terrain nothing nearer hides; move or remove a split")
tiles, dist, bands = [], [], []; any_solid = [False] * k
for tile in bake['cards']:
row, drow, brow = [], [], []
for i, c in enumerate(tile):
if c['alpha'].shape[0] == 0: row.append(None); drow.append(None); continue
al, wl, ld = c['alpha'][:, inner], c['wall'][:, inner], c['logd'][:, inner]; solid = (al >= 0.5) & ~wl; any_solid[i] |= bool(solid.any())
pool = next((m, l) for m, l in ((solid, ld), ((al > 0) & ~wl, ld), (al > 0, ld), (c['alpha'] > 0, c['logd'])) if m.any())
dm = float(np.exp(np.median(pool[1][pool[0]])))
row.append(dict(top=c['top'], colour=encode_colour(c['albedo'], c['alpha']), geometry=encode_geometry(c['n_r'], c['n_t'], c['logd'], enc, c['wall']), distance_m=dm)); drow.append(dm); brow.append(c['alpha'].shape[0])
tiles.append(row); dist.append(drow); bands.append(brow)
for i in range(k):
if not any_solid[i]: raise ValueError(f'card {i} holds no solid terrain apart from its wall rows')
r_max = solve_r_max(dist, bands, ppd); rmin = min(row[0] for row in dist if row[0] is not None); n = run_tiles(r_max, rmin); worst = np.nanmax(fit_table(dist, r_max, ppd), axis=0)
cards = [dict(near_m=float(np.median(sm[i - 1])) if i else None, far_m=float(np.median(sm[i])) if i < len(sm) else None) for i in range(k)]
return dict(cards=cards, tiles=tiles, camera=dict(r_max_m=r_max), report=dict(fit_px=[float(x) for x in worst], run_tiles=n, resident_bytes=resident_bytes(bands, n), nearest_m=rmin))
def lit(c):
"""albedo x (0.35 + 0.65 max(n.L, 0)) under the fixed sheet light, with the card's alpha: (rgb, alpha). Wall pixels are lit with the face up, as the runtime reads their code."""
@ -181,16 +265,23 @@ def lit(c):
up = np.sqrt(np.clip(1 - n_r ** 2 - n_t ** 2, 0, 1)); L = np.array(SHEET_LIGHT) / np.linalg.norm(SHEET_LIGHT); nl = np.clip(n_r * L[0] + n_t * L[1] + up * L[2], 0, 1)
return c['albedo'] * (0.35 + 0.65 * nl)[..., None], c['alpha']
def sheet(bake):
"""Contact sheet (png bytes), stacked: the composite, every card alone, and the depth image (log-distance bins, far at the top, every seam drawn). All lit by SHEET_LIGHT over the flat SHEET_SKY; reads the arrays the encoder writes."""
h, w = bake['opaque'].shape; sky = np.broadcast_to(np.array(SHEET_SKY), (h, w, 3)); comp = sky.copy(); panels = []
for c in bake['cards']:
rgb, al = lit(c); alone = sky.copy(); sl = slice(c['top'], c['top'] + al.shape[0]); alone[sl] = sky[sl] * (1 - al[..., None]) + rgb * al[..., None]; panels.append(alone)
for c in reversed(bake['cards']): rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); comp[sl] = comp[sl] * (1 - al[..., None]) + rgb * al[..., None]
cov = bake['cov']; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w)
for k, s in enumerate(bake['seams']):
j = np.clip(np.searchsorted(bake['edges'], np.log(s), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][k % 5]
for dy in (0, 1): depth[(nb - 1 - j) * 2 + dy, cols] = col
return bytes(imagecodecs.png_encode(u8(np.concatenate([comp] + panels + [depth], 0))))
"""Contact sheet (png bytes) at 1/4 of the ring's width, stacked: the ring composite, every card's strip alone, and the depth image (log-distance bins, far at the top, every seam); the TILES tile boundaries drawn on each. All lit by SHEET_LIGHT over the flat
SHEET_SKY; reads the arrays the encoder writes (each tile's interior columns, the apron dropped)."""
h = bake['opaque'][0].shape[0]; k = len(bake['cards'][0]); sky = np.broadcast_to(np.array(SHEET_SKY, np.float32), (h, RING_W, 3)); rgbs = [np.zeros((h, RING_W, 3), np.float32) for _ in range(k)]; als = [np.zeros((h, RING_W), np.float32) for _ in range(k)]
for t, tile in enumerate(bake['cards']):
for i, c in enumerate(tile):
if c['alpha'].shape[0] == 0: continue
rgb, al = lit(c); sl = slice(c['top'], c['top'] + al.shape[0]); x0 = t * TILE_W; rgbs[i][sl, x0:x0 + TILE_W] = rgb[:, APRON:APRON + TILE_W]; als[i][sl, x0:x0 + TILE_W] = al[:, APRON:APRON + TILE_W]
comp = sky.copy(); panels = []
for rgb, al in zip(rgbs, als): panels.append(sky * (1 - al[..., None]) + rgb * al[..., None])
for rgb, al in zip(reversed(rgbs), reversed(als)): comp = comp * (1 - al[..., None]) + rgb * al[..., None]
q = lambda a: a.reshape((a.shape[0], RING_W // 4, 4) + a.shape[2:]).mean(2); mark = np.arange(TILES) * TILE_W // 4; red = np.array([1.0, 0.2, 0.2])
def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img
cov = bake['cov'][:, ::4]; w = cov.shape[1]; img = np.repeat(np.log1p(cov[::-1]) / np.log1p(cov.max()), 2, 0); depth = np.dstack([img] * 3) * 0.92 + 0.04; nb = cov.shape[0]; cols = np.arange(w)
for j, s in enumerate(bake['seams']):
b = np.clip(np.searchsorted(bake['edges'], np.log(s[::4]), 'right') - 1, 0, nb - 1); col = [(0.24, 0.78, 1.0), (1.0, 0.47, 0.24), (0.6, 1.0, 0.4), (1.0, 0.9, 0.3), (0.9, 0.4, 1.0)][j % 5]
for dy in (0, 1): depth[(nb - 1 - b) * 2 + dy, cols] = col
return bytes(imagecodecs.png_encode(u8(np.concatenate([bounds(q(comp))] + [bounds(q(p)) for p in panels] + [bounds(depth)], 0))))
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0]); ap.add_argument('place', nargs='?'); ap.add_argument('--tiles'); ap.add_argument('--out'); ap.add_argument('--work'); ap.add_argument('--sheet'); ap.add_argument('--write-schema', action='store_true')
@ -200,7 +291,8 @@ def main(argv=None):
os.environ['RIDGE_TILES'] = a.tiles; os.environ['RIDGE_WORK'] = a.work or os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'ridge-bake-work'); os.makedirs(os.environ['RIDGE_WORK'], exist_ok=True)
bake = bake_place(a.place)
if a.sheet: Path(a.sheet).write_bytes(sheet(bake))
dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], pack(bake), bake['opaque'])
print(dest); return 0
packed = pack(bake); rp = packed['report']
print(f"r_max_m {packed['camera']['r_max_m']:g} nearest card {rp['nearest_m']:.0f} m resident run {rp['run_tiles']} tiles = {rp['resident_bytes']} bytes worst fit error per card (card px, bound {FIT_PX_MAX:g}) {[round(x, 1) for x in rp['fit_px']]}", file=sys.stderr, flush=True)
dest = write_bake(a.out, bake['place'], bake['view'], bake['meta'], packed, bake['opaque']); print(dest); return 0
if __name__ == '__main__': sys.exit(main())

View file

@ -1,8 +1,9 @@
{
"_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
"_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing is the rest azimuth, where the view looks at rest (or az_deg); the ring itself is the whole 360 degrees, absolute compass, column 0 = north; tz = the place's IANA time zone (required, never defaulted: the runtime draws named sky moments in the place's local day); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).",
"presets": [
{
"id": "vienna",
"tz": "Europe/Vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
"kind": "far range over a flat foreground",
"lat": 48.1929826,
@ -22,6 +23,7 @@
},
{
"id": "matterhorn",
"tz": "Europe/Zurich",
"name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)",
"kind": "lone horn, close, 27 deg of relief",
"lat": 45.983139,
@ -151,6 +153,7 @@
},
{
"id": "fuji",
"tz": "Asia/Tokyo",
"name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)",
"kind": "lone cone, smooth",
"lat": 35.312467222222494,
@ -297,6 +300,7 @@
},
{
"id": "halfdome",
"tz": "America/Los_Angeles",
"name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)",
"kind": "granite wall across a valley",
"lat": 37.745833333333,
@ -454,6 +458,7 @@
},
{
"id": "amadablam",
"tz": "Asia/Kathmandu",
"name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)",
"kind": "far high range behind a near spire",
"lat": 27.822000000000003,
@ -528,6 +533,7 @@
},
{
"id": "trecime",
"tz": "Europe/Rome",
"name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)",
"kind": "cirque wall, spires",
"lat": 46.636906,

View file

@ -1,6 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ridge-bake manifest v2 and index v1",
"title": "ridge-bake manifest v3 and index v1",
"$defs": {
"manifest": {
"type": "object",
@ -14,15 +14,14 @@
"encoding",
"camera",
"cards",
"w",
"h",
"tiles",
"bytes",
"attribution"
],
"additionalProperties": false,
"properties": {
"schema": {
"const": 2
"const": 3
},
"baker_version": {
"type": "integer"
@ -38,7 +37,8 @@
"lat",
"lon",
"altitude_km",
"eye_m"
"eye_m",
"tz"
],
"additionalProperties": false,
"properties": {
@ -59,6 +59,10 @@
},
"eye_m": {
"type": "number"
},
"tz": {
"type": "string",
"format": "iana-tz"
}
}
},
@ -66,8 +70,10 @@
"type": "object",
"required": [
"look_az_deg",
"window_deg",
"plane_w",
"ring_w",
"tile_w",
"tiles",
"apron",
"plane_h",
"px_per_deg_h",
"px_per_deg_v",
@ -81,12 +87,17 @@
"look_az_deg": {
"type": "number"
},
"window_deg": {
"const": 72
"ring_w": {
"const": 6400
},
"plane_w": {
"type": "integer",
"maximum": 4096
"tile_w": {
"const": 200
},
"tiles": {
"const": 32
},
"apron": {
"const": 2
},
"plane_h": {
"type": "integer"
@ -150,15 +161,11 @@
"camera": {
"type": "object",
"required": [
"r_m",
"heading_max_deg"
"r_max_m"
],
"additionalProperties": false,
"properties": {
"r_m": {
"type": "number"
},
"heading_max_deg": {
"r_max_m": {
"type": "number"
}
}
@ -170,24 +177,11 @@
"items": {
"type": "object",
"required": [
"top",
"h",
"near_m",
"far_m",
"median_m",
"distance_m",
"scale",
"colour",
"geometry"
"far_m"
],
"additionalProperties": false,
"properties": {
"top": {
"type": "integer"
},
"h": {
"type": "integer"
},
"near_m": {
"type": [
"number",
@ -199,57 +193,78 @@
"number",
"null"
]
},
"median_m": {
"type": "number"
},
"distance_m": {
"type": "number"
},
"scale": {
"type": "number"
},
"colour": {
"type": "object",
"required": [
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
}
}
},
"description": "nearest first; the runtime paints the list last to first. near_m and far_m are the median seam depths over the ring, null at the ends."
},
"tiles": {
"type": "array",
"minItems": 32,
"maxItems": 32,
"items": {
"type": "array",
"minItems": 1,
"maxItems": 6,
"items": {
"type": [
"object",
"null"
],
"required": [
"top",
"h",
"distance_m",
"colour",
"geometry"
],
"additionalProperties": false,
"properties": {
"top": {
"type": "integer"
},
"h": {
"type": "integer"
},
"distance_m": {
"type": "number"
},
"colour": {
"type": "object",
"required": [
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
}
}
}
},
"geometry": {
"type": "object",
"required": [
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"geometry": {
"type": "object",
"required": [
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
}
}
}
}
},
"description": "nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size."
}
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
},
"description": "tiles[t][i] is card i in tile t, or null where the card holds nothing in that tile (the client takes its distance from the neighbouring tiles). Tile t owns the ring columns [tile_w t, tile_w (t + 1)), column c at azimuth (c + 0.5) / ring_w x 360, 0 = north; its files hold [tile_w t - apron, tile_w (t + 1) + apron), wrapping at the ring's end, and are tile_w + 2 apron columns wide. top and h place the card's band back at its rows of the frame; distance_m = exp(median ln d) of the card's solid pixels in the tile that are not wall (the interior tile_w columns)."
},
"bytes": {
"type": "integer"

View file

@ -1,15 +1,17 @@
"""Ridge baker: the ray march of a place, cut into K+1 layered-depth G-buffer cards by K authored seams (places.json), no painter, no sun.
Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it.
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window azimuth, card splits and prefilter from places.json
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, rest azimuth, card splits and prefilter from places.json
stage0(detail) : ray march of all 6400 azimuth columns (curvature+refraction), optional authored sub-DEM foreground detail, cached
prefilter(d, h, sigma_m) : Gaussian low-pass of the sampled heights (along each ray, across rays at equal distance), angles recomputed with elev
set_view(skyline) : authored Y mapping from the march skyline: angle -> row, see set_view
coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column
set_view(skyline) : authored Y mapping from the march skyline of the whole ring: angle -> row, see set_view
ring_cols(a, c0, n) : n columns of the ring from column c0, periodic (the tile cut)
coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column, periodic round the ring
normals(d, h) / cards(...) : per-sample normals; the K+1 cards (coverage, distance, normal, albedo), each cropped to its band of rows
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit)."""
import sys, time, math, json
import os, hashlib
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as np, tifffile
@ -21,7 +23,6 @@ def _env_dir(name, what):
B = _env_dir('RIDGE_WORK', 'the work directory (the mosaic / ray caches)')
COP = _env_dir('RIDGE_TILES', 'the directory of Copernicus GLO-30 tiles (Copernicus_DSM_COG_10_*_DEM.tif)')
W = 6400 # ring columns: 360 deg at 17.78 px/deg
WIN = 1280 # window = 72 deg of the ring
HPX_DEG = W / 360.0
H = 600 # frame rows
COLW = math.radians(360.0 / W)
@ -31,11 +32,15 @@ P = {} # configured preset
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4
def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'):
"""The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
"""The preset dict. tz is required, an IANA zone the system knows (the runtime draws named sky moments in the place's local day). card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km')
from export import MAX_CARDS
if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)")
if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries")
tz = p.get('tz')
if not isinstance(tz, str) or not tz: raise ValueError(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)")
try: ZoneInfo(tz)
except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f"preset {pid}: tz {tz!r} is not a time zone the system knows")
return p
# ====================================================================== configuration, DEM
@ -77,7 +82,7 @@ def bil(a, lat_top, lon_left, lat, lon):
return (a[y0, x0] * (1 - fx) * (1 - fy) + a[y0, x0 + 1] * fx * (1 - fy) + a[y0 + 1, x0] * (1 - fx) * fy + a[y0 + 1, x0 + 1] * fx * fy)
def configure(p):
"""Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), window azimuth."""
"""Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), rest azimuth (az_center: where the view looks at rest; the ring itself is absolute compass, column 0 = north)."""
global P
P = p; m, lt, ll = mosaic(p)
ground = p['ground_override_m'] if 'ground_override_m' in p else float(bil(m, lt, ll, np.array(p['lat']), np.array(p['lon'])))
@ -85,10 +90,11 @@ def configure(p):
if 'look_at' in p:
la, lo = p['look_at']; P['az_center'] = (math.degrees(math.atan2((lo - p['lon']) * math.cos(math.radians(p['lat'])), la - p['lat'])) + 360) % 360
else: P['az_center'] = p['az_deg']
P['win0'] = int(round(P['az_center'] / 360 * W - WIN / 2)) % W
return P
def win(img): return np.take(img, (P['win0'] + np.arange(WIN)) % W, axis=1)
def ring_cols(a, c0, n):
"""n columns of the ring array a (last axis W) from column c0 (negative or past W wraps): the one periodic take, the wrap at 0 / 360 degrees is handled here."""
return np.take(a, (c0 + np.arange(n)) % W, axis=-1)
# ====================================================================== authored sub-DEM foreground detail (Aetheria / CultMath ridged multifractal)
def _frac(v): return v - np.floor(v)
@ -177,10 +183,10 @@ def normals(d, h):
# ====================================================================== the authored Y mapping
def set_view(skyline, sky_row=0.04, near_row=0.66):
"""AUTHORED vertical mapping, linear in elevation angle: row = (TOP_DEG - angle) * PXDEG_V over the whole 600-row frame (cylindrical, horizontal 17.78 px/deg). skyline is the highest angle any sample reaches in each
ring column (W,), straight from the march. Two anchors: the highest skyline angle in the window sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%); everything below is body and ground.
PXDEG_V = (near_row - sky_row) * 600 / (highest - lowest), clamped to [17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V."""
ring column (W,), straight from the march. Two anchors on the whole ring (ruling ridge-ring-vertical-anchors): the highest skyline angle of the ring sits at `sky_row` (4%) of the frame height, the LOWEST sits at `near_row` (66%);
everything below is body and ground. PXDEG_V = (near_row - sky_row) * 600 / (highest - lowest), clamped to [17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V."""
global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG
w = win(np.asarray(skyline)[None, :])[0]; sky = float(w.max()); low = float(w.min())
sk = np.asarray(skyline); sky = float(sk.max()); low = float(sk.min())
ppd = float(np.clip((near_row - sky_row) * H / max(sky - low, 0.05), HPX_DEG, 10 * HPX_DEG))
PXDEG_V = ppd; TOP_DEG = sky + sky_row * H / ppd; BOTTOM_DEG = TOP_DEG - H / ppd; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V
return dict(top_deg=TOP_DEG, bottom_deg=BOTTOM_DEG, px_per_deg=PXDEG_V, exaggeration=PXDEG_V / HPX_DEG, horizon_row=TOP_DEG * PXDEG_V, sky_deg=sky, low_deg=low, sky_row=sky_row, near_row=near_row)
@ -189,7 +195,7 @@ def set_view(skyline, sky_row=0.04, near_row=0.66):
COV_BINS = 160 # log-distance bins between the first and the last sample
SIG_B = 1.5 # blur of the coverage along depth (bins): seams settle in gaps
SEAM_LAM, SEAM_UNARY = 2.0, 0.25 # forward energy: a seam that moves a bin between neighbouring columns pays SEAM_LAM per bin plus every visible row it sweeps; one that sits in visible terrain pays SEAM_UNARY x those rows (cross-fadable)
SEAM_PRIOR = 0.02 # the authored depth is a faint pull, rows per nat^2 (the test pins the window: six synthetic receding ridges tear at 0.1, and without the swept-rows term at 0.02 they tear again)
SEAM_PRIOR = 0.02 # the authored depth is a faint pull, rows per nat^2 (the tests pin the window: six synthetic receding ridges, a sawtooth round the ring, tear at 0.05, and without the swept-rows term at 0.02 they tear too)
SEAM_SEP = 0.4 # seams at least this far apart in log-distance (nat)
XF = 0.07 # half-width of a seam's cross-fade, nat (about two bins)
@ -211,21 +217,22 @@ def _dt(f, u):
u = u.reshape((-1,) + (1,) * (f.ndim - 1)); return np.minimum(np.minimum.accumulate(f - u, axis=0) + u, np.flip(np.minimum.accumulate(np.flip(f + u, 0), axis=0), 0) - u)
def seams(cov, targets, d):
"""(K, n) ordered seam distances (m), one per authored target (m), each column. One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary
"""(K, n) ordered seam distances (m), one per authored target (m), each column of a RING (cov is periodic: the last column neighbours the first). One 1D forward-energy DP per seam, in target order (seam carving, Avidan & Shamir 2007; forward energy, Rubinstein et al. 2008): unary
SEAM_UNARY x the rows at the seam; moving a bin between neighbouring columns costs SEAM_LAM per bin plus the rows swept, an L1 distance in u = cumsum(rows) + SEAM_LAM x bin; a weak prior to the target. Seam k is held at
least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact."""
cov = np.asarray(cov, np.float64); nb, n = cov.shape; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12
least SEAM_SEP nat beyond seam k-1 in every column. Sequential, not joint: a joint DP has NB^K states per column and seams in gaps do not interact. Periodic: the DP runs over the ring three times side by side and keeps the middle lap,
so a seam is continuous across the wrap and a tile boundary is only a crop."""
cov = np.tile(np.asarray(cov, np.float64), (1, 3)); nb, n3 = cov.shape; n = n3 // 3; edges = log_edges(d, nb); bc = 0.5 * (edges[:-1] + edges[1:]); sep = int(math.ceil(SEAM_SEP / (edges[1] - edges[0]))); INF = 1e12
r = int(3 * SIG_B) + 1; kern = np.exp(-0.5 * (np.arange(-r, r + 1) / SIG_B) ** 2); kern /= kern.sum(); pad = np.pad(cov, ((r, r), (0, 0)), mode='edge'); Cs = sum(kv * pad[i:i + nb] for i, kv in enumerate(kern))
bins = np.arange(nb); lo = np.zeros(n, int); out = np.zeros((len(targets), n))
bins = np.arange(nb); lo = np.zeros(n3, int); out = np.zeros((len(targets), n3))
for t, T in enumerate(targets):
prior = SEAM_PRIOR * (bc - math.log(T)) ** 2; need = np.minimum(lo + (sep if t else 0), nb - 1); feas = bins[:, None] >= need[None, :]
warp = lambda x: np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins
cost = np.where(feas[:, 0], SEAM_UNARY * Cs[:, 0] + prior, INF); store = [cost]
for x in range(1, n): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost)
j = np.zeros(n, int); j[-1] = int(np.argmin(store[-1]))
for x in range(n - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]])))
for x in range(1, n3): cost = np.where(feas[:, x], _dt(cost, warp(x)) + SEAM_UNARY * Cs[:, x] + prior, INF); store.append(cost)
j = np.zeros(n3, int); j[-1] = int(np.argmin(store[-1]))
for x in range(n3 - 1, 0, -1): u = warp(x); j[x - 1] = int(np.argmin(store[x - 1] + np.abs(u - u[j[x]])))
out[t] = np.exp(bc[j]); lo = j
return out
return out[:, n:2 * n]
# ====================================================================== cards: layered depth, one per band between seams
GRASS, FOREST, ROCK, SNOW = (0.36, 0.44, 0.26), (0.22, 0.31, 0.20), (0.47, 0.44, 0.41), (0.93, 0.95, 0.97)
@ -239,7 +246,7 @@ def cards(d, a, h, seams, nrm=None):
card keeps the terrain a nearer ridge hides. Its alpha is that pixel's coverage (a crest row holds the share of its angular span under the card's running maximum) times 1 - smoothstep over seam i +- XF in
log-distance of the hit; card 0 owns the rows below the first sample, the last card has no far edge. Alphas are then made nested so the alpha-over composite of all cards is exactly the opaque coverage (a row two
cards both hold partly is not counted twice). Distance and normal are interpolated between sample k-1 and k by angle. Each card is cropped to the rows where its 8-bit alpha is not zero.
nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for a window cut from the ring). Rows of a card i > 0 below the angle of its first sample (hit and idx == 0) are the extruded wall of the ridge the card starts at: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1),
nrm is normals(d, h) of the same columns (default: computed from h as given, so pass it for columns cut from the ring: the lateral slope reads the neighbouring columns). Rows of a card i > 0 below the angle of its first sample (hit and idx == 0) are the extruded wall of the ridge the card starts at: they keep that sample's distance, their albedo is the ground material at their height with the face up (n_up = 1),
and `wall` flags them (card 0 has no wall: its rows below the first sample are the ground). Each card: dict(top, alpha (h,n), albedo (h,n,3), n_r, n_t, logd (ln metres) (h,n), wall (h,n) bool)."""
d = np.asarray(d, np.float64); a = np.asarray(a, np.float64); h = np.asarray(h, np.float64); seams = np.asarray(seams, np.float64); nk, n = a.shape; nc = len(seams) + 1
n_r, n_t, n_u = nrm if nrm is not None else normals(d, h); ld = np.broadcast_to(np.log(d)[:, None], (nk, n)); p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p

View file

@ -1,5 +1,5 @@
"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails.
venv/bin/python tests/mutate.py (prints one line per mutant; exit 1 if a mutant survives)"""
venv/bin/python tests/mutate.py [word ...] (prints one line per mutant whose name holds every word; exit 1 if a mutant survives)"""
import os, shutil, subprocess, sys, tempfile
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
@ -14,7 +14,6 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
'prefilter across rays uses one sigma in columns (not per distance)': ("sc = sigma_m / (d * COLW)", "sc = sigma_m / (d[0] * COLW) * np.ones_like(d)"),
'bake_id hashes geometry before colour': ("h.update(colour); h.update(geometry)", "h.update(geometry); h.update(colour)"),
'check_cover accepts any composite': ("if bad.any(): y, x", "if False: y, x"),
'check_budget ignores the cropped bands (decoded as full frames)': ("decoded = sum(2 * w * h * 4 for h in bands)", "decoded = 0"),
'load_preset accepts splits that do not increase': ("or any(b <= a for a, b in zip(sp, sp[1:]))", ""),
'geometry: n_r and n_t channels swapped': ("r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)", "r, t = u8((np.asarray(n_t) + 1) / 2), u8((np.asarray(n_r) + 1) / 2)"),
'geometry: log-distance not normalised by the encoding range': ("b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min'])", "b = np.asarray(logd) / 12.0"),
@ -31,15 +30,28 @@ MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
'wall: albedo takes the face normal, not the face up': ("np.where(Wl[i, sl], 1.0, g[4] / nz)", "g[4] / nz"),
'wall: the code is not written to the geometry': ("if wall is not None: m = np.asarray(wall, bool)", "if False: m = np.asarray(wall, bool)"),
'wall: the sheet lights wall rows with their normal': ("wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])", "n_r, n_t = c['n_r'], c['n_t']"),
'camera: the sign of r is flipped in the scale': ("return [d / (d - r_m) for d in distances]", "return [d / (d + r_m) for d in distances]"),
'camera: the scale is clamped (a function of r that is not the formula)': ("return [d / (d - r_m) for d in distances]", "return [min(d / (d - r_m), 1.2) for d in distances]"),
'camera: the card distance includes wall rows': ("ground = (c['alpha'] >= 0.5) & ~c['wall']", "ground = (c['alpha'] >= 0.5)"),
'camera: the offset bound is ignored': ("if abs(r_m) >= R_FRAC_MAX * min(distances): raise", "if False: raise"),
'camera: the frame-bottom coverage check is removed': ("if bottom < view['plane_h'] - 1e-6: raise", "if False: raise"),
'camera: the 16:9 rest coverage check is removed': ("if min(scales) < REST_SCALE_MIN: raise", "if False: raise"),
'camera: the preset camera_r_m is ignored': ("r_m=float(p.get('camera_r_m', CAMERA_R_M))", "r_m=float(CAMERA_R_M)"),
'camera: the manifest writes the default heading range, not the bake\'s': ("heading_max_deg=meta['camera']['heading_max_deg']),", "heading_max_deg=HEADING_MAX_DEG),"),
'export: an empty card is not refused': ("if c['alpha'].shape[0] == 0: raise", "if False: raise"),
'ring: the seam DP is not periodic (the first lap is kept, not the middle)': ("return out[:, n:2 * n]", "return out[:, :n]"),
'ring: the tile take does not wrap (the ring ends repeat their edge column)': ("return np.take(a, (c0 + np.arange(n)) % W, axis=-1)", "return np.take(a, np.clip(c0 + np.arange(n), 0, W - 1), axis=-1)"),
'tile: the apron is shifted (a tile starts at its own first column)': ("ridge.ring_cols(x, t * TILE_W - APRON, TILE_W + 2 * APRON)", "ridge.ring_cols(x, t * TILE_W, TILE_W + 2 * APRON)"),
'tile: the seams are cut from tile 0 for every tile': ("cols(sm, t), tuple(cols(x, t) for x in nrm)", "cols(sm, 0), tuple(cols(x, t) for x in nrm)"),
'view: the vertical anchors read the first 72 degrees only (the old window)': ("sk = np.asarray(skyline); sky", "sk = np.asarray(skyline)[:1280]; sky"),
'bake_id: card-major instead of tile-major': ("bake_id([(e['colour'], e['geometry']) for row in tiles for e in row if e])", "bake_id([(row[i]['colour'], row[i]['geometry']) for i in range(k) for row in tiles if row[i]])"),
'write: the per-tile cover check is dropped': ("except ValueError as ex: raise ValueError(f'tile {t}: {ex}')", "except ValueError as ex: pass"),
'write: the apron width is not checked': ("if c.shape[1] != w: raise", "if False: raise"),
'budget: the tile cap is ignored': ("if b > TILE_BYTES_MAX: raise", "if False: raise"),
'budget: the place cap is ignored': ("if sum(tile_bytes) > PLACE_BYTES_MAX: raise", "if False: raise"),
'budget: the resident gate is ignored': ("if res > RESIDENT_BYTES_MAX: raise", "if False: raise"),
'budget: the resident run does not wrap the ring': ("sum(per[(t + k) % TILES] for k in range(n))", "sum(per[t + k] for k in range(n) if t + k < TILES)"),
'budget: the run length forgets the margin tiles': ("math.ceil(arc / TILE_DEG) + 1 + 4", "math.ceil(arc / TILE_DEG)"),
'r_max: the camera sweeps forward only (phi = 0)': ("PHI_STEPS = 24 ", "PHI_STEPS = 1 "),
'r_max: every card of a tile is fitted at the nearest card distance': ("fit_px(d, r, px_per_deg) for d in row", "fit_px(row[0] if row[0] is not None else d, r, px_per_deg) for d in row"),
'r_max: not capped at half the nearest distance': ("cap = 0.5 * rmin", "cap = 5.0 * rmin"),
'r_max: the resident gate is not part of the search': (" and resident_bytes(bands, run_tiles(r, rmin)) <= RESIDENT_BYTES_MAX\n", "\n"),
'r_max: a bake below the floor is accepted': ("if r_max < R_MAX_FLOOR_M:", "if False:"),
'pack: the distance counts wall rows': ("solid = (al >= 0.5) & ~wl; any_solid", "solid = (al >= 0.5); any_solid"),
'pack: the distance reads the apron columns too': ("inner = slice(APRON, APRON + TILE_W)", "inner = slice(0, TILE_W + 2 * APRON)"),
'sheet: the tile boundaries are not drawn': ("def bounds(img): img[:, mark] = 0.45 * img[:, mark] + 0.55 * red; return img", "def bounds(img): return img"),
'export: an empty card is not refused': ("if all(tile[i]['alpha'].shape[0] == 0 for tile in bake['cards']): raise", "if False: raise"),
'rays cache key ignores the refraction constant': ("R_EARTH, KREF, W, bool(detail)", "R_EARTH, W, bool(detail)"),
'rays cache key ignores the eye elevation': ("round(float(P['eye_m']), 3), ", ""),
'mosaic cache key ignores the tile list': ("sorted(tiles_for(p)), 3600", "3600"),
@ -54,7 +66,7 @@ def run(item):
return line, r.returncode == 0
if __name__ == '__main__':
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT]))
with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT and all(w in n for w in sys.argv[1:])]))
for line, _ in res: print(line, flush=True)
for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why)
sys.exit(1 if any(sv for _, sv in res) else 0)

View file

@ -4,10 +4,13 @@ Synthetic terrain has a known right answer; the Vienna tests bake the real prese
import os, sys, math, json, shutil, tempfile, traceback
SRC = os.environ.get('RIDGE_SRC') or os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'); sys.path.insert(0, SRC) # RIDGE_WORK and RIDGE_TILES must be set (tests/run.sh sets them)
import numpy as np, ridge, export
from ridge import W, WIN, H
from ridge import W, H
NW = 1280 # the synthetic bakes' window: columns 0..NW of the ring (azimuth 0..72); the pieces that need the whole ring (seams across the wrap, the tile cut) run on the ring
TW = export.TILE_W + 2 * export.APRON
_w = lambda x: ridge.ring_cols(x, 0, NW)
EYE = 100.0; GROUND = 50.0 # ground below the eye: every ray climbs, so only the placed blocks make ridges
ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0, win0=0)
ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0)
D = ridge.schedule(False)
def az_of(x): return (x + 0.5) / W * 360.0
def col_of(az): return int(round(az / 360.0 * W - 0.5)) % W
@ -45,16 +48,13 @@ def test_paths_come_from_the_environment_with_no_default():
r = subprocess.run([sys.executable, '-I', '-c', 'import sys; sys.path.insert(0, %r); import ridge' % SRC], env=e, capture_output=True, text=True); assert r.returncode and var in r.stderr and 'not set' in r.stderr, (var, r.stderr[-200:])
# ---------------------------------------------------------------------------------------- synthetic bakes: the shared steps of export.bake_place on rays the fixtures make
def _bake(hfun, splits_km, sigma=0.0):
"""prefilter, set_view, coverage, seams, cards on synthetic rays (window = columns 0..WIN, i.e. azimuth 0..72): the dict bake_place returns."""
A, Hh = rays(hfun); ridge.P.update(win0=0, eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
nrm = tuple(ridge.win(x) for x in ridge.normals(D, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(D, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits_km], D)
place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE)
view = dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H)
meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), camera=dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0))
return dict(place=place, view=view, meta=meta, cards=ridge.cards(D, aw, hw, sm, nrm, ), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, v=v)
def _bake(hfun, splits_km, sigma=0.0, fixed_m=None):
"""prefilter, whole-ring set_view, coverage and the periodic seams on the whole ring (or fixed_m, one seam depth in m for every column), then the window columns 0..NW (azimuth 0..72) of them and the cards on those, of synthetic rays: the pieces of the bake a fixture can look at cheaply."""
A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, sigma); v = ridge.set_view(a.max(0))
nrm = tuple(_w(x) for x in ridge.normals(D, h)); aw, hw = _w(a), _w(h); cov_ring = ridge.coverage(D, a); cov = _w(cov_ring); sm = _w(ridge.seams(cov_ring, [k * 1000.0 for k in splits_km], D)) if fixed_m is None else np.array([np.full(NW, float(v)) for v in fixed_m])
return dict(cards=ridge.cards(D, aw, hw, sm, nrm), splits_km=list(splits_km), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(D), a=aw, h=hw, nrm=nrm, v=v)
def _canvas(card, key='alpha'):
out = np.zeros((H, WIN) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
out = np.zeros((H, NW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
def _row(deg): return int(np.argmin(np.abs(ridge.rowang - deg)))
THREE = terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 7000)) # ridges at 3, 20 and 70 km, each taller in angle than the one before
WIDE3 = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000), block(0, 359.99, 70000, 72000, 3000)) # low near hills, then ridges at 39 and 71 km: the frame reaches below the ground at the seams (so cards have wall rows) and the horizon is inside it
@ -62,26 +62,35 @@ WALLED = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 400
NEARHILL = terrain(block(0, 359.99, 0, 4000, 150), block(0, 359.99, 38000, 40000, 2000)) # ground above the eye from the first sample on: every row of card 0 lies below its first sample
def _ramp(dk, az): return np.maximum(GROUND, np.where(dk > 12000, (dk - 12000) * 0.045 + 50.0, 0.0)) # a slope the first sample of card 1 stands on: n_up about 0.9, so the material would be rock if the face counted
def test_the_vertical_anchors_read_the_whole_ring():
"""set_view anchors the highest skyline angle of the ring at 4% of the frame and the lowest at 66%, wherever they are: a peak at column 3555 and a low at column 5333, both outside the first 72 degrees, set the mapping."""
sk = np.full(W, 1.0); sk[3555] = 3.0; sk[5333] = -1.0; sk[10] = 1.5; v = ridge.set_view(sk)
assert v['sky_deg'] == 3.0 and v['low_deg'] == -1.0 and abs(v['px_per_deg'] - 0.62 * H / 4.0) < 1e-9 and abs(v['horizon_row'] - ridge.TOP_DEG * v['px_per_deg']) < 1e-9 and abs(ridge.TOP_DEG - (3.0 + 0.04 * H / v['px_per_deg'])) < 1e-9, v
def test_seams_fall_in_depth_gaps():
"""Three ridges at 3, 20 and 70 km: targets [6, 40] give a seam in (3, 20) and one in (20, 70) in EVERY column, ordered with at least 0.4 nat between; targets [6] give one seam in (3, 20)."""
b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, WIN)
b = _bake(THREE, [6, 40]); s = b['seams']; assert s.shape == (2, NW)
assert (s[0] > 3600).all() and (s[0] < 20000).all() and (s[1] > 21500).all() and (s[1] < 70000).all(), (s.min(1), s.max(1)); assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all()
s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, WIN) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max())
s1 = _bake(THREE, [6])['seams']; assert s1.shape == (1, NW) and (s1[0] > 3600).all() and (s1[0] < 20000).all(), (s1.min(), s1.max())
def _recede(d0, d1, thick=300.0, hgt=1500.0):
"""A ridge `thick` m thick whose distance runs from d0 m at azimuth 0 to d1 m at azimuth 72."""
return terrain(lambda dk, az: np.where((az <= 72) & (np.abs(dk - (d0 + (d1 - d0) * np.clip(az / 72.0, 0, 1))) < thick / 2), hgt, 0.0))
"""A ridge `thick` m thick whose distance runs from d0 m at azimuth 0 to d1 m at azimuth 72, and again in every 72 degrees of the ring (so the ring's skyline is the ridge's everywhere, as the window's was)."""
return terrain(lambda dk, az: np.where(np.abs(dk - (d0 + (d1 - d0) * ((az % 72) / 72.0))) < thick / 2, hgt, 0.0))
def _receding(dk, az): return _recede(4000.0, 15000.0)(dk, az)
def test_the_swept_rows_term_keeps_the_seam_from_hopping_under_a_stronger_pull():
"""With the authored depth pulling harder (0.1 instead of 0.02) the 4 to 15 km ridge's seam still follows the ridge: only the cost of the visible rows it would sweep holds it back (with that term out of the cost it hops between two columns)."""
old = ridge.SEAM_PRIOR; ridge.SEAM_PRIOR = 0.1
try: j0, j1, cover = _alpha_jumps(4, 15, 6)
"""With the authored depth pulling five times as hard (0.1 instead of 0.02) the seams of the 3-12, 4-15 (split 10) and 6-14 km ridges still follow the ridge, and twice as hard (0.04) those of the 4-15 (split 6), 5-30 and 8-40 km ridges: only the cost of the visible rows it would sweep holds it back (with that term out of the cost it hops between two columns)."""
old = ridge.SEAM_PRIOR
try:
ridge.SEAM_PRIOR = 0.1
for d0, d1, sp in ((3, 12, 6), (4, 15, 10), (6, 14, 9)):
j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', (d0, d1, sp), j0, j1)
ridge.SEAM_PRIOR = 0.04 # these three tear above 0.04 (measured: 0.05 tears 5-30 and 8-40, 0.1 tears 4-15/6): the seam is closed on the ring, so a stronger pull makes one tear per period cheaper than staying beyond the ridge
for d0, d1, sp in ((4, 15, 6), (5, 30, 12), (8, 40, 15)):
j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', (d0, d1, sp), j0, j1)
finally: ridge.SEAM_PRIOR = old
assert j0 < 0.35 and j1 < 0.35 and cover > 0.999, ('the seam hopped across the ridge', j0, j1)
RECEDING = [(4, 15, 6), (3, 12, 6), (5, 30, 12), (8, 40, 15), (4, 15, 10), (6, 14, 9)] # km at azimuth 0, km at azimuth 72, authored split km
def _alpha_jumps(d0, d1, split):
"""The two cards' alpha on the ridge body (crest + 4 rows), column to column: the largest step of each. """
b = _bake(_recede(d0 * 1000.0, d1 * 1000.0), [split]); c0 = _canvas(b['cards'][0]); c1 = _canvas(b['cards'][1]); crest = np.argmax(b['opaque'] > 0.5, axis=0); r = np.clip(crest + 4, 0, H - 1); ok = crest > 0
a0 = c0[r, np.arange(WIN)]; a1 = c1[r, np.arange(WIN)]; return float(np.abs(np.diff(a0[ok])).max()), float(np.abs(np.diff(a1[ok])).max()), (a0 + (1 - a0) * a1)[ok].min()
a0 = c0[r, np.arange(NW)]; a1 = c1[r, np.arange(NW)]; return float(np.abs(np.diff(a0[ok])).max()), float(np.abs(np.diff(a1[ok])).max()), (a0 + (1 - a0) * a1)[ok].min()
def test_seam_never_splits_a_receding_ridge_side_by_side():
"""Six synthetic ridges whose distance recedes across the window (4 to 15, 3 to 12, 5 to 30, 8 to 40, 4 to 15 and 6 to 14 km, targets 6, 6, 12, 15, 10, 9 km): the nearer and the farther card's alpha on the ridge's body never jumps by 0.35 between neighbouring
columns (a tear: one card here, the other next door; fading slowly over the cross-fade is fine) and the two cards together cover the body. With the swept-rows term out of the seam cost the seam hops across the ridge; with the prior at 0.1 it hops on two of the six."""
@ -96,8 +105,8 @@ def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge():
r = _row(0.5 * (theta(350, 3000) + theta(2400, 20000))); assert c0[r, 900] < 0.01 and a1[r, 900] > 0.99 and abs(math.exp(ld1[r, 900]) - 20000) < 1500, (c0[r, 900], a1[r, 900])
def test_crossfade_is_complementary():
"""A ridge across the seam (seam fixed at 6 km, the ridge's front face at 5.9 km inside the cross-fade): the nearer card is partly transparent over the window, the farther card is opaque on the ridge, and the composite stays at coverage 1 below the crest."""
A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh)
cs = ridge.cards(D, aw, hw, np.full((1, WIN), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
A, Hh = rays(terrain(block(0, 359.99, 5900, 6100, 900))); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh)
cs = ridge.cards(D, aw, hw, np.full((1, NW), 6000.0)); c0, c1 = _canvas(cs[0]), _canvas(cs[1]); crest = int(np.argmax(ridge.opaque(aw)[:, 500] > 0.5)); r = crest + 6
assert 0.2 < c0[r, 500] < 0.8, ('the near card does not fade over the window', c0[r, 500]); assert c1[r, 500] > 0.99, 'the far card is not opaque on the ridge'
comp = 1 - (1 - c0) * (1 - c1); assert (comp[crest + 3:, :] > 0.999).all(), 'the composite dips below coverage 1 under the crest'
def test_normals_of_a_tilted_plane():
@ -127,7 +136,7 @@ def test_prefilter_flattens_roofs_and_keeps_hills():
assert np.allclose(ridge.prefilter(D, Hh, 0.0)[1], Hh), 'sigma 0 changed the heights'
def test_crest_rows_have_fractional_coverage():
"""The top row of a card's run has alpha equal to the share of its angular span under the running maximum, and the rows below it are 1 (a lower ridge in columns 0..640 so its crest is not at the frame's top edge)."""
A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, WIN)))[0]
A, Hh = rays(terrain(block(0, 36, 5000, 5600, 500), block(36, 359.99, 5000, 5600, 560))); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh); c = ridge.cards(D, aw, hw, np.zeros((0, NW)))[0]
cv = _canvas(c)[:, 300]; r = int(np.argmax(cv > 0)); top = float(aw.max(0)[300]); p = 1.0 / ridge.PXDEG_V; want = (top - (ridge.rowang[r] - 0.5 * p)) / p
assert 0.0 < want < 1.0 and abs(cv[r] - want) < 0.01, (cv[r], want, r); assert (cv[r + 1:] > 0.999).all()
def test_cards_composite_to_the_opaque_view():
@ -139,93 +148,168 @@ def test_cards_composite_to_the_opaque_view():
if _canvas(c)[r, col] > 0.99: first = math.exp(_canvas(c, 'logd')[r, col]); break
assert first is not None and abs(first - D[k]) < 0.1 * D[k] + 60, (first, D[k])
# ---------------------------------------------------------------------------------------- the real thing: Vienna
def _vienna(splits):
saved = ridge.P
try:
p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); aw = ridge.win(a); hw = ridge.win(h)
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in splits], d); return d, aw, ridge.cards(d, aw, hw, sm, nrm), sm, ridge.opaque(aw)
finally: ridge.P = saved
def test_vienna_k1_k2_k3():
"""Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column, each composite equals the opaque view within 0.02; the cross-fade column count of each K is printed."""
for sp in ([6], [6, 40], [6, 20, 40]):
d, aw, cs, sm, op = _vienna(sp); assert len(cs) == len(sp) + 1 and sm.shape == (len(sp), WIN)
if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order'
comp = 1 - np.prod([1 - _canvas(c) for c in cs], axis=0); assert np.abs(comp - op).max() < 0.02, (sp, np.abs(comp - op).max())
xf = int(np.any([((0.02 < _canvas(c)) & (_canvas(c) < 0.98)).sum(0) > 3 for c in cs], axis=0).sum())
print(f' K={len(sp)} splits {sp}: {len(cs)} cards, bands {[(c["top"], c["alpha"].shape[0]) for c in cs]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {WIN}')
def test_bake_place_manifest_fields_on_vienna():
"""bake_place on the real Vienna preset: three cards, the place carries the ground (km) and the eye, horizon_row is the row where the elevation angle is 0, px_per_deg_h is the ring's; write_bake of its packed cards validates, index default 'vienna', and no temp dir is left."""
saved = ridge.P
load = ridge.load_preset; ridge.load_preset = lambda pid, *a: dict(load(pid, *a), camera_r_m=123.0) # a preset's camera_r_m is the bake's camera
try: b = export.bake_place('vienna'); P = ridge.P; rowang = ridge.rowang; pxv = ridge.PXDEG_V
finally: ridge.P = saved; ridge.load_preset = load
assert b['meta']['camera'] == dict(r_m=123.0, heading_max_deg=export.HEADING_MAX_DEG), b['meta']['camera']
pl, view = b['place'], b['view']; assert abs(pl['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and abs(pl['eye_m'] - P['eye_m']) < 1e-9 and pl['id'] == 'vienna' and len(b['cards']) == 3
assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])]); assert view['px_per_deg_h'] == ridge.HPX_DEG and abs(view['exaggeration'] - pxv / ridge.HPX_DEG) < 1e-9
d = tempfile.mkdtemp()
try:
dest = export.write_bake(d, pl, view, b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest'])
assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'cards', [(c['top'], c['h'], c['colour']['bytes'] + c['geometry']['bytes']) for c in m['cards']])
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- the ring: tiles are crops of per-column results, the wrap is periodic
_RING = {}
def _ring(key, hfun, splits_km):
"""export.cut_ring on synthetic rays (prefilter, whole-ring set_view, then the ring cut), cached by key: dict(bake = what export.bake_place returns, minus the place)."""
if key not in _RING:
A, Hh = rays(hfun); ridge.P.update(eye_m=EYE); a, h = ridge.prefilter(D, Hh, 0.0); v = ridge.set_view(a.max(0)); r = export.cut_ring(D, a, h, splits_km)
_RING[key] = dict(r, op_ring=ridge.opaque(a), place=dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE, tz='Europe/Vienna'), v=v,
view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * H, near_row=v['near_row'] * H),
meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1]))))
return _RING[key]
def _tile_canvas(card, key='alpha'):
out = np.zeros((H, TW) + card[key].shape[2:], np.float32); out[card['top']:card['top'] + card[key].shape[0]] = card[key]; return out
def _across_north(dk, az): return np.where(in_arc(az, 340, 20) & (np.abs(dk - (12000.0 + 400.0 * (((az + 180) % 360) - 180))) < 200), 1500.0, 0.0) # a ridge across the wrap at 4 km (az -20) to 20 km (az +20)
ACROSS = terrain(block(0, 359.99, 3000, 3600, 350), _across_north, block(0, 359.99, 70000, 72000, 3000), block(0.0, 0.05, 6000, 7000, 2500), block(359.95, 359.99, 6000, 7000, 2500)) # and a tower one column wide on each side of north
def test_ring_wrap():
"""A ridge across column 6399 / 0 (receding from 4 km at -20 deg to 20 km at +20 deg): the seam is continuous over the wrap (its jump there no larger than the largest jump elsewhere), tile 31's right apron equals tile 0's first columns and tile 0's left apron
tile 31's last (every card, pixel for pixel), neighbouring tiles agree on their shared apron, and the interiors of all tiles composite to the opaque ring."""
b = _ring('across', ACROSS, [8]); sm = np.log(b['seams'][0]); jumps = np.abs(np.diff(np.append(sm, sm[0]))); assert jumps[-1] <= jumps[:-1].max() + 1e-9, ('the seam jumps over the wrap', jumps[-1], jumps[:-1].max())
A_ = export.APRON; T_ = export.TILE_W; ring = np.zeros((H, W)); op = np.zeros((H, W))
for t, tile in enumerate(b['cards']):
nxt = b['cards'][(t + 1) % export.TILES]
for i, c in enumerate(tile):
assert (_tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] == _tile_canvas(nxt[i])[:, A_:2 * A_]).all(), ('the apron differs from the neighbour', t, i); seen = _tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] > 0
for key in ('logd', 'wall'): assert (_tile_canvas(c, key)[:, T_ + A_:T_ + 2 * A_][seen] == _tile_canvas(nxt[i], key)[:, A_:2 * A_][seen]).all(), ('the apron differs from the neighbour', t, i, key)
comp = 1 - np.prod([1 - _tile_canvas(c) for c in tile], axis=0); ring[:, t * T_:(t + 1) * T_] = comp[:, A_:A_ + T_]; op[:, t * T_:(t + 1) * T_] = b['opaque'][t][:, A_:A_ + T_]
assert np.abs(ring - op).max() < 0.02, np.abs(ring - op).max(); assert np.abs(ring - b['op_ring']).max() < 0.02 and b['op_ring'][:, [0, W - 1]].sum(0).min() > b['op_ring'][:, [1, W - 2]].sum(0).max() + 10, 'the tiles hold the wrong columns of the ring (a tower on column 0 and column 6399 is the fixture)'
assert b['opaque'][0].shape == (H, T_ + 2 * A_) and (b['opaque'][0][:, :A_] == b['opaque'][export.TILES - 1][:, T_:T_ + A_]).all(), 'the left apron of tile 0 is not the last columns of tile 31'
def test_every_tile_is_cut_at_its_own_seam():
"""The seams sweep from 5 km to 30 km once round the ring (ridge.seams stands in): in every tile the near card holds nothing beyond its columns' seam (plus the cross-fade) and the far card nothing before it, so no tile is cut with another tile's seams."""
saved = ridge.seams; sweep = 5000.0 * 6.0 ** (np.arange(W) / W)
ridge.seams = lambda cov, targets, d: sweep[None, :]
try: b = _ring('swept', terrain(block(0, 359.99, 3000, 3600, 350), block(0, 359.99, 20000, 21500, 1800), block(0, 359.99, 70000, 72000, 3000)), [8])
finally: ridge.seams = saved
T_, A_ = export.TILE_W, export.APRON; ix = slice(A_, A_ + T_); xf = ridge.XF; seen = 0
for t, tile in enumerate(b['cards']):
s_t = np.broadcast_to(sweep[np.arange(T_) + t * T_], (H, T_)); c0, c1 = tile[0], tile[1]; d0 = np.exp(_tile_canvas(c0, 'logd')[:, ix]); d1 = np.exp(_tile_canvas(c1, 'logd')[:, ix])
n0 = (_tile_canvas(c0)[:, ix] >= 0.5) & (_tile_canvas(c0, 'wall')[:, ix] < 0.5); n1 = (_tile_canvas(c1)[:, ix] >= 0.5) & (_tile_canvas(c1, 'wall')[:, ix] < 0.5); seen += int(n0.sum() + n1.sum())
assert (d0[n0] <= s_t[n0] * math.exp(xf) * 1.02 + 100).all() and (d1[n1] >= s_t[n1] * math.exp(-xf) * 0.98 - 100).all(), ('a card tile is cut at another tile seam', t)
assert seen > 100_000, 'the fixture holds no card pixels'
def test_tile_is_a_crop_of_the_columns():
"""ridge.cards on a tile's columns (the 200 it owns and the apron) equals the same columns of ridge.cards on a wider run of columns, pixel for pixel, for fixed seams: the tile cut changes no pixel and adds no seam."""
b = _bake(terrain(_receding, block(0, 359.99, 3000, 3600, 350)), [6]); x0 = 500; n = export.TILE_W + 2 * export.APRON; sl = slice(x0, x0 + n)
tile = ridge.cards(D, b['a'][:, sl], b['h'][:, sl], b['seams'][:, sl], tuple(x[:, sl] for x in b['nrm']))
for c, w in zip(tile, b['cards']):
assert np.array_equal(_canvas(w)[:, sl], _tile_canvas(c)), 'a tile is not a crop of the columns'; seen = _tile_canvas(c) > 0
for key in ('albedo', 'n_r', 'n_t', 'logd', 'wall'): assert np.array_equal(_canvas(w, key)[:, sl][seen], _tile_canvas(c, key)[seen]), ('a tile is not a crop of the columns', key)
# ---------------------------------------------------------------------------------------- export: manifest v2, budget, cover
def _packed(b=None):
b = b or _bake(WIDE3, [20, 55]); return b, export.pack(b)
# ---------------------------------------------------------------------------------------- toy bakes: tile data made by hand, for the packer and the writer
def _toy(dists=(3000.0, 15000.0, 50000.0), bands=(300, 400, 500), tops=(300, 150, 60), amp=0.01):
"""TILES tiles of len(dists) cards: card i is a solid band of rows (top, h) whose distance is dists[i] x (1 + amp sin x) across the columns, no wall; the opaque view is their composite. Returns the bake dict pack() reads."""
n = export.TILE_W + 2 * export.APRON; x = np.arange(n); tile = []; k = len(dists)
for i in range(k):
ld = np.log(dists[i] * (1 + amp * np.sin(x * 0.3)))[None, :].repeat(bands[i], 0).astype(np.float32)
tile.append(dict(top=tops[i], alpha=np.ones((bands[i], n), np.float32), albedo=np.full((bands[i], n, 3), 0.4, np.float32), n_r=np.full((bands[i], n), 0.1, np.float32), n_t=np.full((bands[i], n), -0.1, np.float32), logd=ld, wall=np.zeros((bands[i], n), bool)))
comp = export.composite_alpha([(c['top'], c['alpha']) for c in tile], H, n)
return dict(cards=[[dict(c) for c in tile] for _ in range(export.TILES)], splits_km=[6.0 * (j + 1) for j in range(k - 1)], seams=np.tile(np.array(dists[:-1])[:, None] * 0.5, (1, W)), opaque=[comp.copy() for _ in range(export.TILES)],
view=dict(look_az_deg=36.0, plane_h=H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=100.0, exaggeration=5.0, horizon_row=60.0, sky_row=24.0, near_row=396.0), meta=dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(500.0), log_d_max=math.log(100000.0))),
place=dict(id='toy', name='Toy', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'))
def _write(out, b, packed, **kw):
args = dict(place=b['place'], view=b['view'], meta=b['meta'], packed=packed, opaque=b['opaque']); args.update(kw); return export.write_bake(out, **args)
def _refuses(out, b, packed, why, **kw):
args = dict(place=b['place'], view=b['view'], meta=b['meta'], cards=packed, opaque=b['opaque']); args.update(kw)
try: export.write_bake(out, **args)
try: _write(out, b, packed, **kw)
except ValueError: assert not os.path.exists(out), ('a refused bake left files', why)
else: assert False, why
def test_manifest_v2_writer():
"""Two independent bakes give the same bytes and bake_id; the manifest validates (an extra key does not), cards are nearest first with their bands and seam medians, the files are what the manifest says, the index points at the dir, a rebake replaces
the old dir, the committed schema is current, and the Copernicus attribution is the four pinned strings."""
def _pins():
assert (export.RING_W, export.TILES, export.TILE_W, export.APRON, export.MAX_CARDS, export.BAKER_VERSION) == (6400, 32, 200, 2, 6, 4), 'the ring layout is pinned'
assert (export.TILE_BYTES_MAX, export.PLACE_BYTES_MAX, export.RESIDENT_BYTES_MAX, export.FIT_PX_MAX, export.R_MAX_FLOOR_M, export.PHI_STEPS) == (235_000, 7_500_000, 20_000_000, 24.0, 25.0, 24), 'the budgets and the fit bound are pinned'
assert abs(export.HFOV_MAX_DEG - 72 / 1.1) < 1e-12
def test_schema3():
"""The manifest validates; a tile array of the wrong length, a missing apron, a file named for another tile, and any key of schema 2 left behind (the camera's heading range and offset, the window, the plane width, the card's median and scale, the whole-bake w and h) are refused; the schema file is pinned; the layout constants are pinned."""
_pins(); d = tempfile.mkdtemp()
try:
b = _toy(); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); mk = lambda: json.loads(json.dumps(m))
assert m['schema'] == 3 and m['baker_version'] == 4 and set(m['view']) >= {'ring_w', 'tile_w', 'tiles', 'apron'} and 'rows_above' not in m['view'] and m['camera'] == dict(r_max_m=pk['camera']['r_max_m']) and len(m['tiles']) == 32 and 'w' not in m and 'h' not in m
def bad(f, why):
x = mk(); f(x)
try: export.validate_manifest(x)
except ValueError: return
raise AssertionError(why)
bad(lambda x: x['tiles'].pop(), 'a manifest of 31 tiles validated'); bad(lambda x: x['tiles'][3].pop(), 'a tile with a card missing validated'); bad(lambda x: x['tiles'][3].append(None), 'a tile with an extra card validated'); bad(lambda x: x['view'].pop('apron'), 'a missing apron validated')
bad(lambda x: x['view'].update(apron=0), 'an apron of 0 validated'); bad(lambda x: x['tiles'][2][1]['colour'].update(file='card-1-t03-colour.webp'), 'a file named for another tile validated')
bad(lambda x: x['tiles'].__setitem__(slice(None), [[None] * 3 for _ in range(32)]), 'a card null in every tile validated'); bad(lambda x: x.update(bytes=x['bytes'] + 1), 'a wrong byte total validated')
for where, key in (('camera', 'heading_max' + '_deg'), ('view', 'window' + '_deg'), ('view', 'plane' + '_w'), ('view', 'rows_above'), ('camera', 'r_m'), (None, 'w'), (None, 'h')): # schema 2's names are spelled in pieces: the baker's tree must hold none of them
bad(lambda x: (x[where] if where else x).update({key: 1}), f'a leftover {key} validated')
bad(lambda x: x['cards'][0].update(**{'median' + '_m': 1.0}), 'a leftover median validated'); bad(lambda x: x['cards'][0].update(scale=1.0), 'a leftover scale validated'); bad(lambda x: x['tiles'][0][0].update(scale=1.0), 'a tile entry with a scale validated')
bad(lambda x: x['tiles'][0][0].update(distance_m='far'), 'a distance that is not a number validated'); bad(lambda x: x['place'].update(tz='Mars/Olympus'), 'a zone the system does not know validated')
assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
finally: shutil.rmtree(d)
def test_manifest_v3_writer():
"""Two packs of one bake give the same bytes and bake_id; tiles[t][i] files are where the manifest says with the sizes it says and decode to tile_w + 2 apron columns; the bake_id is the sha256 of the files tile-major, then card, colour then geometry; the index points at the dir, a
rebake replaces the old dir, cards are nearest first with their seam medians, the attribution is the four pinned strings."""
d = tempfile.mkdtemp()
try:
b, pk = _packed(); b2, pk2 = _packed(_bake(WIDE3, [20, 55])); assert [(c['colour'], c['geometry']) for c in pk] == [(c['colour'], c['geometry']) for c in pk2], 'two independent bakes gave different bytes'
a = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque']); assert a.name == 'synthetic-' + export.bake_id([(c['colour'], c['geometry']) for c in pk]); assert sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name])
m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['schema'] == 2 and m['baker_version'] == export.BAKER_VERSION and len(m['cards']) == 3 and m['w'] == WIN and m['h'] == H
assert m['camera'] == dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0) and all(c['scale'] == c['distance_m'] / (c['distance_m'] - export.CAMERA_R_M) and c['distance_m'] == c['median_m'] for c in m['cards']), m['camera']
assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m']
for c in m['cards']:
for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c
assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id'
import hashlib; want = hashlib.sha256(b''.join(c['colour'] + c['geometry'] for c in pk)).hexdigest()[:12]; assert export.bake_id([(c['colour'], c['geometry']) for c in pk]) == want, 'bake_id is not the sha256 of the card files, colour then geometry, in index order'
assert export.bake_id([(c['geometry'], c['colour']) for c in pk]) != want and export.bake_id([(c['colour'], c['geometry']) for c in pk[::-1]]) != want, 'bake_id ignores the file order'
bad = json.loads(json.dumps(m)); bad['cards'][0]['extra'] = 1
try: export.validate(bad, export.SCHEMA['$defs']['manifest'])
except ValueError: pass
else: assert False, 'an extra key passed the schema'
assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
b = _toy(); pk = export.pack(b); pk2 = export.pack(b); files = lambda p: [(e['colour'], e['geometry']) for row in p['tiles'] for e in row if e]; assert files(pk) == files(pk2), 'two packs gave different bytes'
a = _write(d + '/a', b, pk); assert a.name == 'toy-' + export.bake_id(files(pk)) and sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name]); m = json.load(open(a / 'manifest.json')); export.validate_manifest(m)
import hashlib; want = hashlib.sha256(b''.join(c + g for c, g in files(pk))).hexdigest()[:12]; assert export.bake_id(files(pk)) == want, 'bake_id is not the sha256 of the tile files, tile-major then card, colour then geometry'
assert export.bake_id([(g, c) for c, g in files(pk)]) != want and export.bake_id(files(pk)[::-1]) != want and export.bake_id([f for i, f in enumerate(files(pk)) if i % 3 != 1] + [f for i, f in enumerate(files(pk)) if i % 3 == 1]) != want, 'bake_id ignores the file order'
pk3 = [list(f) for f in files(pk)]; pk3[40][1] += b'x'; assert export.bake_id([tuple(f) for f in pk3]) != want, 'a changed byte kept the bake_id'
assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and len(m['cards']) == 3
for t, row in enumerate(m['tiles']):
for i, e in enumerate(row):
for kind in ('colour', 'geometry'): f = a / e[kind]['file']; assert f.stat().st_size == e[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON), (t, i, kind)
assert m['bytes'] == sum(e[k]['bytes'] for row in m['tiles'] for e in row for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='toy', places={'toy': a.name})
want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
assert m['attribution'] == want, m['attribution']
c = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque'])
assert c.name == a.name; other = dict(b['place'], id='other'); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'synthetic'
export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque'], default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model'); assert m['attribution'] == want, m['attribution']
c = _write(d + '/a', b, pk); assert c.name == a.name; other = dict(b['place'], id='other'); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'toy'
_write(d + '/a', b, pk, place=other, default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); _write(d + '/a', b, pk, place=other); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
finally: shutil.rmtree(d)
def test_tile_crop_and_null():
"""Each card tile is exactly the rows where its 8-bit alpha is non-zero (top and h in the manifest are those rows, the files decode to that band, the written alpha is the card's); a card with no rows in a tile is null there, writes no file and the bake still validates;
a card empty everywhere is refused naming the splits, and a card with no solid terrain in any tile is refused."""
d = tempfile.mkdtemp()
try:
b = _ring('wide3', WIDE3, [20, 55]); pk = export.pack(b); dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json'))
for t in (0, 9, 31):
for c, e in zip(b['cards'][t], m['tiles'][t]):
rows = np.flatnonzero(np.rint(_tile_canvas(c) * 255).max(1) > 0); assert e['top'] == rows[0] and e['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (t, e, rows[0], rows[-1])
col = export.decode((dest / e['colour']['file']).read_bytes()); assert col.shape[:2] == (e['h'], export.TILE_W + 2 * export.APRON) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha'
t0 = _toy(); cs = [[dict(c) for c in tile] for tile in t0['cards']]; empty = dict(top=0, alpha=np.zeros((0, 204), np.float32), albedo=np.zeros((0, 204, 3), np.float32), n_r=np.zeros((0, 204), np.float32), n_t=np.zeros((0, 204), np.float32), logd=np.zeros((0, 204), np.float32), wall=np.zeros((0, 204), bool))
cs[5][2] = empty; op = [x.copy() for x in t0['opaque']]; op[5] = export.composite_alpha([(c['top'], c['alpha']) for c in cs[5] if c['alpha'].shape[0]], H, 204); b5 = dict(t0, cards=cs, opaque=op); pk5 = export.pack(b5)
assert pk5['tiles'][5][2] is None and pk5['tiles'][4][2] is not None; dest = _write(d + '/null', b5, pk5); m5 = json.load(open(dest / 'manifest.json')); assert m5['tiles'][5][2] is None and not (dest / export.tile_file(2, 5, 'colour')).exists() and (dest / export.tile_file(2, 4, 'colour')).exists()
for i, why in ((1, '20 km'), (2, '55 km')):
gone = [[empty if j == i else c for j, c in enumerate(tile)] for tile in b['cards']]
try: export.pack(dict(b, cards=gone))
except ValueError as e: assert f'card {i} is empty' in str(e) and why in str(e), str(e)
else: assert False, ('an empty card', i, 'was packed')
liquid = [[dict(c, alpha=c['alpha'] * 0.4) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']]
try: export.pack(dict(t0, cards=liquid))
except ValueError as e: assert 'no solid terrain' in str(e), str(e)
else: assert False, 'a card with no solid pixel in any tile was packed'
walled = [[dict(c, wall=np.ones_like(c['wall'])) if j == 1 else c for j, c in enumerate(tile)] for tile in t0['cards']]
try: export.pack(dict(t0, cards=walled))
except ValueError as e: assert 'no solid terrain' in str(e), str(e)
else: assert False, 'a card that is all wall was packed'
finally: shutil.rmtree(d)
def test_cover_and_size_refusals_write_nothing():
"""write_bake measures the files it is handed: a card with a hole (alpha zeroed in a band of columns) fails the cover check, a card leaving the frame, cards of two widths and a colour/geometry size mismatch are refused, and nothing is written."""
"""write_bake measures the files it is handed: a hole in one tile's card (alpha zeroed over a band of columns) fails that tile's cover check and names the tile, a card leaving the frame, a tile file without its apron, colour and geometry of two sizes and an opaque view of the wrong
rows are refused, and nothing is written."""
d = tempfile.mkdtemp()
try:
b, pk = _packed(); c1 = b['cards'][1]; hole = c1['alpha'].copy(); hole[:, 200:260] = 0
holed = [dict(c) for c in pk]; holed[1]['colour'] = export.encode_colour(c1['albedo'], hole); holed[2] = dict(pk[2], colour=export.encode_colour(b['cards'][2]['albedo'], b['cards'][2]['alpha'] * 0)); _refuses(d + '/hole', b, holed, 'a bake whose cards leave a hole was written')
_refuses(d + '/off', b, [dict(c, top=H - 5) if i == 0 else c for i, c in enumerate(pk)], 'a card leaving the frame was written')
narrow = [dict(c) for c in pk]; narrow[0]['colour'] = export.encode_colour(b['cards'][0]['albedo'][:, :1000], b['cards'][0]['alpha'][:, :1000]); _refuses(d + '/wide', b, narrow, 'cards of two widths were written')
_refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1))
b = _toy(); pk = export.pack(b); c = b['cards'][3][2]; hole = c['alpha'].copy(); hole[:, 100:140] = 0; bad = [list(r) for r in pk['tiles']]; bad[3][2] = dict(bad[3][2], colour=export.encode_colour(c['albedo'], hole)); _refuses(d + '/hole', b, dict(pk, tiles=bad), 'a bake whose card leaves a hole was written')
try: _write(d + '/hole', b, dict(pk, tiles=bad))
except ValueError as e: assert 'tile 3' in str(e), str(e)
off = [list(r) for r in pk['tiles']]; off[7][0] = dict(off[7][0], top=H - 5); _refuses(d + '/off', b, dict(pk, tiles=off), 'a card leaving the frame was written')
narrow = [list(r) for r in pk['tiles']]; c0 = b['cards'][2][0]; narrow[2][0] = dict(narrow[2][0], colour=export.encode_colour(c0['albedo'][:, 2:-2], c0['alpha'][:, 2:-2]), geometry=export.encode_geometry(c0['n_r'][:, 2:-2], c0['n_t'][:, 2:-2], c0['logd'][:, 2:-2], b['meta']['encoding'])); _refuses(d + '/apron', b, dict(pk, tiles=narrow), 'a tile without its apron was written')
try: _write(d + '/apron', b, dict(pk, tiles=narrow))
except ValueError as e: assert 'apron' in str(e), str(e)
mism = [list(r) for r in pk['tiles']]; mism[4][1] = dict(mism[4][1], geometry=export.encode_geometry(c0['n_r'][:50], c0['n_t'][:50], c0['logd'][:50], b['meta']['encoding'])); _refuses(d + '/size', b, dict(pk, tiles=mism), 'a colour and geometry of two sizes were written')
_refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1)); _refuses(d + '/short', b, dict(pk, tiles=pk['tiles'][:31]), 'a bake of 31 tiles was written')
finally: shutil.rmtree(d)
def _flat_card(top, h, w=WIN, seed=0, noise=False):
def _flat_entry(top, h, w=export.TILE_W + 2 * export.APRON, seed=0, noise=False, distance_m=1000.0):
rng = np.random.default_rng(seed); alpha = np.ones((h, w), np.float32); rgb = rng.random((h, w, 3)).astype(np.float32) if noise else np.full((h, w, 3), 0.5, np.float32); geo = rng.random((h, w)).astype(np.float32) if noise else np.full((h, w), 0.5, np.float32)
enc = dict(log_d_min=0.0, log_d_max=1.0); return dict(top=top, colour=export.encode_colour(rgb, alpha), geometry=export.encode_geometry(geo, geo, geo, enc), near_m=None, far_m=None, median_m=1.0, distance_m=1.0, scale=1.0)
enc = dict(log_d_min=0.0, log_d_max=1.0); return dict(top=top, colour=export.encode_colour(rgb, alpha), geometry=export.encode_geometry(geo, geo, geo, enc), distance_m=distance_m)
def test_card_cap_refusals():
"""A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; write_bake refuses 4 full-frame 1280x600 cards (24.6 MB decoded) and writes nothing; 6 cards whose bands fit the budget are written; the card count and bytes are capped."""
"""A preset with 6 splits, or splits not increasing, is refused by load_preset before any march; a bake of 7 cards is refused; 6 cards that fit the budgets are written; 6 full-frame cards in every tile (the lit canvases of 13 tiles are 38 MB) are refused and write nothing."""
d = tempfile.mkdtemp()
try:
for bad in ([5, 10, 20, 30, 40, 50], [6, 6], [6, 5], []):
p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', card_split_km=bad)]), open(p, 'w'))
p = os.path.join(d, 'p.json'); json.dump(dict(presets=[dict(id='x', tz='UTC', card_split_km=bad)]), open(p, 'w')) # a valid zone, so only the splits can refuse it
try: ridge.load_preset('x', p)
except ValueError: pass
else: assert False, ('a preset with splits', bad, 'was accepted')
@ -233,79 +317,153 @@ def test_card_cap_refusals():
try: ridge.load_preset('x', os.path.join(d, 'q.json'))
except ValueError: pass
else: assert False, 'a preset without card_split_km was defaulted'
json.dump(dict(presets=[dict(id='x', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5]
place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0)
full = np.ones((H, WIN))
_refuses(d + '/four', dict(place=place, view=view, meta=meta, opaque=full), [_flat_card(0, H) for _ in range(4)], 'four full-frame cards (24.6 MB decoded) were written')
ok = [_flat_card(0, H)] + [_flat_card(0, 150, seed=i) for i in range(1, 6)]; dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6
try: export.check_budget([1000] * 7, WIN, [10] * 7)
json.dump(dict(presets=[dict(id='x', tz='Europe/Vienna', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5]
for bad_tz in (None, '', 'Not/AZone'):
p = os.path.join(d, 'tz.json'); json.dump(dict(presets=[dict(id='x', card_split_km=[6], **({} if bad_tz is None else dict(tz=bad_tz)))]), open(p, 'w'))
try: ridge.load_preset('x', p)
except ValueError: pass
else: assert False, ('a preset with tz', bad_tz, 'was accepted')
place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0)
full = [np.ones((H, 204)) for _ in range(32)]; cards = lambda k: [dict(near_m=None if i == 0 else 1.0, far_m=None if i == k - 1 else 1.0) for i in range(k)]; cam = dict(r_max_m=100.0)
big = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, H) for _ in range(5)] for _ in range(32)], camera=cam)
try: export.write_bake(d + '/big', place, view, meta, big, full)
except ValueError as e: assert 'consecutive tiles' in str(e), str(e)
else: assert False, 'six full-frame cards in every tile were written'
assert not os.path.exists(d + '/big')
ok = dict(cards=cards(6), tiles=[[_flat_entry(0, H, seed=0)] + [_flat_entry(0, 100, seed=i) for i in range(1, 6)] for _ in range(32)], camera=cam); dest = export.write_bake(d + '/six', place, view, meta, ok, full); assert len(json.load(open(dest / 'manifest.json'))['cards']) == 6
try: export.check_budget(7, [1000] * 32, [[10] * 7] * 32, 100.0, 1000.0)
except ValueError as e: assert 'above 6' in str(e)
else: assert False, '7 cards were accepted'
try: export.check_budget([750_001, 750_000], WIN, [10, 10])
except ValueError as e: assert 'bytes' in str(e)
else: assert False, 'cards above TOTAL_BYTES_MAX were accepted'
export.check_budget([750_000, 750_000], WIN, [10, 10])
try: export.check_budget([1, 1], export.PLANE_W_MAX + 1, [10, 10])
except ValueError: pass
else: assert False, 'a card wider than the cap was accepted'
finally: shutil.rmtree(d)
def test_cards_are_cropped_to_their_band():
"""Each card is exactly the rows where its 8-bit alpha is non-zero; the manifest top and h place it back at the same rows (colour and geometry decode to that band, alpha in the file equals the canvas row for row)."""
def test_budgets():
"""A tile over 235 kB, a place over 7.5 MB and a resident run over 20 MB each refuse and one byte (one band row) under passes; the resident run wraps the ring: the last tiles and the first count as consecutive."""
none = [[] for _ in range(export.TILES)]; call = lambda tb, bands, r=100.0, rmin=1000.0: export.check_budget(3, tb, bands, r, rmin)
def refused(*a, **k):
try: call(*a, **k)
except ValueError: return True
return False
assert not refused([235_000] + [0] * 31, none) and refused([235_001] + [0] * 31, none), 'the tile cap'
assert not refused([234_375] * 32, none) and refused([234_375] * 31 + [234_376], none), 'the place cap'
rows = 20_000_000 // (4 * export.LIT_W); one = lambda h: [[h]] + [[] for _ in range(31)]
assert not refused([0] * 32, one(rows)) and refused([0] * 32, one(rows + 1)), 'the resident cap'
n = export.run_tiles(100.0, 1000.0); assert 5 < n < 32; split = [[] for _ in range(32)]; split[31] = [rows // 2]; split[0] = [rows - rows // 2 + 1]
assert refused([0] * 32, split), 'the resident run does not wrap the ring (tile 31 and tile 0 are consecutive)'; split[0] = [rows - rows // 2]; assert not refused([0] * 32, split)
far = [[] for _ in range(32)]; far[0] = [rows // 2]; far[n + 3] = [rows - rows // 2 + 1]; assert not refused([0] * 32, far), 'a run is only N tiles long'; far[n - 1] = far[n + 3]; far[n + 3] = []; assert refused([0] * 32, far)
assert export.run_tiles(0.0, 1000.0) == math.ceil(export.HFOV_MAX_DEG / 11.25) + 5 and export.run_tiles(250.0, 20000.0) > export.run_tiles(25.0, 20000.0) and export.run_tiles(1e9, 1.0) == 32, 'N = ceil(arc_max / 11.25) + 1 + 4'
rows_t = [[10, 20] if t in (30, 31, 0, 1) else [] for t in range(32)]; assert export.resident_bytes(rows_t, 4) == 4 * export.LIT_W * 120 and export.resident_bytes(rows_t, 3) == 4 * export.LIT_W * 90 and export.resident_bytes(rows_t, 40) == 4 * export.LIT_W * 120
def _fit(d, r): return export.fit_px(d, r, ridge.HPX_DEG)
def test_r_max():
"""On a card at 1.5 km: r_max_m falls as FIT_PX_MAX falls and is at most half the distance; it is the largest offset within the bound (the fit error at r_max is within it, a little more is not); a forward-only sweep of phi finds a larger r_max than the whole circle (the error is in the phi
that is not forward); the binding card tile is the nearest one (each tile's line is fitted at its own distance_m); the resident gate binds when its tiles are heavy; a place whose r_max_m is below 25 refuses and names the card and tile."""
ppd = ridge.HPX_DEG; dist = [[1500.0] for _ in range(32)]; bands = [[100] for _ in range(32)]; saved = (export.FIT_PX_MAX, export.PHI_STEPS)
try:
r = export.solve_r_max(dist, bands, ppd); assert 25 < r <= 750 and _fit(1500.0, r) <= export.FIT_PX_MAX + 1e-9 and _fit(1500.0, r + 0.5) > export.FIT_PX_MAX, ('r_max is not the largest offset within the bound', r, _fit(1500.0, r), _fit(1500.0, r + 0.5))
export.FIT_PX_MAX = 12.0; r12 = export.solve_r_max(dist, bands, ppd); export.FIT_PX_MAX = 60.0; r60 = export.solve_r_max(dist, bands, ppd); export.FIT_PX_MAX = saved[0]; assert r12 < r < r60, (r12, r, r60)
export.FIT_PX_MAX = 1e9; assert export.solve_r_max(dist, bands, ppd) == 750.0, 'r_max is not capped at half the nearest distance'; export.FIT_PX_MAX = saved[0]
export.PHI_STEPS = 1; rf = export.solve_r_max(dist, bands, ppd); export.PHI_STEPS = saved[1]; assert rf > r + 5, ('a forward-only sweep finds the same r_max', rf, r)
mixed = [[1500.0 if t == 3 else 9000.0] for t in range(32)]; assert export.solve_r_max(mixed, bands, ppd) == r, 'the binding tile is not the nearest one'
dist2 = [[20000.0] for _ in range(32)]; free = export.solve_r_max(dist2, bands, ppd); heavy = [[1700000 // (4 * export.LIT_W)] for _ in range(32)]; held = export.solve_r_max(dist2, heavy, ppd)
assert held < free - 100 and export.resident_bytes(heavy, export.run_tiles(held, 20000.0)) <= export.RESIDENT_BYTES_MAX < export.resident_bytes(heavy, export.run_tiles(held + 1.0, 20000.0)), ('the resident gate does not bind r_max', held, free)
two = [[5000.0, 40.0 if t == 7 else 5000.0] for t in range(32)]
try: export.solve_r_max(two, [[100, 100] for _ in range(32)], ppd)
except ValueError as e: assert 'below 25' in str(e) and 'card 1' in str(e) and 'tile 7' in str(e), str(e)
else: assert False, 'a bake whose r_max_m is below 25 was accepted'
close = [[30.0] for _ in range(32)]
try: export.solve_r_max(close, bands, ppd)
except ValueError as e: assert 'below 25' in str(e) and 'card 0' in str(e), str(e)
else: assert False, 'a nearest card at 30 m was accepted'
finally: export.FIT_PX_MAX, export.PHI_STEPS = saved
def test_pack_distance_and_r_max_in_the_bake():
"""pack: a card tile's distance_m is exp(median ln d) over the interior solid pixels that are not wall (not the wall rows, not the apron columns); the manifest camera is the r_max_m of those distances and no per-card scale or median is written."""
b = _toy(); cs = [[dict(c) for c in tile] for tile in b['cards']]; c = dict(cs[10][1]); n = c['alpha'].shape[0]; wall = np.zeros_like(c['wall']); wall[:n * 3 // 4] = True; ld = np.where(wall, c['logd'] + 3.0, c['logd']).copy(); ld[:, :2] += 2.0; ld[:, -2:] += 2.0; cs[10][1] = dict(c, wall=wall, logd=ld)
pk = export.pack(dict(b, cards=cs)); inner = (slice(None), slice(2, -2)); want = float(np.exp(np.median(ld[inner][~wall[inner]]))); with_wall = float(np.exp(np.median(ld[inner]))); assert abs(with_wall - want) > 0.05 * want, 'the fixture cannot tell wall rows from ground'
assert abs(pk['tiles'][10][1]['distance_m'] - want) < 1e-9 * want, ('the distance counted wall rows or the apron', pk['tiles'][10][1]['distance_m'], want); assert set(pk['tiles'][10][1]) == {'top', 'colour', 'geometry', 'distance_m'} and set(pk['cards'][0]) == {'near_m', 'far_m'}
base = export.pack(b); assert base['camera']['r_max_m'] >= 25 and abs(base['report']['nearest_m'] - min(e[0]['distance_m'] for e in base['tiles'])) < 1e-9 and len(base['report']['fit_px']) == 3 and max(base['report']['fit_px']) <= export.FIT_PX_MAX + 1e-6
assert abs(base['cards'][0]['far_m'] - 1500.0) < 1e-6 and base['cards'][0]['near_m'] is None and base['cards'][1]['near_m'] == base['cards'][0]['far_m']
def test_the_sheet_draws_the_ring():
"""The contact sheet is the ring at 1/4 width (1600 px) with a mark on each of the 32 tile boundaries, in the composite, every card's strip and the depth image, stacked: composite, K cards, depth."""
b = _ring('wide3', WIDE3, [20, 55]); png = export.sheet(b); img = export.imagecodecs.png_decode(png); k = 3; nb = b['cov'].shape[0]; assert img.shape == ((1 + k) * H + 2 * nb, W // 4, 3), img.shape
mark = np.arange(32) * 200 // 4; sky = np.array(export.SHEET_SKY); reddish = lambda px: (px[..., 0] > px[..., 2] + 40); assert reddish(img[2, mark].astype(int)).all() and not reddish(img[2, mark + 7].astype(int)).any(), 'the tile boundaries are not drawn on the composite'
assert reddish(img[(1 + k) * H + 3, mark].astype(int)).all(), 'the tile boundaries are not drawn on the depth image'; assert abs(img[2, 1].astype(int) - np.rint(np.array(export.SHEET_SKY) * 255)).max() <= 2, 'the sky is not the flat sky'
# ---------------------------------------------------------------------------------------- the real thing: Vienna
_VIENNA = {}
def _vienna_bake():
if 'b' not in _VIENNA:
saved = ridge.P
try: b = export.bake_place('vienna'); _VIENNA.update(b=b, pxv=ridge.PXDEG_V, P=dict(ridge.P), rowang=ridge.rowang.copy(), skyline=None)
finally: ridge.P = saved
return _VIENNA['b']
def _vienna_ring(splits, tiles):
"""Vienna's whole-ring march and seams for the given splits, cards on only the given tiles: (d, seams, {t: cards}, {t: opaque})."""
saved = ridge.P
try:
p = ridge.configure(dict(ridge.load_preset('vienna'), card_split_km=splits)); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p['prefilter_m']); ridge.set_view(a.max(0)); nrm = ridge.normals(d, h); sm = ridge.seams(ridge.coverage(d, a), [k * 1000.0 for k in splits], d); op = ridge.opaque(a)
cols = lambda x, t: ridge.ring_cols(x, t * export.TILE_W - export.APRON, export.TILE_W + 2 * export.APRON)
return d, sm, {t: ridge.cards(d, cols(a, t), cols(h, t), cols(sm, t), tuple(cols(x, t) for x in nrm)) for t in tiles}, {t: cols(op, t) for t in tiles}
finally: ridge.P = saved
def test_vienna_k1_k2_k3():
"""Vienna with card_split_km [6], [6, 40] and [6, 20, 40]: 2, 3 and 4 cards, seams ordered in every column of the ring, each composite of a tile (the rest azimuth's, the north's and the last one) equals the opaque view within 0.02; the cross-fade column count is printed."""
for sp in ([6], [6, 40], [6, 20, 40]):
d, sm, cs, op = _vienna_ring(sp, (0, 19, 31)); assert sm.shape == (len(sp), W)
if len(sp) > 1: assert (np.diff(np.log(sm), axis=0) >= 0.4 - 1e-9).all(), 'seams out of order'
for t, tile in cs.items():
assert len(tile) == len(sp) + 1; comp = 1 - np.prod([1 - _tile_canvas(c) for c in tile], axis=0); assert np.abs(comp - op[t]).max() < 0.02, (sp, t, np.abs(comp - op[t]).max())
xf = int(np.any([((0.02 < _tile_canvas(c)) & (_tile_canvas(c) < 0.98)).sum(0) > 3 for c in cs[19]], axis=0).sum())
print(f' K={len(sp)} splits {sp}: {len(cs[19])} cards, tile 19 bands {[(c["top"], c["alpha"].shape[0]) for c in cs[19]]}, seam medians km {[round(float(np.median(s)) / 1000, 1) for s in sm]}, cross-fade columns {xf} of {export.TILE_W + 4} in tile 19')
def test_bake_place_manifest_fields_on_vienna():
"""bake_place on the real Vienna preset: 32 tiles of three cards, the place carries the ground (km) and the eye, horizon_row is the row where the elevation angle is 0, px_per_deg_h is the ring's, look_az_deg is the rest azimuth; the shared apron of neighbouring tiles is the same pixels
(the tile cut at the real preset), and write_bake of its packed tiles validates with index default 'vienna', no temp dir left, r_max_m and the worst fit error per card printed."""
b = _vienna_bake(); P = _VIENNA['P']; rowang = _VIENNA['rowang']; pxv = _VIENNA['pxv']; pl, view = b['place'], b['view']; assert len(b['cards']) == 32 and all(len(t) == 3 for t in b['cards']) and len(b['opaque']) == 32 and b['seams'].shape == (2, W)
assert abs(pl['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and abs(pl['eye_m'] - P['eye_m']) < 1e-9 and pl['id'] == 'vienna' and view['look_az_deg'] == P['az_center'] == 214.0
assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])]); assert view['px_per_deg_h'] == ridge.HPX_DEG and abs(view['exaggeration'] - pxv / ridge.HPX_DEG) < 1e-9
T_, A_ = export.TILE_W, export.APRON
for t in (0, 19, 31):
nxt = b['cards'][(t + 1) % 32]
for i, c in enumerate(b['cards'][t]):
assert (_tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] == _tile_canvas(nxt[i])[:, A_:2 * A_]).all(), ('the apron is not the neighbour tile', t, i); seen = _tile_canvas(c)[:, T_ + A_:T_ + 2 * A_] > 0
assert (_tile_canvas(c, 'logd')[:, T_ + A_:T_ + 2 * A_][seen] == _tile_canvas(nxt[i], 'logd')[:, A_:2 * A_][seen]).all(), ('the apron is not the neighbour tile', t, i, 'logd')
d = tempfile.mkdtemp()
try:
b, pk = _packed(); dest = export.write_bake(d, b['place'], b['view'], b['meta'], pk, b['opaque']); m = json.load(open(dest / 'manifest.json'))
for c, rec in zip(b['cards'], m['cards']):
canvas = _canvas(c); rows = np.flatnonzero(np.rint(canvas * 255).max(1) > 0); assert rec['top'] == rows[0] and rec['h'] == rows[-1] - rows[0] + 1 == c['alpha'].shape[0], (rec, rows[0], rows[-1])
col = export.decode((dest / rec['colour']['file']).read_bytes()); assert col.shape[:2] == (rec['h'], WIN) and np.abs(col[..., 3].astype(int) - np.rint(c['alpha'] * 255)).max() == 0, 'the written alpha is not the card alpha'
assert export.decode((dest / rec['geometry']['file']).read_bytes()).shape[:2] == (rec['h'], WIN)
pk = export.pack(b); rp = pk['report']; print(' vienna r_max_m', pk['camera']['r_max_m'], 'nearest card m', round(rp['nearest_m']), 'resident run', rp['run_tiles'], 'tiles', rp['resident_bytes'], 'bytes; worst fit error per card (card px)', [round(x, 1) for x in rp['fit_px']], 'sky/low deg', round(b['v']['sky_deg'], 2), round(b['v']['low_deg'], 2), 'exaggeration', round(view['exaggeration'], 2))
dest = _write(d, b, pk); m = json.load(open(dest / 'manifest.json')); export.validate_manifest(m); assert m['camera']['r_max_m'] >= export.R_MAX_FLOOR_M
assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d); print(' vienna manifest bytes', m['bytes'], 'largest tile', max(sum(e[k]['bytes'] for e in row if e for k in ('colour', 'geometry')) for row in m['tiles']))
finally: shutil.rmtree(d)
def test_an_empty_card_is_refused_before_writing_naming_the_split():
"""A card with no rows (its splits leave it no terrain) stops pack with a message that names the splits, instead of dying inside the codec."""
b = _bake(THREE, [6, 40]); b['cards'][1] = dict(top=0, alpha=np.zeros((0, WIN), np.float32), albedo=np.zeros((0, WIN, 3), np.float32), n_r=np.zeros((0, WIN), np.float32), n_t=np.zeros((0, WIN), np.float32), logd=np.zeros((0, WIN), np.float32), wall=np.zeros((0, WIN), bool))
try: export.pack(b)
except ValueError as e: assert 'card 1 is empty' in str(e) and '6 km' in str(e) and '40 km' in str(e), str(e)
else: assert False, 'an empty card was packed'
b['cards'][2] = b['cards'][1]
try: export.pack(dict(b, cards=[b['cards'][0], _bake(THREE, [6, 40])['cards'][1], b['cards'][1]]))
except ValueError as e: assert 'card 2 is empty' in str(e) and '40 km' in str(e), str(e)
else: assert False, 'an empty last card was packed'
# ---------------------------------------------------------------------------------------- the written files are the cards
def test_written_cards_decode_to_the_cards_in_memory():
"""Vienna's three cards, written and decoded again: alpha exactly, albedo within the lossy codec (and straight, not premultiplied, at partial alpha), the normal channels in their order (R along the ray, G across it), and the log-distance over the encoding range, within quantisation."""
saved = ridge.P
try: b = export.bake_place('vienna')
finally: ridge.P = saved
d = tempfile.mkdtemp()
"""Vienna's cards in three tiles (north, the rest azimuth's, the wrap), written and decoded again: alpha exactly, albedo within the lossy codec (and straight, not premultiplied, at partial alpha), the normal channels in their order (R along the ray, G across it), and the log-distance over the encoding
range, within quantisation."""
b = _vienna_bake(); d = tempfile.mkdtemp()
try:
dest = export.write_bake(d, b['place'], b['view'], b['meta'], export.pack(b), b['opaque']); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0
for c, rec in zip(b['cards'], m['cards']):
col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.sum())
assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1)
assert e[solid].mean() < 0.02 and np.percentile(e[solid], 99) < 0.08, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean())
assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels'
assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped'
assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range'
assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart'
assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'
dest = _write(d, b, export.pack(b)); m = json.load(open(dest / 'manifest.json')); enc = m['encoding']; span = enc['log_d_max'] - enc['log_d_min']; partial_seen = 0
for t in (0, 19, 31):
for c, rec in zip(b['cards'][t], m['tiles'][t]):
col = export.decode((dest / rec['colour']['file']).read_bytes()); geo = export.decode((dest / rec['geometry']['file']).read_bytes()); al = c['alpha']; wall = c['wall']; solid = (al > 0) & ~wall; part = (al > 0.05) & (al < 0.95) & ~wall; partial_seen += int(part.sum())
assert (col[..., 3] == np.rint(al * 255)).all(), 'alpha is not exact'; e = np.abs(col[..., :3] / 255.0 - c['albedo']).max(-1)
assert e[solid].mean() < 0.021 and np.percentile(e[solid], 99) < 0.081, ('albedo is off', e[solid].mean(), np.percentile(e[solid], 99)); assert part.sum() == 0 or e[part].mean() < 0.1, ('albedo at partial alpha is off: premultiplied?', e[part].mean())
assert (geo[..., 3] == 255).all(); q = 1.0 / 255 + 1e-6; assert (((geo[..., 0] == 255) & (geo[..., 1] == 255)) == wall).all(), 'the wall code is not R = G = 255 on exactly the wall pixels'
assert np.abs(geo[..., 0] / 255.0 * 2 - 1 - c['n_r'])[solid].max() < 2 * q and np.abs(geo[..., 1] / 255.0 * 2 - 1 - c['n_t'])[solid].max() < 2 * q, 'a normal channel is off or swapped'
assert np.abs(enc['log_d_min'] + geo[..., 2] / 255.0 * span - c['logd'])[solid].max() < span * q, 'the log-distance is off or not over the encoding range'
assert np.abs(c['n_r'][solid]).mean() > 0.05 and np.abs(c['n_t'][solid]).mean() > 0.01 and np.abs(c['n_r'][solid].mean() - c['n_t'][solid].mean()) > 0.0, 'the fixture does not tell the channels apart'
assert col[..., :3][solid].mean() > 20, 'albedo is zeroed'
assert partial_seen > 0, 'the fixture has no partial alpha'
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- wall rows and the camera
# ---------------------------------------------------------------------------------------- wall rows
def _first_sample_angle(b, i):
"""Per column, the angle of the first sample card i (> 0) reads: the first sample at or beyond its near seam, less the cross-fade half-width."""
k0 = np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(WIN)]); return k0, b['a'][k0, np.arange(WIN)]
k0 = np.array([np.searchsorted(D, b['seams'][i - 1][x] * math.exp(-ridge.XF)) for x in range(NW)]); return k0, b['a'][k0, np.arange(NW)]
def test_wall_rows_flagged():
"""Card i > 0 flags as wall exactly the rows below the angle of its first sample (the extruded face of the ridge it starts at), card 0 none; the wall carries R = G = 255 in the geometry file and no other pixel has r2 + t2 above 1.02; wall pixels keep that sample's
distance and their albedo is the ground material of the sample's height with the face up (so a steep face is not rock), constant down the column."""
steep = 0
for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20])):
for make in (lambda: _bake(WALLED, [20]), lambda: _bake(WIDE3, [20, 55]), lambda: _bake(_receding, [6]), lambda: _bake(_ramp, [20], fixed_m=[20000.0])): # the ramp's seam is fixed: the wall must stand on the slope, below the height where every material is rock or snow
b = make(); assert not b['cards'][0]['wall'].any(), 'card 0 has a wall'; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; seen = 0
for i, c in enumerate(b['cards']):
if i == 0: continue
k0, a0 = _first_sample_angle(b, i); want = (lo[:, None] < a0[None, :])[c['top']:c['top'] + c['alpha'].shape[0]]; assert (c['wall'] == want).all(), ('wall rows are not the rows below the first sample', i, int((c['wall'] != want).sum())); seen += int(want.sum())
geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], b['meta']['encoding'], c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255)
geo = export.decode(export.encode_geometry(c['n_r'], c['n_t'], c['logd'], dict(log_d_min=math.log(D[0]), log_d_max=math.log(D[-1])), c['wall'])); r, t = geo[..., 0] / 255.0 * 2 - 1, geo[..., 1] / 255.0 * 2 - 1; code = (geo[..., 0] == 255) & (geo[..., 1] == 255)
assert (code == c['wall']).all() and (r[~code] ** 2 + t[~code] ** 2 <= 1.02).all(), 'the wall code is not on exactly the wall pixels, or a real normal reaches it'
for x in np.flatnonzero(c['wall'].any(0)):
rows = np.flatnonzero(c['wall'][:, x]); ld = c['logd'][rows, x]; assert np.ptp(ld) < 1e-5 and abs(math.exp(ld[0]) - D[k0[x]]) < 1e-3 * D[k0[x]] + 60, ('a wall keeps its sample distance', x)
@ -321,36 +479,6 @@ def test_the_sheet_lights_a_wall_with_the_face_up():
n = 4; c = dict(albedo=np.ones((n, n, 3), np.float32), alpha=np.ones((n, n), np.float32), n_r=np.full((n, n), 0.9, np.float32), n_t=np.zeros((n, n), np.float32), wall=np.zeros((n, n), bool)); c['wall'][:, :2] = True
rgb, _ = export.lit(c); L = np.array(export.SHEET_LIGHT) / np.linalg.norm(export.SHEET_LIGHT); up = 0.35 + 0.65 * L[2]; tilted = 0.35 + 0.65 * np.clip(0.9 * L[0] + np.sqrt(1 - 0.81) * L[2], 0, 1)
assert np.allclose(rgb[:, :2], up) and np.allclose(rgb[:, 2:], tilted) and abs(up - tilted) > 0.05, (rgb[0, 0], rgb[0, 3])
def test_camera_contract():
"""scale_i = d_i / (d_i - r) for r = +200 and r = -100 (a function of r, not a constant or a clamp); a card's distance excludes its wall rows; |r| at half the nearest distance is refused; an r that lifts the nearest card off the frame bottom (backward) is
refused and writes nothing; a card shrunk below what a 16:9 viewport needs is refused; one card works."""
ds = [1000.0, 12000.0, 40000.0]
for r in (200.0, -100.0, 0.0): assert export.card_scales(ds, r) == [d / (d - r) for d in ds], r
assert export.card_scales(ds, 200.0)[0] > 1.2 and export.card_scales(ds, -100.0)[0] < 0.92 and export.card_scales(ds, 0.0) == [1.0, 1.0, 1.0]
for bad in (500.0, -500.0, 800.0):
try: export.card_scales(ds, bad)
except ValueError: pass
else: assert False, ('an offset of', bad, 'was accepted')
export.card_scales(ds, 499.0); export.card_scales(ds, -499.0)
b = _bake(WIDE3, [20, 55]); c1 = b['cards'][1]; solid = c1['alpha'] >= 0.5; c1['wall'] = np.zeros_like(c1['wall']); c1['wall'][:c1['alpha'].shape[0] * 3 // 4] = True; c1['logd'] = np.where(c1['wall'], c1['logd'] + 3.0, c1['logd']) # three quarters of the card is wall, far off the rest
want = float(np.exp(np.median(c1['logd'][solid & ~c1['wall']]))); with_wall = float(np.exp(np.median(c1['logd'][solid]))); assert abs(with_wall - want) > 0.05 * want, ('the fixture cannot tell the median with walls from the one without', with_wall, want)
pk = export.pack(b); assert abs(pk[1]['distance_m'] - want) < 1e-6 * want and pk[1]['median_m'] == pk[1]['distance_m'], ('the distance counted wall rows', pk[1]['distance_m'], want)
assert [p['scale'] for p in pk] == [p['distance_m'] / (p['distance_m'] - export.CAMERA_R_M) for p in pk]
d = tempfile.mkdtemp()
try:
back = dict(b['meta'], camera=dict(r_m=-100.0, heading_max_deg=23.0)); pkb = export.pack(dict(b, meta=back)); assert all(p['scale'] < 1 for p in pkb)
_refuses(d + '/back', b, pkb, 'a backward camera that lifts the nearest card off the frame bottom was written', meta=back)
try: export.pack(dict(b, meta=dict(b['meta'], camera=dict(r_m=0.5 * pk[0]['distance_m'], heading_max_deg=23.0))))
except ValueError: pass
else: assert False, 'an offset of half the nearest distance was packed'
view = b['view']; tops = [c['top'] for c in b['cards']]; bands = [c['alpha'].shape[0] for c in b['cards']]; export.check_camera([1.0, 1.0, 1.0], tops, bands, view)
try: export.check_camera([1.0, 1.0, 0.8], tops, bands, view)
except ValueError as e: assert '16:9' in str(e), str(e)
else: assert False, 'a card too small for a 16:9 viewport at rest was accepted'
one, pk1 = _packed(_bake(WALLED, [])); assert len(pk1) == 1 and pk1[0]['scale'] == pk1[0]['distance_m'] / (pk1[0]['distance_m'] - export.CAMERA_R_M); dest = export.write_bake(d + '/one', one['place'], one['view'], one['meta'], pk1, one['opaque'])
assert len(json.load(open(dest / 'manifest.json'))['cards']) == 1
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- rules that no other test touched
def test_seams_keep_their_separation():
"""Two authored targets closer than SEAM_SEP (6 and 7 km, 0.15 nat): the seams still sit at least 0.4 nat apart in every column."""
@ -363,15 +491,15 @@ def test_elev_is_the_curved_refracted_angle():
def test_coverage_counts_every_visible_row_including_the_foreground():
"""Per column the coverage sums to the visible rows of the opaque view: (min(skyline, top) - bottom) x px per degree, the rows below the first sample included once, not twice (a ground just under the eye shows below the first sample)."""
for i, hf in enumerate((terrain(block(0, 359.99, 0, 20000, 91), block(0, 359.99, 20000, 21500, 600)), THREE)):
A, Hh = rays(hf); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw = ridge.win(A); cov = ridge.coverage(D, aw); want = np.clip(np.minimum(aw.max(0), ridge.TOP_DEG) - ridge.BOTTOM_DEG, 0, None) * ridge.PXDEG_V
assert np.abs(cov.sum(0) - want).max() < 1e-6, np.abs(cov.sum(0) - want).max(); assert cov.shape == (ridge.COV_BINS, WIN)
A, Hh = rays(hf); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw = _w(A); cov = ridge.coverage(D, aw); want = np.clip(np.minimum(aw.max(0), ridge.TOP_DEG) - ridge.BOTTOM_DEG, 0, None) * ridge.PXDEG_V
assert np.abs(cov.sum(0) - want).max() < 1e-6, np.abs(cov.sum(0) - want).max(); assert cov.shape == (ridge.COV_BINS, NW)
if i == 0: assert (cov[0] > 100).all(), ('no foreground rows in the first bin', float(cov[0].min()))
def test_cards_interpolate_between_samples_and_renormalise():
"""On a ramp face every card pixel sits between two samples: its log-distance lies strictly between theirs (not on the nearer sample), and its normal is the normalised blend of theirs by that same fraction (the samples carry alternating normals, so a blend
that is not renormalised, or a hit that is not interpolated, differs)."""
A, Hh = rays(terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az)); ridge.P.update(win0=0, eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = ridge.win(A), ridge.win(Hh); k = np.arange(len(D))[:, None]
A, Hh = rays(terrain(lambda dk, az: np.where(dk >= 4000, GROUND + 0.5 * (dk - 4000), 0.0) + 0 * az)); ridge.P.update(eye_m=EYE); ridge.set_view(A.max(0)); aw, hw = _w(A), _w(Hh); k = np.arange(len(D))[:, None]
nr = np.broadcast_to(np.where(k % 2 == 0, -0.8, 0.8), aw.shape).astype(float); nt = np.broadcast_to(np.where(k % 3 == 0, 0.3, -0.3), aw.shape).astype(float); nu = np.sqrt(1 - nr ** 2 - nt ** 2) * 0 + 0.5
c = ridge.cards(D, aw, hw, np.zeros((0, WIN)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(D); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
c = ridge.cards(D, aw, hw, np.zeros((0, NW)), nrm=(nr, nt, nu))[0]; x = 300; sel = np.flatnonzero(c['alpha'][:, x] > 0.999); ld = c['logd'][sel, x].astype(np.float64); L = np.log(D); kk = np.searchsorted(L, ld, 'left'); kp = kk - 1; ok = kp >= 0
t = (ld - L[np.maximum(kp, 0)]) / (L[kk] - L[np.maximum(kp, 0)]); inner = ok & (t > 0.02) & (t < 0.98); assert inner.sum() > 0.3 * len(sel), ('hits sit on samples, not between them', int(inner.sum()), len(sel))
mix = lambda arr: arr[np.maximum(kp, 0), x] + t * (arr[kk, x] - arr[np.maximum(kp, 0), x]); m = np.sqrt(mix(nr) ** 2 + mix(nt) ** 2 + mix(nu) ** 2); er = np.abs(c['n_r'][sel, x] - mix(nr) / m)[inner]; et = np.abs(c['n_t'][sel, x] - mix(nt) / m)[inner]
assert er.max() < 1e-3 and et.max() < 1e-3, ('the normal is not the normalised blend of the two samples', er.max(), et.max())

View file

@ -50,8 +50,24 @@ callbacks and the creature sizing rule. Nothing has drawn a creature.
## Ridge scene: Vienna and the weather
The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E
(`ridge/vienna.ts`).
The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the sun over the viewpoint (Vienna's is 48.1929826 N, 16.3534237 E, from the manifest).
### The sky choice
The viewer's choice is Auto, one of six named moments (Dawn, Morning, Noon, Golden hour, Dusk, Night) or a free moment (a place-local date and
minute of the day). `ridge/skyMoment.ts` is the one owner of what it draws: `momentFor(choice, place, now)` returns the instant and `skyBand(elevation)`
turns the sun at that instant into day, dusk or night (day from 6 degrees up, night from 6 down), which the ink theme (`skyTheme.ts`, `skyInk.ts`), the
display budget (`ridge/toneMap.ts`) and the rebuild key (`skyForState.ts`) all read. Auto is the real sun over the loaded place now. A named moment is
today's at the place (Night tonight's: the solar midnight nearest, before the day's noon the one just passed or coming, after it the one coming), from the sun's elevation crossings of the place-local day (`SKY_MOMENTS`, one row each: dawn and dusk at -3 degrees, golden hour at
+4, morning at the lesser of 15 degrees and half the noon elevation, noon the day's maximum, night solar midnight). Place-local time comes only from
`place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the
named moments draw today's weather; a free moment draws a clear sky.
`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key
of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the configured place (nothing else fetches it, so a page with no scene fetches nothing) and the build
settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, a card that will not decode), so the sky, the weather, the ink and the Auto
timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band
changes or a named moment's place-local day rolls over.
The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear.
The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit

View file

@ -0,0 +1,173 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { SkyChoice } from './ridge/skyMoment';
import { FALLBACK_VIEW } from './ridge/view';
import {
MENU_CHOICES,
SkyMomentPicker,
SkyStateControl,
choiceLabel,
useNativeChange,
} from './SkyStateControl';
// The component's hooks are held still, as in RoomOutbox.actions.test.tsx: state is its initial value, refs are plain boxes, effects are
// kept to be run once the test has put an element in each ref. The element tree it returns is read and its native events are dispatched
// on a fake input, so no DOM is needed.
const held = vi.hoisted(() => ({
effects: [] as Array<() => unknown>,
choice: { kind: 'auto' } as unknown,
}));
vi.mock('react', async (importOriginal) => {
const actual = await importOriginal<typeof import('react')>();
const useState = (init: unknown) => [
typeof init === 'function' ? (init as () => unknown)() : init,
() => undefined,
];
const useRef = (init: unknown) => ({ current: init });
const useEffect = (fn: () => unknown) => {
held.effects.push(fn);
};
return {
...actual,
default: { ...actual, useState, useRef, useEffect },
useState,
useRef,
useEffect,
};
});
vi.mock('../../hooks/useSkyState', () => ({
useSkyChoice: () => held.choice,
useDrawnPlace: () => FALLBACK_VIEW.place,
}));
vi.mock('../../hooks/useClientConfig', () => ({ useClientConfig: () => ({}) }));
type El = { type?: unknown; ref?: unknown; props?: Record<string, unknown> };
/** Every element reachable through any prop (children, `content`, `after`). */
const walk = (node: unknown): El[] => {
if (Array.isArray(node)) return node.flatMap(walk);
if (node && typeof node === 'object' && 'props' in node) {
const el = node as El;
return [el, ...Object.values(el.props ?? {}).flatMap(walk)];
}
return [];
};
const textOf = (node: unknown): string => {
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(textOf).join('');
if (node && typeof node === 'object' && 'props' in node) {
return textOf((node as El).props?.children);
}
return '';
};
/** A stand-in input: a real EventTarget with a value. */
const fakeInput = (value: string) => Object.assign(new EventTarget(), { value });
const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type));
beforeEach(() => {
held.effects.length = 0;
held.choice = { kind: 'auto' };
});
describe('the sky menu choices', () => {
const tree = () => walk(SkyStateControl());
const radios = () => tree().filter((e) => e.props?.role === 'menuitemradio');
it('lists Auto and the six named moments, then Pick a moment', () => {
expect(MENU_CHOICES.map(choiceLabel)).toEqual([
'Auto',
'Dawn',
'Morning',
'Noon',
'Golden hour',
'Dusk',
'Night',
]);
expect(radios().map((e) => textOf(e))).toEqual([
'Auto',
'Dawn',
'Morning',
'Noon',
'Golden hour',
'Dusk',
'Night',
'Pick a moment',
]);
});
it.each([
[{ kind: 'auto' }, 0],
[{ kind: 'named', id: 'dawn' }, 1],
[{ kind: 'named', id: 'night' }, 6],
[{ kind: 'free', date: '2026-12-21', minutes: 400 }, 7],
] as Array<[SkyChoice, number]>)('aria-checked follows the choice %j', (choice, checked) => {
held.choice = choice;
radios().forEach((e, i) => expect(e.props?.['aria-checked'], `item ${i}`).toBe(i === checked));
});
it("the button reads 'Sky: Auto', 'Sky: Dawn' or 'Sky: <date> <time>'", () => {
const label = () =>
tree().find((e) => e.props?.['aria-haspopup'] === 'menu')?.props?.['aria-label'];
expect(label()).toBe('Sky: Auto');
held.choice = { kind: 'named', id: 'dawn' };
expect(label()).toBe('Sky: Dawn');
held.choice = { kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 };
expect(label()).toBe('Sky: 2026-12-21 06:40');
});
});
describe('committing on change, not on input', () => {
it('a native input event commits nothing and the change event commits once', () => {
const commits: string[] = [];
const ref = useNativeChange<HTMLInputElement>((el) => commits.push(el.value));
const target = fakeInput('600');
(ref as { current: unknown }).current = target;
held.effects.forEach((run) => run());
for (let i = 0; i < 5; i += 1) fire(target, 'input');
expect(commits).toEqual([]);
fire(target, 'change');
expect(commits).toEqual(['600']);
});
it('the picker commits the slider on release only, with the date it holds, and the date on change when it is a date in range', () => {
const commits: unknown[] = [];
const tree = walk(
SkyMomentPicker({
seed: { kind: 'free', date: '2026-12-21', minutes: 600 },
tz: 'Europe/Vienna',
onCommit: (c) => commits.push(c),
})
);
const input = (type: string) => tree.find((e) => e.type === 'input' && e.props?.type === type);
const date = fakeInput('2026-12-21');
const slider = fakeInput('600');
(input('date')?.ref as { current: unknown }).current = date;
(input('range')?.ref as { current: unknown }).current = slider;
held.effects.forEach((run) => run());
slider.value = '735';
fire(slider, 'input');
fire(slider, 'input');
expect(commits).toEqual([]);
fire(slider, 'change');
expect(commits).toEqual([{ kind: 'free', date: '2026-12-21', minutes: 735 }]);
date.value = '2026-07-15';
fire(date, 'change');
expect(commits[1]).toEqual({ kind: 'free', date: '2026-07-15', minutes: 735 });
date.value = '1800-01-01';
fire(date, 'change');
date.value = '';
fire(date, 'change');
expect(commits).toHaveLength(2);
expect(input('range')?.props).toMatchObject({ min: 0, max: 1439, step: 5 });
expect(input('date')?.props).toMatchObject({ min: '1900-01-01', max: '2100-12-31' });
});
it('the picker shows the place-local time and the zone beside the slider', () => {
const tree = SkyMomentPicker({
seed: { kind: 'free', date: '2026-12-21', minutes: 400 },
tz: 'Europe/Vienna',
onCommit: () => undefined,
});
expect(textOf(tree)).toMatch(/^06:40 \S+/);
});
});

View file

@ -1,4 +1,4 @@
import React, { MouseEventHandler, useEffect, useState } from 'react';
import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import {
Box,
config,
@ -13,8 +13,19 @@ import {
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '../../utils/keyboard';
import { useSkyState } from '../../hooks/useSkyState';
import { SKY_STATES, pickSkyState, type SkyState } from './skyState';
import { useDrawnPlace, useSkyChoice } from '../../hooks/useSkyState';
import { pickSkyChoice, skyNow } from './skyState';
import {
FREE_DATE_MAX,
FREE_DATE_MIN,
MOMENT_IDS,
isDate,
seedFree,
zoneName,
zonedInstant,
} from './ridge/skyMoment';
import type { MomentId, SkyChoice } from './ridge/skyMoment';
import { FALLBACK_VIEW } from './ridge/view';
import { loadManifest } from './ridge/manifest';
import {
LINES_CREDIT,
@ -27,36 +38,129 @@ import {
import { useClientConfig } from '../../hooks/useClientConfig';
import { PhoneHit } from '../../styles/PhoneHit.css';
const LABEL: Record<SkyState, string> = {
auto: 'Auto',
day: 'Day',
export const MOMENT_LABEL: Record<MomentId, string> = {
dawn: 'Dawn',
morning: 'Morning',
noon: 'Noon',
golden: 'Golden hour',
dusk: 'Dusk',
night: 'Night',
};
const hhmm = (minutes: number): string =>
`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
/** What the button and the menu call a choice: Auto, the moment's name, or the free moment's place-local date and time. */
export const choiceLabel = (c: SkyChoice): string =>
c.kind === 'auto'
? 'Auto'
: c.kind === 'named'
? MOMENT_LABEL[c.id]
: `${c.date} ${hhmm(c.minutes)}`;
/** The choices the menu lists, in order. */
export const MENU_CHOICES: readonly SkyChoice[] = [
{ kind: 'auto' },
...MOMENT_IDS.map((id): SkyChoice => ({ kind: 'named', id })),
];
const sameChoice = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
/**
* One title-bar button that opens the four sky states. A single button, not a row, so the bar
* still fits a 320 px phone beside the search button; the menu items carry the state names.
* Run `onChange` on the element's native `change` event: for a slider, its release, not every `input` tick (React's onChange is the
* input event). Each commit rebuilds the scene, so a drag must commit once.
*/
export function useNativeChange<T extends HTMLElement>(onChange: (el: T) => void) {
const ref = useRef<T>(null);
const latest = useRef(onChange);
latest.current = onChange;
useEffect(() => {
const el = ref.current;
if (!el) return undefined;
const handler = () => latest.current(el);
el.addEventListener('change', handler);
return () => el.removeEventListener('change', handler);
}, []);
return ref;
}
type Free = Extract<SkyChoice, { kind: 'free' }>;
/** A date and a time of day at the place, committed when each input changes (the slider on release), never per `input` tick. */
export function SkyMomentPicker({
seed,
tz,
onCommit,
}: {
seed: Free;
tz: string;
onCommit: (c: Free) => void;
}) {
const [minutes, setMinutes] = useState(seed.minutes);
const at = useRef({ date: seed.date, minutes: seed.minutes });
const dateRef = useNativeChange<HTMLInputElement>((el) => {
if (!isDate(el.value) || el.value < FREE_DATE_MIN || el.value > FREE_DATE_MAX) return;
at.current.date = el.value;
onCommit({ kind: 'free', ...at.current });
});
const sliderRef = useNativeChange<HTMLInputElement>((el) => {
at.current.minutes = Number(el.value);
onCommit({ kind: 'free', ...at.current });
});
const zone = zoneName(zonedInstant(at.current.date, minutes, tz), tz);
return (
<Box direction="Column" gap="100" style={{ padding: config.space.S200 }}>
<input
ref={dateRef}
type="date"
aria-label="Date"
min={FREE_DATE_MIN}
max={FREE_DATE_MAX}
defaultValue={seed.date}
/>
<input
ref={sliderRef}
type="range"
aria-label="Time of day"
min={0}
max={1439}
step={5}
defaultValue={seed.minutes}
onInput={(evt) => setMinutes(Number(evt.currentTarget.value))}
/>
<Text size="T200" priority="300">
{hhmm(minutes)} {zone}
</Text>
</Box>
);
}
/**
* One title-bar button that opens the sky choices: Auto, the six named moments of today at the place, and a free date and time. A single
* button, not a row, so the bar still fits a 320 px phone beside the search button; the menu items carry the names.
*/
export function SkyStateControl() {
const state = useSkyState();
const choice = useSkyChoice();
const drawn = useDrawnPlace();
const [picking, setPicking] = useState(false);
const [cords, setCords] = useState<RectCords>();
const backgroundScene = useClientConfig().backgroundScene;
const place = backgroundScene?.place;
const placeId = backgroundScene?.place;
const place = drawn ?? FALLBACK_VIEW.place;
const [credit, setCredit] = useState<string>();
const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch';
useEffect(() => {
if (!ridgeOn) return undefined;
let live = true;
loadManifest(import.meta.env.BASE_URL, place).then(
loadManifest(import.meta.env.BASE_URL, placeId).then(
(m) => live && setCredit(terrainCredit(m)),
() => live && setCredit(undefined)
);
return () => {
live = false;
};
}, [ridgeOn, place]);
}, [ridgeOn, placeId]);
const open: MouseEventHandler<HTMLButtonElement> = (evt) => {
setCords(evt.currentTarget.getBoundingClientRect());
};
@ -71,34 +175,63 @@ export function SkyStateControl() {
focusTrapOptions={{
initialFocus: '[aria-checked="true"]',
returnFocusOnDeactivate: true,
onDeactivate: () => setCords(undefined),
onDeactivate: () => {
setCords(undefined);
setPicking(false);
},
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
isKeyForward: (evt: KeyboardEvent) =>
evt.key === 'ArrowDown' && !(evt.target instanceof HTMLInputElement),
isKeyBackward: (evt: KeyboardEvent) =>
evt.key === 'ArrowUp' && !(evt.target instanceof HTMLInputElement),
escapeDeactivates: stopPropagation,
}}
>
<Menu role="menu" aria-label="Sky">
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
{SKY_STATES.map((s) => (
<MenuItem
key={s}
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={state === s}
onClick={() => {
pickSkyState(s);
setCords(undefined);
}}
after={state === s ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">{LABEL[s]}</Text>
</Box>
</MenuItem>
))}
{MENU_CHOICES.map((c) => {
const checked = sameChoice(c, choice);
return (
<MenuItem
key={choiceLabel(c)}
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={checked}
onClick={() => {
pickSkyChoice(c);
setCords(undefined);
}}
after={checked ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">{choiceLabel(c)}</Text>
</Box>
</MenuItem>
);
})}
<MenuItem
size="300"
variant="Surface"
radii="300"
role="menuitemradio"
aria-checked={choice.kind === 'free'}
aria-expanded={picking}
onClick={() => setPicking(!picking)}
after={choice.kind === 'free' ? <Icon size="100" src={Icons.Check} /> : undefined}
>
<Box grow="Yes">
<Text size="T300">Pick a moment</Text>
</Box>
</MenuItem>
{picking && (
<SkyMomentPicker
seed={seedFree(choice, place, skyNow())}
tz={place.tz}
onCommit={pickSkyChoice}
/>
)}
{ridgeOn && (
<Box
direction="Column"
@ -136,8 +269,8 @@ export function SkyStateControl() {
<IconButton
className={PhoneHit}
variant="Background"
aria-label={`Sky: ${LABEL[state]}`}
title={`Sky: ${LABEL[state]}`}
aria-label={`Sky: ${choiceLabel(choice)}`}
title={`Sky: ${choiceLabel(choice)}`}
aria-haspopup="menu"
aria-expanded={!!cords}
onClick={open}

View file

@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit';
import { atSolarTime } from './ridge/skyTestkit';
import type { Scene } from './Scene';
import { startBackgroundScene } from './index';
import { pickSkyState, setSkyClock, setSkyState } from './skyState';
import { getResolvedSkyState, getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState';
import { skyBand } from './ridge/skyMoment';
import type { SkyChoice } from './ridge/skyMoment';
import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
@ -30,14 +32,19 @@ vi.mock('./skyForState', async (importOriginal) => {
...actual,
ridgeSkyFor: (...args: Parameters<typeof actual.ridgeSkyFor>) => {
const [state, view] = args;
// One bake per state and place; the view is the one owner of the place, so it is part of what a sky is.
const key = `${state}@${JSON.stringify(view.place)}`;
// One bake per choice and place; the view is the one owner of the place, so it is part of what a sky is.
const key = `${JSON.stringify(state)}@${JSON.stringify(view.place)}`;
if (!baked.has(key)) baked.set(key, actual.ridgeSkyFor(...args));
return baked.get(key) as ReturnType<typeof actual.ridgeSkyFor>;
},
};
});
const AUTO: SkyChoice = { kind: 'auto' };
const NOON: SkyChoice = { kind: 'named', id: 'noon' };
const DUSK: SkyChoice = { kind: 'named', id: 'dusk' };
const NIGHT: SkyChoice = { kind: 'named', id: 'night' };
const canvas = {} as HTMLCanvasElement;
const config = { tier: 'low' as const };
const caps = { hardwareConcurrency: 8 };
@ -84,17 +91,22 @@ const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() });
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
beforeEach(() => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
vi.stubGlobal('localStorage', {
getItem: () => null,
setItem: () => undefined,
removeItem: () => undefined,
});
// Local midnight: 'auto' resolves to night.
setSkyClock(() => atStandardTime(0, 0));
setSkyState('auto');
setSkyClock(() => atSolarTime(0, 0));
setSkyChoice(AUTO);
setSkyPlace(FALLBACK_VIEW.place);
createRidgeScene.mockReset();
createScene.mockReset();
loadBackdrop.mockReset();
});
afterEach(() => {
setSkyClock();
setSkyState('auto');
setSkyChoice(AUTO);
vi.unstubAllGlobals();
});
@ -104,28 +116,31 @@ describe('startBackgroundScene follows the sky state', () => {
const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
hex(ridgeSkyFor(AUTO, FALLBACK_VIEW).top)
);
scene?.dispose();
});
it('does not rebuild when auto is replaced by the explicit state it already resolves to', async () => {
const a = fakeScene();
createRidgeScene.mockReturnValueOnce(a);
it('rebuilds when Auto is replaced by the named moment of the same band: live and frozen are different skies, and the same pick again is not a rebuild', async () => {
const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('night');
setSkyChoice(NIGHT);
await flush();
expect(a.dispose).not.toHaveBeenCalled();
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(a.dispose).toHaveBeenCalledOnce();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
setSkyChoice(NIGHT);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
scene?.dispose();
});
it('starts on the stored state', async () => {
setSkyState('night');
setSkyChoice(NIGHT);
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
hex(ridgeSkyFor(NIGHT, FALLBACK_VIEW).top)
);
scene?.dispose();
});
@ -135,11 +150,11 @@ describe('startBackgroundScene follows the sky state', () => {
const second = fakeScene();
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(first.dispose).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top)
);
scene?.dispose();
expect(second.dispose).toHaveBeenCalledOnce();
@ -149,12 +164,12 @@ describe('startBackgroundScene follows the sky state', () => {
const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const started = startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyChoice(NOON);
const scene = await started;
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
hex(ridgeSkyFor(NOON, FALLBACK_VIEW).top)
);
expect(a.dispose).toHaveBeenCalledOnce();
scene?.dispose();
@ -165,12 +180,12 @@ describe('startBackgroundScene follows the sky state', () => {
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(b.login).not.toHaveBeenCalled();
scene?.login();
expect(b.login).toHaveBeenCalledOnce();
setSkyState('dusk');
setSkyChoice(DUSK);
await flush();
expect(c.login).toHaveBeenCalledOnce();
scene?.dispose();
@ -183,11 +198,11 @@ describe('startBackgroundScene follows the sky state', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onInactive, onActive });
expect(onInactive).not.toHaveBeenCalled();
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(onInactive).toHaveBeenCalledOnce();
expect(onActive).not.toHaveBeenCalled();
setSkyState('dusk');
setSkyChoice(DUSK);
await flush();
expect(onActive).toHaveBeenCalledOnce();
expect(onInactive).toHaveBeenCalledOnce();
@ -198,7 +213,7 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null);
const onInactive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onInactive });
setSkyState('day');
setSkyChoice(NOON);
scene?.dispose();
await flush();
expect(onInactive).not.toHaveBeenCalled();
@ -210,7 +225,7 @@ describe('startBackgroundScene follows the sky state', () => {
const scene = await startBackgroundScene(config, caps, { canvas });
scene?.dispose();
scene?.dispose();
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(first.dispose).toHaveBeenCalledOnce();
@ -219,7 +234,7 @@ describe('startBackgroundScene follows the sky state', () => {
it('builds nothing for a rebuild that is disposed before it starts', async () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyChoice(NOON);
scene?.dispose();
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
@ -229,13 +244,13 @@ describe('startBackgroundScene follows the sky state', () => {
const scenes = [fakeScene(), fakeScene(), fakeScene()];
scenes.forEach((s) => createRidgeScene.mockReturnValueOnce(s));
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyState('dusk');
setSkyChoice(NOON);
setSkyChoice(DUSK);
await flush();
// The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else.
const built = createRidgeScene.mock.calls.length;
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
);
const live = scenes[built - 1];
scene?.login();
@ -253,13 +268,13 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(fakeScene());
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
setSkyState('day');
setSkyState('dusk');
setSkyChoice(NOON);
setSkyChoice(DUSK);
await flush();
// The initial build and one rebuild, for dusk; day's rebuild stood down before building anything.
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
);
scene?.dispose();
});
@ -268,19 +283,19 @@ describe('startBackgroundScene follows the sky state', () => {
// change finished loading, was found stale and was never made (so it never showed or spoke), and only the newest sky was announced.
const changeAfter = async (ticks: number) => {
createRidgeScene.mockReset();
setSkyState('auto');
setSkyChoice(AUTO);
const [a, b, c] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b).mockReturnValueOnce(c);
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
setSkyState('day');
setSkyChoice(NOON);
await microtasks(ticks);
setSkyState('dusk');
setSkyChoice(DUSK);
await flush();
const at = `at ${ticks} microtasks`;
const built = createRidgeScene.mock.calls.length;
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
hex(ridgeSkyFor(DUSK, FALLBACK_VIEW).top)
);
// The newest build is live, every earlier one disposed exactly once, and only the live one is shown.
const live = [a, b, c][built - 1];
@ -313,7 +328,7 @@ describe('startBackgroundScene follows the sky state', () => {
createScene.mockReturnValue(inner);
const scene = await startBackgroundScene({ ...config, style: 'raymarch' }, caps, { canvas });
expect(scene).toBe(inner);
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(createScene).toHaveBeenCalledOnce();
});
@ -380,6 +395,89 @@ describe('the ridge planes', () => {
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
});
it("makes the manifest's place the sky's place, so the ink and the scene read one place; a failed load makes it the drawn fallback's", async () => {
served();
loader();
createRidgeScene.mockReturnValue(fakeScene());
setSkyPlace(undefined);
(await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose();
expect(getSkyPlace()?.id).toBe('graz');
expect(getSkyPlace()?.tz).toBe('Europe/Vienna');
forgetManifests();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
);
setSkyPlace(undefined);
(await startBackgroundScene(config, caps, { canvas }))?.dispose();
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
});
it('a manifest that fails to load: the ink follows the drawn fallback sky, and Auto still ticks', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
);
createRidgeScene.mockReturnValue(fakeScene());
setSkyPlace(undefined);
setSkyChoice(NOON);
const scene = await startBackgroundScene(config, caps, { canvas });
try {
const opts = createRidgeScene.mock.calls[0][0];
expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
expect(getResolvedSkyState()).toBe('day');
expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation));
} finally {
scene?.dispose();
}
// Auto crosses dusk with the place the fallback scene drew.
setSkyChoice(AUTO);
vi.useFakeTimers();
try {
let now = atSolarTime(17, 0);
setSkyClock(() => now);
const heard = vi.fn();
const off = subscribe(heard);
now = atSolarTime(18, 10);
vi.advanceTimersByTime(60_000);
expect(heard).toHaveBeenCalledWith('dusk');
off();
} finally {
vi.useRealTimers();
}
});
it('cards that fail on a place that is not the fallback: the sky and the ink are at the one place, the fallback', async () => {
const fuji = {
...(wireManifest() as any).place,
id: 'fuji',
lat: 35.36,
lon: 138.73,
tz: 'Asia/Tokyo',
};
served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ place: fuji }) });
const { ctl } = loader();
ctl.fail = true;
createRidgeScene.mockReturnValue(fakeScene());
setSkyPlace(undefined);
setSkyChoice(NOON);
const scene = await startBackgroundScene(config, caps, { canvas });
try {
const opts = createRidgeScene.mock.calls[0][0];
expect(opts.backdrop).toBeUndefined();
expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
expect(getResolvedSkyState()).toBe(skyBand(opts.sky.physical.sun.elevation));
// The next key, made before the next build, is for the view that is drawn: the place does not flip back to the manifest's.
setSkyChoice(DUSK);
await flush();
expect(getSkyPlace()).toEqual(FALLBACK_VIEW.place);
} finally {
scene?.dispose();
}
});
const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
@ -420,7 +518,7 @@ describe('the ridge cards failing', () => {
const onCompileFail = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined();
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(onPlanesFail).toHaveBeenCalledOnce();
@ -448,7 +546,7 @@ describe('the ridge cards and the live scene', () => {
const onPlanesFail = vi.fn();
const onPlanesOk = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true);
@ -463,12 +561,12 @@ describe('the ridge cards and the live scene', () => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(ctl.calls.map((s) => s.state)).toEqual(['night']);
setSkyState('night'); // the sky already drawn: no rebuild, no lighting
await flush();
expect(ctl.calls).toHaveLength(1);
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']);
setSkyChoice(NOON); // the sky already drawn: no rebuild, no lighting
await flush();
expect(ctl.calls).toHaveLength(2);
expect(createRidgeScene.mock.calls[1][0].sky.physical).toBe(ctl.calls[1]);
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
scene?.dispose();
@ -480,16 +578,17 @@ describe('the ridge cards and the live scene', () => {
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
expect(createRidgeScene.mock.calls[0][0].lines).toBe(false);
pickSkyState('night'); // from Auto: a choice, the same sky
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(1);
pickSkyState('night'); // re-picked: the lines
pickSkyChoice(NIGHT); // from Auto: a choice, a frozen sky
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls[1][0].lines).toBe(true);
pickSkyState('night');
expect(createRidgeScene.mock.calls[1][0].lines).toBe(false);
pickSkyChoice(NIGHT); // re-picked: the lines
await flush();
expect(createRidgeScene.mock.calls[2][0].lines).toBe(false);
expect(createRidgeScene).toHaveBeenCalledTimes(3);
expect(createRidgeScene.mock.calls[2][0].lines).toBe(true);
pickSkyChoice(NIGHT);
await flush();
expect(createRidgeScene.mock.calls[3][0].lines).toBe(false);
scene?.dispose();
});
@ -508,20 +607,21 @@ describe('the ridge cards and the live scene', () => {
scene?.dispose();
});
it("keys a rebuild by the manifest's place: the same sky state over a rebaked place rebuilds", async () => {
it("keys a rebuild by the manifest's place: the same sky over a rebaked place rebuilds", async () => {
serve();
loader();
const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const w = wireManifest() as any;
setSkyChoice(NIGHT);
const scene = await startBackgroundScene(config, caps, { canvas });
// 'auto' at midnight and 'night' are one sky: no rebuild, while the place is the one drawn.
setSkyState('night');
// The same choice, told again while the place is the one drawn: no rebuild.
setSkyPlace(undefined);
await flush();
expect(createRidgeScene).toHaveBeenCalledOnce();
forgetManifests();
serve({ ...w, place: { ...w.place, id: 'graz' } });
setSkyState('auto');
setSkyPlace(undefined);
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz');
@ -563,7 +663,7 @@ describe('the ridge cards and the live scene', () => {
const at = (p: { lat: number; lon: number }) =>
weatherFromFile(
file,
sunAt({ id: 'x', altitudeKm: 0, ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000))
sunAt({ id: 'x', altitudeKm: 0, tz: 'UTC', ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000))
.elevation
);
expect(at(FALLBACK_VIEW.place)).not.toBe(at(place));
@ -591,7 +691,7 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(d.ctl.pending.length).toBeGreaterThan(0);
expect(first.dispose).not.toHaveBeenCalled();
@ -616,7 +716,7 @@ describe('the ridge cards and the live scene', () => {
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
d.ctl.hold = true;
d.ctl.fail = true;
setSkyState('day');
setSkyChoice(NOON);
await flush();
scene?.dispose();
await d.release();
@ -632,10 +732,10 @@ describe('the ridge cards and the live scene', () => {
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
d.ctl.hold = true;
d.ctl.fail = true;
setSkyState('day'); // stale: its decodes will reject
setSkyChoice(NOON); // stale: its decodes will reject
await flush();
d.ctl.fail = false;
setSkyState('dusk'); // the live one: its decodes will succeed
setSkyChoice(DUSK); // the live one: its decodes will succeed
await flush();
const stale = d.ctl.pending.splice(0, 1);
d.ctl.pending.length = 0;
@ -657,10 +757,10 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
setSkyState('day'); // stale: its decodes are held until after the newer build is live
setSkyChoice(NOON); // stale: its decodes are held until after the newer build is live
await flush();
const dayDecodes = d.ctl.pending.splice(0);
setSkyState('dusk');
setSkyChoice(DUSK);
await flush();
const duskDecodes = d.ctl.pending.splice(0);
expect(dayDecodes.length).toBeGreaterThan(0);
@ -690,7 +790,7 @@ describe('the ridge cards and the live scene', () => {
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
setSkyState('day');
setSkyChoice(NOON);
await flush();
scene?.dispose();
await d.release();
@ -707,7 +807,7 @@ describe('the ridge cards and the live scene', () => {
const onInactive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive });
d.ctl.fail = true;
setSkyState('day');
setSkyChoice(NOON);
await flush();
expect(onInactive).toHaveBeenCalledOnce();
expect(onPlanesFail).not.toHaveBeenCalled();
@ -723,17 +823,17 @@ describe('the ridge cards and the live scene', () => {
const onPlanesOk = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
expect(onPlanesFail).toHaveBeenCalledOnce();
setSkyState('day'); // still failing: the host is not told twice
setSkyChoice(NOON); // still failing: the host is not told twice
await flush();
expect(onPlanesFail).toHaveBeenCalledOnce();
expect(onPlanesOk).not.toHaveBeenCalled();
d.ctl.fail = false;
setSkyState('dusk');
setSkyChoice(DUSK);
await flush();
expect(onPlanesOk).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined();
d.ctl.fail = true;
setSkyState('night');
setSkyChoice(NIGHT);
await flush();
expect(onPlanesFail).toHaveBeenCalledTimes(2);
scene?.dispose();

View file

@ -1,12 +1,11 @@
import type { Scene, SceneOptions } from './Scene';
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
import { debugOverlaysAllowed } from './debugOverlays';
import { getConstellationLines, getSkyState, subscribe } from './skyState';
import type { SkyState } from './skyState';
import { getConstellationLines, getSkyChoice, subscribe } from './skyState';
import type { SkyChoice } from './ridge/skyMoment';
import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop';
import { loadManifest } from './ridge/manifest';
import type { RidgeManifest } from './ridge/manifest';
import { FALLBACK_VIEW } from './ridge/view';
export type { Scene, SceneStats } from './Scene';
@ -15,7 +14,7 @@ export type { SceneStyle, SceneTier } from './tier';
export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompileFail'> & {
/** A shader failed to compile, or the scene chunk failed to load. The host keeps its ground. */
onCompileFail?: (e: Error) => void;
/** A rebuild for a new sky state made no scene: the host puts the CSS ground back (as on a lost context). */
/** A rebuild for a new sky made no scene: the host puts the CSS ground back (as on a lost context). */
onInactive?: () => void;
/** A rebuild made a scene again: the host lets it show. */
onActive?: () => void;
@ -28,20 +27,6 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
/** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */
const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`;
/**
* The baked place's manifest, or why there is none. Its View is the one owner of the sun's place and the camera for the weather, the sky,
* the rebuild key and the planes; a scene with no manifest has FALLBACK_VIEW.
*/
async function manifestOf(
config: BackgroundSceneConfig | undefined
): Promise<{ manifest: RidgeManifest | null; fail: Error | null }> {
try {
return { manifest: await loadManifest(import.meta.env.BASE_URL, config?.place), fail: null };
} catch (e) {
return { manifest: null, fail: e instanceof Error ? e : new Error(String(e)) };
}
}
/** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */
interface Prepared {
make: () => Scene | null;
@ -52,7 +37,7 @@ interface Prepared {
async function prepare(
config: BackgroundSceneConfig | undefined,
options: StartOptions & { tier: SceneTier; debug?: boolean },
state: SkyState
choice: SkyChoice
): Promise<Prepared> {
// Whatever throws in making the scene is a compile failure, as whatever throws in loading it.
const guarded = (make: () => Scene | null): Prepared => ({
@ -74,33 +59,35 @@ async function prepare(
return guarded(() => createScene(options));
}
const { createRidgeScene } = await import('./ridge/Ridge');
const { manifest, fail } = await manifestOf(config);
const { manifest, fail } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place);
// The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per
// frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone.
// frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone, over the view the store is told of.
let backdrop: Backdrop | null = null;
let sky: SkyColours | undefined;
let lit: SkyColours | undefined;
let planesFail: Error | null = fail;
if (manifest) {
try {
const manifestSky = ridgeSkyFor(state, manifest.view);
sky = manifestSky;
const manifestSky = ridgeSkyFor(choice, manifest.view);
const { loadBackdrop } = await import('./ridge/Backdrop');
backdrop = await loadBackdrop(
manifest,
manifestSky.physical as NonNullable<typeof manifestSky.physical>
);
if (!backdrop) throw new Error('ridge cards did not load');
lit = manifestSky;
} catch (e) {
backdrop = null;
sky = undefined;
planesFail = e instanceof Error ? e : new Error(String(e));
}
}
const view = drawnView(backdrop ? manifest : null);
if (!lit) await loadWeather(weatherUrl(), view.place);
const sky = lit ?? ridgeSkyFor(choice, view);
const made = guarded(() =>
createRidgeScene({
...options,
sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW),
sky,
backdrop: backdrop ?? undefined,
lines: getConstellationLines(),
})
@ -114,17 +101,17 @@ async function prepare(
/**
* What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky
* (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild.
* (Auto picked as a named moment it already is drawing) is not a rebuild.
*/
async function skyKey(
config: BackgroundSceneConfig | undefined,
state: SkyState
choice: SkyChoice
): Promise<string | null> {
try {
const { loadWeather, ridgeSkyKey } = await import('./skyForState');
const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW;
const { view } = await ensureSkyPlace(config);
await loadWeather(weatherUrl(), view.place);
return ridgeSkyKey(state, view);
return ridgeSkyKey(choice, view);
} catch {
// The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure).
return null;
@ -138,7 +125,7 @@ async function skyKey(
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
* failure goes to onCompileFail and nothing throws.
*
* The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by
* The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice at the place, so Auto follows the clock) by
* being rebuilt on the same canvas when it changes: the door subscribes on start and the returned
* scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is
* replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state.
@ -158,10 +145,11 @@ export async function startBackgroundScene(
if (!planesFail && planesFailed) options.onPlanesOk?.();
planesFailed = planesFail !== null;
};
const prepared = (state: SkyState) => prepare(config, { ...options, tier, debug }, state);
const state = getSkyState();
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state);
const firstReady = await prepared(state);
const prepared = (choice: SkyChoice) => prepare(config, { ...options, tier, debug }, choice);
resetSkyPlanes();
const choice = getSkyChoice();
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, choice);
const firstReady = await prepared(choice);
const first = firstReady.make();
if (!first || config?.style === 'raymarch') return first;
announce(firstReady.planesFail);
@ -174,9 +162,9 @@ export async function startBackgroundScene(
// A rebuild is for a different sky ('auto' crossing a boundary, a new choice), not for a repeat of the one drawn.
const rebuild = async () => {
// The choice can move while the key is awaited; that change has its own rebuild, so this one stands down.
const next = getSkyState();
const next = getSkyChoice();
const key = await skyKey(config, next);
if (getSkyState() !== next) return;
if (getSkyChoice() !== next) return;
if ((key !== null && key === built) || disposed) return;
generation += 1;
const mine = generation;

View file

@ -6,6 +6,7 @@ import type { SkyColours } from './skyColour';
import { nightBodies } from './nightBodies';
import { sunAt } from './sunAt';
import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky';
import { sunOfBand } from './skyTestkit';
import { startBackgroundScene } from '../index';
import { parseManifest } from './manifest';
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
@ -283,7 +284,7 @@ describe('createRidgeScene', () => {
it("paints the sky through the camera of the physical sky's own View, not a default one", () => {
const { canvas } = host();
const physical = makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, ELSEWHERE_VIEW);
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);
expect(painted).toHaveLength(1);
@ -385,7 +386,7 @@ describe('the starfield in the scene', () => {
const count = (kind: string) => draws.filter((d) => d === kind).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 physical = makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW);
const night: SkyColours = { ...DAY, physical };
const N = nightBodies(
physical,
@ -503,7 +504,7 @@ describe('the starfield in the scene', () => {
describe('rain in the scene', () => {
const rainy = (w: number): SkyColours => ({
...DAY,
physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w, FALLBACK_VIEW),
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');
@ -558,7 +559,7 @@ describe('the ridge cards in the scene', () => {
top: [10, 14, 40],
mid: [30, 34, 80],
horizon: [60, 50, 90],
physical: makePhysicalSky('night', new Date('2026-06-21T22:40:00Z'), 1, FALLBACK_VIEW),
physical: makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', new Date('2026-06-21T22:40:00Z')), 1, FALLBACK_VIEW),
};
const rigOf = (parent: any) =>
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));

View file

@ -18,6 +18,7 @@ export const wireManifest = (
lat: 48.19,
lon: 16.35,
altitude_km: 0.183,
tz: 'Europe/Vienna',
eye_m: 1.7,
},
view: {
@ -66,7 +67,7 @@ export const wireIndex = {
/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, window, horizon row), so a test can tell the two apart. */
export const ELSEWHERE_VIEW: View = {
place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5 },
place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5, tz: 'Australia/Sydney' },
lookAzDeg: 20,
windowDeg: 90,
planeW: 1600,

View file

@ -15,7 +15,13 @@ describe('parseManifest', () => {
pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x
horizonRow: 314.5,
});
expect(m.view.place).toEqual({ id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.183 });
expect(m.view.place).toEqual({
id: 'vienna',
lat: 48.19,
lon: 16.35,
altitudeKm: 0.183,
tz: 'Europe/Vienna',
});
expect(m.encoding).toEqual({ logDMin: 4.6, logDMax: 11.5 });
expect(m.camera).toEqual({ headingMaxDeg: 23 });
expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
@ -70,6 +76,13 @@ describe('parseManifest', () => {
expect(() => parseManifest(null, '/')).toThrow();
});
it('rejects a manifest without place.tz and one naming a zone Intl does not know', () => {
const w = wireManifest() as any;
expect(() => parseManifest({ ...w, place: { ...w.place, tz: undefined } }, '/')).toThrow(/place\.tz/);
expect(() => parseManifest({ ...w, place: { ...w.place, tz: 'Not/AZone' } }, '/')).toThrow(/place\.tz/);
expect(parseManifest({ ...w, place: { ...w.place, tz: 'Asia/Kathmandu' } }, '/').view.place.tz).toBe('Asia/Kathmandu');
});
it('never echoes a value it refused', () => {
const w = wireManifest() as any;
const refusal = (bad: unknown) => {

View file

@ -52,6 +52,17 @@ const num = (x: unknown, path: string): number =>
const str = (x: unknown, path: string): string =>
typeof x === 'string' ? x : fail(path, 'not a string');
/** An IANA zone name Intl knows (the one place besides skyMoment.ts that touches Intl.DateTimeFormat). */
const zone = (x: unknown, path: string): string => {
const tz = str(x, path);
try {
new Intl.DateTimeFormat('en-US', { timeZone: tz });
} catch {
fail(path, `unknown time zone ${tz}`);
}
return tz;
};
export function parseIndex(raw: unknown): RidgeIndex {
const r = rec(raw, 'index');
if (r.schema !== 1) fail('index.schema', 'must be 1');
@ -107,6 +118,7 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest {
lat: num(p.lat, 'place.lat'),
lon: num(p.lon, 'place.lon'),
altitudeKm: num(p.altitude_km, 'place.altitude_km'),
tz: zone(p.tz, 'place.tz'),
},
lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'),
windowDeg: num(v.window_deg, 'view.window_deg'),

View file

@ -13,7 +13,7 @@ const camera: Camera = { azimuthDeg: 180, hfovDeg: 340, vfovDeg: 170, horizonAt:
const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => {
const t = new Date(iso);
return makePhysicalSky(state, t, 0, FALLBACK_VIEW, sunAt(P, t));
return makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW);
};
const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => {
const p = sky(iso, state);
@ -134,7 +134,7 @@ describe('the stars under the figures', () => {
const { linesAt } = await import('./starCatalogue');
const cam = windowFor(FALLBACK_VIEW, 1100, 619).camera;
const t = new Date('2026-11-25T00:00:00Z'); // full moon, high in the south
const p = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(P, t));
const p = makePhysicalSky(sunAt(P, t), 0, FALLBACK_VIEW);
const nb = nightBodies(p, paintSky(p, 1100, 619, cam), false);
let vertices = 0;
let carried = 0;

View file

@ -1,10 +1,12 @@
import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view';
import { ELSEWHERE_VIEW } from './manifest.fixture';
import { sunForState } from './sunAt';
import { sunAt } from './sunAt';
import { momentFor } from './skyMoment';
import { makePhysicalSky, paintSky } from './physicalSky';
import { sunOfBand } from './skyTestkit';
import { ridgeDrawn } from '../skyForState';
import type { FixedSkyState } from '../skyState';
import type { FixedSkyState } from './skyMoment';
import { windowFor } from './view';
import type { PhysicalSky } from './physicalSky';
@ -43,7 +45,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])(
let hi = -1;
for (const day of DAYS) {
for (const w of WEATHER) {
const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w, FALLBACK_VIEW);
const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date(`${day}T10:40:00Z`)), w, FALLBACK_VIEW);
for (const [vw, vh] of VIEWPORTS) {
const px = paintSky(sky, vw, vh, camera(sky, vw, vh));
for (let i = 0; i < px.w * px.h * 4; i += 4) {
@ -64,7 +66,7 @@ describe('weather in the sky', () => {
it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => {
const at = new Date('2026-06-21T10:40:00Z');
const paint = (w: number) => {
const sky = makePhysicalSky('day', at, w, FALLBACK_VIEW);
const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', at), w, FALLBACK_VIEW);
return paintSky(sky, 640, 360, camera(sky, 640, 360));
};
const clear = paint(0);
@ -92,7 +94,7 @@ describe('the sun disc', () => {
const disc = (sky: PhysicalSky) => paintSky(sky, 1280, 720, facingSun(sky, 1280, 720));
const noon = new Date('2026-12-21T11:00:00Z'); // about 18 degrees: higher suns are above the top of the window
it('is drawn by the host, in a clear sky by day, white with the sun high', () => {
const sky = makePhysicalSky('day', noon, 0, FALLBACK_VIEW);
const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0, FALLBACK_VIEW);
const d = disc(sky).sunDisc;
expect(d).toBeDefined();
expect(d!.x).toBeGreaterThan(0);
@ -103,11 +105,12 @@ describe('the sun disc', () => {
expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees
});
it('is hidden by overcast and absent at night', () => {
expect(disc(makePhysicalSky('day', noon, 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined();
expect(disc(makePhysicalSky('night', noon, 0, FALLBACK_VIEW)).sunDisc).toBeUndefined();
expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', noon), 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined();
expect(disc(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'night', noon), 0, FALLBACK_VIEW)).sunDisc).toBeUndefined();
});
it('is orange-tinted low in the sky', () => {
const d = disc(makePhysicalSky('dusk', noon, 0, FALLBACK_VIEW)).sunDisc;
it('is orange-tinted low in the sky (golden hour, 4 degrees up)', () => {
const golden = momentFor({ kind: 'named', id: 'golden' }, FALLBACK_VIEW.place, noon);
const d = disc(makePhysicalSky(sunAt(FALLBACK_VIEW.place, golden), 0, FALLBACK_VIEW)).sunDisc;
expect(d).toBeDefined();
expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]);
});
@ -118,16 +121,16 @@ describe('the sky is made from the View it is given', () => {
const sameSpotOtherCamera = { ...FALLBACK_VIEW, lookAzDeg: 30, windowDeg: 100, horizonRow: 200 };
it("lights the sky from the sun over the View's place, at its altitude", () => {
const sky = makePhysicalSky('day', NOW, 0, ELSEWHERE_VIEW);
const sky = makePhysicalSky(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW), 0, ELSEWHERE_VIEW);
expect(sky.view).toBe(ELSEWHERE_VIEW);
expect(sky.sun).toEqual(sunForState(ELSEWHERE_VIEW.place, 'day', NOW));
expect(sky.sun).not.toEqual(sunForState(FALLBACK_VIEW.place, 'day', NOW));
expect(sky.sun).toEqual(sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW));
expect(sky.sun).not.toEqual(sunAt(FALLBACK_VIEW.place, sunOfBand(ELSEWHERE_VIEW.place, 'day', NOW).time));
expect(sky.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
});
it("fits and samples the stops through the View's camera: the same place and sun with another look is another gradient", () => {
const a = makePhysicalSky('day', NOW, 0, FALLBACK_VIEW);
const b = makePhysicalSky('day', NOW, 0, sameSpotOtherCamera);
const a = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', NOW), 0, FALLBACK_VIEW);
const b = makePhysicalSky(sunOfBand(sameSpotOtherCamera.place, 'day', NOW), 0, sameSpotOtherCamera);
expect(b.sun).toEqual(a.sun);
expect(b.stops).not.toEqual(a.stops);
});

View file

@ -1,7 +1,8 @@
// The ridge scene's sky: the View's place's sun on the real clock, the atmosphere baked from it, a camera, and the display that makes it
// The ridge scene's sky: the sun over the View's place at the drawn moment, the atmosphere baked from it, a camera, and the display that makes it
// pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9
// grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only.
import type { FixedSkyState } from '../skyState';
import { skyBand } from './skyMoment';
import type { FixedSkyState } from './skyMoment';
import { bakeAtmosphere } from './earthAtmosphere';
import type { Atmosphere } from './earthAtmosphere';
import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome';
@ -11,7 +12,6 @@ import { display8, fitDisplay } from './toneMap';
import type { Display, Fit } from './toneMap';
import { moonAt } from './nightSky';
import type { MoonSample, NightLight } from './nightSky';
import { sunForState } from './sunAt';
import type { SunSample } from './sunAt';
import { windowFor } from './view';
import type { Camera, View } from './view';
@ -55,16 +55,10 @@ export function rowMean(dome: Dome, display: Display, row: number): Srgb {
return [Math.round(acc[0] / dome.w), Math.round(acc[1] / dome.w), Math.round(acc[2] / dome.w)];
}
export function makePhysicalSky(
state: FixedSkyState,
now: Date,
weatherValue: number,
view: View,
/** A sun to draw instead of the state's own (the look sheet's grid of elevations); `state` still picks the display budget. */
sunOverride?: SunSample
): PhysicalSky {
/** The sky lit by the sun it is given (the moment is skyMoment.ts's choice); the display budget is the band of that sun. */
export function makePhysicalSky(sun: SunSample, weatherValue: number, view: View): PhysicalSky {
const t0 = clock();
const sun = sunOverride ?? sunForState(view.place, state, now);
const state = skyBand(sun.elevation);
const weather = weatherOf(weatherValue);
const atm = bakeAtmosphere({
sunElevationDeg: sun.elevation,

View file

@ -120,6 +120,12 @@ describe('the committed ridge assets', () => {
expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true);
});
it('names a time zone Intl knows (the sky draws its named moments in the place local day)', () => {
const tz = (raw as unknown as { place: { tz?: unknown } }).place.tz;
expect(typeof tz).toBe('string');
expect(() => new Intl.DateTimeFormat('en-US', { timeZone: tz as string })).not.toThrow();
});
it('has every card file, at the length the manifest states', () => {
raw.cards.flatMap(files).forEach((f) => {
expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes);

View file

@ -0,0 +1,271 @@
import { describe, expect, it } from 'vitest';
import {
DAY_FROM,
MOMENT_IDS,
localDate,
localMinutes,
momentFor,
momentKey,
seedFree,
skyBand,
zonedInstant,
} from './skyMoment';
import type { MomentId } from './skyMoment';
import { sunAt } from './sunAt';
import type { Place } from './view';
const PLACES: Record<string, Place> = {
vienna: { id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.18, tz: 'Europe/Vienna' },
matterhorn: { id: 'matterhorn', lat: 45.98, lon: 7.78, altitudeKm: 3.1, tz: 'Europe/Zurich' },
fuji: { id: 'fuji', lat: 35.31, lon: 138.63, altitudeKm: 0.4, tz: 'Asia/Tokyo' },
amadablam: { id: 'amadablam', lat: 27.9, lon: 86.9, altitudeKm: 4.2, tz: 'Asia/Kathmandu' },
halfdome: {
id: 'halfdome',
lat: 37.73,
lon: -119.55,
altitudeKm: 1.2,
tz: 'America/Los_Angeles',
},
};
const DAYS = ['2026-06-21', '2026-12-21', '2026-03-20'];
const MIN = 60_000;
/** 18:00 place-local on `date`: any instant of that local day names it, and one after the sun's noon, so Night is the coming midnight. */
const during = (date: string, p: Place): Date => zonedInstant(date, 1080, p.tz);
const at = (id: MomentId, p: Place, date: string): Date =>
momentFor({ kind: 'named', id }, p, during(date, p));
const el = (p: Place, t: Date): number => sunAt(p, t).elevation;
describe('the named moments', () => {
describe.each(Object.entries(PLACES))('%s', (_name, p) => {
it.each(DAYS)(
'%s: dawn < morning < noon < golden < dusk inside the local day, night after noon',
(date) => {
const t = Object.fromEntries(MOMENT_IDS.map((id) => [id, at(id, p, date).getTime()]));
expect(t.dawn).toBeLessThan(t.morning);
expect(t.morning).toBeLessThan(t.noon);
expect(t.noon).toBeLessThan(t.golden);
expect(t.golden).toBeLessThan(t.dusk);
expect(t.night).toBeGreaterThan(t.noon);
(['dawn', 'morning', 'noon', 'golden', 'dusk'] as const).forEach((id) =>
expect(localDate(new Date(t[id]), p.tz)).toBe(date)
);
}
);
it.each(DAYS)('%s: each crossing is at its table elevation, within 0.05 degrees', (date) => {
const noonEl = el(p, at('noon', p, date));
expect(el(p, at('dawn', p, date))).toBeCloseTo(-3, 1);
expect(el(p, at('morning', p, date))).toBeCloseTo(Math.min(15, noonEl / 2), 1);
expect(el(p, at('golden', p, date))).toBeCloseTo(4, 1);
expect(el(p, at('dusk', p, date))).toBeCloseTo(-3, 1);
});
it.each(DAYS)(
'%s: noon is the day maximum and night the lowest of the 24 h after it',
(date) => {
const noon = at('noon', p, date);
const night = at('night', p, date);
for (let m = 0; m < 24 * 60; m += 5) {
const t = new Date(noon.getTime() + m * MIN);
expect(el(p, t)).toBeGreaterThanOrEqual(el(p, night) - 1e-3);
}
const dayStart = zonedInstant(date, 0, p.tz).getTime();
for (let m = 0; m < 24 * 60; m += 5) {
expect(el(p, new Date(dayStart + m * MIN))).toBeLessThanOrEqual(el(p, noon) + 1e-3);
}
}
);
});
it('morning is half the noon elevation at Vienna in December (the 15 degree rule would never be met)', () => {
const p = PLACES.vienna;
const noonEl = el(p, at('noon', p, '2026-12-21'));
expect(noonEl).toBeLessThan(30);
expect(el(p, at('morning', p, '2026-12-21'))).toBeCloseTo(noonEl / 2, 1);
expect(el(p, at('morning', p, '2026-06-21'))).toBeCloseTo(15, 1);
});
it('a named moment is today of the place: the same local date gives the same instant, the next day another', () => {
const p = PLACES.fuji;
const a = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 30, p.tz));
const b = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-21', 1400, p.tz));
const c = momentFor({ kind: 'named', id: 'dusk' }, p, zonedInstant('2026-12-22', 30, p.tz));
expect(a.getTime()).toBe(b.getTime());
expect(c.getTime()).not.toBe(a.getTime());
});
it('is total at a pole, where there is no dawn or no dusk: it falls to noon or midnight', () => {
const pole: Place = { id: 'pole', lat: 80, lon: 0, altitudeKm: 0, tz: 'UTC' };
for (const date of ['2026-06-21', '2026-12-21']) {
const now = zonedInstant(date, 720, 'UTC');
for (const id of MOMENT_IDS) {
const t = momentFor({ kind: 'named', id }, pole, now);
expect(Number.isFinite(t.getTime())).toBe(true);
}
}
const june = zonedInstant('2026-06-21', 720, 'UTC');
expect(momentFor({ kind: 'named', id: 'dawn' }, pole, june).getTime()).toBe(
momentFor({ kind: 'named', id: 'noon' }, pole, june).getTime()
);
});
});
describe('zones', () => {
it.each(['Europe/Vienna', 'Asia/Tokyo', 'Asia/Kathmandu', 'America/Phoenix'])(
'%s: zonedInstant round-trips every minute of a day',
(tz) => {
for (let m = 0; m < 1440; m += 1) {
const t = zonedInstant('2026-06-21', m, tz);
expect(localDate(t, tz)).toBe('2026-06-21');
expect(localMinutes(t, tz)).toBe(m);
}
}
);
it('Kathmandu is UTC+5:45 and Phoenix has no daylight saving', () => {
expect(zonedInstant('2026-12-21', 720, 'Asia/Kathmandu').toISOString()).toBe(
'2026-12-21T06:15:00.000Z'
);
expect(zonedInstant('2026-07-01', 720, 'America/Phoenix').toISOString()).toBe(
'2026-07-01T19:00:00.000Z'
);
});
it('a wall time in the spring-forward gap lands after it; one that happens twice is the first', () => {
// Vienna, 2026-03-29: 02:00 became 03:00 (01:00Z). 2026-10-25: 03:00 became 02:00 (01:00Z).
expect(zonedInstant('2026-03-29', 150, 'Europe/Vienna').toISOString()).toBe(
'2026-03-29T01:30:00.000Z'
);
expect(zonedInstant('2026-10-25', 150, 'Europe/Vienna').toISOString()).toBe(
'2026-10-25T00:30:00.000Z'
);
});
it('the place decides, not the zone of the client', () => {
const p = PLACES.fuji;
const probe = () => ({
noon: momentFor({ kind: 'named', id: 'noon' }, p, new Date('2026-12-21T05:00:00Z')).getTime(),
free: momentFor({ kind: 'free', date: '2026-07-15', minutes: 330 }, p, new Date()).getTime(),
date: localDate(new Date('2026-12-21T16:00:00Z'), p.tz),
zi: zonedInstant('2026-03-29', 150, 'Europe/Vienna').getTime(),
});
const was = process.env.TZ;
try {
const seen = ['Pacific/Kiritimati', 'America/Anchorage', 'UTC'].map((tz) => {
process.env.TZ = tz;
return probe();
});
expect(seen[1]).toEqual(seen[0]);
expect(seen[2]).toEqual(seen[0]);
} finally {
if (was === undefined) delete process.env.TZ;
else process.env.TZ = was;
}
});
});
describe('Fuji dawn is Japanese dawn', () => {
it('lands in the Japanese morning, east of south-east, and a world away from the Vienna one', () => {
const fuji = PLACES.fuji;
const now = new Date('2026-12-21T04:00:00Z'); // local noon at Fuji
const t = momentFor({ kind: 'named', id: 'dawn' }, fuji, now);
const hourUtc = t.getUTCHours() + t.getUTCMinutes() / 60;
expect(t.getUTCDate()).toBe(20); // the previous UTC day
expect(hourUtc).toBeGreaterThan(20.5);
expect(hourUtc).toBeLessThan(22);
const s = sunAt(fuji, t);
expect(s.elevation).toBeCloseTo(-3, 1);
expect(s.azimuth).toBeGreaterThan(110);
expect(s.azimuth).toBeLessThan(125);
const vienna = momentFor({ kind: 'named', id: 'dawn' }, PLACES.vienna, now);
expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeGreaterThan(7);
expect(Math.abs(vienna.getTime() - t.getTime()) / 3_600_000).toBeLessThan(9.5);
});
});
describe("Night is tonight's, the nearest one", () => {
const night = { kind: 'named', id: 'night' } as const;
const p = PLACES.vienna;
it('at 00:30 it is the midnight coming within the hour, not the one a day ahead; after noon the one coming', () => {
const at = Date.parse('2026-06-21T22:30:00Z'); // 00:30 on June 22, Vienna
const early = momentFor(night, p, new Date(at));
expect(localDate(early, p.tz)).toBe('2026-06-22');
expect(early.getTime() - at).toBeGreaterThan(0);
expect(early.getTime() - at).toBeLessThan(2 * 3_600_000);
const evening = momentFor(night, p, new Date('2026-06-22T12:00:00Z')); // 14:00 June 22
expect(localDate(evening, p.tz)).toBe('2026-06-23');
expect(evening.getTime() - early.getTime()).toBeGreaterThan(23.9 * 3_600_000);
expect(evening.getTime() - early.getTime()).toBeLessThan(24.1 * 3_600_000);
expect(momentFor(night, p, new Date('2026-06-22T18:00:00Z')).getTime()).toBe(evening.getTime());
});
it('the key follows the instant drawn: it is the same across the midnight roll and changes at the noon side', () => {
const k = (iso: string) => momentKey(night, p, new Date(iso));
expect(k('2026-06-21T22:30:00Z')).toBe(k('2026-06-21T21:30:00Z')); // 00:30 and 23:30
expect(k('2026-06-21T22:30:00Z')).not.toBe(k('2026-06-22T12:00:00Z'));
expect(k('2026-06-22T12:00:00Z')).toBe(k('2026-06-22T20:00:00Z'));
});
});
describe('purity and bands', () => {
it('auto is the time it is given', () => {
const now = new Date('2026-05-05T05:05:05Z');
expect(momentFor({ kind: 'auto' }, PLACES.vienna, now)).toBe(now);
expect(momentKey({ kind: 'auto' }, PLACES.vienna, now)).toBe('live');
});
it('a free moment is the place-local wall time, held inside 1900..2100', () => {
const p = PLACES.vienna;
const t = momentFor({ kind: 'free', date: '2026-12-21', minutes: 400 }, p, new Date());
expect(localDate(t, p.tz)).toBe('2026-12-21');
expect(localMinutes(t, p.tz)).toBe(400);
expect(
localDate(momentFor({ kind: 'free', date: '1800-01-01', minutes: 0 }, p, new Date()), p.tz)
).toBe('1900-01-01');
expect(
localDate(momentFor({ kind: 'free', date: '2999-05-05', minutes: 0 }, p, new Date()), p.tz)
).toBe('2100-12-31');
});
it('skyBand: day at 6.0, night at -6.0, dusk between', () => {
expect(skyBand(DAY_FROM)).toBe('day');
expect(skyBand(-DAY_FROM)).toBe('night');
expect(skyBand(DAY_FROM - 0.001)).toBe('dusk');
expect(skyBand(-DAY_FROM + 0.001)).toBe('dusk');
expect(skyBand(0)).toBe('dusk');
expect(skyBand(80)).toBe('day');
expect(skyBand(-80)).toBe('night');
});
it('the key of a moment follows its local date and id, or its date and minutes', () => {
const p = PLACES.vienna;
const n = { kind: 'named', id: 'noon' } as const;
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).toBe(
momentKey(n, p, new Date('2026-06-21T20:00:00Z'))
);
expect(momentKey(n, p, new Date('2026-06-21T10:00:00Z'))).not.toBe(
momentKey(n, p, new Date('2026-06-22T10:00:00Z'))
);
expect(momentKey({ kind: 'free', date: '2026-06-21', minutes: 5 }, p, new Date())).not.toBe(
momentKey({ kind: 'free', date: '2026-06-21', minutes: 10 }, p, new Date())
);
});
});
describe('the picker seed', () => {
it('opens from the moment Auto or a named choice is drawing, in the place zone, to the 5 minutes the slider steps', () => {
const p = PLACES.fuji;
const now = new Date('2026-12-21T04:03:00Z'); // 13:03 at Fuji
expect(seedFree({ kind: 'auto' }, p, now)).toEqual({
kind: 'free',
date: '2026-12-21',
minutes: 13 * 60,
});
const noon = seedFree({ kind: 'named', id: 'noon' }, p, now);
expect(noon.date).toBe('2026-12-21');
expect(Math.abs(noon.minutes - 11 * 60 - 45)).toBeLessThanOrEqual(15); // solar noon at 138.6 E is about 11:45 JST
expect(noon.minutes % 5).toBe(0);
const free = { kind: 'free', date: '2026-07-15', minutes: 330 } as const;
expect(seedFree(free, p, now)).toBe(free);
});
});

View file

@ -0,0 +1,286 @@
// Which instant the sky is drawn at, and which band it is. One owner, pure (no store, no React, no clock):
// `momentFor(choice, place, now)` turns the viewer's choice, the place and the time into the instant, and `skyBand` turns the sun
// at that instant into the sky the ink and the tone map are fitted to. Place-local time exists only here, through Intl with `place.tz`;
// the viewer's own zone decides nothing. The named moments are one table (`SKY_MOMENTS`), a row each, tuned by eye.
import type { Place } from './view';
import { sunAt } from './sunAt';
/**
* The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
* the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
* #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
* sit inside them.
*/
export type FixedSkyState = 'day' | 'dusk' | 'night';
/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */
export const DAY_FROM = 6;
/** The one function that turns a sun into day, dusk or night. */
export const skyBand = (elevationDeg: number): FixedSkyState =>
elevationDeg >= DAY_FROM ? 'day' : elevationDeg <= -DAY_FROM ? 'night' : 'dusk';
export const MOMENT_IDS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const;
export type MomentId = typeof MOMENT_IDS[number];
/** What the viewer picked: the live sky, a named moment of today at the place, or a place-local date and minute of the day. */
export type SkyChoice =
| { kind: 'auto' }
| { kind: 'named'; id: MomentId }
| { kind: 'free'; date: string; minutes: number };
/** The ephemeris range (sunAt.ts header): free dates are held inside it. */
export const FREE_DATE_MIN = '1900-01-01';
export const FREE_DATE_MAX = '2100-12-31';
const MIN = 60_000;
const DAY = 24 * 60 * MIN;
// ---------------------------------------------------------------------------------------------------------------- place-local time
const formats = new Map<string, Intl.DateTimeFormat>();
const formatFor = (tz: string): Intl.DateTimeFormat => {
let f = formats.get(tz);
if (!f) {
f = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
hourCycle: 'h23',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
formats.set(tz, f);
}
return f;
};
/** The wall clock of `t` in `tz`, read as if it were UTC (ms): its difference from `t` is the zone's offset. */
const wallAsUtc = (t: number, tz: string): number => {
const v: Record<string, number> = {};
formatFor(tz)
.formatToParts(new Date(t))
.forEach((p) => {
if (p.type !== 'literal') v[p.type] = Number(p.value);
});
return Date.UTC(v.year, v.month - 1, v.day, v.hour, v.minute, v.second);
};
const offsetAt = (t: number, tz: string): number => wallAsUtc(t, tz) - Math.floor(t / 1000) * 1000;
const pad = (n: number, w = 2): string => String(n).padStart(w, '0');
const dateOf = (utcMs: number): string => {
const d = new Date(utcMs);
return `${pad(d.getUTCFullYear(), 4)}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
};
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
const utcOfDate = (date: string): number => {
const m = DATE.exec(date);
if (!m) return NaN;
return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
};
/** True for a real calendar date 'YYYY-MM-DD'. */
export const isDate = (date: unknown): date is string =>
typeof date === 'string' && DATE.test(date) && dateOf(utcOfDate(date)) === date;
/** The place-local calendar date of `now`, 'YYYY-MM-DD'. */
export const localDate = (now: Date, tz: string): string => dateOf(wallAsUtc(now.getTime(), tz));
/** The place-local minute of the day (0..1439) of `now`. */
export const localMinutes = (now: Date, tz: string): number => {
const wall = new Date(wallAsUtc(now.getTime(), tz));
return wall.getUTCHours() * 60 + wall.getUTCMinutes();
};
/**
* The instant at which the wall clock of `tz` reads `date` and `minutes`. A wall time that does not exist (the spring-forward gap) is
* shifted forward by the gap, so it lands after it; one that happens twice (fall-back) resolves to the first.
*/
export function zonedInstant(date: string, minutes: number, tz: string): Date {
const guess = utcOfDate(date) + minutes * MIN;
const before = offsetAt(guess - DAY, tz);
const after = offsetAt(guess + DAY, tz);
const valid = [...new Set([before, after])]
.map((o) => guess - o)
.filter((t) => offsetAt(t, tz) === guess - t)
.sort((a, b) => a - b);
return new Date(valid.length ? valid[0] : guess - before);
}
/** The short name of the zone at that instant ('CET', 'GMT+5:45'): what the picker shows beside a place-local time. */
export const zoneName = (at: Date, tz: string): string =>
new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'short' })
.formatToParts(at)
.find((p) => p.type === 'timeZoneName')?.value ?? tz;
// ---------------------------------------------------------------------------------------------------------------- the named moments
const elevationAt = (place: Place, t: number): number => sunAt(place, new Date(t)).elevation;
const STEP = 5 * MIN;
/** The time in [a, b] (ms) where `f` is largest (sign 1) or smallest (sign -1), to under a minute: the function is unimodal there. */
function extremum(f: (t: number) => number, a: number, b: number, sign: 1 | -1): number {
let lo = a;
let hi = b;
while (hi - lo > MIN / 2) {
const m1 = lo + (hi - lo) / 3;
const m2 = hi - (hi - lo) / 3;
if (sign * f(m1) < sign * f(m2)) lo = m1;
else hi = m2;
}
return (lo + hi) / 2;
}
/** The time in [from, to] where `f` is largest (sign 1) or smallest (sign -1): a scan in 5-minute steps, refined to under a minute. */
function peak(f: (t: number) => number, from: number, to: number, sign: 1 | -1): number {
let best = from;
let bestV = -Infinity;
for (let t = from; t <= to; t += STEP) {
const v = sign * f(t);
if (v > bestV) {
bestV = v;
best = t;
}
}
return extremum(f, Math.max(from, best - STEP), Math.min(to, best + STEP), sign);
}
/** The first rising (or last setting) crossing of `deg` in [from, to]: a 5-minute scan, bisected under a second; undefined when there is none. */
function crossing(
f: (t: number) => number,
deg: number,
from: number,
to: number,
rising: boolean
): number | undefined {
const above = (t: number) => f(t) >= deg;
let found: [number, number] | undefined;
for (let a = from; a < to; a += STEP) {
const b = Math.min(a + STEP, to);
if (above(a) !== above(b) && above(b) === rising) {
found = [a, b];
if (rising) break;
}
}
if (!found) return undefined;
let [lo, hi] = found;
while (hi - lo > 500) {
const m = (lo + hi) / 2;
if (above(m) === rising) hi = m;
else lo = m;
}
return (lo + hi) / 2;
}
/** The place-local day a named moment is a moment of: its start and end, and the sun's noon in between. */
interface Day {
place: Place;
from: number;
to: number;
noon: number;
noonElevation: number;
}
interface Rule {
/** 'noon' and 'midnight' are the extremes; 'rising' and 'setting' are the crossing of `deg` (a function of the day's noon elevation) before and after noon. */
at: 'noon' | 'midnight' | 'rising' | 'setting';
deg?: (noonElevation: number) => number;
}
/**
* The named moments, one row each (tuned by eye, ruling ridge-look-tuned-by-eye-no-contrast-gates). A crossing the day does not have
* (polar) falls to the day's noon (rising) or midnight (setting). Night is solar midnight, tonight's: before the day's noon the one that
* just passed or is coming this morning, after it the one that is coming (`momentOf`'s `before`), never one a whole day away.
*/
export const SKY_MOMENTS: Record<MomentId, Rule> = {
dawn: { at: 'rising', deg: () => -3 },
morning: { at: 'rising', deg: (noon) => Math.min(15, noon / 2) },
noon: { at: 'noon' },
golden: { at: 'setting', deg: () => 4 },
dusk: { at: 'setting', deg: () => -3 },
night: { at: 'midnight' },
};
function momentOf(id: MomentId, d: Day, before: boolean): number {
const rule = SKY_MOMENTS[id];
const f = (t: number) => elevationAt(d.place, t);
const midnight = () => peak(f, d.noon, d.noon + DAY, -1);
if (rule.at === 'noon') return d.noon;
if (rule.at === 'midnight') return before ? peak(f, d.noon - DAY, d.noon, -1) : midnight();
const deg = rule.deg ? rule.deg(d.noonElevation) : 0;
if (rule.at === 'rising') return crossing(f, deg, d.from, d.noon, true) ?? d.noon;
return crossing(f, deg, d.noon, d.to, false) ?? midnight();
}
const days = new Map<string, Day>();
const named = new Map<string, number>();
/** The place-local day `date` at the place (memoised: a pure function of these). */
function dayOf(place: Place, date: string): Day {
const key = `${date}|${place.tz}|${place.lat}|${place.lon}`;
let d = days.get(key);
if (!d) {
const from = zonedInstant(date, 0, place.tz).getTime();
const to = zonedInstant(dateOf(utcOfDate(date) + DAY), 0, place.tz).getTime();
const noon = peak((x) => elevationAt(place, x), from, to, 1);
d = { place, from, to, noon, noonElevation: elevationAt(place, noon) };
if (days.size > 256) days.clear();
days.set(key, d);
}
return d;
}
/** The instant of a named moment on a place-local date at the place (memoised). Only Night looks at `now`: which side of the day's noon it is. */
function namedInstant(id: MomentId, place: Place, date: string, now: Date): Date {
const d = dayOf(place, date);
const before = now.getTime() < d.noon;
const key = `${id}|${date}|${before}|${place.tz}|${place.lat}|${place.lon}`;
let t = named.get(key);
if (t === undefined) {
t = momentOf(id, d, before);
if (named.size > 256) named.clear();
named.set(key, t);
}
return new Date(t);
}
// ---------------------------------------------------------------------------------------------------------------- the one decision
/** A free date held inside the ephemeris range; anything that is not a date reads as the range's start. */
const clampDate = (date: string): string =>
!isDate(date) || date < FREE_DATE_MIN
? FREE_DATE_MIN
: date > FREE_DATE_MAX
? FREE_DATE_MAX
: date;
const clampMinutes = (m: number): number => Math.min(1439, Math.max(0, Math.floor(m) || 0));
/** The instant the sky is drawn at for a choice at a place: auto is `now`; a named moment is today's at the place (Night: tonight's, the nearest one); a free moment is its own. */
export function momentFor(choice: SkyChoice, place: Place, now: Date): Date {
if (choice.kind === 'auto') return now;
if (choice.kind === 'named') return namedInstant(choice.id, place, localDate(now, place.tz), now);
return zonedInstant(clampDate(choice.date), clampMinutes(choice.minutes), place.tz);
}
/** The free moment (place-local date, minute to the 5 the slider steps) a choice is drawing now: where the picker opens from. */
export function seedFree(
choice: SkyChoice,
place: Place,
now: Date
): Extract<SkyChoice, { kind: 'free' }> {
if (choice.kind === 'free') return choice;
const at = momentFor(choice, place, now);
return {
kind: 'free',
date: localDate(at, place.tz),
minutes: Math.floor(localMinutes(at, place.tz) / 5) * 5,
};
}
/** What a rebuild is for, of the moment: live for auto, the id and place-local date of the instant for a named one, the date and minutes for a free one. */
export function momentKey(choice: SkyChoice, place: Place, now: Date): string {
if (choice.kind === 'auto') return 'live';
if (choice.kind === 'named') return `${choice.id}@${localDate(momentFor(choice, place, now), place.tz)}`;
return `${clampDate(choice.date)}@${clampMinutes(choice.minutes)}`;
}

View file

@ -0,0 +1,28 @@
// Test helpers for the sky: a moment named by the clock of the place, and the sun of a band. Tests only.
import { momentFor } from './skyMoment';
import type { FixedSkyState } from './skyMoment';
import { sunAt } from './sunAt';
import type { SunSample } from './sunAt';
import { FALLBACK_VIEW } from './view';
import type { Place } from './view';
const VIENNA = FALLBACK_VIEW.place;
/** 22 September 2026 at h:m of local solar time at Vienna (the equinox: the sun is up from about 06:00 to 18:00 and the equation of time is a few minutes). */
export const atSolarTime = (h: number, m = 0): Date =>
new Date(Date.UTC(2026, 8, 22, h, m) - VIENNA.lon * 4 * 60_000);
/** The sun of a band on the local day of `date` at `place`: Day is noon, Dusk the evening's -3 degrees, Night solar midnight. */
export const sunOfBand = (
place: Place,
band: FixedSkyState,
date: Date,
): SunSample =>
sunAt(
place,
momentFor(
{ kind: 'named', id: band === 'day' ? 'noon' : band },
place,
date
)
);

View file

@ -1,10 +1,13 @@
import { describe, expect, it } from 'vitest';
import { solarNoon, STATE_ELEVATION, sunAt, sunForState } from './sunAt';
import { sunAt } from './sunAt';
import { momentFor } from './skyMoment';
import { FALLBACK_VIEW } from './view';
const P = FALLBACK_VIEW.place;
const at = (iso: string) => new Date(iso);
/** The sun's noon of the local day of `t` (the named moment of the sky menu). */
const noonOf = (p: typeof P, t: Date) => momentFor({ kind: 'named', id: 'noon' }, p, t);
describe('the sun over Vienna', () => {
it('the Vienna place reproduces the sun the old Vienna constant gave, exactly, at three dates', () => {
@ -22,24 +25,24 @@ describe('the sun over Vienna', () => {
});
it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => {
const june = sunAt(P, solarNoon(P, at('2026-06-21T12:00:00Z')));
const june = sunAt(P, noonOf(P, at('2026-06-21T12:00:00Z')));
expect(june.elevation).toBeCloseTo(90 - P.lat + 23.44, 0);
const december = sunAt(P, solarNoon(P, at('2026-12-21T12:00:00Z')));
const december = sunAt(P, noonOf(P, at('2026-12-21T12:00:00Z')));
expect(december.elevation).toBeCloseTo(90 - P.lat - 23.44, 0);
const march = sunAt(P, solarNoon(P, at('2026-03-20T12:00:00Z')));
const march = sunAt(P, noonOf(P, at('2026-03-20T12:00:00Z')));
expect(march.elevation).toBeCloseTo(90 - P.lat, 0);
});
it('is due south at solar noon, east in the morning and west in the afternoon', () => {
const noon = solarNoon(P, at('2026-09-23T12:00:00Z'));
expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // solarNoon is found to 5 minutes, which is 1.25 degrees of azimuth
const noon = noonOf(P, at('2026-09-23T12:00:00Z'));
expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // noonOf is found to under a minute
expect(sunAt(P, new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150);
expect(sunAt(P, new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210);
});
it('solar noon at 16.35 E falls near 10:40 UTC in mid November', () => {
// 16.3534 E is 65.4 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC.
const n = solarNoon(P, at('2026-11-11T12:00:00Z'));
const n = noonOf(P, at('2026-11-11T12:00:00Z'));
const minutes = n.getUTCHours() * 60 + n.getUTCMinutes();
expect(minutes).toBeGreaterThan(10 * 60 + 30);
expect(minutes).toBeLessThan(10 * 60 + 50);
@ -55,20 +58,4 @@ describe('the sun over Vienna', () => {
expect(Math.abs(daylight('2026-12-21T00:00:00Z') - (8 * 60 + 4))).toBeLessThan(15);
expect(Math.abs(daylight('2026-06-21T00:00:00Z') - (16 * 60 + 0))).toBeLessThan(15);
});
it('sunForState: the real sun when it is in the state, else a moment of today that is', () => {
const noon = solarNoon(P, at('2026-11-11T12:00:00Z'));
expect(sunForState(P, 'day', noon).time).toEqual(noon);
const midnight = new Date(noon.getTime() + 12 * 3600_000);
for (const state of ['day', 'dusk', 'night'] as const) {
for (const now of [noon, midnight, at('2026-11-11T15:30:00Z')]) {
const s = sunForState(P, state, now);
const [lo, hi] = STATE_ELEVATION[state];
expect(s.elevation).toBeGreaterThanOrEqual(lo - 0.01);
expect(s.elevation).toBeLessThanOrEqual(hi + 0.01);
}
}
expect(sunForState(P, 'dusk', noon).elevation).toBeCloseTo(0, 1);
expect(sunForState(P, 'dusk', noon).azimuth).toBeGreaterThan(180); // sets in the west half
});
});

View file

@ -1,9 +1,6 @@
// The sun over a Place (`view.ts`) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the
// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction), and the choice of a moment for each
// fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction). The moment a sky is drawn at is skyMoment.ts's. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
import { sunPosition } from '../../../../sky/sun.js';
import { DAY_FROM } from '../skyState';
import type { FixedSkyState } from '../skyState';
import type { Place } from './view';
export interface SunSample {
@ -22,53 +19,3 @@ export function sunAt(place: Place, time: Date): SunSample {
};
return { elevation, azimuth, time };
}
const MIN = 60_000;
/** Sun elevation range of each fixed state: the thresholds `resolveSkyState` uses (day from DAY_FROM, night below -DAY_FROM). */
export const STATE_ELEVATION: Record<FixedSkyState, readonly [number, number]> = {
day: [DAY_FROM, 90],
dusk: [-DAY_FROM, DAY_FROM],
night: [-90, -DAY_FROM],
};
const startOfUtcDay = (t: Date): number =>
Math.floor(t.getTime() / (24 * 60 * MIN)) * 24 * 60 * MIN;
/** The moment of the day (UTC day of `t`, every 5 minutes) the sun is highest over the place: solar noon to the step. */
export function solarNoon(place: Place, t: Date): Date {
const d0 = startOfUtcDay(t);
let best = d0;
let bestEl = -90;
for (let m = 0; m < 24 * 60; m += 5) {
const el = sunAt(place, new Date(d0 + m * MIN)).elevation;
if (el > bestEl) {
bestEl = el;
best = d0 + m * MIN;
}
}
return new Date(best);
}
/**
* The sun a state draws. The real sun over the place now when it is in the state's range (so 'auto' is the real sky); otherwise the
* sun of today at a moment that is: noon for Day, the evening sunset for Dusk, the opposite of noon for Night. A picker that
* forces Day at night shows a noon sky, as a person looking at a noon photograph would.
*/
export function sunForState(place: Place, state: FixedSkyState, now: Date): SunSample {
const real = sunAt(place, now);
const [lo, hi] = STATE_ELEVATION[state];
if (real.elevation >= lo && real.elevation <= hi) return real;
const noon = solarNoon(place, now);
if (state === 'day') return sunAt(place, noon);
if (state === 'night') return sunAt(place, new Date(noon.getTime() + 12 * 60 * MIN));
// Dusk: bisect the evening crossing of the horizon between noon and the opposite moment.
let a = noon.getTime();
let b = noon.getTime() + 12 * 60 * MIN;
for (let i = 0; i < 30; i += 1) {
const m = (a + b) / 2;
if (sunAt(place, new Date(m)).elevation > 0) a = m;
else b = m;
}
return sunAt(place, new Date((a + b) / 2));
}

View file

@ -1,11 +1,12 @@
import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view';
import { makePhysicalSky } from './physicalSky';
import { sunOfBand } from './skyTestkit';
import { renderDome } from './skyDome';
import { windowFor } from './view';
import { applyCurve, BLACK_LIFT, BUDGET, NIGHT_CEILING, NIGHT_LIFT, SCOTOPIC, displayLumaOf, fitDisplay, makeCurve, scotopic, scotopicWeight } from './toneMap';
import { sunAt } from './sunAt';
import type { FixedSkyState } from '../skyState';
import type { FixedSkyState } from './skyMoment';
const sweep = (c: ReturnType<typeof makeCurve>) =>
Array.from({ length: 401 }, (_, i) => applyCurve(c, i / 400));
@ -28,7 +29,7 @@ describe('the tone curve', () => {
});
describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted to a sky', (state) => {
const sky = makePhysicalSky(state, new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW);
const sky = makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, state, new Date('2026-06-21T10:40:00Z')), 0, FALLBACK_VIEW);
const { camera } = windowFor(sky.view, 64, 36);
const dome = renderDome(sky.atm, sky.sun, camera, 64, 36, sky.weather.cover, sky.night);
const b = BUDGET[state];
@ -67,7 +68,7 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s curve fitted
describe('the night display', () => {
const night = (iso: string) => {
const t = new Date(iso);
return makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t));
return makePhysicalSky(sunAt(FALLBACK_VIEW.place, t), 0, FALLBACK_VIEW);
};
const fullMoon = night('2026-11-24T22:00:00Z');
const newMoon = night('2026-12-09T20:00:00Z');
@ -86,7 +87,7 @@ describe('the night display', () => {
it('grades toward the rods at night and not by day', () => {
expect(fullMoon.fit.display.grade).toBeGreaterThan(0.8);
expect(newMoon.fit.display.grade).toBeGreaterThan(0.99);
expect(makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0);
expect(makePhysicalSky(sunOfBand(FALLBACK_VIEW.place, 'day', new Date('2026-06-21T10:40:00Z')), 0, FALLBACK_VIEW).fit.display.grade ?? 0).toBe(0);
});
it('has no fixed night ceiling: the curve tops out at NIGHT_CEILING', () => {

View file

@ -10,7 +10,7 @@
// distribution of the sky grid so that its 5th, 50th and 95th percentiles land on the state's target display luminances. The curve
// starts at a small black lift and ends at white, or at the state's ceiling when it has one. It is fitted on the sky grid alone: the
// cards are not sampled, they ride the same curve.
import type { FixedSkyState } from '../skyState';
import type { FixedSkyState } from './skyMoment';
import { SUN_LUX } from './nightSky';
type Rgb = readonly [number, number, number];

View file

@ -9,6 +9,8 @@ export interface Place {
lat: number;
lon: number;
altitudeKm: number;
/** The place's IANA time zone (the baker writes it): the one owner of place-local time is skyMoment.ts. */
tz: string;
}
/** The manifest's `view`: the baked window of the sky the planes cover. Angles are degrees, planes are in plane pixels. */
@ -45,7 +47,7 @@ export interface Camera {
/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */
export const FALLBACK_VIEW: View = {
place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 },
place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183, tz: 'Europe/Vienna' },
lookAzDeg: 214,
windowDeg: 72,
planeW: 1280,

View file

@ -1,81 +1,132 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { FALLBACK_VIEW } from './ridge/view';
import { ELSEWHERE_VIEW } from './ridge/manifest.fixture';
import { atStandardTime } from './standardTime.testkit';
import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
import { DAY_FROM, setSkyClock } from './skyState';
import { atSolarTime } from './ridge/skyTestkit';
import { CLEAR_SKY, ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
import { setSkyClock } from './skyState';
import { DAY_FROM } from './ridge/skyMoment';
import type { SkyChoice } from './ridge/skyMoment';
import { BUDGET } from './ridge/toneMap';
import { ridgeWeather, setFedWeather } from './ridge/weather';
const STATES = ['day', 'dusk', 'night'] as const;
const auto: SkyChoice = { kind: 'auto' };
const named = (id: 'dawn' | 'morning' | 'noon' | 'golden' | 'dusk' | 'night'): SkyChoice => ({
kind: 'named',
id,
});
const BANDS = [
['day', named('noon')],
['dusk', named('dusk')],
['night', named('night')],
] as const;
afterEach(() => {
setSkyClock();
setFedWeather(undefined);
vi.unstubAllGlobals();
});
describe('ridgeSkyFor', () => {
it('carries the physical sky of the state', () => {
for (const state of STATES) {
const sky = ridgeSkyFor(state, FALLBACK_VIEW, 0.3);
expect(sky.physical?.state).toBe(state);
expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
}
it.each(BANDS)('carries the physical sky of the %s moment', (band, choice) => {
const sky = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3);
expect(sky.physical?.state).toBe(band);
expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
});
it('draws the sky auto resolves to, never nothing', () => {
const key = (s: ReturnType<typeof ridgeSkyFor>) => [
s.top,
s.mid,
s.horizon,
s.physical?.sun,
];
setSkyClock(() => atStandardTime(12, 0));
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('day', FALLBACK_VIEW, 0.3)));
setSkyClock(() => atStandardTime(0, 0));
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('night', FALLBACK_VIEW, 0.3)));
setSkyClock(() => atStandardTime(18, 10));
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('dusk', FALLBACK_VIEW, 0.3)));
it('Auto draws the real sun now, never nothing', () => {
const key = (s: ReturnType<typeof ridgeSkyFor>) => [s.top, s.mid, s.horizon, s.physical?.sun.time];
const noon = atSolarTime(12, 0);
expect(key(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon))[3]).toEqual(noon);
expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, noon).physical?.state).toBe('day');
expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, atSolarTime(0, 0)).physical?.state).toBe('night');
expect(ridgeSkyFor(auto, FALLBACK_VIEW, 0.3, atSolarTime(18, 10)).physical?.state).toBe('dusk');
});
it("is lit from the real sun over Vienna: a forced state's sun is inside the state, the clear noon sky is blue", () => {
const day = ridgeSkyFor('day', FALLBACK_VIEW, 0);
it("is lit from the real sun over Vienna: a moment's sun is inside its band, the clear noon sky is blue", () => {
const day = ridgeSkyFor(named('noon'), FALLBACK_VIEW, 0);
expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM);
expect(day.top[2]).toBeGreaterThan(day.top[0]);
const dusk = ridgeSkyFor('dusk', FALLBACK_VIEW, 0);
expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
expect(ridgeSkyFor('night', FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
expect(Math.abs(ridgeSkyFor(named('dusk'), FALLBACK_VIEW, 0).physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
expect(ridgeSkyFor(named('night'), FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
});
it('a free moment is lit from the sun of its own date', () => {
const sky = ridgeSkyFor({ kind: 'free', date: '2026-07-15', minutes: 13 * 60 }, FALLBACK_VIEW);
expect(sky.physical?.sun.time.toISOString()).toBe('2026-07-15T11:00:00.000Z');
expect(sky.physical?.state).toBe('day');
});
it("is made over the View's place: the sun and the observer are the View's", () => {
const sky = ridgeSkyFor('day', ELSEWHERE_VIEW, 0);
const sky = ridgeSkyFor(named('noon'), ELSEWHERE_VIEW, 0);
expect(sky.physical?.view).toBe(ELSEWHERE_VIEW);
expect(sky.physical?.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
});
it("keys a rebuild by the View's place as well: another place is another key", () => {
const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } };
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', other, 0.3));
expect(ridgeSkyKey('day', other, 0.3)).toContain('graz');
});
it('keys a rebuild by state and weather, not by the moving sun', () => {
setSkyClock(() => atStandardTime(12, 0));
expect(ridgeSkyKey('auto', FALLBACK_VIEW, 0.3)).toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.3));
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.8));
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('night', FALLBACK_VIEW, 0.3));
});
// Each state's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
it.each(STATES)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (state) => {
const r = ridgeDrawn(state);
expect(r.darkest).toBe(BUDGET[state].floor);
expect(r.lightest).toBeLessThanOrEqual(BUDGET[state].ceiling);
const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit;
// Each band's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
it.each(BANDS)('%s: the display is the curve of its budget: black lift at the floor, and its ceiling', (band, choice) => {
const r = ridgeDrawn(band);
expect(r.darkest).toBe(BUDGET[band].floor);
expect(r.lightest).toBeLessThanOrEqual(BUDGET[band].ceiling);
const fit = ridgeSkyFor(choice, FALLBACK_VIEW, 0.3).physical?.fit;
expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9);
expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9);
});
});
describe('ridgeSkyKey', () => {
const noonNow = atSolarTime(12, 0);
it("keys a rebuild by the View's place as well: another place is another key", () => {
const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } };
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, noonNow)).not.toBe(ridgeSkyKey(named('noon'), other, 0.3, noonNow));
expect(ridgeSkyKey(named('noon'), other, 0.3, noonNow)).toContain('graz');
});
it('differs between Auto-at-day and Noon: live against frozen', () => {
expect(ridgeSkyKey(auto, FALLBACK_VIEW, 0.3, noonNow)).not.toBe(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, noonNow));
});
it('is equal for one named moment across two calls on one local date, and changes with the weather and the moment', () => {
const a = ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, atSolarTime(9, 0));
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, atSolarTime(21, 0))).toBe(a);
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.8, noonNow)).not.toBe(a);
expect(ridgeSkyKey(named('night'), FALLBACK_VIEW, 0.3, noonNow)).not.toBe(a);
expect(ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0.3, new Date(noonNow.getTime() + 24 * 3_600_000))).not.toBe(a);
});
it('changes with the free date or minutes', () => {
const k = (date: string, minutes: number) => ridgeSkyKey({ kind: 'free', date, minutes }, FALLBACK_VIEW, 0, noonNow);
expect(k('2026-07-15', 300)).not.toBe(k('2026-07-16', 300));
expect(k('2026-07-15', 300)).not.toBe(k('2026-07-15', 305));
expect(k('2026-07-15', 300)).toBe(k('2026-07-15', 300));
});
it('is stable under the minute tick inside a band (Auto)', () => {
const at = (m: number) => ridgeSkyKey(auto, FALLBACK_VIEW, 0.3, new Date(atSolarTime(11, 0).getTime() + m * 60_000));
expect(at(0)).toBe(at(1));
expect(at(0)).toBe(at(90));
});
});
describe('the weather of a moment', () => {
it('a free moment draws a clear sky whatever the feed holds; Auto and the named moments draw the feed', () => {
setFedWeather(0.9);
expect(ridgeWeather()).toBe(0.9);
const noonNow = atSolarTime(12, 0);
const free: SkyChoice = { kind: 'free', date: '2026-07-15', minutes: 13 * 60 };
expect(ridgeSkyFor(free, FALLBACK_VIEW, undefined, noonNow).physical?.weather).toEqual(
ridgeSkyFor(free, FALLBACK_VIEW, CLEAR_SKY, noonNow).physical?.weather
);
expect(ridgeSkyKey(free, FALLBACK_VIEW, undefined, noonNow)).toContain(`:${CLEAR_SKY}:`);
for (const choice of [auto, named('noon')]) {
expect(ridgeSkyKey(choice, FALLBACK_VIEW, undefined, noonNow)).toContain(':0.9:');
expect(ridgeSkyFor(choice, FALLBACK_VIEW, undefined, noonNow).physical?.weather).toEqual(
ridgeSkyFor(choice, FALLBACK_VIEW, 0.9, noonNow).physical?.weather
);
}
});
});
describe('loadWeather', () => {
it('reads the file again for another place inside the refresh window: the weather it set belongs to the sun of the place it was read for', async () => {
const fetched = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
@ -92,15 +143,16 @@ describe('loadWeather', () => {
describe('the rebuild key and the constellation lines', () => {
it('carries the lines at night only: toggling them is a different sky, a day sky is the same', async () => {
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined, removeItem: () => undefined });
vi.resetModules();
const st = await import('./skyState');
const f = await import('./skyForState');
const off = f.ridgeSkyKey('night', FALLBACK_VIEW, 0);
const dayOff = f.ridgeSkyKey('day', FALLBACK_VIEW, 0);
st.pickSkyState('night');
st.pickSkyState('night');
expect(f.ridgeSkyKey('night', FALLBACK_VIEW, 0)).toBe(`${off}:lines`);
expect(f.ridgeSkyKey('day', FALLBACK_VIEW, 0)).toBe(dayOff);
const now = atSolarTime(12, 0);
const off = f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now);
const dayOff = f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now);
st.pickSkyChoice(named('night'));
st.pickSkyChoice(named('night'));
expect(f.ridgeSkyKey(named('night'), FALLBACK_VIEW, 0, now)).toBe(`${off}:lines`);
expect(f.ridgeSkyKey(named('noon'), FALLBACK_VIEW, 0, now)).toBe(dayOff);
});
});

View file

@ -1,27 +1,36 @@
// What the ridge scene is told for a sky state. 'auto' is a choice, not a sky: it draws the sky it
// resolves to (`resolveSkyState`, the clock), so the scene paints one of day, dusk or night, fitted to that
// state's luminance budget (ridge/toneMap.ts).
// What the ridge scene is told for a sky choice. The choice is not a sky: `momentFor` (ridge/skyMoment.ts) decides the instant it draws,
// the sun at that instant is what the physical sky is lit from, and its band (`skyBand`) picks the display's luminance budget (ridge/toneMap.ts).
import type { SkyColours } from './ridge/skyColour';
import { makePhysicalSky } from './ridge/physicalSky';
import { momentFor, momentKey, skyBand } from './ridge/skyMoment';
import type { FixedSkyState, SkyChoice } from './ridge/skyMoment';
import { sunAt } from './ridge/sunAt';
import type { Place, View } from './ridge/view';
import { BUDGET } from './ridge/toneMap';
import { ridgeWeather, setFedWeather } from './ridge/weather';
import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed';
import { getConstellationLines, resolveSkyState, skyNow } from './skyState';
import type { SkyState } from './skyState';
import { getConstellationLines, skyNow } from './skyState';
/** A clear sky: what a free moment is drawn with (ruling ridge-weather-on-frozen-moments: today's weather says nothing of another date). */
export const CLEAR_SKY = 0;
/** The weather a choice is drawn with: a free moment is clear; Auto and the named moments of today draw today's weather. */
const weatherFor = (choice: SkyChoice): number =>
choice.kind === 'free' ? CLEAR_SKY : ridgeWeather();
/**
* What a rebuild of the ridge scene is for: the fixed state it draws, the weather and, at night, the constellation lines. The sun moves with the clock inside a state and
* is not part of the key (the scene is baked at its start), as the sky was one gradient per state before.
* What a rebuild of the ridge scene is for: the band and moment it draws, the weather, the place and, at night, the constellation lines.
* The sun moves with the clock inside an Auto band and is not part of the key (the scene is baked at its start); a named moment is its id
* and local date, a free one its date and minutes.
*/
export const ridgeSkyKey = (
state: SkyState,
choice: SkyChoice,
view: View,
weather: number = ridgeWeather(),
weather: number = weatherFor(choice),
now: Date = skyNow()
): string => {
const fixed = resolveSkyState(state, now);
return `ridge:${fixed}:${weather}:${view.place.id}${fixed === 'night' && getConstellationLines() ? ':lines' : ''}`;
const band = skyBand(sunAt(view.place, momentFor(choice, view.place, now)).elevation);
return `ridge:${band}:${weather}:${view.place.id}:${momentKey(choice, view.place, now)}${band === 'night' && getConstellationLines() ? ':lines' : ''}`;
};
const WEATHER_REFRESH_MS = 10 * 60_000;
@ -39,18 +48,17 @@ export async function loadWeather(url: string, place: Place, now: Date = skyNow(
}
/**
* The ridge scene's `sky` option: the physical sky over the View's place for the state ('auto': the real sun now; a forced state: the
* sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas
* The ridge scene's `sky` option: the physical sky over the View's place at the instant the choice draws (`momentFor`: Auto the real sun now,
* a named or free moment its own), as a palette for the layers and stars plus the `physical` sky the host canvas
* is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms).
*/
export function ridgeSkyFor(
state: SkyState,
choice: SkyChoice,
view: View,
weather: number = ridgeWeather(),
weather: number = weatherFor(choice),
now: Date = skyNow()
): SkyColours {
const fixed = resolveSkyState(state, now);
const physical = makePhysicalSky(fixed, now, weather, view);
const physical = makePhysicalSky(sunAt(view.place, momentFor(choice, view.place, now)), weather, view);
return {
...physical.stops,
physical,
@ -67,8 +75,7 @@ export interface Range {
* The ridge sky's range: what its display is fitted to hold (`BUDGET`, toneMap.ts), which `physicalSky.test.ts` proves over the
* sun's whole year over Vienna. Dark ink needs the floor; light ink the ceiling.
*/
export function ridgeDrawn(state: SkyState): Range {
const b = BUDGET[resolveSkyState(state)];
export function ridgeDrawn(band: FixedSkyState): Range {
const b = BUDGET[band];
return { darkest: b.floor, lightest: b.ceiling };
}

View file

@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import { baked } from '../../../sky/baked';
import { AA, luminance } from '../../../sky/skyTokens.js';
import { indexColorMXID } from '../../../util/colorMXID';
import type { FixedSkyState } from './skyState';
import type { FixedSkyState } from './ridge/skyMoment';
import {
LIGHTEST_PATCH,
NIGHT_INK_MAX_L,

View file

@ -15,7 +15,7 @@ import chroma from 'chroma-js';
import { AA, luminance } from '../../../sky/skyTokens.js';
import { baked } from '../../../sky/baked';
import { indexColorMXID } from '../../../util/colorMXID';
import type { FixedSkyState } from './skyState';
import type { FixedSkyState } from './ridge/skyMoment';
import type { SkyThemeId } from './skyTheme';
export interface SkyInk {
@ -31,9 +31,9 @@ export interface SkyInk {
export const sceneInk = (
themeId: SkyThemeId | undefined,
sceneOn: boolean,
state: FixedSkyState,
state: FixedSkyState | undefined,
phone: boolean
): SkyInk | undefined => (themeId && sceneOn ? { state, phone } : undefined);
): SkyInk | undefined => (themeId && sceneOn && state ? { state, phone } : undefined);
/** WCAG relative luminance of the lightest 24x12 patch of terrain behind the timeline. */
export const LIGHTEST_PATCH: Record<FixedSkyState, { desktop: number; phone: number }> = {

View file

@ -0,0 +1,47 @@
// The place the sky is over, and the one decision of which place is drawn. The store (skyState.ts) holds the place; this file is the only writer
// of it: the baked place's manifest, loaded once and shared, when the ridge planes are drawn, and the fallback view (view.ts FALLBACK_VIEW) when
// they are not (the manifest or its cards did not load), because the scene is then the sky alone over that view. So the sky, the weather, the
// rebuild key, the ink and the Auto timer all read the place the scene draws. Main-chunk safe: no sky, no ridge code, only the manifest parser,
// the fallback view and the store.
import type { BackgroundSceneConfig } from './tier';
import { loadManifest } from './ridge/manifest';
import type { RidgeManifest } from './ridge/manifest';
import { FALLBACK_VIEW } from './ridge/view';
import type { View } from './ridge/view';
import { setSkyPlace } from './skyState';
// Set when a build drew the sky alone, so a rebuild key made before the next build is for the view that is drawn.
let skyOnly = false;
/** A scene start is a fresh attempt at the planes. */
export function resetSkyPlanes(): void {
skyOnly = false;
}
/**
* Load the manifest of the place `config` names (unknown or absent: the index's default, as `loadManifest` decides) and make the view being
* drawn the sky's place. Safe to call whenever a reader wants the view: the load is memoised and setting the same place is not a change. A
* failed load is the fallback view, returned with its error so the scene can be the sky alone.
*/
export async function ensureSkyPlace(
config: Pick<BackgroundSceneConfig, 'place'> | undefined
): Promise<{ manifest: RidgeManifest | null; view: View; fail: Error | null }> {
let manifest: RidgeManifest | null = null;
let fail: Error | null = null;
try {
manifest = await loadManifest(import.meta.env.BASE_URL, config?.place);
} catch (e) {
fail = e instanceof Error ? e : new Error(String(e));
}
const view = manifest && !skyOnly ? manifest.view : FALLBACK_VIEW;
setSkyPlace(view.place);
return { manifest, view, fail };
}
/** A build has settled what it draws: the manifest's planes (the manifest), or the sky alone (null). Makes that view's place the sky's and returns the view. */
export function drawnView(manifest: RidgeManifest | null): View {
skyOnly = manifest === null;
const view = manifest?.view ?? FALLBACK_VIEW;
setSkyPlace(view.place);
return view;
}

View file

@ -1,12 +1,17 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit';
import {
SKY_STATE_KEY,
resolveSkyState,
type SkyState,
} from './skyState';
import { atSolarTime } from './ridge/skyTestkit';
import { FALLBACK_VIEW } from './ridge/view';
import { sceneThemeId } from './skyTheme';
import { SKY_CHOICE_KEY } from './skyState';
import type { SkyChoice } from './ridge/skyMoment';
type Mod = typeof import('./skyState');
const VIENNA = FALLBACK_VIEW.place;
const OLD_KEY = 'ratatoskr.skyState';
const noon: SkyChoice = { kind: 'named', id: 'noon' };
const dusk: SkyChoice = { kind: 'named', id: 'dusk' };
const night: SkyChoice = { kind: 'named', id: 'night' };
const auto: SkyChoice = { kind: 'auto' };
function fakeStorage(initial: Record<string, string> = {}) {
const data = new Map(Object.entries(initial));
@ -16,6 +21,9 @@ function fakeStorage(initial: Record<string, string> = {}) {
setItem: (k: string, v: string) => {
data.set(k, v);
},
removeItem: (k: string) => {
data.delete(k);
},
};
}
const fresh = (): Promise<Mod> => {
@ -27,31 +35,74 @@ afterEach(() => {
vi.unstubAllGlobals();
});
describe('sky state', () => {
describe('persistence', () => {
let storage: ReturnType<typeof fakeStorage>;
beforeEach(() => {
storage = fakeStorage();
vi.stubGlobal('localStorage', storage);
});
it('defaults to auto when nothing is stored', async () => {
expect((await fresh()).getSkyState()).toBe('auto');
it('defaults to Auto when nothing is stored', async () => {
expect((await fresh()).getSkyChoice()).toEqual(auto);
});
it.each(['night', 'day', 'dusk', 'auto'] as const)('restores a stored %s', async (s) => {
storage.data.set(SKY_STATE_KEY, s);
expect((await fresh()).getSkyState()).toBe(s);
});
it.each(['', 'noon', 'NIGHT', '"night"', 'null'])(
'falls back to auto on stored %j',
async (v) => {
storage.data.set(SKY_STATE_KEY, v);
expect((await fresh()).getSkyState()).toBe('auto');
it.each([auto, noon, night, { kind: 'free', date: '2026-12-21', minutes: 400 }] as SkyChoice[])(
'restores a stored %j',
async (c) => {
storage.data.set(SKY_CHOICE_KEY, JSON.stringify(c));
expect((await fresh()).getSkyChoice()).toEqual(c);
}
);
it('falls back to auto when storage throws', async () => {
it.each([
'',
'night',
'null',
'{',
JSON.stringify({ kind: 'named', id: 'midday' }),
JSON.stringify({ kind: 'named' }),
JSON.stringify({ kind: 'free', date: '1899-12-31', minutes: 0 }),
JSON.stringify({ kind: 'free', date: '2101-01-01', minutes: 0 }),
JSON.stringify({ kind: 'free', date: '2026-02-30', minutes: 0 }),
JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: 1440 }),
JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: -1 }),
JSON.stringify({ kind: 'free', date: '2026-06-21', minutes: 1.5 }),
JSON.stringify({ kind: 'free', date: 20260621, minutes: 5 }),
])('reads %j as Auto', async (v) => {
storage.data.set(SKY_CHOICE_KEY, v);
expect((await fresh()).getSkyChoice()).toEqual(auto);
});
it.each([
['auto', auto],
['day', noon],
['dusk', dusk],
['night', night],
] as const)('migrates the old key %s to %j once, and removes it', async (old, want) => {
storage.data.set(OLD_KEY, old);
const m = await fresh();
expect(m.getSkyChoice()).toEqual(want);
expect(storage.data.has(OLD_KEY)).toBe(false);
expect(JSON.parse(storage.data.get(SKY_CHOICE_KEY) as string)).toEqual(want);
m.setSkyChoice(dusk);
expect(storage.data.has(OLD_KEY)).toBe(false);
expect((await fresh()).getSkyChoice()).toEqual(dusk);
});
it.each(['noon', 'NIGHT', '', '"night"', 'null'])('ignores the old key holding %j, and removes it', async (old) => {
storage.data.set(OLD_KEY, old);
expect((await fresh()).getSkyChoice()).toEqual(auto);
expect(storage.data.has(OLD_KEY)).toBe(false);
});
it('the new key wins over a stale old one', async () => {
storage.data.set(OLD_KEY, 'night');
storage.data.set(SKY_CHOICE_KEY, JSON.stringify(dusk));
expect((await fresh()).getSkyChoice()).toEqual(dusk);
expect(storage.data.has(OLD_KEY)).toBe(false);
});
it('keeps the pick for the page load when storage is refused', async () => {
vi.stubGlobal('localStorage', {
getItem: () => {
throw new Error('denied');
@ -59,70 +110,154 @@ describe('sky state', () => {
setItem: () => {
throw new Error('denied');
},
removeItem: () => {
throw new Error('denied');
},
});
const m = await fresh();
expect(m.getSkyState()).toBe('auto');
m.setSkyState('night');
expect(m.getSkyState()).toBe('night');
expect(m.getSkyChoice()).toEqual(auto);
m.setSkyChoice(night);
expect(m.getSkyChoice()).toEqual(night);
});
it('persists a set state under one key and reads it back after a reload', async () => {
(await fresh()).setSkyState('dusk');
expect([...storage.data.entries()]).toEqual([[SKY_STATE_KEY, 'dusk']]);
expect((await fresh()).getSkyState()).toBe('dusk');
it('migrates an old pick even when the new key cannot be written: the pick holds for the page load, the old key stays', async () => {
storage.data.set(OLD_KEY, 'day');
vi.stubGlobal('localStorage', {
...storage,
setItem: () => {
throw new Error('denied');
},
});
expect((await fresh()).getSkyChoice()).toEqual(noon);
expect(storage.data.has(OLD_KEY)).toBe(true);
});
it('ignores an invalid state', async () => {
it('writes the new key before it removes the old one', async () => {
storage.data.set(OLD_KEY, 'dusk');
const order: string[] = [];
vi.stubGlobal('localStorage', {
...storage,
setItem: (k: string, v: string) => {
order.push(`set ${k}`);
storage.data.set(k, v);
},
removeItem: (k: string) => {
order.push(`remove ${k}`);
storage.data.delete(k);
},
});
expect((await fresh()).getSkyChoice()).toEqual(dusk);
expect(order).toEqual([`set ${SKY_CHOICE_KEY}`, `remove ${OLD_KEY}`]);
});
it('persists a set choice under one key and reads it back after a reload', async () => {
(await fresh()).setSkyChoice(dusk);
expect([...storage.data.entries()]).toEqual([[SKY_CHOICE_KEY, JSON.stringify(dusk)]]);
expect((await fresh()).getSkyChoice()).toEqual(dusk);
});
it('ignores an invalid choice', async () => {
const m = await fresh();
m.setSkyState('night');
m.setSkyState('noon' as SkyState);
expect(m.getSkyState()).toBe('night');
expect(storage.data.get(SKY_STATE_KEY)).toBe('night');
m.setSkyChoice(night);
m.setSkyChoice({ kind: 'named', id: 'midday' } as unknown as SkyChoice);
expect(m.getSkyChoice()).toEqual(night);
});
it('notifies subscribers on change only, and stops after unsubscribe', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
const cb = vi.fn();
const off = m.subscribe(cb);
m.setSkyState('day');
m.setSkyState('day');
expect(cb.mock.calls).toEqual([['day']]);
m.setSkyChoice(noon);
m.setSkyChoice(noon);
expect(cb).toHaveBeenCalledTimes(1);
off();
m.setSkyState('night');
m.setSkyChoice(night);
expect(cb).toHaveBeenCalledTimes(1);
});
it('tells a late subscriber nothing until the next change', async () => {
const m = await fresh();
m.setSkyState('day');
m.setSkyChoice(noon);
const cb = vi.fn();
m.subscribe(cb);
expect(cb).not.toHaveBeenCalled();
});
});
describe('auto follows the clock', () => {
const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock
let storage: ReturnType<typeof fakeStorage>;
describe('one authority: the choice at the place decides the sky and the ink', () => {
let m: Mod;
beforeEach(async () => {
vi.stubGlobal('localStorage', fakeStorage());
m = await fresh();
m.setSkyClock(() => atSolarTime(0, 0));
});
it('Noon picked at local midnight is day, and the ink theme is Noonday Sky', () => {
m.setSkyPlace(VIENNA);
m.setSkyChoice(noon);
expect(m.getResolvedSkyState()).toBe('day');
expect(sceneThemeId(m.getResolvedSkyState(), true)).toBe('noonday-sky');
});
it('Night picked at noon is night, and the ink theme is Midnight Sky', () => {
m.setSkyPlace(VIENNA);
m.setSkyClock(() => atSolarTime(12, 0));
m.setSkyChoice(night);
expect(m.getResolvedSkyState()).toBe('night');
expect(sceneThemeId(m.getResolvedSkyState(), true)).toBe('midnight-sky');
});
it('a free moment is its own sky: December at 06:40 Vienna is dusk or night, July at 13:00 day', () => {
m.setSkyPlace(VIENNA);
m.setSkyChoice({ kind: 'free', date: '2026-12-21', minutes: 6 * 60 + 40 });
expect(m.getResolvedSkyState()).toBe('night');
m.setSkyChoice({ kind: 'free', date: '2026-07-15', minutes: 13 * 60 });
expect(m.getResolvedSkyState()).toBe('day');
});
it('with no place the resolved sky is undefined and the theme is not decided', () => {
m.setSkyChoice(noon);
expect(m.getResolvedSkyState()).toBeUndefined();
expect(sceneThemeId(m.getResolvedSkyState(), true)).toBeUndefined();
});
it('setting the place tells the listeners, once', () => {
const cb = vi.fn();
m.subscribe(cb);
m.setSkyPlace(VIENNA);
m.setSkyPlace({ ...VIENNA });
expect(cb.mock.calls).toEqual([['night']]);
expect(m.getSkyPlace()).toEqual(VIENNA);
});
});
describe('Auto follows the clock', () => {
const local = (h: number, m = 0) => atSolarTime(h, m);
beforeEach(() => {
vi.useFakeTimers();
storage = fakeStorage();
vi.stubGlobal('localStorage', storage);
vi.stubGlobal('localStorage', fakeStorage());
});
afterEach(() => {
vi.useRealTimers();
});
it('resolves noon to day, midnight to night and the twilight after sunset to dusk', () => {
expect(resolveSkyState('auto', local(12))).toBe('day');
expect(resolveSkyState('auto', local(0))).toBe('night');
expect(resolveSkyState('auto', local(18, 10))).toBe('dusk');
expect(resolveSkyState('auto', local(5, 50))).toBe('dusk');
expect(resolveSkyState('day', local(0))).toBe('day');
it('is the real sun over the place: noon is day, midnight night and the twilight after sunset dusk', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
const at = (t: Date) => {
m.setSkyClock(() => t);
return m.getResolvedSkyState();
};
expect(at(local(12))).toBe('day');
expect(at(local(0))).toBe('night');
expect(at(local(18, 10))).toBe('dusk');
expect(at(local(5, 50))).toBe('dusk');
});
it('tells listeners the resolved sky when the clock crosses a boundary, and only then', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
let now = local(17, 0);
m.setSkyClock(() => now);
const cb = vi.fn();
@ -139,6 +274,7 @@ describe('auto follows the clock', () => {
it('still tells everyone when a listener comes or goes inside the window before the clock crosses', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
let now = local(17, 0);
m.setSkyClock(() => now);
const [a, b, late] = [vi.fn(), vi.fn(), vi.fn()];
@ -155,25 +291,46 @@ describe('auto follows the clock', () => {
offLate();
});
it('keeps no timer without listeners or when a fixed state is chosen', async () => {
it('keeps no timer without listeners or when a free moment is chosen; one timer serves Auto and a named moment', async () => {
const m = await fresh();
const off = m.subscribe(() => undefined);
expect(vi.getTimerCount()).toBe(1);
m.setSkyState('night');
m.setSkyChoice({ kind: 'free', date: '2026-07-01', minutes: 600 });
expect(vi.getTimerCount()).toBe(0);
m.setSkyState('auto');
m.setSkyChoice(night);
expect(vi.getTimerCount()).toBe(1);
m.setSkyChoice(auto);
expect(vi.getTimerCount()).toBe(1);
off();
expect(vi.getTimerCount()).toBe(0);
});
it('a named moment is told again when the place-local day rolls over, once, and not before', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
m.setSkyChoice(noon);
let now = new Date('2026-06-21T21:30:00Z'); // 23:30 in Vienna
m.setSkyClock(() => now);
const cb = vi.fn();
const off = m.subscribe(cb);
vi.advanceTimersByTime(10 * 60_000);
expect(cb).not.toHaveBeenCalled();
now = new Date('2026-06-21T22:05:00Z'); // 00:05 on the 22nd
vi.advanceTimersByTime(60_000);
expect(cb).toHaveBeenCalledTimes(1);
vi.advanceTimersByTime(60 * 60_000);
expect(cb).toHaveBeenCalledTimes(1);
off();
});
it('notifies a change of choice with the resolved sky', async () => {
const m = await fresh();
m.setSkyPlace(VIENNA);
m.setSkyClock(() => local(12));
const cb = vi.fn();
m.subscribe(cb);
m.setSkyState('night');
m.setSkyState('auto');
m.setSkyChoice(night);
m.setSkyChoice(auto);
expect(cb.mock.calls).toEqual([['night'], ['day']]);
});
});
@ -188,40 +345,41 @@ describe('the constellation lines toggle', () => {
it('are off by default, and a first pick of Night is a plain choice that leaves them off', async () => {
const m = await fresh();
expect(m.getConstellationLines()).toBe(false);
m.pickSkyState('night');
expect(m.getSkyState()).toBe('night');
m.pickSkyChoice(night);
expect(m.getSkyChoice()).toEqual(night);
expect(m.getConstellationLines()).toBe(false);
});
it('re-picking Night while the choice is Night toggles them, tells the listeners, and keeps the choice', async () => {
const m = await fresh();
m.pickSkyState('night');
m.setSkyPlace(VIENNA);
m.pickSkyChoice(night);
const cb = vi.fn();
m.subscribe(cb);
m.pickSkyState('night');
m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(true);
expect(cb.mock.calls).toEqual([['night']]);
expect(m.getSkyState()).toBe('night');
m.pickSkyState('night');
expect(m.getSkyChoice()).toEqual(night);
m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(false);
expect(cb).toHaveBeenCalledTimes(2);
});
it('are not toggled by re-picking any other state, nor by picking Night from Auto that resolves to night', async () => {
it('are not toggled by re-picking any other choice, nor by picking Night from Auto that is drawing night', async () => {
const m = await fresh();
m.pickSkyState('day');
m.pickSkyState('day');
m.pickSkyChoice(noon);
m.pickSkyChoice(noon);
expect(m.getConstellationLines()).toBe(false);
m.setSkyClock(() => new Date('2026-12-04T00:00:00Z'));
m.pickSkyState('auto');
m.pickSkyState('night');
m.pickSkyChoice(auto);
m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(false);
});
it('persist per viewer, and come back from storage', async () => {
const m = await fresh();
m.pickSkyState('night');
m.pickSkyState('night');
m.pickSkyChoice(night);
m.pickSkyChoice(night);
expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on');
const again = await fresh();
expect(again.getConstellationLines()).toBe(true);
@ -235,11 +393,14 @@ describe('the constellation lines toggle', () => {
setItem: () => {
throw new Error('denied');
},
removeItem: () => {
throw new Error('denied');
},
});
const m = await fresh();
expect(m.getConstellationLines()).toBe(false);
m.pickSkyState('night');
m.pickSkyState('night');
m.pickSkyChoice(night);
m.pickSkyChoice(night);
expect(m.getConstellationLines()).toBe(true);
});
});

View file

@ -1,54 +1,73 @@
// Which sky the signed-out page is drawn against. The choice is one value, kept in one
// localStorage key; whoever draws the sky (the scene, the title bar's control) reads it here.
// 'auto' is a choice, not a sky: it resolves from the clock to day, dusk or night
// (`resolveSkyState`), and every sky drawn is one of those three.
import { sunElevation } from '../../../sky/sun.js';
// Which sky the signed-out page is drawn against: three small stores and the notice that one of them moved. The viewer's choice (Auto, a
// named moment, a free moment), the place the sky is over, and the constellation lines. They decide nothing: which instant is drawn is
// `momentFor` and which band it is, `skyBand` (ridge/skyMoment.ts); the resolved sky here is those two applied to the stores.
import { MOMENT_IDS, FREE_DATE_MAX, FREE_DATE_MIN, isDate, momentFor, momentKey, skyBand } from './ridge/skyMoment';
import type { FixedSkyState, MomentId, SkyChoice } from './ridge/skyMoment';
import { sunAt } from './ridge/sunAt';
import type { Place } from './ridge/view';
export type SkyState = 'auto' | 'day' | 'dusk' | 'night';
export const SKY_CHOICE_KEY = 'ratatoskr.skyChoice';
export const SKY_STATES: readonly SkyState[] = ['auto', 'day', 'dusk', 'night'];
export const SKY_STATE_KEY = 'ratatoskr.skyState';
const AUTO: SkyChoice = { kind: 'auto' };
const isSkyState = (v: unknown): v is SkyState => SKY_STATES.includes(v as SkyState);
/** A stored value as a choice, or undefined when it is not one (wrong shape, unknown moment, a date outside 1900..2100, minutes outside 0..1439). */
export function parseSkyChoice(raw: unknown): SkyChoice | undefined {
if (typeof raw !== 'object' || raw === null) return undefined;
const c = raw as Record<string, unknown>;
if (c.kind === 'auto') return AUTO;
if (c.kind === 'named' && MOMENT_IDS.includes(c.id as MomentId)) {
return { kind: 'named', id: c.id as MomentId };
}
if (
c.kind === 'free' &&
isDate(c.date) &&
c.date >= FREE_DATE_MIN &&
c.date <= FREE_DATE_MAX &&
Number.isInteger(c.minutes) &&
(c.minutes as number) >= 0 &&
(c.minutes as number) <= 1439
) {
return { kind: 'free', date: c.date, minutes: c.minutes as number };
}
return undefined;
}
function load(): SkyState {
const same = (a: SkyChoice, b: SkyChoice): boolean => JSON.stringify(a) === JSON.stringify(b);
// The sky menu once held Auto, Day, Dusk and Night under another key. It is read once, here, and removed: Day became Noon.
const OLD_KEY = 'ratatoskr.skyState';
const FROM_OLD = new Map<string, SkyChoice>([
['auto', AUTO],
['day', { kind: 'named', id: 'noon' }],
['dusk', { kind: 'named', id: 'dusk' }],
['night', { kind: 'named', id: 'night' }],
]);
function load(): SkyChoice {
try {
const stored = localStorage.getItem(SKY_STATE_KEY);
return isSkyState(stored) ? stored : 'auto';
const old = localStorage.getItem(OLD_KEY);
if (old !== null) {
const migrated = FROM_OLD.get(old);
if (migrated && localStorage.getItem(SKY_CHOICE_KEY) === null) {
try {
// The new key first: a refusal leaves the old one in place, and the pick holds for this page load.
localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(migrated));
} catch {
return migrated;
}
localStorage.removeItem(OLD_KEY);
return migrated;
}
localStorage.removeItem(OLD_KEY);
}
const stored = localStorage.getItem(SKY_CHOICE_KEY);
return (stored !== null && parseSkyChoice(JSON.parse(stored))) || AUTO;
} catch {
return 'auto';
return AUTO;
}
}
/**
* The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
* the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
* #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
* sit inside them.
*/
export type FixedSkyState = 'day' | 'dusk' | 'night';
/** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */
const LAT = 45;
/** Sun elevation (degrees) from which it is day, and below the negative of which it is night; between, dusk (dawn included). */
export const DAY_FROM = 6;
let clock: () => Date = () => new Date();
/** Minutes west of UTC of this timezone's standard time (the larger of its January and July offsets), so daylight saving does not move the sun. */
export const standardOffsetMinutes = (now: Date): number =>
Math.max(
new Date(now.getFullYear(), 0, 1).getTimezoneOffset(),
new Date(now.getFullYear(), 6, 1).getTimezoneOffset()
);
/** The fixed sky a choice draws now: itself, or for 'auto' the sky the sun's elevation here calls for. */
export function resolveSkyState(s: SkyState, now: Date = clock()): FixedSkyState {
if (s !== 'auto') return s;
const lon = -standardOffsetMinutes(now) / 4;
const el = sunElevation(now, LAT, lon) as number;
if (el >= DAY_FROM) return 'day';
return el <= -DAY_FROM ? 'night' : 'dusk';
}
/** The constellation lines (a hidden extra, ruling ridge-constellation-lines-hidden-extra): on or off, per viewer, off by default. */
export const SKY_LINES_KEY = 'ratatoskr.skyLines';
@ -66,55 +85,67 @@ export const getConstellationLines = (): boolean => {
return lines;
};
let current: SkyState | undefined;
const listeners = new Set<(s: FixedSkyState) => void>();
let current: SkyChoice | undefined;
let place: Place | undefined;
const listeners = new Set<(s: FixedSkyState | undefined) => void>();
let timer: ReturnType<typeof setTimeout> | undefined;
let shown: FixedSkyState | undefined;
let shownKey: string | undefined;
const TICK_MS = 60_000;
/** The choice (what the control shows). */
export const getSkyState = (): SkyState => {
export const getSkyChoice = (): SkyChoice => {
current ??= load();
return current;
};
/** The sky being drawn: the choice, resolved. */
export const getResolvedSkyState = (): FixedSkyState => resolveSkyState(getSkyState());
/** The place the sky is over: the loaded manifest's, set by skyPlace.ts; undefined until one is known. */
export const getSkyPlace = (): Place | undefined => place;
/** The moment the sky is drawn for: the real time, or the test clock. */
export const skyNow = (): Date => clock();
/** The band being drawn: the choice at the place, through `momentFor` and `skyBand`; undefined until a place is known (no sky is drawn for ink). */
export const getResolvedSkyState = (): FixedSkyState | undefined =>
place && skyBand(sunAt(place, momentFor(getSkyChoice(), place, skyNow())).elevation);
/** What a rebuild would be for, of the moment now drawn (`momentKey`): a named moment's changes when the place-local day rolls over. */
const drawnKey = (): string | undefined => place && momentKey(getSkyChoice(), place, skyNow());
const emit = () => {
shown = getResolvedSkyState();
[...listeners].forEach((cb) => cb(shown as FixedSkyState));
shownKey = drawnKey();
[...listeners].forEach((cb) => cb(shown));
};
// While anyone listens and the choice is 'auto', one timer checks the clock each minute and tells
// listeners when the resolved sky changes from the one last told (`shown`, set when telling and when the
// first listener arrives, never by a later arrival or departure). Otherwise there is no timer.
// While anyone listens and the choice is Auto or a named moment, one timer checks the clock each minute and tells
// listeners when the resolved band, or the moment drawn (an Auto band, a named moment's place-local day), changes from the one
// last told (`shown` and `shownKey`, set when telling and when the first listener arrives, never by a later arrival or departure).
// A free moment does not move with the clock, so it has no timer.
function sync(): void {
clearTimeout(timer);
timer = undefined;
if (listeners.size === 0 || getSkyState() !== 'auto') return;
if (listeners.size === 0 || getSkyChoice().kind === 'free') return;
const tick = () => {
if (getResolvedSkyState() !== shown) emit();
if (getResolvedSkyState() !== shown || drawnKey() !== shownKey) emit();
timer = setTimeout(tick, TICK_MS);
};
timer = setTimeout(tick, TICK_MS);
}
/** The moment the sky is drawn for: the real time, or the test clock. */
export const skyNow = (): Date => clock();
/** Replace the clock (tests); no argument restores the real one. */
export function setSkyClock(now?: () => Date): void {
clock = now ?? (() => new Date());
sync();
}
export function setSkyState(s: SkyState): void {
if (!isSkyState(s)) return;
const changed = s !== getSkyState();
current = s;
export function setSkyChoice(c: SkyChoice): void {
const next = parseSkyChoice(c);
if (!next) return;
const changed = !same(next, getSkyChoice());
current = next;
try {
localStorage.setItem(SKY_STATE_KEY, s);
localStorage.setItem(SKY_CHOICE_KEY, JSON.stringify(next));
} catch {
// Storage is refused (private mode, quota): the choice holds for this page load only.
}
@ -124,12 +155,22 @@ export function setSkyState(s: SkyState): void {
}
}
/** The place the sky is over (skyPlace.ts, once the manifest is loaded). Listeners hear it, since the band depends on it. */
export function setSkyPlace(p: Place | undefined): void {
if (p?.id === place?.id && p?.tz === place?.tz && p?.lat === place?.lat && p?.lon === place?.lon) {
return;
}
place = p;
emit();
}
/**
* A pick in the sky menu. Picking a state sets it; picking Night while the choice already is Night toggles the constellation lines, which
* A pick in the sky menu. Picking a choice sets it; picking Night while the choice already is Night toggles the constellation lines, which
* listeners hear as a sky change (the scene is rebuilt for it: `ridgeSkyKey` carries the flag).
*/
export function pickSkyState(s: SkyState): void {
if (s === 'night' && getSkyState() === 'night') {
export function pickSkyChoice(c: SkyChoice): void {
const now = getSkyChoice();
if (c.kind === 'named' && c.id === 'night' && now.kind === 'named' && now.id === 'night') {
lines = !getConstellationLines();
try {
localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off');
@ -139,12 +180,15 @@ export function pickSkyState(s: SkyState): void {
emit();
return;
}
setSkyState(s);
setSkyChoice(c);
}
/** Listeners hear the resolved sky: on a change of choice, and while 'auto', when the clock crosses a boundary. */
export function subscribe(cb: (s: FixedSkyState) => void): () => void {
if (listeners.size === 0) shown = getResolvedSkyState();
/** Listeners hear the resolved band: on a change of choice or place, while Auto, when the clock crosses a band, and while a named moment, when the place-local day rolls over. */
export function subscribe(cb: (s: FixedSkyState | undefined) => void): () => void {
if (listeners.size === 0) {
shown = getResolvedSkyState();
shownKey = drawnKey();
}
listeners.add(cb);
sync();
return () => {

View file

@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { atSolarTime } from './ridge/skyTestkit';
import { baked } from '../../../sky/baked';
import { AA, contrast } from '../../../sky/skyTokens.js';
import { Editor } from '../../components/editor/Editor.css';
@ -12,9 +12,14 @@ import { SkyPlate, plateRegions } from './skyPlate.css';
import {
getResolvedSkyState,
setSkyClock,
setSkyPlace,
subscribe as subscribeSky,
} from './skyState';
import { sceneThemeId } from './skyTheme';
import { FALLBACK_VIEW } from './ridge/view';
beforeAll(() => setSkyPlace(FALLBACK_VIEW.place));
afterAll(() => setSkyPlace(undefined));
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
const r2 = (n: number) => n.toFixed(2);
@ -32,7 +37,7 @@ describe('sceneThemeId, the theme the page wears', () => {
it('auto draws the clock sky and that sky decides', () => {
[0, 12, 23].forEach((h) => {
setSkyClock(() => atStandardTime(h, 10));
setSkyClock(() => atSolarTime(h, 10));
expect(sceneThemeId(getResolvedSkyState(), true)).toBe(
h === 12 ? 'noonday-sky' : 'midnight-sky'
);
@ -40,6 +45,13 @@ describe('sceneThemeId, the theme the page wears', () => {
setSkyClock();
});
it('with no place known there is no drawn sky to follow: the theme is not decided', () => {
setSkyPlace(undefined);
expect(getResolvedSkyState()).toBeUndefined();
expect(sceneThemeId(getResolvedSkyState(), true)).toBeUndefined();
setSkyPlace(FALLBACK_VIEW.place);
});
it('with the scene off no sky is drawn, so the person theme stands', () => {
(['day', 'dusk', 'night'] as const).forEach((st) =>
expect(sceneThemeId(st, false)).toBeUndefined()
@ -49,12 +61,12 @@ describe('sceneThemeId, the theme the page wears', () => {
it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => {
vi.useFakeTimers();
let hour = 12;
setSkyClock(() => atStandardTime(hour, 10));
const seen: string[] = [];
setSkyClock(() => atSolarTime(hour, 10));
const seen: Array<string | undefined> = [];
const off = subscribeSky((s) => seen.push(s));
expect(getResolvedSkyState()).toBe('day');
hour = 0;
setSkyClock(() => atStandardTime(hour, 10));
setSkyClock(() => atSolarTime(hour, 10));
vi.advanceTimersByTime(61_000);
expect(seen).toEqual(['night']);
expect(getResolvedSkyState()).toBe('night');

View file

@ -1,8 +1,8 @@
// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the fixed pick, or the
// clock's state under 'auto'; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk
// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the
// choice at the place; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk
// wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is
// drawn, that is with the scene off.
import type { FixedSkyState } from './skyState';
import type { FixedSkyState } from './ridge/skyMoment';
export type SkyThemeId = 'midnight-sky' | 'noonday-sky';
@ -13,5 +13,7 @@ const BY_STATE: Record<FixedSkyState, SkyThemeId> = {
};
/** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */
export const sceneThemeId = (resolved: FixedSkyState, sceneOn: boolean): SkyThemeId | undefined =>
sceneOn ? BY_STATE[resolved] : undefined;
export const sceneThemeId = (
resolved: FixedSkyState | undefined,
sceneOn: boolean
): SkyThemeId | undefined => (sceneOn && resolved ? BY_STATE[resolved] : undefined);

View file

@ -1,7 +0,0 @@
import { standardOffsetMinutes } from './skyState';
/** 22 September 2026 at h:m of local solar time as the sky clock reads it (standard time, whatever daylight saving says). */
export const atStandardTime = (h: number, m = 0): Date => {
const probe = new Date(2026, 8, 22);
return new Date(Date.UTC(2026, 8, 22, h, m) + standardOffsetMinutes(probe) * 60000);
};

View file

@ -1,19 +1,23 @@
import { useSyncExternalStore } from 'react';
import {
getResolvedSkyState,
getSkyState,
getSkyChoice,
getSkyPlace,
subscribe,
type FixedSkyState,
type SkyState,
} from '../features/scene/skyState';
import type { Place } from '../features/scene/ridge/view';
import type { FixedSkyState, SkyChoice } from '../features/scene/ridge/skyMoment';
import { getSceneDrawn, subscribeSceneDrawn } from '../features/scene/sceneDrawn';
/** The choice, as the control shows it ('auto' stays 'auto'). The sky being drawn is `useResolvedSkyState`. */
export const useSkyState = (): SkyState => useSyncExternalStore(subscribe, getSkyState);
/** The choice, as the control shows it (Auto stays Auto). The sky being drawn is `useResolvedSkyState`. */
export const useSkyChoice = (): SkyChoice => useSyncExternalStore(subscribe, getSkyChoice);
/** The sky being drawn: day, dusk or night. Unlike the choice it changes as the clock crosses, so it re-renders. */
export const useResolvedSkyState = (): FixedSkyState =>
/** The sky being drawn: day, dusk or night, or undefined until the place is known. Unlike the choice it changes as the clock crosses under Auto, so it re-renders. */
export const useResolvedSkyState = (): FixedSkyState | undefined =>
useSyncExternalStore(subscribe, getResolvedSkyState);
/** The place the sky is over, or undefined until a scene has settled what it draws (skyPlace.ts). */
export const useDrawnPlace = (): Place | undefined => useSyncExternalStore(subscribe, getSkyPlace);
/** Whether a background scene is drawing a sky right now (not merely configured): false on a failed or lost context. */
export const useSceneOn = (): boolean => useSyncExternalStore(subscribeSceneDrawn, getSceneDrawn);

View file

@ -25,7 +25,7 @@ vi.mock('./useSkyState', async () => {
const drawn = await import('../features/scene/sceneDrawn');
return {
useResolvedSkyState: () => 'night',
useSkyState: () => 'night',
useSkyChoice: () => ({ kind: 'named', id: 'night' }),
useSceneOn: () => drawn.getSceneDrawn(),
};
});