Release candidate a6: dev 24883997 into main #173

Merged
void merged 44 commits from dev into main 2026-11-20 20:57:40 +00:00
91 changed files with 5118 additions and 3094 deletions

21
THIRD_PARTY_NOTICES.md Normal file
View file

@ -0,0 +1,21 @@
# Third-party notices
## d3-celestial (constellation lines)
The constellation line chains in `src/app/features/scene/ridge/nightSkyData.ts` are derived from
`data/constellations.lines.json` of d3-celestial, https://github.com/ofrohn/d3-celestial,
under the licence below.
```
Copyright (c) 2015, Olaf Frohn
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.```

View file

@ -6,14 +6,14 @@ target = "ratatoskr"
# tarball was built from, which is not this commit.
source_stamp_environment = "RATATOSKR_BUILD_COMMIT"
# Release dist a1fdfee3cc1ad370d09761bc337e5aff7e069de3: the output of build-prod-dist.sh (ALLOW_CONFIG_DRIFT=1), packed
# Release dist f562f8fae9a294e04354801538ed7a595133f480: the output of build-prod-dist.sh (live config check passed), packed
# as dist/ at the top of one gzip tar. The tree carries the repo's own config.json; what is served is the operator's
# carried file, which Idunn copies beside dist/ and the vhost aliases over the tree's (a vhost without that alias would
# serve the repo config).
[[external_inputs]]
id = "dist-tarball"
url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-a1fdfee3/ratatoskr-a1fdfee3-dist.tar.gz"
sha256 = "22e4c24c328d33e9c9a5c560646b59e0b91f028b54ffb631d8d42872be7ff938"
url = "https://eureka.gamecult.org/forge/GameCult/Ratatoskr/releases/download/dist-f562f8fa/ratatoskr-f562f8fa-dist.tar.gz"
sha256 = "ec4f4fc3e64dfeb7ba6509b386d2a5efc318211f66de663c061e1240b1f610f0"
runner = "unpack"
destination = "release/dist.tar.gz"

View file

@ -113,10 +113,8 @@ Hard-refresh to clear `sw.js`. Do not delete the failed release; leave it for di
## Open
- Until the release that drops the terrain style (Meta 2026-11-17, ruling
`ratatoskr:ruling:ridge-only-scene-terrain-cut`), the served config said
`backgroundScene.style: terrain` and lacked the repo's `dings`, `fileZoneShare` and
`registration` blocks. That release replaces the carried file with the production config; a
`terrain` value left anywhere now falls to the ridge default. Until the carried file and the
build pin are equal again, every handoff build stops at the live check unless
`ALLOW_CONFIG_DRIFT=1` is set (section 1).
- Release a5 (2026-11-20, dist `a1fdfee3`, receipt `/opt/commons/handoff/rat146-a5-receipt-20261120.md`)
replaced the carried config with the repo's `config.json` (ridge, `fileZoneShare` on; ruling
`ratatoskr:ruling:ridge-only-scene-terrain-cut`). The carried file and the build pin are equal, so a
handoff build passes its live check without `ALLOW_CONFIG_DRIFT=1`. A release that changes
`config.json` changes the carried file deliberately, as a5's `carry.sh` did.

View file

@ -20,3 +20,30 @@ directory whose ancestors hold no empty `package.json` (esbuild reads them).
Timings from SwiftShader are CPU time: use them for the split between passes and for before and
after of one change, never as a phone frame time.
## Ridge look sheet
Renders the Vienna cards (`public/ridge/vienna-6815bb9dca99`) lit for six sky states (dawn 2, morning 15, noon 55, golden 6, dusk -3, night -30 degrees of sun)
by a set of looks (`RidgeLook`, `src/app/features/scene/ridge/lightCards.ts`, the one owner of look values), one 480x270 canvas per cell at heading 0. The sky
behind a cell is the app's own (`makePhysicalSky` + `paintSky`, upscaled), without the sun disc, stars or clouds. Not shipped.
npx vite --port 5199 # from the repo root; the app's vite config serves the page and public/
http://localhost:5199/harness/scene/ridgeSheet.html # four presets x six skies
...ridgeSheet.html?preset=swiss # one preset (physical|swiss|poster|painterly)
...ridgeSheet.html?looks=%5B%7B%22label%22%3A%22no-ink%22%2C%22inkScale%22%3A0%7D%2C%7B%22label%22%3A%22hazy%22%2C%22hazeScale%22%3A8%7D%5D
...?w=640 # cell width
`looks=` is a url-encoded or base64 JSON array of `{label, ...partial RidgeLook}` and replaces the preset rows (`inkKeep` and `reliefLight` merge by key).
A cell costs one WebGL2 context and a card decode, so the full sheet takes tens of seconds (much longer in a background tab).
Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named from `PHYSICAL_LOOK`, the rest from `DEFAULT_LOOK`, the painterly cel look), chosen by reasoning, not by eye, for Self to tune:
| preset | values |
| --- | --- |
| physical | PHYSICAL_LOOK (Lambert, no noise, sky haze, full ink) |
| swiss | reliefLight {mix 0.7, azimuthDeg -45, elevationDeg 40}, contrastByDistance 0.9, hazeScale 6, hazeTint [0, 0.05, 0.25], nearWarm 0.5, inkScale 0.6 |
| poster | reliefWeight 0.15, cardToneStep 0.25, cardGradient 0.5, inkKeep {edge 0.25, occlude 0.9, crease 1}, hazeScale 4 |
| 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).

View file

@ -0,0 +1,8 @@
<!doctype html>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Ridge look sheet</title>
<body style="margin:0;background:#111;color:#ddd;font:12px monospace">
<div id="sheet" style="padding:8px"></div>
<script type="module" src="./ridgeSheet.ts"></script>
</body>

282
harness/scene/ridgeSheet.ts Normal file
View file

@ -0,0 +1,282 @@
// Look sheet for the lit ridge cards: the Vienna bake lit for a grid of sky states (or pinned moments) x looks, each cell a small canvas at heading 0. Not shipped.
// `?preset=all|physical|swiss|poster|painterly|painterly-cel-2|painterly-cel-3|painterly-cel-4` (default all: one row each; painterly is DEFAULT_LOOK); `?looks=<JSON array, url-encoded or base64>` replaces the rows with
// the given `{label, ...partial RidgeLook}` entries (inkKeep and reliefLight merge by key). `?w=480` sets the cell width, 16:9 unless `?h=` gives the height (`?w=375&h=812` is a phone).
// The sky behind a cell is the app's own: `makePhysicalSky` + `paintSky` upscaled smoothly, with the real stars and the moon (`nightBodies`),
// without the sun disc or clouds. Columns are the SKIES below (a sun elevation each, the stars and moon of the moment the sheet was opened), or:
// `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` explicit UTC moments: the sun, moon and stars are those of the moment, the state follows the sun's elevation
// `?night=1` the night set: the next new moon, first quarter and full moon from today (or from `?from=YYYY-MM-DD`), each at four night hours
// (`?hours=18,21,0,4` UTC), plus deep dusk (sun at -10 degrees) of the evening of the full moon
// `?labels=1` DEBUG: label each constellation chain in frame with its d3-celestial abbreviation (fetched from the source repository at run time; not shipped)
// `?lines=1` constellation lines over the stars, as the Sky menu's hidden toggle does (night cells only)
import { DEFAULT_LOOK, PHYSICAL_LOOK, lightCards } from '../../src/app/features/scene/ridge/lightCards';
import type { RidgeLook } from '../../src/app/features/scene/ridge/lightCards';
import { parseManifest } from '../../src/app/features/scene/ridge/manifest';
import { makePhysicalSky, paintSky } from '../../src/app/features/scene/ridge/physicalSky';
import { windowFor } from '../../src/app/features/scene/ridge/view';
import { nightBodies, onScreen, paintNightBodies } from '../../src/app/features/scene/ridge/nightBodies';
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';
const DIR = '/public/ridge/vienna-6815bb9dca99/';
type Override = Partial<Omit<RidgeLook, 'inkKeep' | 'reliefLight'>> & {
label: string;
/** The look the unnamed keys come from (DEFAULT_LOOK, the painterly cel look, if absent). */
base?: 'physical';
inkKeep?: Partial<RidgeLook['inkKeep']>;
reliefLight?: Partial<RidgeLook['reliefLight']>;
};
interface Column {
label: string;
elevation?: number;
azimuth?: number;
/** A moment: the sun is the real one of it. */
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). */
const SKIES: Column[] = [
{ label: 'dawn 2 deg', elevation: 2, azimuth: 100 },
{ label: 'morning 15 deg', elevation: 15, azimuth: 135 },
{ label: 'noon 55 deg', elevation: 55, azimuth: 190 },
{ label: 'golden 6 deg', elevation: 6, azimuth: 244 },
{ label: 'dusk -3 deg', elevation: -3, azimuth: 262 },
{ label: 'night -30 deg', elevation: -30, azimuth: 0 },
];
/** The art directions, chosen by reasoning, not by eye: Self tunes them (values listed in harness/scene/README.md). */
const PRESETS: Record<string, Override> = {
physical: { label: 'physical', base: 'physical' },
swiss: {
label: 'swiss',
base: 'physical',
reliefLight: { mix: 0.7, azimuthDeg: -45, elevationDeg: 40 },
contrastByDistance: 0.9,
hazeScale: 6,
hazeTint: [0, 0.05, 0.25],
nearWarm: 0.5,
inkScale: 0.6,
},
poster: {
label: 'poster',
base: 'physical',
reliefWeight: 0.15,
cardToneStep: 0.25,
cardGradient: 0.5,
inkKeep: { edge: 0.25, occlude: 0.9, crease: 1 },
hazeScale: 4,
},
painterly: { label: 'painterly (default, cel 3)' },
'painterly-cel-2': { label: 'painterly-cel-2', celBands: 2 },
'painterly-cel-3': { label: 'painterly-cel-3', celBands: 3 },
'painterly-cel-4': { label: 'painterly-cel-4', celBands: 4 },
};
const merge = (o: Override): { label: string; look: RidgeLook } => {
const { label, base: baseName, inkKeep, reliefLight, ...rest } = o;
const base = baseName === 'physical' ? PHYSICAL_LOOK : DEFAULT_LOOK;
return {
label,
look: {
...base,
...rest,
inkKeep: { ...base.inkKeep, ...inkKeep },
reliefLight: { ...base.reliefLight, ...reliefLight },
},
};
};
function parseLooks(raw: string): Override[] {
const tries = [() => decodeURIComponent(raw), () => atob(raw.replace(/-/g, '+').replace(/_/g, '/'))];
for (const t of tries) {
try {
const v = JSON.parse(t());
if (Array.isArray(v)) return v.map((e, i) => ({ label: `look ${i + 1}`, ...e }));
} catch {
// try the next encoding
}
}
throw new Error('looks= is neither a url-encoded nor a base64 JSON array');
}
const q = new URLSearchParams(location.search);
const HOUR = 3_600_000;
/** The first moment at or after `from` the moon's elongation passes `target` degrees (new 0, first quarter 90, full 180). */
function nextPhase(from: Date, target: number): Date {
const err = (t: number) => ((moonPhase(t).elongationDeg - target + 540) % 360) - 180;
let t = from.getTime();
while (!(err(t) < 0 && err(t + HOUR) >= 0)) t += HOUR;
let a = t;
let b = t + HOUR;
for (let i = 0; i < 20; i += 1) {
const m = (a + b) / 2;
if (err(m) < 0) a = m;
else b = m;
}
return new Date(b);
}
/** The first evening moment (UTC hour steps of 10 minutes from `day`) the sun is at `deg` below the horizon, going down. */
function sunDownTo(place: Parameters<typeof sunAt>[0], day: Date, deg: number): Date {
let t = Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate(), 12);
while (sunAt(place, new Date(t)).elevation > -deg) t += 10 * 60_000;
return new Date(t);
}
const fmt = (d: Date) => d.toISOString().slice(0, 16).replace('T', ' ') + 'Z';
function momentsFrom(params: URLSearchParams, place: Parameters<typeof sunAt>[0]): Column[] | undefined {
const list = params.get('moments');
if (list)
return list.split(',').map((iso) => {
const time = new Date(iso.trim());
if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`);
return { label: 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);
const cols: Column[] = [];
const phases: [string, number][] = [['new', 0], ['first quarter', 90], ['full', 180]];
phases.forEach(([name, deg]) => {
const peak = nextPhase(from, deg);
const day = Date.UTC(peak.getUTCFullYear(), peak.getUTCMonth(), peak.getUTCDate());
hours.forEach((h) => {
// Hours before 12 belong to the night that ends the day of the phase, so the hours run on from the evening.
const time = new Date(day + (h < 12 ? 24 + h : h) * HOUR);
cols.push({ label: `${name} ${fmt(time)}`, time });
});
if (deg === 180) cols.push({ label: `deep dusk, full moon ${fmt(sunDownTo(place, peak, 10))}`, time: sunDownTo(place, peak, 10) });
});
return cols;
}
const preset = q.get('preset');
const pinned = q.get('moments') || q.get('night');
const rows = (q.get('looks')
? parseLooks(q.get('looks') as string)
: preset && preset !== 'all'
? [PRESETS[preset] ?? PRESETS.physical]
: pinned
? [PRESETS.painterly] // a night set is read in the default look unless a preset or looks say otherwise
: Object.values(PRESETS)
).map(merge);
const withLines = q.get('lines') === '1';
const LINES_JSON = 'https://raw.githubusercontent.com/ofrohn/d3-celestial/master/data/constellations.lines.json';
/** Debug: the constellation id of each packed chain, in the generator's order (feature by feature, chain by chain). */
async function chainIds(): Promise<string[]> {
const gj = await (await fetch(LINES_JSON)).json();
return gj.features.flatMap((f: { id: string; geometry: { coordinates: unknown[] } }) => f.geometry.coordinates.map(() => f.id));
}
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(
manifest.cards.map(async (c) => ({
colour: await (await fetch(`${DIR}${c.colour}`)).blob(),
geometry: await (await fetch(`${DIR}${c.geometry}`)).blob(),
}))
);
const decode = (b: Blob) =>
createImageBitmap(b, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
const { view } = manifest;
const win = windowFor(view, W, H);
const now = new Date();
const columns = momentsFrom(q, view.place) ?? SKIES;
const ids = q.get('labels') === '1' ? await chainIds() : undefined;
const table = document.createElement('table');
table.style.borderSpacing = '4px';
root.append(table);
const head = table.insertRow();
head.insertCell();
columns.forEach((c) => (head.insertCell().textContent = c.label));
const tr = rows.map((r) => {
const row = table.insertRow();
row.insertCell().textContent = r.label;
return row;
});
for (const col of columns) {
const time = col.time ?? now;
const sun =
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 px = paintSky(physical, W, H, win.camera);
const bodies = nightBodies(physical, px, withLines);
const small = document.createElement('canvas');
small.width = px.w;
small.height = px.h;
const sctx = small.getContext('2d') as CanvasRenderingContext2D;
const img = sctx.createImageData(px.w, px.h);
img.data.set(px.data);
sctx.putImageData(img, 0, 0);
for (let r = 0; r < rows.length; r += 1) {
const bitmaps = await Promise.all(
blobs.map(async (b) => ({
colour: await decode(b.colour),
geometry: await decode(b.geometry),
}))
);
const cards = lightCards(manifest, bitmaps, physical, rows[r].look);
const cell = document.createElement('canvas');
cell.width = W;
cell.height = H;
const ctx = cell.getContext('2d') as CanvasRenderingContext2D;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(small, 0, 0, W, H);
paintNightBodies(ctx, bodies, W, H, 1);
if (ids) {
// Debug labels: each chain's id at the mean of its vertices that lie in the frame.
ctx.font = '11px monospace';
ctx.fillStyle = '#ffd24a';
linesAt(physical.sun.time, view.place.lat, view.place.lon).forEach((chain, i) => {
const pts = chain.map((p) => onScreen(win.camera, p.azimuth, p.elevation)).filter((a) => a.x >= 0 && a.x <= 1 && a.y >= 0 && a.y <= 1);
if (!pts.length) return;
const mx = pts.reduce((a, p) => a + p.x, 0) / pts.length;
const my = pts.reduce((a, p) => a + p.y, 0) / pts.length;
ctx.fillText(`${ids[i]} ${pts.length}/${chain.length}`, mx * W, my * H);
});
}
// As Ridge.ts paintCards at heading 0: farthest first, each card at its own scale about the horizon row of the plane.
const s = win.plane.scale;
const x0 = (W - win.plane.w) / 2;
const planeTop = H - (win.plane.h + win.plane.bottom);
const ox = x0 + win.plane.w / 2;
const oy = planeTop + view.horizonRow * s;
for (let k = cards.length - 1; k >= 0; k -= 1) {
ctx.save();
ctx.translate(ox, oy);
ctx.scale(cards[k].scale, cards[k].scale);
ctx.drawImage(
cards[k].canvas,
x0 - ox,
planeTop + cards[k].top * s - oy,
win.plane.w,
cards[k].h * s
);
ctx.restore();
}
tr[r].insertCell().append(cell);
}
}
document.title = 'ridge look sheet: done';
}
main().catch((e) => {
console.error(e);
root.textContent = `ridge look sheet failed: ${e}`;
});

View file

@ -2,6 +2,6 @@
"schema": 1,
"default": "vienna",
"places": {
"vienna": "vienna-12e733dc9f09"
"vienna": "vienna-6815bb9dca99"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

View file

@ -1,232 +0,0 @@
{
"schema": 1,
"baker_version": 1,
"bake_id": "12e733dc9f09",
"place": {
"id": "vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
"lat": 48.1929826,
"lon": 16.3534237,
"altitude_km": 0.18330000000000002,
"tz_h": 2,
"tz_name": "CEST",
"date": "2026-09-23"
},
"view": {
"look_az_deg": 214.0,
"plane_h": 600,
"px_per_deg_h": 17.77777777777778,
"px_per_deg_v": 177.77777777777777,
"horizon_row": 314.5166414048937,
"sky_row": 24.0,
"near_row": 396.0,
"window_deg": 72,
"plane_w": 1280
},
"frames": [
{
"key": "dawn",
"sun": {
"az": 91.31344091054159,
"el": 1.9676060128650812
},
"hour_utc": 4.923611110972221,
"planes": {
"far": {
"file": "dawn-far.webp",
"bytes": 76030,
"w": 1280,
"h": 600
},
"mid": {
"file": "dawn-mid.webp",
"bytes": 53926,
"w": 1280,
"h": 600
},
"near": {
"file": "dawn-near.webp",
"bytes": 113422,
"w": 1280,
"h": 600
}
},
"bytes": 243378,
"luma": {
"min": 0.02173927318967578,
"max": 0.2161143719823614
}
},
{
"key": "morning",
"sun": {
"az": 122.50757257559601,
"el": 26.09311435610136
},
"hour_utc": 7.5,
"planes": {
"far": {
"file": "morning-far.webp",
"bytes": 77330,
"w": 1280,
"h": 600
},
"mid": {
"file": "morning-mid.webp",
"bytes": 58076,
"w": 1280,
"h": 600
},
"near": {
"file": "morning-near.webp",
"bytes": 120478,
"w": 1280,
"h": 600
}
},
"bytes": 255884,
"luma": {
"min": 0.023307705502610833,
"max": 0.5966843818121018
}
},
{
"key": "noon",
"sun": {
"az": 179.90578338676787,
"el": 42.09425207059211
},
"hour_utc": 10.778105086666667,
"planes": {
"far": {
"file": "noon-far.webp",
"bytes": 78634,
"w": 1280,
"h": 600
},
"mid": {
"file": "noon-mid.webp",
"bytes": 58684,
"w": 1280,
"h": 600
},
"near": {
"file": "noon-near.webp",
"bytes": 123036,
"w": 1280,
"h": 600
}
},
"bytes": 260354,
"luma": {
"min": 0.028024916825206435,
"max": 0.7110067687110413
}
},
{
"key": "golden",
"sun": {
"az": 263.5260325423649,
"el": 6.139314360766868
},
"hour_utc": 16.193611110972224,
"planes": {
"far": {
"file": "golden-far.webp",
"bytes": 76038,
"w": 1280,
"h": 600
},
"mid": {
"file": "golden-mid.webp",
"bytes": 54686,
"w": 1280,
"h": 600
},
"near": {
"file": "golden-near.webp",
"bytes": 114944,
"w": 1280,
"h": 600
}
},
"bytes": 245668,
"luma": {
"min": 0.02139437660612246,
"max": 0.2869579287555448
}
},
{
"key": "dusk",
"sun": {
"az": 273.0513939324655,
"el": -1.8289117519819837
},
"hour_utc": 17.04388888875,
"planes": {
"far": {
"file": "dusk-far.webp",
"bytes": 75552,
"w": 1280,
"h": 600
},
"mid": {
"file": "dusk-mid.webp",
"bytes": 52176,
"w": 1280,
"h": 600
},
"near": {
"file": "dusk-near.webp",
"bytes": 112176,
"w": 1280,
"h": 600
}
},
"bytes": 239904,
"luma": {
"min": 0.018028911802351475,
"max": 0.18804654725014905
}
},
{
"key": "night",
"sun": {
"az": 283.9869292652113,
"el": -11.998720821772542
},
"hour_utc": 18.004444444305555,
"planes": {
"far": {
"file": "night-far.webp",
"bytes": 74732,
"w": 1280,
"h": 600
},
"mid": {
"file": "night-mid.webp",
"bytes": 50192,
"w": 1280,
"h": 600
},
"near": {
"file": "night-near.webp",
"bytes": 110780,
"w": 1280,
"h": 600
}
},
"bytes": 235704,
"luma": {
"min": 0.012974147057371975,
"max": 0.14255636176898956
}
}
],
"attribution": {
"credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 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"
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 128 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

View file

@ -0,0 +1,100 @@
{
"schema": 2,
"baker_version": 2,
"bake_id": "6815bb9dca99",
"place": {
"id": "vienna",
"name": "Vienna, looking SW to Rax/Schneeberg",
"lat": 48.1929826,
"lon": 16.3534237,
"altitude_km": 0.18330000000000002,
"eye_m": 213.3
},
"view": {
"look_az_deg": 214.0,
"plane_h": 600,
"px_per_deg_h": 17.77777777777778,
"px_per_deg_v": 177.77777777777777,
"exaggeration": 10.0,
"horizon_row": 294.58455032829386,
"sky_row": 24.0,
"near_row": 396.0,
"window_deg": 72,
"plane_w": 1280
},
"curvature": {
"r_earth_m": 6371000.0,
"k_ref": 0.13
},
"encoding": {
"log_d_min": 6.214608098422191,
"log_d_max": 11.462786662662916,
"normal": "rt8"
},
"camera": {
"r_m": 200.0,
"heading_max_deg": 23.0
},
"cards": [
{
"top": 182,
"h": 418,
"near_m": null,
"far_m": 5392.093596252347,
"median_m": 1478.456787109375,
"distance_m": 1478.456787109375,
"scale": 1.1564386078720779,
"colour": {
"file": "card-0-colour.webp",
"bytes": 4598
},
"geometry": {
"file": "card-0-geometry.webp",
"bytes": 95716
}
},
{
"top": 24,
"h": 576,
"near_m": 5392.093596252347,
"far_m": 39877.08347165139,
"median_m": 11107.0283203125,
"distance_m": 11107.0283203125,
"scale": 1.0183368002838622,
"colour": {
"file": "card-1-colour.webp",
"bytes": 8396
},
"geometry": {
"file": "card-1-geometry.webp",
"bytes": 130870
}
},
{
"top": 40,
"h": 560,
"near_m": 39877.08347165139,
"far_m": null,
"median_m": 48378.26953125,
"distance_m": 48378.26953125,
"scale": 1.0041512491408657,
"colour": {
"file": "card-2-colour.webp",
"bytes": 9718
},
"geometry": {
"file": "card-2-geometry.webp",
"bytes": 118378
}
}
],
"w": 1280,
"h": 600,
"bytes": 367676,
"attribution": {
"credit_line": "Contains modified Copernicus data: DEM \u00a9 DLR e.V. 2010-2014 and \u00a9 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"
}
}

View file

@ -1,6 +1,6 @@
# ridge-bake
Offline baker for the ridge backdrop: it turns a Copernicus DEM into six sun frames of three transparent WebP planes (far, mid, near) per place, plus a `manifest.json` and an `index.json` that the runtime reads. The baker is not shipped; `public/ridge/` holds its output.
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.
## Run
@ -8,11 +8,11 @@ Offline baker for the ridge backdrop: it turns a Copernicus DEM into six sun fra
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 six frames over one flat sky. `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`; `export.py` holds the one dict it comes from.
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.
Tests: `RIDGE_PY=<python> RIDGE_TILES=DIR scripts/ridge-bake/tests/run.sh [test_ridge.py|mutate.py|mutate_export.py]` (the full file takes about 9 minutes; `mutate.py` runs the mutants of taper, chains and sweep and `mutate_export.py` those of the planes path and export, each failing if one survives).
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).
## Tiles per preset (`places.json`, date 2026-09-23)
## Tiles per preset (`places.json`)
Files are `Copernicus_DSM_COG_10_<N|S>dd_00_<E|W>ddd_00_DEM.tif`; the list below is `<N|S>dd<E|W>ddd`.
@ -25,11 +25,19 @@ Files are `Copernicus_DSM_COG_10_<N|S>dd_00_<E|W>ddd_00_DEM.tif`; the list below
| amadablam | N27E086 N27E087 N28E086 N28E087 |
| trecime | N46E011 N46E012 |
## Planes
## Cards
`relight_planes` renders every layer twice, with haze colour 0 and 1; the relight is affine in the haze colour, so the difference is each pixel's haze share. That share becomes transparency and the sky behind supplies the haze. Far is slot 0 plus the floor, near is the last slot, mid is every slot between (a place needs at least 3). Colour is exact over the frame's own haze colour; over another sky it drifts by the difference between the two. Stacked planes would leak: each plane's haze is alpha over whatever is behind it, so a nearer plane's haze would veil the farther ridge instead of the sky, and the farther ridge would show through it (a slanted seam through Vienna's near plane). `relight_planes` therefore scales a farther plane's alpha, near to far, to what the nearer layers leave open in the opaque frame (their transmittance over the stack's), looked up as the most open pixel within `OCCLUDE_MARGIN_PX` columns and eased by a Gaussian, because the runtime slides the planes against each other and a hidden pixel must stay hidden after the slide. The nearest layer is the ground in front of the eye: `bake_layer(near=True)` keeps its body opaque down to the horizon (its dissolve starts there), where the farther layers keep theirs (the haze arches). `export.check_near_cover` refuses, at `write_bake`, a near plane with a fully transparent column or a hole between a column's crest and the horizon row, in every frame; the farther planes may have empty columns. Over a flat sky the stack differs from the opaque frame by 1.8/255 over the whole frame (Vienna noon; 4.9 before the knock-out), but that is 11.2/255 mean over the 16.4% of pixels where two planes overlap and 0.005/255 everywhere else; the tests bound the frame at 3/255 and the overlap at 12.5/255. The spec's 2/255 pin is met on the frame; the overlap keeps the margin's soft blob.
`places.json` gives each preset `card_split_km`, an ordered list of 1 to 5 seam depths in km, and optionally `prefilter_m`. A preset without `card_split_km` is refused, and so is a split that leaves a card empty (the message names the splits); K splits make K+1 cards, at most `MAX_CARDS` = 6 per place. New places get a seam probe look before their first bake.
Manifest `luma` is the min and max relative luminance (WCAG, linear 0..1) of the three planes composited far, mid, near over a flat mid-grey sky, over the pixels whose composite coverage `1 - prod(1 - alpha)` is at least 0.5. No plane pixel is opaque (haze is alpha), so no per-plane solid set exists; the composite is what the runtime shows.
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.
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.
## Licence

View file

@ -1,33 +1,31 @@
"""Ridge backdrop export: bake a place with ridge.py and write its three WebP planes per sun key, a manifest and the index.
"""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.
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 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 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)."""
import os, sys, json, math, shutil, hashlib, argparse, tempfile
from datetime import datetime, timezone, timedelta
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import numpy as np, imagecodecs
import sun
BAKER_VERSION = 1
KEYS = ('dawn', 'morning', 'noon', 'golden', 'dusk', 'night')
PLANES = ('far', 'mid', 'near')
NIGHT_EL = -12.0 # the night frame: sun this far below the horizon
BAKER_VERSION = 2
WINDOW_DEG = 72
PLANE_W = 1280 # every plane is the whole 72 deg window
PLANE_W = 1280 # every card is the whole 72 deg window wide
PLANE_W_MAX = 4096
PAIR_BYTES_MAX = 800_000 # two adjacent frames (the runtime's worst case) together; the same number is a CI constant in cut-ridge-ad-gates
DECODE_BYTES_MAX = 20_000_000 # the six planes of a frame pair decoded (2 x 3 x w x h x 4 bytes = 18.4 MB at the full window)
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
WEBP_QUALITY = 80
LUMA_SKY = 0.5 # the flat mid-grey sky the planes are composited over for the luma probe
LUMA_COVER = 0.5 # composite coverage (1 - prod(1 - alpha)) at or above which a pixel is measured
NEAR_CREST_ALPHA = 64 # alpha (0..255) at which a near-plane pixel counts as the ridge's body: the crest of a column is its first such row
NEAR_HOLE_ALPHA = 24 # alpha below which a pixel under the crest is a hole (the sky would show through the ground in front of the eye)
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
ATTRIBUTION = 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',
@ -36,28 +34,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']}
def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props}
_plane = _obj(file=_str, bytes=_int, w=_int, h=_int)
SCHEMA = {'$schema': 'https://json-schema.org/draft/2020-12/schema', 'title': 'ridge-bake manifest v1 and index v1', '$defs': {
'manifest': _obj(schema={'const': 1}, baker_version=_int, bake_id=_str,
place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, tz_h=_num, tz_name=_str, date=_str),
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, horizon_row=_num, sky_row=_num, near_row=_num),
frames={'type': 'array', 'minItems': len(KEYS), 'maxItems': len(KEYS), 'items': _obj(key={'enum': list(KEYS)}, sun=_obj(az=_num, el=_num), hour_utc=_num, planes=_obj(**{k: _plane for k in PLANES}), bytes=_int, luma=dict(_obj(min=_num, max=_num), description='min and max WCAG relative luminance of the three planes composited far, mid, near over a flat mid-grey sky, over pixels whose composite coverage 1 - prod(1 - alpha) is at least 0.5'))},
_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),
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,
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 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)
ty = s.get('type'); py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int}
if ty and (not isinstance(x, py[ty]) or isinstance(x, bool)): raise ValueError(f'{path}: not a {ty}')
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 '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"]}')
if ty == 'array':
if isinstance(x, list):
if not s.get('minItems', 0) <= len(x) <= s.get('maxItems', 1 << 30): raise ValueError(f'{path}: wrong length')
for i, v in enumerate(x): validate(v, s['items'], f'{path}[{i}]')
if ty == 'object':
if isinstance(x, dict):
props = s.get('properties', {}); extra = s.get('additionalProperties', True)
for k in s.get('required', []):
if k not in x: raise ValueError(f'{path}: missing {k}')
@ -66,85 +70,73 @@ 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}')
# ------------------------------------------------------------------------------------ sun keys
def sun_set(p, date):
"""The five day keys from the preset date (copied from the mockup's run2.sun_set) plus the night key at NIGHT_EL: key -> {az, el, hour_utc}."""
day = datetime.fromisoformat(date).replace(tzinfo=timezone.utc); lat, lon, tz = p['lat'], p['lon'], p['tz_h']
geo = lambda t: sun.solar(day + timedelta(hours=t), lat, lon)[2]
def find(target, a, b):
fa = geo(a) - target
for _ in range(50):
m = (a + b) / 2; fm = geo(m) - target
if (fa < 0) == (fm < 0): a, fa = m, fm
else: b = m
return (a + b) / 2
noon = max((12 - lon / 15.0 - 1 + x / 600 for x in range(0, 1200)), key=lambda t: sun.solar(day + timedelta(hours=t), lat, lon)[1])
rise = find(-0.833, noon - 9, noon)
hours = dict(dawn=rise + 0.25, morning=9.5 - tz, noon=noon, golden=find(6.0, noon, noon + 9), dusk=find(-2.5, noon, noon + 9), night=find(NIGHT_EL, noon, noon + 14))
return {k: dict(az=sun.solar(day + timedelta(hours=h), lat, lon)[0], el=sun.solar(day + timedelta(hours=h), lat, lon)[1], hour_utc=h) for k, h in hours.items()}
# ------------------------------------------------------------------------------------ planes -> bytes
def u8(plane): return np.clip(np.rint(plane * 255.0), 0, 255).astype(np.uint8)
def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane), level=WEBP_QUALITY, lossless=False))
# ------------------------------------------------------------------------------------ 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):
"""Lossy RGB albedo with lossless alpha coverage, straight (not premultiplied); the colour under a zero alpha is zeroed."""
a = u8(alpha); rgb = u8(albedo) * (a[..., None] > 0); return bytes(imagecodecs.webp_encode(np.dstack([rgb, a]), level=WEBP_QUALITY, lossless=False))
def encode_geometry(n_r, n_t, logd, enc, wall=None):
"""Lossless, opaque RGB: R, G = (n_r + 1) / 2, (n_t + 1) / 2 ('rt8'), B = the log-distance normalised between enc log_d_min and log_d_max. Wall pixels (the extruded face under a ridge; wall (h, w) bool) write R = G = 255: a code outside the unit disc
that no real normal reaches (real r2 + t2 peaks at 0.998), which the runtime reads as 'normal up, no crease'."""
b = (np.asarray(logd) - enc['log_d_min']) / (enc['log_d_max'] - enc['log_d_min']); r, t = u8((np.asarray(n_r) + 1) / 2), u8((np.asarray(n_t) + 1) / 2)
if wall is not None: m = np.asarray(wall, bool); r, t = np.where(m, 255, r).astype(np.uint8), np.where(m, 255, t).astype(np.uint8)
return bytes(imagecodecs.webp_encode(np.dstack([r, t, u8(b)]), lossless=True))
def decode(b):
"""A plane's bytes as RGBA uint8; the codec returns RGB for a plane that is opaque everywhere, which is solid."""
"""A WebP's bytes as RGBA uint8; the codec returns RGB for an image that is opaque everywhere, which is solid."""
a = imagecodecs.webp_decode(b)
return a if a.shape[-1] == 4 else np.concatenate([a, np.full(a.shape[:2] + (1,), 255, np.uint8)], -1)
def luma_range(decoded):
"""WCAG relative luminance (linear 0..1) of the sRGB composite of the planes (far, mid, near order) over a flat LUMA_SKY grey, over the pixels whose composite coverage 1 - prod(1 - alpha) is at least LUMA_COVER: (min, max).
The planes are haze-as-alpha (no pixel is opaque), so the measure is of the composite, never of one plane's solid pixels."""
img = np.full(decoded[0].shape[:2] + (3,), LUMA_SKY); clear = np.ones(img.shape[:2])
for a in decoded:
al = a[..., 3:].astype(np.float64) / 255.0; img = img * (1 - al) + a[..., :3].astype(np.float64) / 255.0 * al; clear = clear * (1 - al[..., 0])
m = (1 - clear) >= LUMA_COVER
if not m.any(): raise ValueError('a frame has no pixel at coverage >= %s to measure' % LUMA_COVER)
c = img[m]; lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4); y = lin @ np.array([0.2126, 0.7152, 0.0722])
return float(y.min()), float(y.max())
def check_near_cover(near, horizon_row):
"""Refuse a near plane (RGBA uint8) that does not cover the ground in front of the eye: every column must have a crest (an alpha >= NEAR_CREST_ALPHA row), and from the crest down to the horizon row no pixel may be a hole (alpha < NEAR_HOLE_ALPHA).
A transparent column, or a wedge of holes under a crest, shows the sky through the foreground; the farther planes may leave columns empty (a place with no ridge at that distance), the nearest may not."""
a = near[..., 3]; h, w = a.shape; crest = np.argmax(a >= NEAR_CREST_ALPHA, axis=0); none = ~(a >= NEAR_CREST_ALPHA).any(0)
if none.any(): raise ValueError(f'near plane: {int(none.sum())} fully transparent columns, first at x={int(np.argmax(none))}')
rows = np.arange(h)[:, None]; hole = (a < NEAR_HOLE_ALPHA) & (rows >= crest[None, :]) & (rows < int(horizon_row))
if hole.any(): x = int(np.argmax(hole.any(0))); raise ValueError(f'near plane: {int(hole.any(0).sum())} columns have a hole between the crest and the horizon, first at x={x} row {int(np.argmax(hole[:, x]))}')
def composite_alpha(cards, h, w):
"""Coverage of the alpha-over of all cards, each (top, rgba uint8 or float alpha (rows, w)) placed at its rows of an h x w frame."""
clear = np.ones((h, w))
for top, al in cards: clear[top:top + al.shape[0]] *= 1 - np.asarray(al, np.float64)
return 1 - clear
def check_cover(cards, opaque, tol=COVER_TOL):
"""Refuse a bake whose cards, alpha-over, differ from the opaque view's coverage by more than tol anywhere: a hole shows the sky through terrain, an excess is a ghost. cards: [(top, alpha 0..1 (rows, w))], opaque (h, w)."""
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(frame_bytes, plane_w, plane_h):
"""Refuse a bake the runtime could not hold: any two adjacent frames (night with dawn too) above PAIR_BYTES_MAX, or the planes of a frame pair decoding above DECODE_BYTES_MAX."""
if plane_w > PLANE_W_MAX: raise ValueError(f'plane width {plane_w} above {PLANE_W_MAX}')
for i in range(len(frame_bytes)):
j = (i + 1) % len(frame_bytes) # night wraps to dawn, as the runtime's frameChoice and the CI sizeGate pair them
if frame_bytes[i] + frame_bytes[j] > PAIR_BYTES_MAX: raise ValueError(f'frames {KEYS[i]} + {KEYS[j]} are {frame_bytes[i] + frame_bytes[j]} bytes, above {PAIR_BYTES_MAX}')
decoded = 2 * len(PLANES) * plane_w * plane_h * 4
if decoded > DECODE_BYTES_MAX: raise ValueError(f'a frame pair decodes to {decoded} bytes, above {DECODE_BYTES_MAX}')
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 bake_id(frames_webp):
"""First 12 hex of sha256 over the plane bytes in key order, then far, mid, near."""
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 bake_id(cards):
"""First 12 hex of sha256 over the card files in index order, colour then geometry. cards: [(colour bytes, geometry bytes)]."""
h = hashlib.sha256()
for k in KEYS:
for n in PLANES: h.update(frames_webp[k][n])
for colour, geometry in cards: h.update(colour); h.update(geometry)
return h.hexdigest()[:12]
def write_bake(out, place, view, suns, frames_webp, default=None):
"""Write out/<place>-<bake_id>/ (planes + manifest.json), rewrite out/index.json, delete the place's previous dir. Refuses before writing a bake whose planes are not one size, differ from view plane_h, or exceed the budget measured on the decoded planes. Returns the directory."""
sizes = {k: {n: len(frames_webp[k][n]) for n in PLANES} for k in KEYS}; dec = {k: [decode(frames_webp[k][n]) for n in PLANES] for k in KEYS}
shapes = {a.shape[:2] for k in KEYS for a in dec[k]}
if len(shapes) != 1: raise ValueError(f'the planes are not one size: {sorted(shapes)}')
h, w = shapes.pop()
if h != view['plane_h']: raise ValueError(f"the planes are {h} rows, the view says {view['plane_h']}")
check_budget([sum(sizes[k].values()) for k in KEYS], w, h)
for k in KEYS: check_near_cover(dec[k][-1], view['horizon_row'])
bid = bake_id(frames_webp); name = f"{place['id']}-{bid}"; out = Path(out); out.mkdir(parents=True, exist_ok=True); dest = out / name
frames = []
for k in KEYS:
lo, hi = luma_range(dec[k])
frames.append(dict(key=k, sun=dict(az=suns[k]['az'], el=suns[k]['el']), hour_utc=suns[k]['hour_utc'],
planes={n: dict(file=f'{k}-{n}.webp', bytes=sizes[k][n], w=w, h=h) for n in PLANES}, bytes=sum(sizes[k].values()), luma=dict(min=lo, max=hi)))
manifest = dict(schema=1, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), frames=frames, attribution=ATTRIBUTION)
validate(manifest, SCHEMA['$defs']['manifest'])
tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
for k in KEYS:
for n in PLANES: (tmp / f'{k}-{n}.webp').write_bytes(frames_webp[k][n])
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'])
(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'])
@ -155,25 +147,50 @@ def write_bake(out, place, view, suns, frames_webp, default=None):
return dest
# ------------------------------------------------------------------------------------ the bake
def bake_place(pid, relight_keys=KEYS):
"""stage 0, sweep, set_view, bake, then relight_planes for every sun key: (place dict, view dict, suns, {key: {plane: float RGBA}}). Needs RIDGE_TILES / RIDGE_WORK."""
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."""
import ridge
assert ridge.WIN == PLANE_W and ridge.H > 0
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, A, Hh, _ = ridge.stage0(False); r = ridge.sweep(d, A, Hh); v = ridge.set_view(r['slots']); layers = ridge.bake(r['slots']); statics = ridge.statics()
suns = sun_set(p, p['date']); planes = {k: ridge.relight_planes(layers, suns[k]['az'], suns[k]['el'], *statics) for k in relight_keys}
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, tz_h=p['tz_h'], tz_name=p['tz_name'], date=p['date'])
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'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H)
return place, view, suns, planes
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'])
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))
def sheet(planes):
"""Contact sheet: the six frames over one flat sky, 2 columns x 3 rows (png bytes)."""
rows = []
for k in KEYS:
img = np.broadcast_to(np.array(SHEET_SKY), planes[k]['far'].shape[:2] + (3,)).copy()
for n in PLANES: a = planes[k][n]; img = img * (1 - a[..., 3:]) + a[..., :3] * a[..., 3:]
rows.append(img)
grid = np.concatenate([np.concatenate(rows[i:i + 2], 1) for i in range(0, 6, 2)], 0)
return bytes(imagecodecs.png_encode(u8(grid)))
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
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."""
wall = c['wall']; n_r, n_t = np.where(wall, 0.0, c['n_r']), np.where(wall, 0.0, c['n_t'])
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))))
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')
@ -181,9 +198,9 @@ def main(argv=None):
if a.write_schema: (HERE / 'ridge-bake.schema.json').write_text(json.dumps(SCHEMA, indent=1, ensure_ascii=False) + '\n'); return 0
if not (a.place and a.tiles and a.out): ap.error('place, --tiles and --out are required')
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)
place, view, suns, planes = bake_place(a.place)
if a.sheet: Path(a.sheet).write_bytes(sheet(planes))
dest = write_bake(a.out, place, view, suns, {k: {n: encode(planes[k][n]) for n in PLANES} for k in KEYS})
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
if __name__ == '__main__': sys.exit(main())

View file

@ -1,6 +1,5 @@
{
"_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); floor_agl_m = authored eye height above the notional valley floor used only for the floor-plane colour gradient; s_ref_deg = front slope that counts as steep for the painter; tz_h = standard-time offset of the local clock on the sun date.",
"date": "2026-09-23",
"_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).",
"presets": [
{
"id": "vienna",
@ -12,10 +11,11 @@
"ground_override_m": 183.3,
"az_deg": 214.0,
"rmax_km": 95,
"floor_agl_m": 30,
"s_ref_deg": 8,
"tz_h": 2,
"tz_name": "CEST",
"card_split_km": [
6,
40
],
"prefilter_m": 100,
"viewpoint_source": {
"status": "existing observer of the round-1 mockup (the scene camera used by the game), not photo-sourced; eye 30 m above ground as in round 1"
}
@ -32,10 +32,6 @@
7.65678
],
"rmax_km": 60,
"floor_agl_m": 992.3298828124998,
"s_ref_deg": 30,
"tz_h": 2,
"tz_name": "CEST",
"initial_guess_not_used": {
"lat": 45.9856,
"lon": 7.7452
@ -165,10 +161,6 @@
138.72731
],
"rmax_km": 60,
"floor_agl_m": 138.6306213378906,
"s_ref_deg": 20,
"tz_h": 9,
"tz_name": "JST",
"initial_guess_not_used": {
"lat": 35.4994,
"lon": 138.7686
@ -315,10 +307,6 @@
-119.53426
],
"rmax_km": 40,
"floor_agl_m": 5.5442382812500455,
"s_ref_deg": 30,
"tz_h": -7,
"tz_name": "PDT",
"initial_guess_not_used": {
"lat": 37.7305,
"lon": -119.5734
@ -476,10 +464,6 @@
86.86079
],
"rmax_km": 60,
"floor_agl_m": 829.8232421875,
"s_ref_deg": 30,
"tz_h": 5.75,
"tz_name": "NPT",
"initial_guess_not_used": {
"lat": 27.8369,
"lon": 86.7643
@ -554,10 +538,6 @@
12.29583
],
"rmax_km": 40,
"floor_agl_m": 735.6748046875,
"s_ref_deg": 30,
"tz_h": 2,
"tz_name": "CEST",
"initial_guess_not_used": {
"lat": 46.5833,
"lon": 12.2536

View file

@ -1,6 +1,6 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ridge-bake manifest v1 and index v1",
"title": "ridge-bake manifest v2 and index v1",
"$defs": {
"manifest": {
"type": "object",
@ -10,13 +10,19 @@
"bake_id",
"place",
"view",
"frames",
"curvature",
"encoding",
"camera",
"cards",
"w",
"h",
"bytes",
"attribution"
],
"additionalProperties": false,
"properties": {
"schema": {
"const": 1
"const": 2
},
"baker_version": {
"type": "integer"
@ -32,9 +38,7 @@
"lat",
"lon",
"altitude_km",
"tz_h",
"tz_name",
"date"
"eye_m"
],
"additionalProperties": false,
"properties": {
@ -53,14 +57,8 @@
"altitude_km": {
"type": "number"
},
"tz_h": {
"eye_m": {
"type": "number"
},
"tz_name": {
"type": "string"
},
"date": {
"type": "string"
}
}
},
@ -73,6 +71,7 @@
"plane_h",
"px_per_deg_h",
"px_per_deg_v",
"exaggeration",
"horizon_row",
"sky_row",
"near_row"
@ -98,6 +97,9 @@
"px_per_deg_v": {
"type": "number"
},
"exaggeration": {
"type": "number"
},
"horizon_row": {
"type": "number"
},
@ -109,157 +111,149 @@
}
}
},
"frames": {
"curvature": {
"type": "object",
"required": [
"r_earth_m",
"k_ref"
],
"additionalProperties": false,
"properties": {
"r_earth_m": {
"type": "number"
},
"k_ref": {
"type": "number"
}
}
},
"encoding": {
"type": "object",
"required": [
"log_d_min",
"log_d_max",
"normal"
],
"additionalProperties": false,
"properties": {
"log_d_min": {
"type": "number"
},
"log_d_max": {
"type": "number"
},
"normal": {
"const": "rt8"
}
}
},
"camera": {
"type": "object",
"required": [
"r_m",
"heading_max_deg"
],
"additionalProperties": false,
"properties": {
"r_m": {
"type": "number"
},
"heading_max_deg": {
"type": "number"
}
}
},
"cards": {
"type": "array",
"minItems": 6,
"minItems": 1,
"maxItems": 6,
"items": {
"type": "object",
"required": [
"key",
"sun",
"hour_utc",
"planes",
"bytes",
"luma"
"top",
"h",
"near_m",
"far_m",
"median_m",
"distance_m",
"scale",
"colour",
"geometry"
],
"additionalProperties": false,
"properties": {
"key": {
"enum": [
"dawn",
"morning",
"noon",
"golden",
"dusk",
"night"
]
},
"sun": {
"type": "object",
"required": [
"az",
"el"
],
"additionalProperties": false,
"properties": {
"az": {
"type": "number"
},
"el": {
"type": "number"
}
}
},
"hour_utc": {
"type": "number"
},
"planes": {
"type": "object",
"required": [
"far",
"mid",
"near"
],
"additionalProperties": false,
"properties": {
"far": {
"type": "object",
"required": [
"file",
"bytes",
"w",
"h"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
}
},
"mid": {
"type": "object",
"required": [
"file",
"bytes",
"w",
"h"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
}
},
"near": {
"type": "object",
"required": [
"file",
"bytes",
"w",
"h"
],
"additionalProperties": false,
"properties": {
"file": {
"type": "string"
},
"bytes": {
"type": "integer"
},
"w": {
"type": "integer"
},
"h": {
"type": "integer"
}
}
}
}
},
"bytes": {
"top": {
"type": "integer"
},
"luma": {
"h": {
"type": "integer"
},
"near_m": {
"type": [
"number",
"null"
]
},
"far_m": {
"type": [
"number",
"null"
]
},
"median_m": {
"type": "number"
},
"distance_m": {
"type": "number"
},
"scale": {
"type": "number"
},
"colour": {
"type": "object",
"required": [
"min",
"max"
"file",
"bytes"
],
"additionalProperties": false,
"properties": {
"min": {
"type": "number"
"file": {
"type": "string"
},
"max": {
"type": "number"
"bytes": {
"type": "integer"
}
},
"description": "min and max WCAG relative luminance of the three planes composited far, mid, near over a flat mid-grey sky, over pixels whose composite coverage 1 - prod(1 - alpha) is at least 0.5"
}
},
"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"
},
"bytes": {
"type": "integer"
},
"attribution": {
"type": "object",
"required": [

View file

@ -1,13 +1,13 @@
"""Round-2 baker: A's painter baked from D's sweep, driven by a place preset from places.json (ray sampling, the round-1 recommendation).
"""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, painter constants from places.json
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window 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
sweep() : D's per-column scan -> spans (with own height/run = per-peak slope) -> wrapped chains -> 7-knot layer cap
set_view(slots) : authored Y mapping: angle -> row, ground plane at the bottom (see set_view)
bake(slots) : sun-independent per-layer arrays
relight(layers, az, el) : shading + atmosphere + floor + sky
Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page)."""
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
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 pathlib import Path
@ -26,25 +26,17 @@ HPX_DEG = W / 360.0
H = 600 # frame rows
COLW = math.radians(360.0 / W)
R_EARTH, KREF = 6371000.0, 0.13
PROM_M, NEAR_CAP, MINW, LINK_D, LINK_A, LOOK = 25.0, 4000.0, 50, 0.45, 0.25, 4
FOREGROUND_M = 5000.0 # a chain nearer than this that is narrower than MINW is kept only where no kept foreground chain covers its columns (the nearest layer must cover every column; a lone stub beside a long near ridge is an arch)
FADE_AT = 0.6 # a layer's body is opaque down to this share of its foot length, then smoothsteps to nothing at the foot
TAPER = 8 # minimum columns over which a chain end dies into its valley (D's 8; round 1 used a fixed 20 AND borrowed the far end's value: the spike)
TAPER_K, TAPER_MAX = 30.0, 72 # a taller end falls over more columns: ceil(30 columns per degree of drop), 8..72: at the authored 1.5-4x exaggeration an end leaves the ridge at about 45 deg or less, not a wall
def taper_len(drop_deg): return np.clip(np.ceil(np.asarray(drop_deg) * TAPER_K), TAPER, TAPER_MAX)
KNOTS = np.array([80, 48, 28, 16, 9, 5, 2.5]) * 1000.0
_r5 = ('#a9b9d3', '#8e9fc2', '#6f86a6', '#556f7d', '#3f5546')
def hx(h): return np.array([int(h[i:i+2], 16) for i in (1, 3, 5)]) / 255.0
def mix(a, b, t): return a + (b - a) * np.asarray(t)[..., None]
RAMP = [mix(hx(_r5[min(int(t), 3)]), hx(_r5[min(int(t), 3) + 1]), t - min(int(t), 3)) for t in np.linspace(0, 4, len(KNOTS))]
GROUND = hx('#4a5f45'); CONTOUR_NICE = (30.0, 50.0, 100.0, 150.0, 200.0, 300.0, 500.0, 1000.0); CONTOUR_MIN_PX = 9.0 # iso-height interval is the smallest nice value that keeps lines >= 9 px apart (p10 of the layer)
ROT = 0 # test hook: frame rotated by ROT columns; noise/azimuth stay tied to the absolute column
P = {} # configured preset
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4; Hc = H
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'):
d = json.load(open(path)); p = next(x for x in d['presets'] if x['id'] == pid); p = dict(p); p['date'] = d['date']; return p
"""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."""
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")
return p
# ====================================================================== configuration, DEM
def tiles_for(p):
@ -125,6 +117,11 @@ def schedule(detail):
d.append(d[-1] + min(250.0, max(10.0 if detail else 40.0, 0.004 * d[-1])))
return np.array(d)
def elev(h, d, curvature=True):
"""Elevation angle (degrees) of height h (m) at distance d (m) from the eye: Earth curvature with refraction. The one formula of march and prefilter."""
drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0
return np.degrees(np.arctan2(h - P['eye_m'] - drop, d))
def march(detail=False, curvature=True):
m, lt, ll = mosaic(P); az = np.radians((np.arange(W) + 0.5) / W * 360.0); d = schedule(detail); cosl = math.cos(math.radians(P['lat']))
A = np.zeros((len(d), W), np.float32); Hh = np.zeros_like(A); sa, ca = np.sin(az), np.cos(az)
@ -132,8 +129,7 @@ def march(detail=False, curvature=True):
lat = P['lat'] + dk * ca / 111320.0; lon = P['lon'] + dk * sa / (111320.0 * cosl)
h = bil(m, lt, ll, lat, lon)
if detail and dk < DETAIL['fade_to_m']: h = h + detail_height(dk * sa, dk * ca, dk)
drop = dk * dk / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0
A[k] = np.degrees(np.arctan2(h - P['eye_m'] - drop, dk)); Hh[k] = h
A[k] = elev(h, dk, curvature); Hh[k] = h
return d, A, Hh
def rays_key(detail):
@ -153,400 +149,119 @@ def blurw(a, s):
a = np.asarray(a, np.float64); xp = np.concatenate([a[..., -r:], a, a[..., :r]], axis=-1); o = np.zeros_like(a)
for i, kv in enumerate(k): o += kv * xp[..., i:i + a.shape[-1]]
return o
def gradw(a): return (np.roll(a, -1) - np.roll(a, 1)) / 2.0
def _smooth(f): return f * f * (3 - 2 * f)
def pn2(cell, seed):
rng = np.random.default_rng(seed); n = max(int(round(W / cell)), 2); gh = int(H / cell) + 3
g = rng.random((gh, n)).astype(np.float32)
xs = ((np.arange(W) + ROT) % W) * (n / W); x0 = xs.astype(int); fx = _smooth(xs - x0).astype(np.float32); x1 = (x0 + 1) % n
ys = np.arange(H) / cell; y0 = ys.astype(int); fy = _smooth(ys - y0).astype(np.float32)
tp = g[y0][:, x0] * (1 - fx) + g[y0][:, x1] * fx; bt = g[y0 + 1][:, x0] * (1 - fx) + g[y0 + 1][:, x1] * fx
return tp * (1 - fy)[:, None] + bt * fy[:, None]
def pn1(cell, seed): return pn2(cell, seed)[0].astype(np.float64)
def abscol(): return (np.arange(W) + ROT) % W
# ====================================================================== sweep (D), wrapped
NH = 24 # samples of the face history kept per peak (valley -> crest, uniform in elevation angle)
def strip_history(a, dl, hh, k0, k1):
"""The marcher's record of one peak strip: the ray samples from the last local minimum (k0) to the peak (k1), reduced to what the eye sees (a sample hides
behind any earlier, higher one: running maximum of the angle) and resampled at NH uniform steps of elevation angle. Returns (distance[NH], height[NH]), index 0 = valley, NH-1 = crest."""
seg = np.asarray(a[k0:k1 + 1]); runmax = np.maximum.accumulate(seg); vis = np.concatenate([[True], runmax[1:] > runmax[:-1]])
va = runmax[vis]; vd = np.asarray(dl[k0:k1 + 1])[vis]; vh = np.asarray(hh[k0:k1 + 1])[vis]
if len(va) < 2 or va[-1] <= va[0]: return np.full(NH, vd[-1]), np.full(NH, vh[-1])
t = np.linspace(va[0], va[-1], NH); return np.interp(t, va, vd), np.interp(t, va, vh)
def extract(d, ang, hgt, prom=PROM_M):
"""Per column: (peak_ang, valley_ang, peak_d, peak_h, valley_h, valley_d) followed by the face history (NH distances, NH heights) of the strip valley -> peak.
A peak commits when the ray has fallen hy[k] below it and it stands `prom` METRES above the lowest ground the strip has seen (the lowest height, not the height of the lowest-ANGLE sample: that one is often near and high)."""
K, Wc = ang.shape; hy = np.degrees(prom / d).tolist(); dl = d.tolist(); cols = []
for x in range(Wc):
a = ang[:, x].tolist(); hh = hgt[:, x].tolist(); out = []
def span(pk, lo, pd, ph, vh, vd, k0, k1): out.append((pk, lo, pd, ph, vh, vd) + tuple(np.concatenate(strip_history(a, dl, hh, k0, k1))))
runmax = -90.0; mn = a[0]; mnh = hh[0]; mnd = dl[0]; mnk = 0; cand = a[0]; ch = hh[0]; cd = dl[0]; ck = 0; lowh = hh[0]; capped = False # NEAR_CAP is tried once, at the first sample past 4 km
for k in range(1, K):
v = a[k]; dk = dl[k]; hk = hh[k]; lowh = min(lowh, hk)
if dk >= NEAR_CAP and not capped and not out and runmax < -80:
capped = True; j = max(range(k), key=a.__getitem__)
if hh[j] - lowh >= prom: span(a[j], mn, dl[j], hh[j], mnh, mnd, min(mnk, j), j); runmax = a[j]; mn = cand = v; mnh = ch = hk; mnd = cd = dk; mnk = ck = k; lowh = hk
if v < mn: mn = cand = v; mnh = ch = hk; mnd = cd = dk; mnk = ck = k
elif v > cand: cand = v; ch = hk; cd = dk; ck = k
if cand - v >= hy[k] and ch - lowh >= prom:
if cand > runmax: span(cand, mn, cd, ch, mnh, mnd, mnk, ck); runmax = cand
mn = cand = v; mnh = ch = hk; mnd = cd = dk; mnk = ck = k; lowh = hk
if ch - lowh >= prom and cand > runmax: span(cand, mn, cd, ch, mnh, mnd, mnk, ck)
cols.append(out)
return cols
def chains(cols):
Wc = len(cols); parent = []; ids = []
for sp in cols: ids.append(list(range(len(parent), len(parent) + len(sp)))); parent.extend(range(len(parent), len(parent) + len(sp)))
def find(i):
while parent[i] != i: parent[i] = parent[parent[i]]; i = parent[i]
return i
for x, sp in enumerate(cols):
for i, s in zip(ids[x], sp):
p, dd = s[0], s[2]; best = None
for back in range(1, LOOK + 1):
xb = (x - back) % Wc
for j, s2 in zip(ids[xb], cols[xb]):
ld = abs(math.log(dd / s2[2]))
if ld < LINK_D and abs(p - s2[0]) < LINK_A * (1 + 0.5 * (back - 1)):
sc = ld / LINK_D + abs(p - s2[0]) / LINK_A + 0.3 * back
if best is None or sc < best[0]: best = (sc, j)
if best: parent[find(i)] = find(best[1])
out = {}
for x, sp in enumerate(cols):
for i, s in zip(ids[x], sp): out.setdefault(find(i), []).append((x,) + tuple(s))
return list(out.values())
# ====================================================================== prefilter: the march is a heightfield of roofs and hills; the cards want the hills
def prefilter(d, h, sigma_m):
"""Gaussian low-pass of the ray heights h (K, W): along each ray with sigma sigma_m metres (weighted by sample spacing, the schedule is not uniform), then across rays at equal distance with
sigma = sigma_m / (d * COLW) columns (periodic, exact in the Fourier domain). Angles are recomputed from the filtered heights with elev. Returns (angles, heights); sigma_m 0 leaves the heights as they are."""
d = np.asarray(d, np.float64); h = np.asarray(h, np.float64)
if sigma_m > 0:
f = np.fft.rfftfreq(h.shape[1]); sc = sigma_m / (d * COLW)
h = np.fft.irfft(np.fft.rfft(h, axis=1) * np.exp(-2 * (np.pi * f[None, :] * sc[:, None]) ** 2), n=h.shape[1], axis=1)
dd = np.gradient(d); out = np.empty_like(h)
for k in range(len(d)):
r = int(min(3 * sigma_m / dd[k] + 1, 60)); lo, hi = max(0, k - r), min(len(d), k + r + 1)
w = np.exp(-0.5 * ((d[lo:hi] - d[k]) / sigma_m) ** 2) * dd[lo:hi]; out[k] = (w[:, None] * h[lo:hi]).sum(0) / w.sum()
h = out
return elev(h, d[:, None]), h
def chain_layer(c):
"""Chain -> dense per-column arrays (deg / m). The chain is unrolled at its largest circular gap into an arc [0, x1] of local columns; every
column outside the arc takes the value of the NEAREST arc end (start end or finish end) and then dies toward that end's valley over TAPER columns."""
a = np.array(c); xs = a[:, 0].astype(int); u = np.unique(xs)
gaps = np.diff(np.concatenate([u, [u[0] + W]])); start = int(u[(gaps.argmax() + 1) % len(u)]); xl = (xs - start) % W
Pk, L, D, PH, VH, VD = (a[:, i] for i in range(1, 7)); HD = a[:, 7:7 + NH]; HH = a[:, 7 + NH:7 + 2 * NH]
run = np.maximum(np.abs(D - VD), 300.0); slope = np.degrees(np.arctan2(np.maximum(PH - VH, 0), run))
x1 = int(xl.max()); ii = np.arange(0, x1 + 1); res = {}; x = np.arange(W)
near_end = np.where(x - x1 <= W - x, x1, 0) # outside the arc: which end is nearer going around the ring
dist = np.where(x <= x1, 0, np.minimum(x - x1, W - x)).astype(float)
def dense(v):
full = np.full(W, np.nan); full[xl] = v; ok = ~np.isnan(full[ii]); full[ii] = np.interp(ii, ii[ok], full[ii][ok]); return np.where(x <= x1, full, full[near_end])
for k, v in dict(top=Pk, lo=L, ph=PH, vh=VH, slope=slope, pd=D, vd=VD).items(): res[k] = dense(v)
res['hd'] = np.stack([dense(HD[:, j]) for j in range(NH)]); res['hh'] = np.stack([dense(HH[:, j]) for j in range(NH)]) # the face history, one (NH, W) array each: column x carries the history of the peak that owns it
drop = res['top'] - np.minimum(res['lo'], res['top'] - 0.4); Tn = taper_len(drop) # end drop in degrees -> taper length at this column
t = np.clip(dist / Tn, 0, 1); t = t * t * (3 - 2 * t)
res['top'] = res['top'] - drop * t
res['wt'] = 1 - np.clip(dist / Tn, 0, 1)
for k in ('top', 'lo', 'ph', 'vh', 'slope', 'wt', 'pd', 'vd', 'hd', 'hh'): res[k] = np.roll(res[k], start, axis=-1)
res['dist'] = float(np.median(D)); res['n'] = len(c); res['x0'] = start; res['x1'] = (start + x1) % W; res['span'] = x1 + 1
res['rise_ang'] = float(np.median(Pk - L)); res['rise_h'] = float(np.median(PH - VH)); res['slope_med'] = float(np.median(slope))
return res
def col_gap(present):
"""Circular distance in columns from each column to the nearest present column (0 where present)."""
x = np.arange(3 * W); p = np.tile(present, 3); last = np.maximum.accumulate(np.where(p, x, -10 * W)); nxt = np.minimum.accumulate(np.where(p, x, 10 * W)[::-1])[::-1]
return np.minimum(x - last, nxt - x)[W:2 * W].astype(float)
def to_slots(layers):
slots = {}
for L in layers: slots.setdefault(int(np.argmin(np.abs(np.log(KNOTS) - math.log(L['dist'])))), []).append(L)
out = []
for s in sorted(slots):
g = slots[s]; top = np.stack([np.where(l['wt'] > 0, l['top'], -1e3 - col_gap(l['wt'] > 0)) for l in g]); j = top.argmax(0) # only chains that are present in a column compete; where none is, the chain whose extent is NEAREST stands (a geometric rule: the list order of chains depends on where column 0 is, and absent-column values feed the blurs at every chain end)
S = dict(slot=s, dist=float(KNOTS[s]), chains=len(g), dists=[l['dist'] for l in g])
for k in ('top', 'lo', 'ph', 'vh', 'slope', 'wt', 'pd', 'vd'): S[k] = np.take_along_axis(np.stack([l[k] for l in g]), j[None], 0)[0]
for k in ('hd', 'hh'): S[k] = np.take_along_axis(np.stack([l[k] for l in g]), j[None, None], 0)[0]
out.append(S)
return out
def sweep(d, ang, hgt, prom=PROM_M):
t0 = time.time(); cols = extract(d, ang, hgt, prom); t1 = time.time()
ch = chains(cols); near = lambda c: np.median([t[3] for t in c]) < FOREGROUND_M; keep = [c for c in ch if len(c) >= MINW]
def arc(c):
u = np.unique([t[0] for t in c]); g = np.diff(np.concatenate([u, [u[0] + W]])); i = g.argmax(); st = u[(i + 1) % len(u)]; return (st + np.arange((u[i] - st) % W + 1)) % W # the columns a chain spans, unrolled at its largest gap
cov = np.zeros(W, bool)
for c in keep:
if near(c): cov[(arc(c)[:, None] + np.arange(-MINW // 4, MINW // 4 + 1)[None, :]).ravel() % W] = True # dilated by MINW/4 columns: a stub that occludes a near ridge for a few columns sits inside it
for c in sorted((c for c in ch if len(c) < MINW and near(c)), key=lambda c: -len(c)): # widest first: a stub is judged against the stubs already kept
xs = arc(c)
if not cov[xs].any(): keep.append(c); cov[xs] = True
lay = [chain_layer(c) for c in keep]; slots = to_slots(lay); t2 = time.time()
return dict(cols=cols, nchains=len(ch), keep=lay, slots=slots, raw=sum(len(c) for c in cols), t_extract=t1 - t0, t_chain=t2 - t1)
def normals(d, h):
"""Surface normal at every ray sample (n_r, n_t, n_up), each (K, W): n_r along the ray, n_t across it (towards increasing azimuth), n_up vertical. The slopes are the ray's own dh/dd and the difference of the
neighbouring columns at the SAME sample (equal distance, never equal row) over 2 d COLW, both times the authored vertical exaggeration PXDEG_V / HPX_DEG, so a face reads as steep as the view draws it."""
d = np.asarray(d, np.float64); h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG
sr = E * np.gradient(h, d, axis=0); st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1)) / (2 * d[:, None] * COLW); nz = 1.0 / np.sqrt(1 + sr * sr + st * st)
return -sr * nz, -st * nz, nz
# ====================================================================== the authored Y mapping
def set_view(slots, 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).
Two anchors: the highest ridge top in the window sits at `sky_row` (4%) of the frame height, the LOWEST crest of the nearest layer in the window sits at `near_row` (66%);
everything below is that layer's body, its foot, and the ground-plane band. PXDEG_V = (near_row - sky_row) * 600 / (highest top - lowest near crest), clamped to
[17.78, 178] px/deg = vertical exaggeration 1x..10x. TOP_DEG = highest top + sky_row*600/PXDEG_V; BOTTOM_DEG = TOP_DEG - 600/PXDEG_V; horizon (angle 0) at row TOP_DEG*PXDEG_V."""
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."""
global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG
cols = (P['win0'] + np.arange(WIN)) % W; sky = max(float(S['top'][cols][S['wt'][cols] > 0].max()) for S in slots if (S['wt'][cols] > 0).any())
near = slots[-1]; act = near['wt'][cols] > 0; c_low = float(blurw(near['top'], 3.0)[cols][act].min()) if act.any() else sky - 2.0
ppd = float(np.clip((near_row - sky_row) * H / max(sky - c_low, 0.05), HPX_DEG, 10 * HPX_DEG))
w = win(np.asarray(skyline)[None, :])[0]; sky = float(w.max()); low = float(w.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, near_crest_low_deg=c_low,
sky_row=sky_row, near_row=near_row)
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)
# ====================================================================== bake (sun-independent), per layer
def azrad(): return (abscol() + 0.5) / W * 2 * math.pi
# ====================================================================== coverage and seams
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_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)
def face_field(hd, hh, ang, lo, pd, ph, vd, vh):
"""Per-pixel face from the marcher's history (hd, hh: NH distances / heights per column, valley -> crest). A pixel at elevation `rowang` of column x sits at fraction
f = (rowang - lo) / (ang - lo) of the strip; its distance and height are the history interpolated at f. Front slope s = dh/dd along the ray comes from the history over +-2 nodes
(the strip's mean slope where the window has no run); the lateral tilt is the height change between the neighbouring columns at the SAME pixel row, corrected for the radial
step (c - a*s) / (tangential length). n ~ (-s r - la t, 1). Returns Z, D, s, la, f as (H, W) arrays."""
f = np.clip((rowang[:, None] - lo[None, :]) / np.maximum(ang - lo, 1e-3)[None, :], 0, 1); pos = f * (NH - 1); i0 = np.minimum(pos.astype(int), NH - 2); t = pos - i0; xs = np.arange(W)[None, :]
lerp = lambda A: A[i0, xs] * (1 - t) + A[i0 + 1, xs] * t
lo_i, hi_i = np.clip(np.arange(NH) - 2, 0, NH - 1), np.clip(np.arange(NH) + 2, 0, NH - 1)
dd = hd[hi_i] - hd[lo_i]; mean_s = ((ph - vh) / np.maximum(np.abs(pd - vd), 300.0))[None, :]
sn = np.where(dd >= 20.0, (hh[hi_i] - hh[lo_i]) / np.maximum(dd, 20.0), mean_s)
Z, Dp, sl = lerp(hh), lerp(hd), lerp(sn)
a_ = np.roll(Dp, -1, axis=1) - np.roll(Dp, 1, axis=1); c_ = np.roll(Z, -1, axis=1) - np.roll(Z, 1, axis=1)
b_ = np.maximum(2 * COLW * Dp, 1.0); la = np.where(np.abs(a_) > 3 * b_, 0.0, np.clip((c_ - a_ * sl) / b_, -1.5, 1.5)) # neighbours at very different distances are an occlusion edge, not a surface: no tilt
return Z.astype(np.float32), Dp, blurw(sl, 2.0).astype(np.float32), blurw(la, 2.0).astype(np.float32), f
def log_edges(d, nb=COV_BINS): L = np.log(np.asarray(d, np.float64)); return np.linspace(L[0], L[-1] + 1e-9, nb + 1)
def bake_layer(S, rank, far, near=False):
b = S['slot']; base = RAMP[b]; reg = int(round((rank - 2) * 1.5)); R_ = lambda v: np.roll(v, reg, axis=-1); px = 1.0 / PXDEG_V
s_ref = P.get('s_ref_deg', 8.0)
ang = blurw(S['top'], 2.5) + (pn1(38, 100 + b) - 0.5) * 6 * px + (pn1(7, 200 + b) - 0.5) * 2 * px; ang = R_(ang) # edge wobble authored in pixels
lo = R_(blurw(S['lo'], 2.5)); ph = R_(blurw(S['ph'], 2.0)); vh = R_(blurw(S['vh'], 2.0))
sn = np.clip(R_(blurw(S['slope'], 3.0)) / s_ref, 0, 1); wt = R_(S['wt'])
hd = R_(blurw(S['hd'], 2.0)); hhist = R_(blurw(S['hh'], 2.0)); pd_ = R_(blurw(S['pd'], 2.0)); vd_ = R_(blurw(S['vd'], 2.0))
top = ang[None, :] - rowang[:, None]; toppx = (top * PXDEG_V).astype(np.float32)
m = np.clip(toppx / 1.6 + 0.5, 0, 1) * np.clip(blurw((wt > 0).astype(float), 1.0) * 1.5, 0, 1)[None, :] # a layer is drawn only where a chain exists (or tapers)
rise_px = np.clip((ang - blurw(lo, 12.0)) * PXDEG_V, 1, None) # foot length from a smoothed valley: no per-column curtains
foot = np.clip(0.85 * rise_px, 28 * np.clip(wt, 0, 1), 210).clip(1) # a tapering end carries no 28 px curtain: the body shrinks with the chain's weight, so a chain end leaves no stub
if near: foot = np.maximum(foot, np.clip(ang * PXDEG_V, 0, None) / FADE_AT) # the nearest layer is the ground in front of the eye: its body stays opaque down to the horizon, whatever the strip's own valley says; it dissolves only below that (above the horizon a dissolved body shows the sky under a crest, and the valley angle jumps where the winning chain changes, so the sky showed as a wedge with a hard edge)
depthpx = np.clip(toppx / foot[None], 0, 1)
fade = np.clip((depthpx - FADE_AT) / (1 - FADE_AT), 0, 1); fade = fade * fade * (3 - 2 * fade); alpha = (m * (1 - fade)).astype(np.float32) # the body dissolves at its foot: what is behind (other layers, floor, sky) shows, so a column boundary leaves no wall down the frame
w = (depthpx ** 0.8 * 0.92).astype(np.float32) # weight of the foot colour (floor/haze mix, decided at relight)
face = np.broadcast_to((base * 1.12).astype(np.float32), (H, W, 3)).copy()
Z, Dp, sl, la, f = face_field(hd, hhist, ang, lo, pd_, ph, vd_, vh)
snp = np.clip(np.degrees(np.arctan(sl)) / s_ref, 0, 1) # per-pixel face steepness from the history (the column scalar `sn` stays for stroke weights only)
face *= (1.07 - 0.22 * snp)[..., None]
mot = 0.55 * pn2(22, 300 + b) + 0.45 * pn2(5, 400 + b)
face *= (0.90 + 0.18 * mot[..., None]) * (0.96 + 0.08 * pn2(1, 500 + b)[..., None])
echo = np.clip(((ang - 24 * px * (1 + rank * .3))[None, :] - rowang[:, None]) * PXDEG_V / 1.6 + .5, 0, 1)
face *= (1 - 0.13 * echo[..., None] * (1 - depthpx[..., None] * .5))
ink = base * 0.42 + np.array([0.02, 0.03, 0.08])
ew = (0.7 + 1.8 * snp) * (1 - 0.35 * far)
edge = np.clip(1 - np.abs(toppx - 0.6 - ew * 0.5) / ew, 0, 1) * (toppx > -0.5)
ea = 0.55 * (1 - 0.45 * far) * edge * (0.4 + 0.6 * snp)
dzdpx = np.maximum(np.abs(np.roll(Z, -1, axis=0) - np.roll(Z, 1, axis=0)) / 2.0, 1e-3); dzdpx[0] = dzdpx[1]; dzdpx[-1] = dzdpx[-2] # metres of true height per pixel row, per pixel
faceok = (f > 0.02) & (f < 0.98) & (wt[None, :] > 0.5)
cm = next((c for c in CONTOUR_NICE if c >= CONTOUR_MIN_PX * float(np.percentile(dzdpx[faceok], 75) if faceok.any() else 3.0)), CONTOUR_NICE[-1]) # metres per contour line: lines >= 9 px apart over three quarters of this layer's face
p_ = (Z / cm) % 1.0; dpx = (np.minimum(p_, 1 - p_) * cm / dzdpx).astype(np.float32)
face_mask = ((top > 0.003) & (rowang[:, None] > lo[None, :])).astype(np.float32)
ca = (0.95 * (1 - 0.45 * far) * (1 - depthpx) ** 2.0 * wt[None, :] * (0.6 + 0.4 * snp) * face_mask).astype(np.float32)
hatch = np.zeros((H, W), np.float32)
if far < 0.8:
rng = np.random.default_rng(700 + b); xs = np.cumsum(rng.integers(2, 7, W // 2)); xs = xs[xs < W]
up = gradw(ang) * PXDEG_V
for i, xa in enumerate(xs):
x = (xa - ROT) % W; u1, u2 = rng.random(2)
if u1 > 0.30 + 0.70 * sn[x] or wt[x] < 0.5: continue
Lpx = (8 + 50 * sn[x] ** 0.7) * (0.55 + 0.7 * u2) * (1 - 0.5 * far)
y0 = (rowang[0] - ang[x]) * PXDEG_V; yy = np.arange(H); t = (yy - y0 - 2) / max(Lpx, 1)
ok = (t >= 0) & (t < 1); xx = (x + np.round(-np.clip(up[x] * 0.25, -0.6, 0.6) * (yy - y0)).astype(int)) % W
hatch[yy[ok], xx[ok]] = np.maximum(hatch[yy[ok], xx[ok]], (1 - t[ok]) ** 1.5)
ha = np.clip(ea + hatch * 0.50 * (1 - 0.4 * far), 0, 1).astype(np.float32)
rb = (np.clip(1 - toppx / 7.0, 0, 1) * (toppx > -0.5)).astype(np.float32)
az = azrad(); dd = np.stack([S['vd'], 0.5 * (S['vd'] + S['pd']), S['pd']]); hh = np.stack([S['vh'], 0.5 * (S['vh'] + S['ph']), S['ph']]) + 3.0 # face samples: valley, middle, crest
spts = dict(lat=np.roll(P['lat'] + dd * np.cos(az) / 111320.0, reg, axis=1), lon=np.roll(P['lon'] + dd * np.sin(az) / (111320.0 * math.cos(math.radians(P['lat']))), reg, axis=1), h=np.roll(hh, reg, axis=1))
return dict(m=m.astype(np.float32), a=alpha, face=face, w=w, dpx=dpx, ca=ca, ha=ha, rb=rb, mot=mot.astype(np.float32), sl=sl, la=la, ink=ink, far=far, dist=S['dist'], rank=rank, ang=ang, lo=lo, spts=spts)
def opaque(a):
"""Coverage 0..1 of every frame row by the opaque view of angles a (K, n): the share of the row's angular span under the column skyline."""
p = 1.0 / PXDEG_V; lo = rowang - 0.5 * p; return np.clip((np.asarray(a, np.float64).max(0)[None, :] - lo[:, None]) / p, 0, 1)
def bake(slots):
return [bake_layer(S, rank, float(np.clip((math.log(S['dist']) - math.log(2000)) / (math.log(70000) - math.log(2000)), 0, 1)), near=rank == len(slots) - 1) for rank, S in enumerate(slots)]
def coverage(d, a, nb=COV_BINS):
"""(nb, n): rows of the opaque view first revealed by the samples of each log-distance bin, per column. The first sample reveals every row from the frame bottom up to its angle, so the rows below it (nearer than it) count in bin 0. Needs set_view."""
a = np.asarray(a, np.float64); edges = log_edges(d, nb); kb = np.clip(np.searchsorted(edges, np.log(d), 'right') - 1, 0, nb - 1)
runmax = np.maximum.accumulate(a, axis=0); prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])
C = np.zeros((nb, a.shape[1])); np.add.at(C, kb, np.clip(np.minimum(a, TOP_DEG) - np.maximum(prev, BOTTOM_DEG), 0, None) * PXDEG_V)
return C
# ====================================================================== cast shadows (sun-dependent): DEM march toward the sun from each layer's face samples
SH_STEPS = 40.0 * 1.1 ** np.arange(0, 66) # 40 m .. 20 km, geometric
def cast_shadows(layers, az_s, el_s):
"""Per layer a (3, W) array in [0,1]: how much of the sun is blocked by the real DEM at that layer's valley / middle / crest sample. One vectorised march for all
layers. Soft: the blocked fraction is the terrain excess over the sun ray, over a penumbra of 6 m + 3% of the distance travelled. Sun at or below 0.3 deg: no direct light, no shadow."""
if el_s <= 0.3: return [np.zeros((3, W)) for _ in layers]
m, lt, ll = mosaic(P); lat = np.concatenate([Ly['spts']['lat'].ravel() for Ly in layers]); lon = np.concatenate([Ly['spts']['lon'].ravel() for Ly in layers]); h = np.concatenate([Ly['spts']['h'].ravel() for Ly in layers])
t = math.tan(math.radians(el_s)); cosl = math.cos(math.radians(P['lat'])); ca, sa = math.cos(math.radians(az_s)), math.sin(math.radians(az_s)); sh = np.zeros_like(h)
for s in SH_STEPS:
terr = bil(m, lt, ll, lat + s * ca / 111320.0, lon + s * sa / (111320.0 * cosl)) - s * s / (2 * R_EARTH)
sh = np.maximum(sh, np.clip((terr - (h + s * t)) / (6.0 + 0.03 * s), 0, 1))
return [a.reshape(3, W) for a in np.split(sh, len(layers))]
def _dt(f, u):
"""out[i] = min_k f[k] + |u[i] - u[k]| along axis 0, u increasing: two cumulative-minimum passes (Felzenszwalb & Huttenlocher's L1 distance transform)."""
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)
# ====================================================================== relight (sun-dependent)
TAU_Z = np.array([0.09, 0.14, 0.30]); BETA_R = np.array([0.0058, 0.0135, 0.0331]); BETA_M = 0.023; ATM = 0.15
ATM_FLOOR = 1.2 # authored: valley haze over the ground plane is heavier than the layer extinction ATM, so the floor thins into haze gradually
G_MIE, W_MIE = 0.7, 0.10; REF = dict(az=180.0, el=62.0); REF_AMB = np.array([0.62, 0.74, 1.0])
def airmass(el): e = max(el, 0.3); return 1.0 / (math.sin(math.radians(e)) + 0.50572 * (e + 6.07995) ** -1.6364)
def sun_colour(el): return np.exp(-TAU_Z * airmass(el))
def phase(c):
pr = 3.0 / (16 * math.pi) * (1 + c * c); pm = (1 - G_MIE ** 2) / (4 * math.pi * (1 + G_MIE ** 2 - 2 * G_MIE * c) ** 1.5)
return (1 - W_MIE) * pr + W_MIE * pm
def sun_vec(az, el): a, e = math.radians(az), math.radians(el); return np.array([math.sin(a) * math.cos(e), math.cos(a) * math.cos(e), math.sin(e)])
def EX_REF_NORM(Ec, I, amb_k): return float((0.45 * REF_AMB * amb_k + 0.75 * Ec * I * 0.7).mean()) / 0.87
def sun_state(az, el):
Ec = sun_colour(el) / sun_colour(REF['el']); I = (max(math.sin(math.radians(el)), 0.0) / math.sin(math.radians(REF['el']))) ** 0.5
tw = 0.30 * float(np.clip((el + 6) / 8, 0, 1)) ** 2; amb_k = 0.12 + 0.88 * float(np.clip((el + 3) / 45, 0, 1)) ** 0.7
ex = 0.45 + 0.55 * float(np.clip((el + 4) / 18, 0, 1)) ** 0.6
return dict(az=az, el=el, L=sun_vec(az, el), sun=Ec * I, sky_sun=Ec * (I + tw), amb=REF_AMB * amb_k, amb_k=amb_k, ex=ex / EX_REF_NORM(Ec, I, amb_k), ex_t=ex)
def _g0():
st = sun_state(REF['az'], REF['el']); d = 0.7; g = (0.45 * st['amb'] + 0.75 * st['sun'] * d) * (np.array([0.90, 0.92, 1.04]) + (np.array([1.03, 1.0, 0.95]) - np.array([0.90, 0.92, 1.04])) * d)
return g / g.mean()
G0 = _g0()
def col_scatter(st):
az = azrad(); c = math.cos(math.radians(st['el'])) * np.cos(az - math.radians(st['az']))
pr = np.array([phase(float(x)) for x in c]); g = np.clip((pr / phase(0.0)) ** 0.35, 0.5, 2.4)
rs = sun_state(REF['az'], REF['el']); ref = 0.8 * rs['sky_sun'] + 0.35 * rs['amb']; ref = ref / ref.mean()
col = 0.8 * st['sky_sun'] + 0.35 * st['amb']; col = col / col.mean()
return c, g[:, None] * (col / ref)[None, :]
def hue_gain(st, d):
lit_tint = np.array([1.03, 1.0, 0.95]); shd_tint = np.array([0.90, 0.92, 1.04])
tint = shd_tint + (lit_tint - shd_tint) * d
return (0.45 * st['amb'] + 0.75 * st['sun'] * d) * tint / G0 * st['ex']
def floor_img(st, hazec, fmot):
"""Ground-plane band: below the horizon a flat floor `floor_agl_m` below the eye; plane distance dg = h / tan(depression); colour = ground albedo lit by an
up-facing normal, thinned into haze by the same Beer-Lambert extinction as the layers. Above the horizon the same array is the haze (sky covers it)."""
a = rowang; dg = P['floor_agl_m'] / np.tan(np.radians(np.clip(-a, 0.002, 89.0)))
T = np.exp(-(BETA_R + BETA_M)[None, :] * (dg / 1000.0)[:, None] * ATM_FLOOR); T[a >= 0] = 0.0
ground = (GROUND * hue_gain(st, float(np.clip((math.sin(math.radians(st['el'])) + 0.2) / 1.2, 0, 1))))
return ground[None, None, :] * fmot[..., None] * T[:, None, :] + hazec[None, :, :] * (1 - T)[:, None, :]
def ndl_field(Ly, L):
"""n . L per pixel from the baked face: n ~ (-sl r - la t, 1), r / t the column's radial / tangential directions. Returns (ndl, |n|-normaliser)."""
az = azrad(); sa, ca_ = np.sin(az), np.cos(az); sl, la = Ly['sl'], Ly['la']
Lr = (L[0] * sa + L[1] * ca_)[None, :]; Lt = (L[0] * ca_ - L[1] * sa)[None, :]; nrm = np.sqrt(1 + sl * sl + la * la)
return (L[2] - sl * Lr - la * Lt) / nrm, nrm
RELIEF_OFF_DEG, RELIEF_EL = 45.0, 32.0 # authored relief light: RELIEF_OFF_DEG off the view axis, RELIEF_EL up
def win_centre_az(): return (P['win0'] + WIN / 2) / W * 360.0
def relief_vec(sun_az):
"""The authored relief light direction (toward the light). The real sun lights a face the viewer looks at only when it is off to one side; with the sun behind the viewer every face is
head-on and the mountain goes flat. Shading n.L (ndl_field, rim, spec) therefore uses this fixed direction: azimuth = the view centre az +/- RELIEF_OFF_DEG, on the left/right side of the view axis
that the real sun is on (so the two agree where they can), RELIEF_EL up. Sun colour/strength, haze, colour temperature and cast shadows keep the real sun:
the relief only decides where on the form the sun's light falls."""
ctr = win_centre_az(); side = 1.0 if math.sin(math.radians(sun_az - ctr)) >= 0 else -1.0
return sun_vec(ctr + side * RELIEF_OFF_DEG, RELIEF_EL)
def fresnel(sl, nrm): return np.clip(1 - sl / nrm, 0, 1) ** 3 # (1 - n . V)^3, V = -r: strongest on faces that lie away from the viewer
def spec_field(L, sl, la, nrm, ndl):
"""GGX-like highlight (alpha 0.3) of the face (sl, la, nrm as in ndl_field) for the light L: half vector between L and the direction back to the viewer (-r) in every column."""
az = azrad(); sa, ca_ = np.sin(az), np.cos(az)
Hv = L[None, :] + np.stack([-sa, -ca_, np.zeros(W)], 1); Hv /= np.linalg.norm(Hv, axis=1, keepdims=True)
Hr = (Hv[:, 0] * sa + Hv[:, 1] * ca_)[None, :]; Ht = (Hv[:, 0] * ca_ - Hv[:, 1] * sa)[None, :]
nh = np.clip((Hv[:, 2][None, :] - sl * Hr - la * Ht) / nrm, 0, 1); al = 0.30
D = (al * al) / (1 + nh * nh * (al * al - 1)) ** 2 * al * al
return 0.30 * D * np.clip(ndl, 0, 1)
def relight_layer(Ly, st, hazec, F, sh3=None):
"""Shading per PIXEL (ndl_field), not per column. n.L uses the relief light; the sun's colour, strength (st['sun'] scales every direct term, so night and dusk stay dark) and shadows are the real sun's."""
L = relief_vec(st['az']); az = azrad(); sa, ca_ = np.sin(az), np.cos(az); sl, la = Ly['sl'], Ly['la']
ndl, nrm = ndl_field(Ly, L); d = np.clip((ndl + 0.2) / 1.2, 0, 1)
gain = hue_gain(st, d[..., None])
rim_dir = (np.stack([sa, ca_], 1) * L[None, :2]).sum(1)[None, :]
fres = fresnel(sl, nrm)
rim = (0.12 + 1.0 * np.clip(rim_dir, 0, 1)) * fres
spec = spec_field(L, sl, la, nrm, ndl)
if sh3 is None: sp = np.zeros((1, 1), np.float32); face = Ly['face'] * gain.astype(np.float32)
else:
sh3 = blurw(sh3, 2.0); f = np.clip((rowang[:, None] - Ly['lo'][None, :]) / np.maximum(Ly['ang'] - Ly['lo'], 1e-3)[None, :], 0, 1) # position on the face: 0 valley .. 1 crest
sp = np.where(f < 0.5, sh3[0] + (sh3[1] - sh3[0]) * 2 * f, sh3[1] + (sh3[2] - sh3[1]) * 2 * (f - 0.5)).astype(np.float32)
g_amb = hue_gain(st, 0.0)[None, None, :]; face = Ly['face'] * (g_amb + (gain - g_amb) * (1 - sp)[..., None]).astype(np.float32) # shadow removes the direct share only
fa = 1 - math.exp(-Ly['dist'] / 20000.0) # valley mist grows with the layer's distance
foot = F * (1 - fa) + hazec[None] * fa
wf = Ly['w'] * (1 - 0.6 * fa) # far layers keep 60% of their own body colour at the foot
wf = 1 - (1 - wf) * np.clip(1 + rowang * PXDEG_V / 40.0, 0, 1)[:, None] # below the horizon every layer's foot has merged into the ground plane within 40 px: no per-slot colour seams down the floor
face = face * (1 - wf[..., None]) + foot * wf[..., None]
face += (Ly['rb'] * (rim * 0.55) * (1 - sp))[..., None] * (st['sun'] * 1.1 + 0.25)[None, None, :]
face += ((spec * (0.5 + Ly['mot'])) * (Ly['m'] > 0.5) * (1 - sp))[..., None] * st['sun'][None, None, :] * 0.5
lw = (0.70 + 0.90 * (1 - d)) * (1 - 0.30 * Ly['far'])
line = np.clip(1 - Ly['dpx'] / lw, 0, 1) * Ly['ca']
ia = np.clip(line + Ly['ha'], 0, 1)
ink = Ly['ink'][None, None, :] * (0.6 + 0.4 * gain.mean(-1))[..., None]
face = face * (1 - ia[..., None]) + ink * ia[..., None]
T = np.exp(-(BETA_R + BETA_M) * Ly['dist'] / 1000.0 * ATM)
return face * T[None, None, :] + hazec[None, :, :] * (1 - T)[None, None, :]
def sky_hz(st, paperf):
az = azrad(); c, hg = col_scatter(st)
hz = hx('#f5e2c8')[None, :] * hg * st['ex_t']
tint = (st['amb'] / st['amb'].mean()) / (REF_AMB / REF_AMB.mean()); zen = hx('#a9bcd6')[None, :] * tint[None, :] * st['ex_t']
u = np.clip(rowang / max(TOP_DEG, 2.5), 0, 1)[:, None] ** 0.7
img = zen[None] * u[..., None] + hz[None] * (1 - u)[..., None]
ev = np.radians(rowang)[:, None]; cs = np.cos(ev) * math.cos(math.radians(st['el'])) * np.cos(az - math.radians(st['az']))[None, :] + np.sin(ev) * math.sin(math.radians(st['el']))
ang = np.degrees(np.arccos(np.clip(cs, -1, 1)))
glow = 0.95 * np.exp(-(ang / 4.5) ** 2) + 0.55 * np.exp(-(ang / 22.0) ** 2)
img = img + glow[..., None] * (st['sky_sun'] * 0.8 * st['ex_t'])[None, None, :]
return img * paperf[..., None] / 0.93, hz
def haze_colour(hz): return hz * (hx('#cdd7e7') / hx('#f5e2c8'))[None, :]
def relight(layers, az, el, paperf, grain, fmot, shadows=True, flat=None):
"""Opaque frame with the sky. `flat` (an RGB triple) replaces the sky and the haze colour by that one colour: the stand-in the planes are compared against."""
st = sun_state(az, el); shs = cast_shadows(layers, az, el) if shadows else [None] * len(layers); sky, hz = sky_hz(st, paperf)
hazec = haze_colour(hz)
if flat is not None: hazec = np.broadcast_to(np.asarray(flat, float), (W, 3)); sky = np.broadcast_to(np.asarray(flat, float), sky.shape)
F = floor_img(st, hazec, fmot) * (paperf[..., None] / 0.93)
img = np.where((rowang >= 0)[:, None, None], sky, F).astype(np.float32)
for Ly, sh3 in zip(layers, shs):
face = relight_layer(Ly, st, hazec.astype(np.float32), F.astype(np.float32), sh3); face *= (paperf[..., None] / 0.93)
img = img * (1 - Ly['a'][..., None]) + face * Ly['a'][..., None]
return img * grain[..., None]
def group_slots(n):
"""Plane grouping by slot index: far = slot 0 (+ the floor), near = the last slot, mid = every slot between. Fewer than 3 slots cannot fill three planes."""
if n < 3: raise ValueError(f"a place needs at least 3 layer slots for the far/mid/near planes, this one has {n}")
return dict(far=[0], mid=list(range(1, n - 1)), near=[n - 1])
OCCLUDE_MARGIN_PX = 48 # the runtime slides the planes against each other by up to this much; a farther plane is hidden only where the nearer layers cover it at every offset within it, so a slide never uncovers a hole
def most_open(seen):
"""The most light any offset within OCCLUDE_MARGIN_PX lets through `seen` (the nearer layers' transmittance), eased over the same distance so the knock-out has no edge of its own: a max filter along the columns, then a Gaussian of sigma OCCLUDE_MARGIN_PX / 2; the window's ends repeat their edge column."""
m = OCCLUDE_MARGIN_PX; r = 2 * m; pad = np.pad(seen, ((0, 0), (r, r)), mode='edge')
return np.clip(blurw(np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=1).max(-1), m / 2.0)[:, m:-m], 0, 1)
def relight_planes(layers, az, el, paperf, grain, fmot, shadows=True, ref=None):
"""The frame as three RGBA planes (window columns, float 0..1, straight alpha) with no sky drawn. Every pixel of relight is affine in the haze colour c: out = X + c Y
(the haze enters only as the foot mix and the final Beer-Lambert mix). Render each layer and the floor with c = 0 (X) and c = 1 (X + Y), composite each group over
nothing, and let the haze share become transparency: alpha = coverage - mean(Y), colour = X / alpha. Whatever sky the runtime draws behind then supplies the haze.
The split is exact for one group over a flat sky; stacked planes put a nearer group's haze over the farther ridge instead of over the sky (see the recomposite test for the measured loss)."""
st = sun_state(az, el); shs = cast_shadows(layers, az, el) if shadows else [None] * len(layers); out = {}
below = (rowang < 0)[:, None]; k = (paperf[..., None] / 0.93); runs = []
ref = haze_colour(sky_hz(st, paperf)[1]) if ref is None else np.broadcast_to(np.asarray(ref, float), (W, 3)); ref_w = win(ref[None].astype(np.float32))[0]
for c in (0.0, 1.0):
hc = np.full((W, 3), c, np.float32); F = (floor_img(st, hc, fmot) * k).astype(np.float32)
runs.append((F, [relight_layer(Ly, st, hc, F, sh3) * k for Ly, sh3 in zip(layers, shs)]))
groups = group_slots(len(layers)); names = list(groups); seen = {}
for name, idx in groups.items():
img = [np.where(below[..., None], r[0], 0.0) if name == 'far' else np.zeros_like(r[0]) for r in runs]; cov = np.broadcast_to(below, (H, W)).astype(np.float32) if name == 'far' else np.zeros((H, W), np.float32)
for i in idx:
a = layers[i]['a'][..., None]
for j in (0, 1): img[j] = img[j] * (1 - a) + runs[j][1][i] * a
cov = cov * (1 - a[..., 0]) + a[..., 0]
X = win(img[0]); Yc = win(img[1] - img[0]); Y = Yc.mean(-1); alpha = np.clip(win(cov) - Y, 0, 1)
P = X + ref_w[None] * (Yc - Y[..., None]) # premultiplied colour: exact over the reference haze, per channel
col = np.where(alpha[..., None] > 1e-4, P / np.maximum(alpha, 1e-4)[..., None], 0.0) * win(grain)[..., None]
seen[name] = win(np.prod([1 - layers[i]['a'] for i in idx], axis=0))
out[name] = np.concatenate([np.clip(col, 0, 1), alpha[..., None]], -1).astype(np.float32)
for i in range(len(names) - 2, -1, -1): # near to far: the opaque frame lets a farther plane through only what the nearer layers leave open (their transmittance `seen`), but the stacked planes let it through by their alpha, which also lost the haze share to transparency; the farther plane's alpha is brought to the opaque frame's
nearer = names[i + 1:]; left = most_open(np.prod([seen[n] for n in nearer], axis=0)); got = np.prod([1 - out[n][..., 3] for n in nearer], axis=0)
out[names[i]][..., 3] *= np.clip(left / np.maximum(got, 1e-3), 0, 1)
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
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
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))
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]])))
out[t] = np.exp(bc[j]); lo = j
return out
def statics():
paperf = 0.93 + 0.09 * (0.5 * pn2(2, 11) + 0.3 * pn2(9, 12) + 0.2 * pn2(40, 13)) + 0.03 * (pn2(1, 14) - .5)
return paperf, 0.95 + 0.07 * pn2(1, 900), 0.88 + 0.2 * (0.6 * pn2(30, 810) + 0.4 * pn2(7, 811))
# ====================================================================== 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)
def albedo(h, n_up):
"""The authored material, a few numbers: valley green to forest to rock by height, rock where the face is steep, snow above the tree line. Straight colour, no light in it."""
t = lambda a, b: np.clip((h - a) / (b - a), 0, 1)[..., None]; c = np.asarray(GRASS) + (np.asarray(FOREST) - GRASS) * t(150, 900); c = c + (np.asarray(ROCK) - c) * t(1300, 2000)
c = c + (np.asarray(ROCK) - c) * np.clip((0.93 - n_up) / 0.25, 0, 1)[..., None]; return c + (np.asarray(SNOW) - c) * (t(1900, 2300) * np.clip((n_up - 0.55) / 0.3, 0, 1)[..., None])
def debug_spans(cols, win0=None, w=WIN):
win0 = P['win0'] if win0 is None else win0
img = np.ones((H, w, 3)) * 0.97; ramp = [hx(c) for c in ('#d03030', '#e8a020', '#60b040', '#2090b0', '#6030c0')]
order = sorted(((s[2], i, s[0], s[1]) for i in range(w) for s in cols[(win0 + i) % W]), key=lambda t: -t[0])
for dd, x, p, l in order:
t = np.clip((math.log(dd) - math.log(500)) / (math.log(95000) - math.log(500)), 0, 1) * 4
i = min(int(t), 3); col = mix(ramp[i], ramp[i + 1], t - i)
y0 = int(np.clip((TOP_DEG - p) * PXDEG_V, 0, H - 1)); y1 = int(np.clip((TOP_DEG - max(l, p - 3.0)) * PXDEG_V, 0, H - 1))
img[y0:y1 + 1, x] = col
return img
def apply_view(v):
"""re-apply a view returned by set_view (used by the rotation test and the before/after comparison so that frames line up exactly)"""
global rowang, PXDEG_V, TOP_DEG, BOTTOM_DEG
PXDEG_V = v['px_per_deg']; TOP_DEG = v['top_deg']; BOTTOM_DEG = v['bottom_deg']; rowang = TOP_DEG - (np.arange(H) + 0.5) / PXDEG_V
def cards(d, a, h, seams, nrm=None):
"""K+1 cards, nearest first, from the angles a and heights h (samples, n) of n columns and the (K, n) seams (m). Card i holds per pixel the FIRST VISIBLE hit at or beyond seam i-1 (less XF): layered depth, so a farther
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),
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
ks0 = [np.searchsorted(d, seams[i - 1] * math.exp(-XF)) for i in range(1, nc)]; ks1 = [np.searchsorted(d, seams[i] * math.exp(XF)) for i in range(nc - 1)]
F = np.zeros((nc, H, n)); X = np.ones((nc, H, n)); G = np.zeros((nc, 5, H, n)); Wl = np.zeros((nc, H, n), bool) # coverage, far fade, then (logd, h, n_r, n_t, n_u); wall rows
for x in range(n):
for i in range(nc):
k0 = 0 if i == 0 else int(ks0[i - 1][x]); k1 = nk if i == nc - 1 else int(ks1[i][x])
if k1 <= k0: continue
rm = np.maximum.accumulate(a[k0:k1, x]); idx = np.searchsorted(rm, lo, 'right'); hit = idx < len(rm); idx = np.minimum(idx, len(rm) - 1); kk = k0 + idx
if not hit.any(): continue
kp = np.maximum(kk - 1, k0); prev = np.where(idx > 0, rm[np.maximum(idx - 1, 0)], rm[idx] - 1.0)
t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0); mix = lambda arr: arr[kp, x] + t * (arr[kk, x] - arr[kp, x])
F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0); lh = mix(ld)
G[i, :, :, x] = np.where(hit, np.stack([lh, mix(h), mix(n_r), mix(n_t), mix(n_u)]), 0)
if i: Wl[i, :, x] = hit & (idx == 0) # rows below the card's first sample: the extruded wall (card 0's are the ground)
if i < nc - 1: s = np.clip((lh - (math.log(seams[i, x]) - XF)) / (2 * XF), 0, 1); X[i, :, x] = 1 - s * s * (3 - 2 * s)
out = []; A = np.zeros((H, n))
for i in range(nc):
part = np.where(F[i] < 1, np.clip((np.maximum(A, F[i]) - A) / np.maximum(1 - A, 1e-6), 0, 1), F[i]); al = np.where(np.rint(X[i] * part * 255) > 0, X[i] * part, 0.0); A = 1 - (1 - A) * (1 - al)
rows = np.flatnonzero(al.max(1) > 0)
if not len(rows): out.append(dict(top=0, alpha=np.zeros((0, n), np.float32), albedo=np.zeros((0, n, 3), np.float32), n_r=np.zeros((0, n), np.float32), n_t=np.zeros((0, n), np.float32), logd=np.zeros((0, n), np.float32), wall=np.zeros((0, n), bool))); continue
sl = slice(int(rows[0]), int(rows[-1]) + 1); g = G[i, :, sl]; nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12
out.append(dict(top=int(rows[0]), alpha=al[sl].astype(np.float32), albedo=albedo(g[1], np.where(Wl[i, sl], 1.0, g[4] / nz)).astype(np.float32), n_r=(g[2] / nz).astype(np.float32), n_t=(g[3] / nz).astype(np.float32), logd=g[0].astype(np.float32), wall=Wl[i, sl].copy()))
return out

View file

@ -1,29 +0,0 @@
"""Solar position: NOAA general solar position formulas (Spencer/fractional-year low precision: equation of time and declination Fourier series,
hour angle, zenith/azimuth), https://gml.noaa.gov/grad/solcalc/solareqns.PDF . Accuracy ~0.1 deg, plenty for a relight. Apparent elevation adds
Saemundsson refraction (Meeus ch.16). UTC in, degrees out. Azimuth clockwise from north."""
import math
from datetime import datetime, timezone, timedelta
def solar(dt_utc, lat, lon):
doy = dt_utc.timetuple().tm_yday; hr = dt_utc.hour + dt_utc.minute / 60 + dt_utc.second / 3600
g = 2 * math.pi / 365 * (doy - 1 + (hr - 12) / 24)
eq = 229.18 * (0.000075 + 0.001868 * math.cos(g) - 0.032077 * math.sin(g) - 0.014615 * math.cos(2 * g) - 0.040849 * math.sin(2 * g))
de = (0.006918 - 0.399912 * math.cos(g) + 0.070257 * math.sin(g) - 0.006758 * math.cos(2 * g) + 0.000907 * math.sin(2 * g)
- 0.002697 * math.cos(3 * g) + 0.00148 * math.sin(3 * g))
tst = hr * 60 + eq + 4 * lon # true solar time, minutes
ha = math.radians(tst / 4 - 180); la = math.radians(lat)
sin_el = math.sin(la) * math.sin(de) + math.cos(la) * math.cos(de) * math.cos(ha)
el = math.degrees(math.asin(sin_el))
az = (math.degrees(math.atan2(math.sin(ha), math.cos(ha) * math.sin(la) - math.tan(de) * math.cos(la))) + 180) % 360
ref = 1.02 / math.tan(math.radians(el + 10.3 / (el + 5.11))) / 60 if el > -5 else 0.0
return az, el + ref, el, math.degrees(de), eq
def find_el(day, lat, lon, target, lo_h, hi_h):
"""bisect the UTC hour in [lo_h, hi_h] where apparent elevation crosses `target`."""
f = lambda h: solar(day + timedelta(hours=h), lat, lon)[1] - target
a, b = lo_h, hi_h; fa = f(a)
for _ in range(50):
m = (a + b) / 2; fm = f(m)
if (fa < 0) == (fm < 0): a, fa = m, fm
else: b = m
return (a + b) / 2

View file

@ -2,57 +2,51 @@
venv/bin/python tests/mutate.py (prints one line per mutant; 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 = {
'round-1 bug: both chain sides take the END value (near_end always x1)': ("near_end = np.where(x - x1 <= W - x, x1, 0)", "near_end = np.where(x - x1 <= W - x, x1, x1)"),
'linking does not wrap (look-back columns clipped at 0)': ("xb = (x - back) % Wc", "xb = max(x - back, 0)"),
'a chain absent from a column still competes in the slot union (held valley value wins)': ("np.where(l['wt'] > 0, l['top'], -1e3 - col_gap(l['wt'] > 0))", "l['top']"),
'shadow march goes AWAY from the sun': ("lat + s * ca / 111320.0, lon + s * sa", "lat - s * ca / 111320.0, lon - s * sa"),
'shadow ignores the sun elevation (ray stays at the sample height)': ("(h + s * t)", "(h + 0 * t)"),
'taper length ignores the drop (always the 8-column minimum)': ("Tn = taper_len(drop)", "Tn = np.full_like(drop, 8.0)"),
'shadow march mirrors east/west (longitude sign)': ("lon + s * sa / (111320.0 * cosl)", "lon - s * sa / (111320.0 * cosl)"),
'shadow longitude scale ignores cos(lat)': ("lon + s * sa / (111320.0 * cosl)", "lon + s * sa / 111320.0"),
'shadow lightens instead of darkens the face': ("(gain - g_amb) * (1 - sp)[..., None]", "(gain - g_amb) * sp[..., None]"),
'taper cap lowered to 8 columns': ("TAPER_K, TAPER_MAX = 30.0, 72", "TAPER_K, TAPER_MAX = 30.0, 8"),
'taper per degree lowered to 2': ("TAPER_K, TAPER_MAX = 30.0, 72", "TAPER_K, TAPER_MAX = 2.0, 72"),
'taper floor ignores the chain end (top held, no fall)': ("res['top'] = res['top'] - drop * t", "res['top'] = res['top']"),
'painter shades one normal per column (the column mean of the per-pixel face)': ("sl, la = Ly['sl'], Ly['la']\n Lr", "sl, la = np.broadcast_to(Ly['sl'].mean(0), Ly['sl'].shape), np.broadcast_to(Ly['la'].mean(0), Ly['la'].shape)\n Lr"),
'history collapsed to ONE slope per peak (the strip mean)': ("Z, Dp, sl = lerp(hh), lerp(hd), lerp(sn)", "Z, Dp, sl = lerp(hh), lerp(hd), np.broadcast_to(mean_s, Z.shape)"),
'history not recorded: only valley and peak samples kept': ("return np.interp(t, va, vd), np.interp(t, va, vh)", "return np.interp(t, va[[0, -1]], vd[[0, -1]]), np.interp(t, va[[0, -1]], vh[[0, -1]])"),
'no lateral tilt from the neighbouring columns': ("np.clip((c_ - a_ * sl) / b_, -1.5, 1.5))", "0 * np.clip((c_ - a_ * sl) / b_, -1.5, 1.5))"),
'NEAR_CAP shoulder committed without the prominence test': ("if hh[j] - lowh >= prom: span(", "if True: span("),
'prominence measured as an angle at the CURRENT sample (round 2)': ("if cand - v >= hy[k] and ch - lowh >= prom:", "if cand - v >= hy[k] and cand - mn >= hy[k]:"),
'contour interval chosen from the shallowest quarter of the face (banding)': ("np.percentile(dzdpx[faceok], 75)", "np.percentile(dzdpx[faceok], 10)"),
'a tapering end keeps the 28 px minimum body (stub / curtain at every chain end)': ("28 * np.clip(wt, 0, 1)", "28"),
'absent columns of a slot take the first chain in list order (rotation-dependent)': ("np.where(l['wt'] > 0, l['top'], -1e3 - col_gap(l['wt'] > 0))", "np.where(l['wt'] > 0, l['top'], -1e9)"),
'history keeps samples the eye cannot see (no running maximum)': ("runmax = np.maximum.accumulate(seg)", "runmax = seg"),
'lateral tilt scale doubled': ("/ b_, -1.5, 1.5))", "/ b_ * 2, -1.5, 1.5))"),
'lateral tilt kept across occlusion edges': ("np.abs(a_) > 3 * b_", "np.abs(a_) > 3e9 * b_"),
'every foreground stub kept (round 2 arches)': ("if not cov[xs].any(): keep.append(c)", "if True: keep.append(c)"),
'no foreground stub kept (holes in the nearest layer)': ("if not cov[xs].any(): keep.append(c)", "if False: keep.append(c)"),
'prominence from the height of the lowest-angle sample (near, high valley)': ("if cand - v >= hy[k] and ch - lowh >= prom:", "if cand - v >= hy[k] and ch - mnh >= prom:"),
'layer body painted to the bottom of the frame (no foot fade: walls)': ("alpha = (m * (1 - fade)).astype(np.float32)", "alpha = m.astype(np.float32)"),
'relief: shading uses the real sun again (face flat with the sun behind the viewer)': ("L = relief_vec(st['az']); az", "L = st['L']; az"),
'relief: 45 deg off the viewer-ward axis (the previous reading) instead of the view axis': ("ctr = win_centre_az(); side", "ctr = (win_centre_az() + 180.0) % 360.0; side"),
'relief: always the + side, whatever side the real sun is on': ("side = 1.0 if math.sin(math.radians(sun_az - ctr)) >= 0 else -1.0", "side = 1.0"),
'relief: colour / strength / haze frozen at a 40 deg sun (night does not go dark)': ("st = sun_state(az, el); shs", "st = sun_state(az, 40.0); shs"),
'relief: cast shadows march toward the relief light instead of the real sun': ("cast_shadows(layers, az, el) if shadows", "cast_shadows(layers, math.degrees(math.atan2(relief_vec(az)[0], relief_vec(az)[1])) % 360.0, RELIEF_EL) if shadows"),
'compositor (relight) reads the layer mask m instead of its alpha a (walls return)': ("img = img * (1 - Ly['a'][..., None]) + face * Ly['a'][..., None]", "img = img * (1 - Ly['m'][..., None]) + face * Ly['m'][..., None]"),
'foot fade starts at 30% of the foot instead of 60%': ("(depthpx - 0.6) / 0.4", "(depthpx - 0.3) / 0.7"),
'foot fade starts at 90% of the foot instead of 60%': ("(depthpx - 0.6) / 0.4", "(depthpx - 0.9) / 0.1"),
'TAPER_MAX 72 -> 40': ("TAPER_K, TAPER_MAX = 30.0, 72", "TAPER_K, TAPER_MAX = 30.0, 40"),
'RELIEF_EL 32 -> 3 (grazing relief light)': ("RELIEF_OFF_DEG, RELIEF_EL = 45.0, 32.0", "RELIEF_OFF_DEG, RELIEF_EL = 45.0, 3.0"),
'spec half vector ignores the light': ("Hv = L[None, :] + np.stack(", "Hv = 0 * L[None, :] + np.stack("),
'lateral tilt not blurred across columns': ("blurw(la, 2.0).astype", "la.astype"),
'contour interval percentile includes the tapering columns (weight condition removed)': ("& (wt[None, :] > 0.5)", ""),
'Fresnel sign flipped (rim strongest on faces standing at the viewer)': ("np.clip(1 - sl / nrm, 0, 1) ** 3", "np.clip(1 + sl / nrm, 0, 1) ** 3"),
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
'seam cost: the rows a seam sweeps are not paid (it hops across a receding ridge)': ("np.cumsum(0.5 * (cov[:, x - 1] + cov[:, x])) + SEAM_LAM * bins", "SEAM_LAM * bins"),
'seam prior pulls hard to the target (2.0, or 0.1: the seam hops across a ridge)': ("SEAM_PRIOR = 0.02 ", "SEAM_PRIOR = 2.0 "),
'normals: the authored exaggeration is dropped': ("h = np.asarray(h, np.float64); E = PXDEG_V / HPX_DEG", "h = np.asarray(h, np.float64); E = 1.0"),
'normals: the lateral neighbour is one sample nearer (not equal distance)': ("st = E * (np.roll(h, -1, axis=1) - np.roll(h, 1, axis=1))", "st = E * (np.roll(np.roll(h, -1, axis=1), 1, axis=0) - np.roll(h, 1, axis=1))"),
'cards: the near edge is ignored (every card starts at sample 0)': ("k0 = 0 if i == 0 else int(ks0[i - 1][x])", "k0 = 0"),
'cards: the farther card fades in over the window too (both cards translucent)': ("X[i, :, x] = 1 - s * s * (3 - 2 * s)", "X[i, :, x] = 1 - s * s * (3 - 2 * s); X[i + 1, :, x] = s * s * (3 - 2 * s)"),
'cards: a crest row is all or nothing (no fractional coverage)': ("F[i, :, x] = np.where(hit, np.clip((rm[-1] - lo) / p, 0, 1), 0)", "F[i, :, x] = np.where(hit, 1.0, 0)"),
'prefilter ignores sigma': ("if sigma_m > 0:", "if False:"),
'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"),
'colour: albedo zeroed in the file': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(albedo) * 0"),
'colour: premultiplied instead of straight': ("rgb = u8(albedo) * (a[..., None] > 0)", "rgb = u8(np.asarray(albedo) * np.asarray(alpha)[..., None])"),
'seams: the separation between seams is ignored': ("SEAM_SEP = 0.4 ", "SEAM_SEP = 0.0 "),
'elev: curvature and refraction dropped': ("drop = d * d / (2 * R_EARTH) * (1 - KREF) if curvature else 0.0", "drop = 0.0"),
'coverage: the rows below the first sample are not counted': ("prev = np.vstack([np.full((1, a.shape[1]), BOTTOM_DEG), runmax[:-1]])", "prev = np.vstack([np.full((1, a.shape[1]), 100.0), runmax[:-1]])"),
'coverage: the rows below the first sample are counted twice': ("* PXDEG_V)\n return C", "* PXDEG_V); C[0] += np.clip(np.minimum(a[0], TOP_DEG) - BOTTOM_DEG, 0, None) * PXDEG_V\n return C"),
'cards: the hit is not interpolated between samples': ("t = np.where(idx > 0, np.clip((rowang - prev) / np.maximum(rm[idx] - prev, 1e-9), 0, 1), 1.0)", "t = np.ones_like(rowang)"),
'cards: the blended normal is not renormalised': ("nz = np.sqrt(g[2] ** 2 + g[3] ** 2 + g[4] ** 2) + 1e-12", "nz = 1.0"),
'wall: no row is flagged (the flag is dropped)': ("if i: Wl[i, :, x] = hit & (idx == 0)", "if i: Wl[i, :, x] = False"),
'wall: card 0 is flagged too (its ground rows become wall)': ("if i: Wl[i, :, x] = hit & (idx == 0)", "Wl[i, :, x] = hit & (idx == 0)"),
'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"),
'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"),
}
EQUIVALENT = {} # mutant name -> one line on why it is behaviourally equivalent (reported, not run)
def run(item):
name, (a, b) = item; d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')); p = os.path.join(d, 'src', 'ridge.py'); s = open(p).read(); assert a in s, name
name, (a, b) = item; d = tempfile.mkdtemp(); shutil.copytree(SRC, os.path.join(d, 'src'), ignore=shutil.ignore_patterns('tests', '__pycache__')); p = next(q for q in (os.path.join(d, 'src', f) for f in ('ridge.py', 'export.py')) if a in open(q).read()); s = open(p).read(); assert a in s, name
open(p, 'w').write(s.replace(a, b))
r = subprocess.run([sys.executable, os.path.join(HERE, 'test_ridge.py')], env=dict(os.environ, RIDGE_SRC=os.path.join(d, 'src')), capture_output=True, text=True); shutil.rmtree(d)
fails = [l.split('|')[0].strip() for l in r.stdout.splitlines() if l.startswith('FAIL')]

View file

@ -1,111 +0,0 @@
"""Mutation check of the planes path: re-introduce a cause into a COPY of export.py / ridge.py (relight_planes) and run the planes/export tests of test_ridge.py (PLANES_TESTS) against it; a mutant must fail at least one.
RIDGE_TILES=<tiles> RIDGE_WORK=<dir> venv/bin/python -I tests/mutate_export.py [JOBS=4 and ONLY=<name substring>[|<another>] in the environment] (prints one line per mutant as it lands; exit 1 if one survives)
Each mutant runs under a 12 GB address-space cap and a 20 minute limit. Equivalent mutants are named in EQUIVALENT with the argument; they are reported but do not fail the run."""
import os, sys, shutil, subprocess, tempfile, resource
from concurrent.futures import ThreadPoolExecutor
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
EQUIVALENT = {'decode budget cap is exclusive': 'decoded = 2 * 3 * w * h * 4 is a multiple of 24 and 20_000_000 is not (20_000_000 / 24 = 833333.33), so decoded == DECODE_BYTES_MAX never holds for integer w and h and > equals >='}
M = {
'no per-channel ref correction (P = X)': ('ridge.py', 'P = X + ref_w[None] * (Yc - Y[..., None])', 'P = X'),
'alpha ignores haze (alpha = cov)': ('ridge.py', 'alpha = np.clip(win(cov) - Y, 0, 1)', 'alpha = np.clip(win(cov), 0, 1)'),
'alpha from the max haze channel': ('ridge.py', 'Y = Yc.mean(-1); alpha', 'Y = Yc.max(-1); alpha'),
'haze share halved in alpha': ('ridge.py', 'alpha = np.clip(win(cov) - Y, 0, 1)', 'alpha = np.clip(win(cov) - 0.5 * Y, 0, 1)'),
'default ref = the sky horizon colour, not the haze colour': ('ridge.py', 'ref = haze_colour(sky_hz(st, paperf)[1]) if ref is None', 'ref = sky_hz(st, paperf)[1] if ref is None'),
'default ref = mid grey': ('ridge.py', 'ref = haze_colour(sky_hz(st, paperf)[1]) if ref is None', 'ref = np.full((W, 3), 0.5) if ref is None'),
'grain dropped from the planes': ('ridge.py', 'P / np.maximum(alpha, 1e-4)[..., None], 0.0) * win(grain)[..., None]', 'P / np.maximum(alpha, 1e-4)[..., None], 0.0)'),
'grain squared': ('ridge.py', 'P / np.maximum(alpha, 1e-4)[..., None], 0.0) * win(grain)[..., None]', 'P / np.maximum(alpha, 1e-4)[..., None], 0.0) * win(grain)[..., None] ** 2'),
'floor dropped from far': ('ridge.py', "if name == 'far' else np.zeros_like(r[0]) for r in runs]", "if False else np.zeros_like(r[0]) for r in runs]"),
'mid = only the first middle slot': ('ridge.py', 'mid=list(range(1, n - 1))', 'mid=[1]'),
'cast shadows off in planes': ('ridge.py', 'shs = cast_shadows(layers, az, el) if shadows else [None] * len(layers); out = {}', 'shs = [None] * len(layers); out = {}'),
'encode premultiplies colour': ('export.py', 'def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane)', 'def encode(plane): return bytes(imagecodecs.webp_encode(u8(np.concatenate([plane[..., :3] * plane[..., 3:], plane[..., 3:]], -1))'),
'encode drops alpha': ('export.py', 'def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane)', 'def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane)[..., :3]'),
'encode quality 5': ('export.py', 'WEBP_QUALITY = 80', 'WEBP_QUALITY = 5'),
'encode flips rows': ('export.py', 'def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane)', 'def encode(plane): return bytes(imagecodecs.webp_encode(u8(plane)[::-1].copy()'),
'night at -6 deg': ('export.py', 'NIGHT_EL = -12.0', 'NIGHT_EL = -6.0'),
'golden at 10 deg': ('export.py', 'golden=find(6.0, noon, noon + 9)', 'golden=find(10.0, noon, noon + 9)'),
'altitude includes eye height': ('export.py', "altitude_km=p['ground_m'] / 1000.0", "altitude_km=(p['ground_m'] + p['eye_m']) / 1000.0"),
'horizon_row in the wrong unit (degrees)': ('export.py', "horizon_row=v['horizon_row']", "horizon_row=v['top_deg']"),
'manifest plane h lies': ('export.py', 'w=w, h=h) for n in PLANES}', 'w=w, h=h + 1) for n in PLANES}'),
'manifest plane w from the constant': ('export.py', 'w=w, h=h) for n in PLANES}', 'w=PLANE_W, h=h) for n in PLANES}'),
'manifest view plane_w from the constant': ('export.py', 'window_deg=WINDOW_DEG, plane_w=w)', 'window_deg=WINDOW_DEG, plane_w=PLANE_W)'),
'luma sky 0.8 grey': ('export.py', 'LUMA_SKY = 0.5', 'LUMA_SKY = 0.8'),
'luma coverage threshold 0.3': ('export.py', 'LUMA_COVER = 0.5', 'LUMA_COVER = 0.3'),
'luma coverage threshold 0.8': ('export.py', 'LUMA_COVER = 0.5', 'LUMA_COVER = 0.8'),
'luma composites near to far': ('export.py', 'for a in decoded:', 'for a in decoded[::-1]:'),
'luma coverage = strongest plane alpha': ('export.py', 'clear = clear * (1 - al[..., 0])', 'clear = np.minimum(clear, 1 - al[..., 0])'),
'luma coverage = last plane alpha': ('export.py', 'clear = clear * (1 - al[..., 0])', 'clear = 1 - al[..., 0]'),
'luma never refuses an empty frame': ('export.py', 'if not m.any(): raise ValueError', 'if False: raise ValueError'),
'planes of mixed size accepted': ('export.py', 'if len(shapes) != 1:', 'if False:'),
'plane rows not checked against the view': ('export.py', 'if h != view', 'if False and h != view'),
'budget checked against the constant width': ('export.py', 'check_budget([sum(sizes[k].values()) for k in KEYS], w, h)', 'check_budget([sum(sizes[k].values()) for k in KEYS], PLANE_W, h)'),
'budget checked against the view height only': ('export.py', 'check_budget([sum(sizes[k].values()) for k in KEYS], w, h)', 'check_budget([sum(sizes[k].values()) for k in KEYS], w, 1)'),
'width cap is exclusive of 4096': ('export.py', 'if plane_w > PLANE_W_MAX:', 'if plane_w >= PLANE_W_MAX:'),
'width cap 8192': ('export.py', 'PLANE_W_MAX = 4096', 'PLANE_W_MAX = 8192'),
'pair cap is exclusive of the cap': ('export.py', 'if frame_bytes[i] + frame_bytes[j] > PAIR_BYTES_MAX:', 'if frame_bytes[i] + frame_bytes[j] >= PAIR_BYTES_MAX:'),
'pair check does not wrap night to dawn': ('export.py', 'for i in range(len(frame_bytes)):', 'for i in range(len(frame_bytes) - 1):'),
'decode budget counts one frame, not a pair': ('export.py', 'decoded = 2 * len(PLANES)', 'decoded = len(PLANES)'),
'decode budget cap doubled': ('export.py', 'DECODE_BYTES_MAX = 20_000_000', 'DECODE_BYTES_MAX = 40_000_000'),
'decode budget cap is exclusive': ('export.py', 'if decoded > DECODE_BYTES_MAX:', 'if decoded >= DECODE_BYTES_MAX:'),
'planes order mid far near': ('export.py', "PLANES = ('far', 'mid', 'near')", "PLANES = ('mid', 'far', 'near')"),
'morning ignores the time zone': ('export.py', 'morning=9.5 - tz', 'morning=9.5'),
'dawn three hours after sunrise': ('export.py', 'dawn=rise + 0.25', 'dawn=rise + 3'),
'dusk at -4 deg': ('export.py', 'dusk=find(-2.5, noon, noon + 9)', 'dusk=find(-4.0, noon, noon + 9)'),
'noon is solar noon of the meridian, not the sun maximum': ('export.py', 'noon = max((12 - lon / 15.0 - 1 + x / 600 for x in range(0, 1200)), key=lambda t: sun.solar(day + timedelta(hours=t), lat, lon)[1])', 'noon = 12 - lon / 15.0 + 1.5'),
'sun key hour_utc off by one hour': ('export.py', "hour_utc=h) for k, h in hours.items()}", "hour_utc=h + 1) for k, h in hours.items()}"),
'altitude from the eye, not the ground': ('export.py', "altitude_km=p['ground_m'] / 1000.0", "altitude_km=p['eye_m'] / 1000.0"),
'look azimuth from the wrong field': ('export.py', "look_az_deg=p['az_center']", "look_az_deg=p['lat']"),
'view px_per_deg_v is the horizontal one': ('export.py', "px_per_deg_v=v['px_per_deg']", "px_per_deg_v=ridge.HPX_DEG"),
'sky_row left as a fraction': ('export.py', "sky_row=v['sky_row'] * ridge.H", "sky_row=v['sky_row']"),
'near_row left as a fraction': ('export.py', "near_row=v['near_row'] * ridge.H", "near_row=v['near_row']"),
'index written without replacing a rebaked place': ('export.py', "idx['places'][place['id']] = name;", "idx['places'].setdefault(place['id'], name);"),
'plane files written under the wrong key': ('export.py', "(tmp / f'{k}-{n}.webp').write_bytes(frames_webp[k][n])", "(tmp / f'{k}-{n}.webp').write_bytes(frames_webp['noon'][n])"),
'a refused bake still creates the out dir': ('export.py', "sizes = {k: {n: len(frames_webp[k][n])", "Path(out).mkdir(parents=True, exist_ok=True); sizes = {k: {n: len(frames_webp[k][n])"),
'luma in sRGB, not linear': ('export.py', 'lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)', 'lin = c'),
'pair check skips the night-dawn pair and the last day pair': ('export.py', 'for i in range(len(frame_bytes)):', 'for i in range(len(frame_bytes) - 2):'),
'decode budget never checked': ('export.py', 'if decoded > DECODE_BYTES_MAX:', 'if False:'),
'old dir of the place kept': ('export.py', 'if old and old != name: shutil.rmtree(out / old, ignore_errors=True)', 'pass'),
'tmp dir left in out on success': ('export.py', 'os.rename(tmp, dest)', 'shutil.copytree(tmp, dest)'),
'index default always the baked place': ('export.py', "idx['default'] = default or (idx['default'] if idx['default'] in idx['places'] else place['id'])", "idx['default'] = place['id']"),
'attribution credit_line blanked': ('export.py', "credit_line='Contains modified", "credit_line='' and 'Contains modified"),
'attribution credit_line loses the Airbus line': ('export.py', ' and © Airbus Defence and Space GmbH 2014-2018', ''),
'attribution licence blanked': ('export.py', "licence='Copernicus DEM licence", "licence='' and 'Copernicus DEM licence"),
'attribution dem_source names the 90 m product': ('export.py', "dem_source='Copernicus DEM GLO-30 (30 m)'", "dem_source='Copernicus DEM GLO-90 (90 m)'"),
'attribution url over plain http': ('export.py', "url='https://spacedata", "url='http://spacedata"),
'attribution url blanked': ('export.py', "url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')", "url='')"),
'knock-out removed: the farther planes show through the nearer': ('ridge.py', "out[names[i]][..., 3] *= np.clip(left / np.maximum(got, 1e-3), 0, 1)", "out[names[i]][..., 3] *= 1.0"),
'knock-out ignores the nearer planes\' own alpha': ('ridge.py', "out[names[i]][..., 3] *= np.clip(left / np.maximum(got, 1e-3), 0, 1)", "out[names[i]][..., 3] *= np.clip(left, 0, 1)"),
'knock-out margin filter is a min (hides what the slide uncovers)': ('ridge.py', 'sliding_window_view(pad, 2 * m + 1, axis=1).max(-1), m / 2.0)', 'sliding_window_view(pad, 2 * m + 1, axis=1).min(-1), m / 2.0)'),
'knock-out has a hard edge (no easing)': ('ridge.py', 'return np.clip(blurw(np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=1).max(-1), m / 2.0)[:, m:-m], 0, 1)', 'return np.clip(np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=1).max(-1)[:, m:-m], 0, 1)'),
'knock-out margin of one column': ('ridge.py', 'OCCLUDE_MARGIN_PX = 48 ', 'OCCLUDE_MARGIN_PX = 1 '),
'knock-out hides the nearer plane from the farther one, not the reverse': ('ridge.py', 'nearer = names[i + 1:]; left', 'nearer = names[:i]; left'),
'near foot floor removed: the near body dissolves above the horizon': ('ridge.py', 'if near: foot = np.maximum(foot,', 'if False: foot = np.maximum(foot,'),
'near foot floor starts the fade at the foot, not at the horizon': ('ridge.py', 'np.clip(ang * PXDEG_V, 0, None) / FADE_AT)', 'np.clip(ang * PXDEG_V, 0, None) / 1.0)'),
'near flag passed to every layer': ('ridge.py', 'near=rank == len(slots) - 1)', 'near=True)'),
'near flag passed to no layer': ('ridge.py', 'near=rank == len(slots) - 1)', 'near=False)'),
'near flag on the first layer, not the last': ('ridge.py', 'near=rank == len(slots) - 1)', 'near=rank == 0)'),
'near cover never checked at the writer': ('export.py', "for k in KEYS: check_near_cover(dec[k][-1], view['horizon_row'])", "pass"),
'near cover checked on the mid plane': ('export.py', "check_near_cover(dec[k][-1], view['horizon_row'])", "check_near_cover(dec[k][1], view['horizon_row'])"),
'near cover checked on noon only': ('export.py', "for k in KEYS: check_near_cover(", "for k in ('noon',): check_near_cover("),
'near cover hole threshold of zero': ('export.py', 'NEAR_HOLE_ALPHA = 24 ', 'NEAR_HOLE_ALPHA = 0 '),
'near cover looks below the horizon too': ('export.py', '& (rows < int(horizon_row))', '& (rows < h)'),
'near cover crest threshold above any alpha': ('export.py', 'NEAR_CREST_ALPHA = 64 ', 'NEAR_CREST_ALPHA = 256 '),
'near cover lets a transparent column through': ('export.py', 'if none.any(): raise ValueError', 'if False: raise ValueError'),
'near cover looks only above the crest row': ('export.py', '(rows >= crest[None, :]) & (rows < int(horizon_row))', '(rows >= crest[None, :] + 400) & (rows < int(horizon_row))'),
'relight is not deterministic (noise in the planes)': ('ridge.py', 'P = X + ref_w[None] * (Yc - Y[..., None])', 'P = X + ref_w[None] * (Yc - Y[..., None]) + np.random.random() * 0.05'),
}
def _cap(): resource.setrlimit(resource.RLIMIT_AS, (12 << 30, 12 << 30))
def run(item):
name, (f, a, b) = item; d = tempfile.mkdtemp(dir=os.environ.get('TMPDIR')); s = os.path.join(d, 'src'); shutil.copytree(SRC, s, ignore=shutil.ignore_patterns('__pycache__'))
p = os.path.join(s, f); t = open(p).read(); assert a in t, name; open(p, 'w').write(t.replace(a, b, 1))
code = ("import sys; sys.path.insert(0, %r); import test_ridge as t\nfor f in sorted(t.PLANES_TESTS, key=lambda f: ('vienna' in f.__name__, f.__name__)):\n"
" try: f()\n except BaseException as e: print(f.__name__[5:50] + ': ' + repr(e)[:120]); break\n") % os.path.join(s, 'tests')
try: r = subprocess.run([sys.executable, '-I', '-B', '-c', code], env=dict(os.environ, RIDGE_SRC=s), capture_output=True, text=True, preexec_fn=_cap, timeout=1200); fails = r.stdout.strip().splitlines()[-1] if r.stdout.strip() else ('CRASH ' + r.stderr[-300:] if r.returncode else '')
except subprocess.TimeoutExpired: fails = 'TIMEOUT'
shutil.rmtree(d); line = ('KILLED ' if fails else 'SURVIVED ') + name + ' -> ' + (fails or '-'); print(line, flush=True); return line
if __name__ == '__main__':
only = os.environ.get('ONLY'); items = [kv for kv in M.items() if not only or any(o in kv[0] for o in only.split('|'))]
with ThreadPoolExecutor(int(os.environ.get('JOBS', '4'))) as ex: lines = list(ex.map(run, items))
live = [l for l in lines if l.startswith('SURVIVED') and l[9:].split(' -> ')[0] not in EQUIVALENT]
print('%d mutants, %d killed, %d survived (%d named equivalent)' % (len(lines), sum(l.startswith('KILLED') for l in lines), sum(l.startswith('SURVIVED') for l in lines), len(EQUIVALENT))); sys.exit(1 if live else 0)

View file

@ -1,13 +1,13 @@
"""Fixtures for the A+D sweep/chain/taper. Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure).
"""Fixtures for the ridge baker (march, prefilter, coverage, seams, normals, cards, export). Plain asserts, no pytest needed: venv/bin/python tests/test_ridge.py (exit code 1 on failure).
RIDGE_SRC selects the source directory (default ..) (the mutation runner points it at a patched copy).
Synthetic terrain has a known right answer; the Vienna test pins the skyline of the real bake (its rays come from stage0 for the vienna preset: RIDGE_TILES needs the tiles, or a cached rays file must exist)."""
import os, sys, math, traceback
Synthetic terrain has a known right answer; the Vienna tests bake the real preset (its rays come from stage0: RIDGE_TILES needs the tiles, or a cached rays file must exist)."""
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
from ridge import W, TAPER, TAPER_MAX, taper_len
import numpy as np, ridge, export
from ridge import W, WIN, H
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=60)
ridge.P = dict(id='synthetic', rmax_km=95, eye_m=100.0, win0=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
@ -21,335 +21,6 @@ def theta(h, d): return math.degrees(math.atan2(h - EYE - d * d / (2 * ridge.R_E
def in_arc(az, a0, a1): return ((az - a0) % 360.0) <= ((a1 - a0) % 360.0)
def block(a0, a1, d0, d1, h): return lambda dk, az: np.where(in_arc(az, a0, a1) & (dk >= d0) & (dk < d1), h, 0.0)
def terrain(*blocks): return lambda dk, az: np.maximum.reduce([np.full_like(az, GROUND)] + [np.asarray(b(dk, az), float) for b in blocks])
def slot_at(r, col, ang):
"""the slot whose top at `col` is closest to `ang` (the layer that owns the block)"""
return min(r['slots'], key=lambda S: abs(S['top'][col] - ang))
def jump_bound(S, x, w=26):
"""steepest step allowed inside a taper: smoothstep slope 1.5 x the end drop / taper_len(drop) (+ margin), the end drop taken as max((highest top within w columns) - lo, 0.4)"""
seg = S['top'][[(x + k) % W for k in range(-w, w + 1)]]; drop = max(seg.max() - S['lo'][x], 0.4); return 1.6 * drop / float(taper_len(drop)) + 0.02 # the taper always falls at least 0.4 deg (top - 0.4 when the valley is shallower)
def active_pairs(S): return [x for x in range(W) if S['wt'][x] > 0 and S['wt'][(x + 1) % W] > 0]
def test_plateau_has_no_spike_and_no_cliff_beyond_taper():
"""Flat-topped plateau, az 100-140, 20-24 km, 900 m. Right answer: top = theta(900, 20 km) inside, nothing above it anywhere, outside the plateau the top only falls
(monotonically, within the taper), and no single-column step exceeds the taper bound."""
A, Hh = rays(terrain(block(100, 140, 20000, 24000, 900))); r = ridge.sweep(D, A, Hh); th = theta(900, 20000)
S = slot_at(r, col_of(120), th); top = S['top']
inside = np.arange(col_of(101), col_of(139)); assert np.abs(top[inside] - th).max() < 0.03, ('plateau top not flat/right', np.abs(top[inside] - th).max())
assert top.max() <= th + 0.03, ('spike above the plateau', top.max() - th)
for side in (-1, 1):
x0 = col_of(100) if side < 0 else col_of(140)
n = int(taper_len(max(th - S['lo'][col_of(120)], 0.4))); seg = np.array([top[(x0 + side * j) % W] for j in range(1, n)])
assert (np.diff(seg) <= 1e-9).all(), ('taper is not monotone away from the plateau', side, np.diff(seg).max())
assert seg[-1] < seg[0] - 0.3, 'taper does not die away'
assert S['wt'][(x0 + side * (n + 3)) % W] == 0, 'the layer is still drawn far outside the plateau'
j = np.abs(np.diff(top, append=top[0])); bad = [(x, round(float(j[x]), 3)) for x in active_pairs(S) if j[x] > jump_bound(S, x)]; assert not bad, ('column jump above the bound', bad[:5])
drop = th - S['lo'][col_of(120)]; width = int(((S['wt'] > 0) & (S['wt'] < 1))[col_of(140):col_of(140) + 90].sum()); assert drop > 1.5 and width >= 0.9 * min(72, 30 * drop), ('a tall end must fall over ~30 columns per degree of drop up to 72 (absolute, not the constant) (its drop is %.2f deg)' % drop, width)
def test_ridge_whose_two_ends_differ_does_not_borrow_the_far_end():
"""Plateau az 100-140 whose height climbs 600 -> 1200 m with azimuth. Right answer: left of the left end nothing is higher than the left end's own top, right of the right end
nothing is higher than the right end's top (the round-1 bug held the END value on both sides: a 0.9 deg step on the low side)."""
hfun = lambda dk, az: np.where(in_arc(az, 100, 140) & (dk >= 20000) & (dk < 24000), 600.0 + 600.0 * np.clip((az - 100.0) / 40.0, 0, 1), 0.0)
A, Hh = rays(terrain(hfun)); r = ridge.sweep(D, A, Hh); tl, tr = theta(600, 20000), theta(1200, 20000)
S = slot_at(r, col_of(120), (tl + tr) / 2); top = S['top']; xl, xr = col_of(100), col_of(140)
left = top[[(xl - j) % W for j in range(0, TAPER_MAX + 3)]]; right = top[[(xr + j) % W for j in range(0, TAPER_MAX + 3)]]
assert left.max() <= tl + 0.05, ('left of the low end rises above it', left.max() - tl)
assert right.max() <= tr + 0.05 and right[0] >= tr - 0.1, ('right end value wrong', right[:3])
assert (np.diff(left) <= 1e-9).all() and (np.diff(right) <= 1e-9).all(), 'tapers are not monotone'
def test_slot_union_only_lets_present_chains_compete():
"""Two chains in one slot: L1 present on cols 0-99 (top 0.2), L2 present on cols 200-299 (top 2.0) but its HELD value elsewhere is 0.5 > 0.2. Right answer: on cols 0-99
the slot is L1 (top 0.2, wt 1); a chain that is absent there must not win with its held value."""
def lay(c0, c1, top, held):
wt = np.zeros(W); wt[c0:c1] = 1.0; tp = np.full(W, held); tp[c0:c1] = top
return dict(top=tp, lo=np.full(W, -1.0), ph=np.full(W, 100.0), vh=np.full(W, 0.0), slope=np.full(W, 5.0), wt=wt, pd=np.full(W, 20000.0), vd=np.full(W, 19000.0), hd=np.full((ridge.NH, W), 19500.0), hh=np.full((ridge.NH, W), 50.0), dist=20000.0)
S = ridge.to_slots([lay(0, 100, 0.2, -1.0), lay(200, 300, 2.0, 0.5)])
assert len(S) == 1 and (S[0]['wt'][0:100] == 1).all() and np.allclose(S[0]['top'][0:100], 0.2), ('absent chain won the slot union', S[0]['top'][:3], S[0]['wt'][:3])
assert (S[0]['wt'][200:300] == 1).all() and np.allclose(S[0]['top'][200:300], 2.0)
def S_ok(S, i): return S['wt'][i] > 0 and S['wt'][(i + 1) % W] > 0
def test_step_cliff_is_one_step_and_levels_are_right():
"""Two plateaus side by side, 700 m (az 60-180) then 1300 m (180-300). Right answer: level theta_A left, theta_B right, one step at az 180 (col 3200)."""
A, Hh = rays(terrain(block(60, 180, 20000, 24000, 700), block(180, 300, 20000, 24000, 1300))); r = ridge.sweep(D, A, Hh)
tA, tB = theta(700, 20000), theta(1300, 20000); x = col_of(180)
SA = slot_at(r, col_of(120), tA); top = SA['top']
assert np.abs(top[col_of(62):x - TAPER_MAX - 2] - tA).max() < 0.03, 'level A wrong'
assert np.abs(top[x + 2:col_of(298)] - tB).max() < 0.03, 'level B wrong'
assert top.max() <= tB + 0.03, 'spike above the higher plateau'
j = np.abs(np.diff(top)); ends = (col_of(60), col_of(300)); big = [i for i in np.where(j > 0.2)[0] if S_ok(SA, i) and not (x - TAPER_MAX - 2 <= i <= x + 2) and min(abs(i - e) for e in ends) > TAPER_MAX + 2]
assert not big, ('a jump away from the step and the two outer ends', big[:6])
assert (top[x - TAPER_MAX - 2:x + 3].max() - tA) <= (tB - tA) + 0.03
def test_single_peak_has_one_maximum():
"""Gaussian peak 1800 m at az 90, 30 km, sigma 1.5 km. Right answer: one maximum at az 90 +-0.2, monotone either side inside the chain, no secondary bump."""
def peak(dk, az):
lat = dk * np.sin(np.radians(az - 90.0)); return 1800.0 * np.exp(-(lat ** 2 + (dk - 30000.0) ** 2) / (2 * 1500.0 ** 2))
A, Hh = rays(terrain(peak)); r = ridge.sweep(D, A, Hh); top_peak = theta(1800, 30000)
S = max(r['slots'], key=lambda S: S['top'][col_of(90)]); top = S['top']
xm = int(np.argmax(top[col_of(60):col_of(120)])) + col_of(60); assert abs(az_of(xm) - 90.0) < 0.25, ('maximum at', az_of(xm))
assert abs(top[xm] - top_peak) < 0.1, (top[xm], top_peak)
seg = top[col_of(60):col_of(120)]; peaks = [i for i in range(1, len(seg) - 1) if seg[i] >= seg[i - 1] and seg[i] > seg[i + 1] and (seg[i] - min(seg[max(0, i - 30):i + 30])) > 0.01]
assert len(peaks) == 1, ('secondary local maxima', len(peaks))
def test_wraparound_ridge_across_north_is_seamless_and_rotation_invariant():
"""Plateau az 350 -> 10 (across 0/360). Right answer: flat top, no step across the seam, one chain crossing it, and the result does not depend on where column 0 is."""
A, Hh = rays(terrain(block(350, 10, 20000, 24000, 900))); r = ridge.sweep(D, A, Hh); th = theta(900, 20000)
S = slot_at(r, 0, th); top = S['top']
assert abs(top[W - 1] - top[0]) < 0.003, ('seam step', top[W - 1] - top[0])
assert np.abs(top[[col_of(351), col_of(355), W - 1, 0, col_of(5), col_of(9)]] - th).max() < 0.03
near20 = [l for l in r['keep'] if abs(math.log(l['dist'] / 20000.0)) < 0.3]
assert len(near20) == 1 and near20[0]['x0'] + near20[0]['span'] > W, ('the 20 km plateau must be ONE chain crossing the seam', [(l['x0'], l['span']) for l in near20])
R = 1600; r2 = ridge.sweep(D, np.roll(A, -R, axis=1), np.roll(Hh, -R, axis=1))
for S1 in r['slots']:
S2 = next(s for s in r2['slots'] if s['slot'] == S1['slot']); d = np.abs(np.roll(S2['top'], R) - S1['top']).max(); assert d < 1e-9, ('not rotation invariant', S1['slot'], d)
def test_vienna_skyline_has_no_invented_jump_and_seam_is_seamless():
"""Real bake: no per-column step above the stated bound. In a chain (wt == 1) a step above 0.12 deg is allowed only if both columns carry the raw span peak that wins there (a real step of the DEM, e.g. a roof edge); in a taper the
steepest allowed step is 1.6 x (top-lo)/TAPER + 0.02. The envelope across the seam must not jump."""
saved = ridge.P
ridge.configure(ridge.load_preset('vienna')); d, A, Hh, _ = ridge.stage0(False) # cached under the key of its own inputs (computed once if absent)
ridge.P = dict(id='vienna', rmax_km=95); r = ridge.sweep(d, A, Hh); ridge.P = saved
worst = []; cols = r['cols']
real = lambda x, top: any(abs(s[0] - top) < 1e-4 for s in cols[x % W]) # the top at x is an actual raw span peak: a step between two such columns is a step of the DEM
for S in r['slots']:
j = np.abs(np.diff(S['top'], append=S['top'][0]))
for x in active_pairs(S):
bound = jump_bound(S, x) if min(S['wt'][x], S['wt'][(x + 1) % W]) < 1 else 0.12
if j[x] > bound and not (S['wt'][x] == 1 and S['wt'][(x + 1) % W] == 1 and real(x, S['top'][x]) and real(x + 1, S['top'][(x + 1) % W])):
worst.append((S['slot'], x, round(float(j[x]), 3), round(float(bound), 3), round(float(S['wt'][x]), 2)))
assert not worst, ('Vienna jumps above the bound', worst[:6])
sky = np.max([S['top'] for S in r['slots']], axis=0); assert abs(sky[W - 1] - sky[0]) < 0.05, ('envelope jumps across the seam', sky[W - 1] - sky[0])
for S in r['slots']:
if S['wt'][W - 1] > 0 and S['wt'][0] > 0: assert abs(S['top'][W - 1] - S['top'][0]) < 0.05, ('layer jumps across the seam', S['slot'])
def _shadow_fixture():
"""flat 100 m terrain with one 1000 m wall at lat 48.45-48.46 (5.6-6.7 km north of the sample point), sample point lat 48.40 lon 16.5 at 103 m"""
m = np.full((3600, 3600), 100.0, np.float32); y0 = int((49 - 48.46) * 3600); y1 = int((49 - 48.45) * 3600); m[y0:y1, :] = 1000.0
ridge.P = dict(id='syn', lat=48.40, lon=16.5, rmax_km=60); ridge._mos[('syn', ridge.mosaic_key(ridge.P))] = (m, 49, 16)
return [dict(spts=dict(lat=np.full((3, W), 48.40), lon=np.full((3, W), 16.5), h=np.full((3, W), 103.0)))]
def test_cast_shadow_follows_the_sun_ray_over_the_dem():
"""Right answer: sun due north at 5 deg: the ray is 580 m at the wall, the wall is 1000 m => fully shadowed (1.0). Sun due north at 30 deg clears the wall (0.0). Sun due south: the wall is behind the sun (0.0).
Sun at 0.2 deg: no direct light, no shadow (0.0)."""
L = _shadow_fixture(); f = lambda az, el: float(ridge.cast_shadows(L, az, el)[0].mean())
assert f(0.0, 5.0) > 0.99, ('wall does not shadow a low sun behind it', f(0.0, 5.0))
assert f(0.0, 30.0) < 0.01, ('high sun clears the wall', f(0.0, 30.0))
assert f(180.0, 5.0) < 0.01, ('wall casts a shadow toward the sun', f(180.0, 5.0))
assert f(0.0, 0.2) == 0.0
def test_cast_shadow_east_west_and_longitude_scale():
"""Wall of 1000 m at lon 16.575-16.585 (5.5-6.2 km EAST of the sample point at lat 48.4, cos(lat) matters), flat 100 m elsewhere. Sun due east at 5 deg: shadowed (580 m ray vs 1000 m).
Sun due west: clear. Without the cos(lat) factor the wall would sit at 8.3 km and a 6 deg ray (980 m) would barely touch it, so the fully-shadowed assertion at 6 deg pins the scale."""
m = np.full((3600, 3600), 100.0, np.float32); x0 = int((16.575 - 16) * 3600); x1 = int((16.585 - 16) * 3600); m[:, x0:x1] = 1000.0
ridge.P = dict(id='syn2', lat=48.40, lon=16.5, rmax_km=60); ridge._mos[('syn2', ridge.mosaic_key(ridge.P))] = (m, 49, 16)
L = [dict(spts=dict(lat=np.full((3, W), 48.40), lon=np.full((3, W), 16.5), h=np.full((3, W), 103.0)))]; f = lambda az, el: float(ridge.cast_shadows(L, az, el)[0].mean())
assert f(90.0, 5.0) > 0.99, ('east wall does not shadow a low east sun', f(90.0, 5.0))
assert f(270.0, 5.0) < 0.01, ('east wall shadows a west sun', f(270.0, 5.0))
assert f(90.0, 6.0) > 0.99 and f(90.0, 12.0) < 0.01, ('east-wall shadow edge is at the wrong elevation (wall is 5.5 km east of the point: the sun ray at 6 deg is 660 m there, at 12 deg 1.2 km)', f(90.0, 6.0), f(90.0, 12.0))
def test_shadow_darkens_the_face_it_covers():
"""Whole pipeline on a synthetic ramp (slope 0.35, lit by the relief light): with the shadow march forced to 1 every face pixel is darker than with it forced to 0 (the shadow removes direct sun); forced 0 equals shadows off."""
A, Hh = rays(terrain(lambda dk, az: np.where(in_arc(az, 100, 140) & (dk >= 20000) & (dk < 24000), 50.0 + 0.35 * (dk - 20000), 0.0))); ridge.P = dict(id='synthetic', rmax_km=60, lat=48.0, lon=16.0, floor_agl_m=30.0, s_ref_deg=8.0, win0=(col_of(120) - 640) % W)
r = ridge.sweep(D, A, Hh); ridge.set_view(r['slots']); L = ridge.bake(r['slots']); pf = ridge.statics(); real = ridge.cast_shadows
try:
ridge.cast_shadows = lambda layers, az, el: [np.ones((3, W)) for _ in layers]; dark = ridge.relight(L, 300.0, 30.0, *pf)
ridge.cast_shadows = lambda layers, az, el: [np.zeros((3, W)) for _ in layers]; lit = ridge.relight(L, 300.0, 30.0, *pf)
finally: ridge.cast_shadows = real
off = ridge.relight(L, 300.0, 30.0, *pf, shadows=False); c = slice(col_of(105), col_of(135)); rows = slice(0, ridge.H); Ly = max(L, key=lambda l: ((l['m'][rows, c] > 0.99) & (l['w'][rows, c] < 0.05)).sum()); m = (Ly['m'][rows, c] > 0.99) & (Ly['w'][rows, c] < 0.05) # body pixels (not the mist foot) of the layer that owns the plateau
assert m.any(), 'no solid face pixels to compare'
assert dark[rows, c][m].mean() < lit[rows, c][m].mean() - 0.02, ('shadow does not darken the face', dark[rows, c][m].mean(), lit[rows, c][m].mean())
assert np.abs(lit - off).max() < 1e-4, 'a zero shadow differs from shadows off'
# ---------------------------------------------------------------------------------------- shading fixtures (round 3): the face history -> per-pixel normal
def _bake_view(hfun, az0):
A, Hh = rays(terrain(hfun)); ridge.P = dict(id='synthetic', rmax_km=60, lat=48.0, lon=16.0, floor_agl_m=30.0, s_ref_deg=8.0, win0=(col_of(az0) - 640) % W)
r = ridge.sweep(D, A, Hh); ridge.set_view(r['slots']); return r, ridge.bake(r['slots'])
def _owner(r, L, col, ang):
S = slot_at(r, col, ang); return S, next(Ly for Ly in L if Ly['dist'] == S['dist'])
CONE = dict(Dc=20000.0, Rb=6000.0, Hc=1800.0, az0=90.0)
def _cone(dk, az):
E = dk * np.sin(np.radians(az)) - CONE['Dc'] * math.sin(math.radians(CONE['az0'])); N = dk * np.cos(np.radians(az)) - CONE['Dc'] * math.cos(math.radians(CONE['az0']))
return np.where(np.hypot(E, N) < CONE['Rb'], CONE['Hc'] * (1 - np.hypot(E, N) / CONE['Rb']), 0.0)
def _cone_pixels(sun):
"""(analytic n.L, baked n.L) at pixels of the cone layer: the analytic one marches the ray finely to the first sample whose running-max angle reaches the pixel's elevation and takes the cone's own normal there."""
r, L = _bake_view(_cone, CONE['az0']); S, Ly = _owner(r, L, col_of(CONE['az0']), theta(CONE['Hc'], CONE['Dc'])); nd, _ = ridge.ndl_field(Ly, sun); dd = np.arange(500.0, 60000.0, 4.0); m = CONE['Hc'] / CONE['Rb']; out = []
for x in range(300, 1000, 7):
c = (ridge.P['win0'] + x) % W
if S['wt'][c] < 1: continue
az = (c + 0.5) / W * 360.0; h = _cone(dd, np.full_like(dd, az)); ang = np.degrees(np.arctan2(h - EYE - dd * dd / (2 * ridge.R_EARTH) * (1 - ridge.KREF), dd)); rm = np.maximum.accumulate(ang)
for f in (0.6, 0.7, 0.8, 0.9, 0.95):
row = int(round((ridge.TOP_DEG - (Ly['lo'][c] + f * (Ly['ang'][c] - Ly['lo'][c]))) * ridge.PXDEG_V - 0.5)); d = dd[min(np.searchsorted(rm, ridge.rowang[row]), len(dd) - 1)]
E = d * math.sin(math.radians(az)) - CONE['Dc'] * math.sin(math.radians(CONE['az0'])); N = d * math.cos(math.radians(az)) - CONE['Dc'] * math.cos(math.radians(CONE['az0'])); rr = math.hypot(E, N)
if rr >= 0.85 * CONE['Rb']: continue # on the cone proper, away from the foot kink (the +-2 node slope window rounds the kink)
n = np.array([m * E / rr, m * N / rr, 1.0]); n /= np.linalg.norm(n); out.append((float(n @ sun), float(nd[row, c])))
return np.array(out), Ly, nd
def test_cone_is_shaded_per_pixel_with_the_analytic_normal():
"""Cone (apex 1800 m, base radius 6 km, 20 km away), sun from the west at 20 deg. Right answer: the shading of each pixel is the cone's own n.L at the point that pixel sees, so it changes down every
column (the radial direction turns as the ray climbs) and across the face; the round-2 baker stored ONE slope per peak and gave every pixel of a column the same value (within-column std 0)."""
sun = ridge.sun_vec(250.0, 20.0); v, Ly, nd = _cone_pixels(sun); assert len(v) > 100, len(v)
err = np.abs(v[:, 0] - v[:, 1]); assert np.median(err) < 0.05 and err.mean() < 0.07, ('baked n.L is not the analytic one', np.median(err), err.mean())
assert np.ptp(v[:, 1]) > 0.8 * np.ptp(v[:, 0]), ('baked shading range is compressed', np.ptp(v[:, 1]), np.ptp(v[:, 0]))
cs = [nd[int((ridge.TOP_DEG - Ly['ang'][c]) * ridge.PXDEG_V) + 6:int((ridge.TOP_DEG - Ly['lo'][c]) * ridge.PXDEG_V) - 6, c].std() for c in (ridge.P['win0'] + np.arange(400, 900, 20)) % W]
assert np.mean(cs) > 0.03, ('shading is constant down a column', np.mean(cs))
def test_plane_face_has_the_planes_slope_and_no_lateral_tilt():
"""Planar ramp facing the viewer, az 60-120, rising 0.35 per metre of distance from 20 km to 24 km, then a drop. Right answer: every face pixel's front slope is 0.35 (19.3 deg) and its lateral tilt is 0,
whatever its row (one slope per peak could not tell a plane from a curved face, only the history can)."""
ramp = lambda dk, az: np.where(in_arc(az, 60, 120) & (dk >= 20000) & (dk < 24000), 50.0 + 0.35 * (dk - 20000), 0.0)
r, L = _bake_view(ramp, 90.0); S, Ly = _owner(r, L, col_of(90), theta(50.0 + 0.35 * 4000, 24000)); cols = (ridge.P['win0'] + np.arange(560, 720)) % W
rows = np.arange(int((ridge.TOP_DEG - Ly['ang'][col_of(90)]) * ridge.PXDEG_V) + 8, int((ridge.TOP_DEG - 1.0) * ridge.PXDEG_V)); sl = Ly['sl'][np.ix_(rows, cols)]; la = Ly['la'][np.ix_(rows, cols)]
assert len(rows) > 20 and abs(np.median(sl) - 0.35) < 0.03 and np.percentile(np.abs(sl - 0.35), 90) < 0.08, ('front slope is not the plane\'s', np.median(sl), np.percentile(np.abs(sl - 0.35), 90))
assert np.abs(la).max() < 0.08, ('lateral tilt on a plane', np.abs(la).max())
def test_ridge_step_tilts_the_face_only_at_the_step():
"""Two plateaus (700 m / 1300 m) meeting at az 180. Right answer: the face is level laterally (la ~ 0) away from the step, and strongly tilted at it (the height changes by 600 m between two neighbouring columns)."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 60, 180) & (dk >= 20000) & (dk < 24000), 700.0, np.where(in_arc(az, 180, 300) & (dk >= 20000) & (dk < 24000), 1300.0, 0.0)), 180.0)
S, Ly = _owner(r, L, col_of(120), theta(700, 20000)); cols = lambda a, b: (ridge.P['win0'] + np.arange(a, b)) % W; rows = slice(int((ridge.TOP_DEG - theta(1300, 20000)) * ridge.PXDEG_V), int((ridge.TOP_DEG - 0.3) * ridge.PXDEG_V))
far = np.abs(Ly['la'][rows, :][:, cols(200, 500)]); assert far.max() < 0.05, ('lateral tilt away from the step', far.max())
near = Ly['la'][rows, :][:, cols(620, 660)]; assert np.abs(near).max() > 0.2, ('no tilt at the step', np.abs(near).max())
def test_roof_height_bump_in_the_foreground_is_not_a_ridge():
"""Flat ground with a 19 m x 40 m block 700 m away (a roof / tree in a DSM). Right answer: no layer: a peak needs PROM_M (25 m) of height over its valley, and the 4 km NEAR_CAP shoulder rule obeys the same
rule (round 2 committed the shoulder with no prominence test: an arch 66 columns wide stood in the foreground). A 60 m block IS a ridge."""
bump = lambda h: (lambda dk, az: np.where(in_arc(az, 88, 92) & (dk >= 700) & (dk < 740), GROUND + h, 0.0))
A, Hh = rays(terrain(bump(19.0))); r = ridge.sweep(D, A, Hh); assert not [l for l in r['keep'] if l['dist'] < 4000], ('a 19 m bump became a ridge', [(l['x0'], l['span'], round(l['dist'])) for l in r['keep']])
A, Hh = rays(terrain(bump(60.0))); r = ridge.sweep(D, A, Hh); assert [l for l in r['keep'] if l['dist'] < 1000], 'a 60 m block must be a ridge'
def test_contour_lines_are_never_denser_than_9_px_over_most_of_the_face():
"""Right answer (cone): the iso-height lines drawn on a layer are at least CONTOUR_MIN_PX apart over three quarters of its face (round 2 picked the interval from the SHALLOWEST columns, so the steep centre
of the mountain carried a line every 2-3 px: the fine horizontal banding)."""
r, L = _bake_view(_cone, CONE['az0']); S, Ly = _owner(r, L, col_of(CONE['az0']), theta(CONE['Hc'], CONE['Dc'])); sp = []
for c in (ridge.P['win0'] + np.arange(450, 850, 10)) % W:
r0, r1 = int((ridge.TOP_DEG - Ly['ang'][c]) * ridge.PXDEG_V) + 4, int((ridge.TOP_DEG - Ly['lo'][c]) * ridge.PXDEG_V) - 4; line = np.where(Ly['dpx'][r0:r1, c] < 0.5)[0]
if len(line) > 1: g = np.diff(line); sp += list(g[g > 1])
assert len(sp) > 20 and np.percentile(sp, 25) >= 8, ('contour lines too dense', np.percentile(sp, 25), len(sp))
def test_no_layer_paints_a_wall_down_the_frame():
"""Right answer: a layer's alpha is 0 further below its own crest than its foot allows (<= 210 px): its column boundary leaves no vertical edge through the floor (round 2 painted the body to the bottom of the
frame wherever the chain existed: hard walls below every chain end)."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 100, 140) & (dk >= 20000) & (dk < 24000), 900.0, 0.0), 120.0)
for Ly in L: below = np.arange(ridge.H)[:, None] - (ridge.TOP_DEG - Ly['ang'])[None, :] * ridge.PXDEG_V; assert Ly['a'][below > 215].max() == 0, ('layer painted below its foot', Ly['rank'])
S = max(r['slots'], key=lambda S: S['top'][col_of(120)])
for Ly in L:
if Ly['dist'] != S['dist']: continue
end = [c for c in range(W) if 0 < S['wt'][c] < 0.12]; assert end, 'fixture has no taper end'
bad = [(c, int((Ly['a'][:, c] > 0.1).sum())) for c in end if (Ly['a'][:, c] > 0.1).sum() > 0.85 * max(Ly['ang'][c] - Ly['lo'][c], 0) * ridge.PXDEG_V + 4]; assert not bad, ('a chain end hangs a curtain thicker than the ridge is tall', bad[:4])
def test_slot_is_rotation_invariant_in_columns_where_no_chain_is_present():
"""Two plateaus in one distance slot (az 100-110 at 700 m, az 200-215 at 1100 m, both 20-24 km). Right answer: rotating the ring by 1600 columns changes nothing, in EVERY column of the slot including those where no chain is present
(round 3 first picked the first chain in list order there; list order depends on where column 0 is, and those values feed the blurs at every chain end: Half Dome's rotation test went from 0 to 97 px)."""
A, Hh = rays(terrain(block(100, 110, 20000, 24000, 700), block(200, 215, 20000, 24000, 1100))); r = ridge.sweep(D, A, Hh); R = 2800; r2 = ridge.sweep(D, np.roll(A, -R, axis=1), np.roll(Hh, -R, axis=1)) # 2800 columns carries the az 200-215 block through column 0: the chains swap places in list order
for S1 in r['slots']:
S2 = next(s for s in r2['slots'] if s['slot'] == S1['slot'])
for k in ('top', 'lo', 'wt', 'pd', 'ph', 'vh', 'slope'): assert np.abs(np.roll(S2[k], R) - S1[k]).max() < 1e-9, ('slot not rotation invariant', S1['slot'], k, np.abs(np.roll(S2[k], R) - S1[k]).max())
for k in ('hd', 'hh'): assert np.abs(np.roll(S2[k], R, axis=1) - S1[k]).max() < 1e-6, ('slot history not rotation invariant', S1['slot'], k)
def test_prominent_far_ridge_behind_a_basin_is_found():
"""Terrace (50 m, eye 100 m) ending at 10 km, a 0 m basin, a 60 m ridge at 30 km (az 80-100). Right answer: the ridge is a layer at 30 km: it stands 0.5 deg above its visible valley, which is 4 times the 25 m / 30 km bar of 0.048 deg.
(Round 3's first cut compared raw heights, ridge 60 m vs the valley's 0 m... and lost ridges whose valley sample is near and high.)"""
hf = lambda dk, az: np.where(dk < 10000, 50.0, np.where(in_arc(az, 80, 100) & (dk >= 30000) & (dk < 30500), 60.0, np.where(in_arc(az, 80, 100) & (dk >= 50000) & (dk < 55000), 300.0, 0.0))) # the 300 m wall at 50 km keeps the ridge from being committed as the ray's last peak
A, Hh = rays(hf); r = ridge.sweep(D, A, Hh); far = [l for l in r['keep'] if abs(l['dist'] - 30000) < 1500]; assert far and far[0]['span'] > 200, ('the 30 km ridge is missing', [(l['x0'], l['span'], round(l['dist'])) for l in r['keep']])
def test_lone_foreground_stub_is_kept_but_a_stub_inside_a_near_ridge_is_not():
"""(a) a 0.5 deg wide, 60 m block at 1.7 km with nothing else near: the nearest layer must cover it (a hole would show the far ridge's body). (b) the same stub in front of a long near ridge (az 100-160, 150 m, 1.5 km):
its columns are covered by that ridge, so it is dropped (round 2 kept every foreground stub: lone arches)."""
A, Hh = rays(terrain(block(90, 90.5, 1700, 1740, 110))); r = ridge.sweep(D, A, Hh); assert [l for l in r['keep'] if l['dist'] < 2500], 'lone foreground stub dropped: hole in the nearest layer'
A, Hh = rays(terrain(block(100, 160, 1500, 1600, 150), block(129, 129.5, 600, 640, 160))); r = ridge.sweep(D, A, Hh); assert not [l for l in r['keep'] if l['dist'] < 1000], ('a stub inside a near ridge became an arch', [(l['x0'], l['span'], round(l['dist'])) for l in r['keep']])
def test_tilted_plane_has_the_planes_front_slope_and_lateral_tilt():
"""Plane h = 50 + 0.3 (E - 20000) - 0.2 N over az 85-95, 20-24 km, then a drop. At az 90 the radial is +E and the tangent is -N, so n ~ (-0.3 r - la t, 1) with la = -(dh/dN) = +0.2. Right answer: front slope 0.3, lateral tilt 0.2, each within 0.04
(a lateral scale of 2x, or no tilt, fails)."""
def plane(dk, az):
E = dk * np.sin(np.radians(az)); N = dk * np.cos(np.radians(az)); return np.where(in_arc(az, 85, 95) & (dk >= 20000) & (dk < 24000), 50.0 + 0.3 * (E - 20000.0) - 0.2 * N, 0.0)
r, L = _bake_view(plane, 90.0); S, Ly = _owner(r, L, col_of(90), theta(50.0 + 0.3 * 4000, 24000)); cols = (ridge.P['win0'] + np.arange(600, 680)) % W
rows = np.arange(int((ridge.TOP_DEG - Ly['ang'][col_of(90)]) * ridge.PXDEG_V) + 8, int((ridge.TOP_DEG - 1.0) * ridge.PXDEG_V)); sl = Ly['sl'][np.ix_(rows, cols)]; la = Ly['la'][np.ix_(rows, cols)]
assert len(rows) > 15 and abs(np.median(sl) - 0.3) < 0.04 and abs(np.median(la) - 0.2) < 0.04, ('plane slope / tilt wrong', np.median(sl), np.median(la))
def test_history_keeps_only_what_the_eye_sees():
"""Samples (angle, distance, height): (0, 100, 0) (2, 200, 10) (1, 300, 5) (1.5, 350, 8) (3, 400, 30). The third and fourth are hidden behind the second (the fourth RISES from the third, so only a running maximum drops it). Right answer: at elevation 2.5 the face is half way between the second and the fourth sample: distance 300, height 20
(without the running maximum the non-monotone angles make the interpolation garbage)."""
d, h = ridge.strip_history([0.0, 2.0, 1.0, 1.5, 3.0], [100.0, 200.0, 300.0, 350.0, 400.0], [0.0, 10.0, 5.0, 8.0, 30.0], 0, 4); t = np.linspace(0, 3.0, ridge.NH); k = int(np.argmin(np.abs(t - 2.5)))
assert abs(d[k] - (200 + 200 * (t[k] - 2) / 1.0)) < 1e-6 and abs(h[k] - (10 + 20 * (t[k] - 2) / 1.0)) < 1e-6 and d[0] == 100 and d[-1] == 400, (d[k], h[k])
def test_no_lateral_tilt_across_an_occlusion_edge():
"""Block A (az 60-130, 15 km out, 700 m) and block B (az 110-180, 21 km out, 940 m): the same top angle, the same distance slot, so the slot owner switches where their tapers cross. Right answer: at every column where the owner's
distance jumps by more than 2 km the two sides are not one surface, so the lateral tilt there is 0 (it saturated at the 1.5 clamp over ~8 columns on Matterhorn)."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 60, 130) & (dk >= 15000) & (dk < 19000), 700.0, np.where(in_arc(az, 110, 180) & (dk >= 21000) & (dk < 25000), 940.0, 0.0)), 120.0)
S, Ly = _owner(r, L, col_of(80), theta(700, 15000)); assert S['dist'] == ridge.KNOTS[3]
sw = [x for x in range(W - 1) if S['wt'][x] > 0 and S['wt'][x + 1] > 0 and abs(S['pd'][x + 1] - S['pd'][x]) > 2000]; assert sw, 'fixture has no owner switch'
for x in sw:
rows = np.arange(max(int((ridge.TOP_DEG - Ly['ang'][x]) * ridge.PXDEG_V) + 4, 0), min(int((ridge.TOP_DEG - Ly['lo'][x]) * ridge.PXDEG_V) - 4, ridge.H)); la = Ly['la'][np.ix_(rows, [x - 1, x, x + 1, x + 2])]
assert np.abs(la).max() < 0.5, ('tilt across an occlusion edge at column', x, np.abs(la).max())
# ---------------------------------------------------------------------------------------- relief light (round 3): n.L uses an authored light, colour / haze / shadows keep the real sun
def _gully(dk, az):
"""A ramp facing the viewer (0.35 slope, az 50-130, 20-24 km) cut by gullies that run down the slope: height +300 m sin(2 pi N / 3 km), so the lateral tilt swings between -0.63 and +0.63 across the face."""
N = dk * np.cos(np.radians(az)); return np.where(in_arc(az, 50, 130) & (dk >= 20000) & (dk < 24000), 50.0 + 0.35 * (dk - 20000) + 300.0 * np.sin(2 * np.pi * N / 3000.0), 0.0)
def _relief_probe(az_s, el_s):
"""Relight the gullied ramp seen from az 90 with spies on ndl_field (the L it shades with and the n.L it returns for the ramp's layer) and on cast_shadows (the sun it marches toward). Returns (image, Ls, n.L of the ramp layer, shadow suns, layer)."""
r, L = _bake_view(_gully, 90.0); pf = ridge.statics(); S = max(r['slots'], key=lambda S: S['top'][col_of(90)]); Ly = next(l for l in L if l['dist'] == S['dist']); real_nd, real_cs = ridge.ndl_field, ridge.cast_shadows; Ls, nds, suns = [], [], []
def nd_spy(layer, Lv): out = real_nd(layer, Lv); Ls.append(np.array(Lv)); nds.append((layer is Ly, out[0])); return out
def cs_spy(layers, az, el): suns.append((az, el)); return [np.zeros((3, W)) for _ in layers]
ridge.ndl_field, ridge.cast_shadows = nd_spy, cs_spy
try: img = ridge.relight(L, az_s, el_s, *pf)
finally: ridge.ndl_field, ridge.cast_shadows = real_nd, real_cs
return img, Ls, next(n for own, n in nds if own), suns, Ly
def _face_std(nd, Ly):
"""n.L std over the ramp's face pixels (6 px under the crest down to 1 deg elevation), columns 500-780 of the window"""
return float(np.concatenate([nd[int((ridge.TOP_DEG - Ly['ang'][c]) * ridge.PXDEG_V) + 6:int((ridge.TOP_DEG - 1.0) * ridge.PXDEG_V), c] for c in (ridge.P['win0'] + np.arange(500, 780, 5)) % W]).std())
def test_sun_behind_the_viewer_still_models_the_face():
"""Gullied ramp seen from az 90, sun directly behind the viewer (az 270, 20 deg up). Lit head-on, a gully's two flanks shade alike (n.L std over the face 0.034 with the real sun as the shading light);
the relief light 45 deg off the axis lights one flank and leaves the other dim (0.23). Right answer: std over the face pixels > 0.12."""
img, Ls, nd, suns, Ly = _relief_probe(270.0, 20.0); b = _face_std(nd, Ly); assert b > 0.12, ('face is flat with the sun behind the viewer', b)
def test_relief_light_is_45_deg_off_the_view_axis_on_the_suns_side():
"""View centre az 90 (the viewer looks east). The relief light is the view centre +/- 45 deg on the side of the view axis the real sun is on. Sun at az 300 (north of the axis, the viewer's left) -> relief az 90-45 = 45;
sun at az 240 (south, the viewer's right) -> relief az 90+45 = 135. Elevation is 25..40 deg (an absolute range, not the constant) both times, whatever the sun's elevation."""
for sun_az, want in ((300.0, 45.0), (240.0, 135.0)):
_, Ls, _, _, _ = _relief_probe(sun_az, 25.0); assert Ls, 'no shading call'; L = Ls[0]; az = math.degrees(math.atan2(L[0], L[1])) % 360.0; el = math.degrees(math.asin(L[2]))
assert abs(az - want) < 0.5 and 25.0 <= el <= 40.0, ('relief direction wrong', sun_az, az, el)
def test_sun_elevation_changes_colour_but_not_the_relief_direction():
"""Same sun azimuth, elevation 10 deg vs 40 deg: the relief direction is identical, the picture is not (sun colour / haze / strength change), and at -10 deg (night) the face is darker than at 40."""
i1, L1, nd1, _, Ly = _relief_probe(300.0, 10.0); i2, L2, nd2, _, _ = _relief_probe(300.0, 40.0); i3, _, _, _, _ = _relief_probe(300.0, -10.0)
assert np.abs(L1[0] - L2[0]).max() < 1e-12 and np.abs(nd1 - nd2).max() < 1e-12, 'the relief direction follows the sun elevation'
c = (ridge.P['win0'] + 640) % W; rows = slice(int((ridge.TOP_DEG - Ly['ang'][c]) * ridge.PXDEG_V) + 8, int((ridge.TOP_DEG - Ly['ang'][c]) * ridge.PXDEG_V) + 40)
assert np.abs(i1[rows, 640] - i2[rows, 640]).mean() > 0.01, 'colour does not follow the real sun'; assert i3[rows, 640].mean() < 0.6 * i2[rows, 640].mean(), ('night is not dark', i3[rows, 640].mean(), i2[rows, 640].mean())
def test_cast_shadows_march_toward_the_real_sun_not_the_relief_light():
"""relight must hand cast_shadows the real sun's azimuth and elevation, not the relief light's."""
_, _, _, suns, _ = _relief_probe(300.0, 17.0); assert suns == [(300.0, 17.0)], suns
# ---------------------------------------------------------------------------------------- Soul round-3 survivors
def test_floor_band_has_no_column_wise_luminance_step():
"""Plateau az 100-140 (20-24 km) seen from az 120. Right answer: in the floor band (the frame's bottom 80 rows) no column differs from its neighbour by more than the grain (baseline 0.009, a painted wall 0.25): the compositor must use the layer's
alpha (body dissolved at the foot), not its mask (body to the bottom of the frame, a wall at every chain end)."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 100, 140) & (dk >= 20000) & (dk < 24000), 900.0, 0.0), 120.0); img = ridge.relight(L, 200.0, 20.0, *ridge.statics(), shadows=False)
lum = img @ np.array([0.2126, 0.7152, 0.0722]); st = np.abs(np.diff(lum[ridge.H - 80:], axis=1)).mean(0); assert st.max() < 0.03, ('wall: column-wise luminance step in the floor band', st.max(), int(np.argmax(st)))
def test_foot_fade_starts_at_60_percent_of_the_foot_and_the_body_is_opaque_above_it():
"""A layer's alpha is 1 down to 60% of its foot length, then smoothsteps to 0 at the foot. Right answer on a plateau column: rows with alpha > 0.99 / rows with alpha > 0.001 = 0.6 (+-0.04), and it has the full 210 px foot at most
(a fade that starts early makes the face translucent, one that starts late leaves a wall)."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 100, 140) & (dk >= 20000) & (dk < 24000), 900.0, 0.0), 120.0); S, Ly = _owner(r, L, col_of(120), theta(900, 20000)); a = Ly['a'][:, col_of(120)]
full, nz = int((a > 0.99).sum()), int((a > 0.001).sum()); assert nz > 100, nz; assert abs(full / nz - 0.6) < 0.04, ('fade does not start at 60% of the foot', full, nz)
def test_lateral_tilt_is_smoothed_across_columns():
"""Two plateaus (700 / 1300 m) meeting at az 180: the raw lateral tilt is a spike at the step. Right answer: the baked tilt is blurred over a few columns: no column-to-column change above 0.5 (unblurred: 0.9), and the tilt is still > 0.2 at the step."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 60, 180) & (dk >= 20000) & (dk < 24000), 700.0, np.where(in_arc(az, 180, 300) & (dk >= 20000) & (dk < 24000), 1300.0, 0.0)), 180.0)
S, Ly = _owner(r, L, col_of(120), theta(700, 20000)); rows = slice(int((ridge.TOP_DEG - theta(1300, 20000)) * ridge.PXDEG_V), int((ridge.TOP_DEG - 0.3) * ridge.PXDEG_V)); la = np.abs(Ly['la'][rows, :][:, (ridge.P['win0'] + np.arange(600, 680)) % W]).max(0)
assert la.max() > 0.2 and np.abs(np.diff(la)).max() < 0.5, ('tilt not smoothed', la.max(), np.abs(np.diff(la)).max())
def test_contour_interval_is_chosen_from_full_weight_columns_only():
"""Ramp (slope 1.0, az 110-130, 20-22 km) whose tapering ends carry coarser metres-per-pixel. Right answer: the contour spacing in the core is 9-10 px (interval from the chain's own face), not 13-14 (the taper columns pulled the percentile up). median <= 12 and p25 >= 8."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 110, 130) & (dk >= 20000) & (dk < 22000), 50.0 + 1.0 * (dk - 20000), 0.0), 120.0); S, Ly = _owner(r, L, col_of(120), theta(2050, 22000)); sp = []
for c in range(col_of(120) - 60, col_of(120) + 61, 6):
r0, r1 = int((ridge.TOP_DEG - Ly['ang'][c]) * ridge.PXDEG_V) + 4, int((ridge.TOP_DEG - Ly['lo'][c]) * ridge.PXDEG_V) - 4; line = np.where(Ly['dpx'][r0:r1, c] < 0.5)[0]
if len(line) > 1: g = np.diff(line); sp += list(g[g > 1])
assert len(sp) > 100 and np.percentile(sp, 25) >= 8 and np.median(sp) <= 12, ('contour spacing', len(sp), np.percentile(sp, 25), np.median(sp))
def test_spec_highlight_follows_the_half_vector_of_light_and_viewer():
"""spec_field against an independent evaluation: half vector H = normalise(L + V), V the unit vector back to the viewer (-r) in every column, n = (-sl r - la t + z)/|.|, GGX alpha 0.3. Two different lights, random faces: the field must match to 1e-9
(a half vector that ignores the light, or any change of the lobe, shows)."""
rng = np.random.default_rng(5); sl = rng.uniform(-0.3, 1.2, (7, W)); la = rng.uniform(-0.6, 0.6, (7, W)); nrm = np.sqrt(1 + sl * sl + la * la); az = ridge.azrad(); r = np.stack([np.sin(az), np.cos(az), 0 * az], 1); t = np.stack([np.cos(az), -np.sin(az), 0 * az], 1)
for laz, lel in ((45.0, 32.0), (200.0, 15.0)):
Lv = ridge.sun_vec(laz, lel); ndl = (Lv[2] - sl * (r @ Lv)[None] - la * (t @ Lv)[None]) / nrm; got = ridge.spec_field(Lv, sl, la, nrm, ndl)
H = Lv[None, :] - r; H /= np.linalg.norm(H, axis=1, keepdims=True); nh = np.clip((H[:, 2][None] - sl * (r * H).sum(1)[None] - la * (t * H).sum(1)[None]) / nrm, 0, 1)
want = 0.30 * 0.0081 / (1 + nh * nh * (0.09 - 1)) ** 2 * np.clip(ndl, 0, 1)
assert np.abs(got - want).max() < 1e-9, ('spec does not match the half-vector model', laz, np.abs(got - want).max())
def test_fresnel_rim_is_strongest_on_faces_that_lie_away_from_the_viewer():
"""fresnel(sl, nrm) = (1 - n.V)^3 with n.V = sl / |n|: 1 for a flat or back-leaning face (sl <= 0), falling monotonically to ~0 for a face that stands up at the viewer (sl = 5: 0.00001)."""
s = np.array([-1.0, 0.0, 0.2, 0.5, 1.0, 2.0, 5.0]); f = ridge.fresnel(s, np.sqrt(1 + s * s))
assert f[0] == 1.0 and f[1] == 1.0 and (np.diff(f[1:]) < 0).all() and f[-1] < 1e-3, ('fresnel shape', f)
def test_cache_keys_follow_every_input_of_the_cached_array():
"""mosaic-/rays- cache files are keyed by a digest of their inputs. Right answer: identical inputs -> identical key (the preset id does not enter), a changed preset field (eye height, range, position), tile list or baker constant (refraction, detail noise) -> a different key."""
saved = ridge.P
@ -373,298 +44,342 @@ def test_paths_come_from_the_environment_with_no_default():
e = dict(env); e.update({'RIDGE_WORK': '.', 'RIDGE_TILES': '.'}); del e[var]
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:])
# ---------------------------------------------------------------------------------------- planes export (export.py, ridge.relight_planes)
_before = {k for k in globals() if k.startswith('test_')} # the tests below are the planes/export tests tests/mutate_export.py runs against each mutant
import export, tempfile, json, shutil
def _three_slot_layers():
"""three blocks at 6, 20 and 50 km in the same azimuth range, each standing above the one before it in angle: three slots"""
blocks = [block(100, 140, 6000, 9000, 300), block(100, 140, 20000, 23000, 900), block(100, 140, 50000, 53000, 2500)]
r, L = _bake_view(terrain(*blocks), 120.0); ridge.P['floor_agl_m'] = 2.0; return r, L # a low floor plane: the nearest rows are solid ground
def _flat_layers(n):
"""n slots, plane-grouping only needs the list length: the real layers of the 3-slot fixture, truncated / repeated"""
r, L = _three_slot_layers(); return [L[i % len(L)] for i in range(n)]
def _statics_flat_grain(): paperf, grain, fmot = ridge.statics(); return paperf, np.ones_like(grain), fmot
def _over(planes, sky):
img = np.broadcast_to(np.array(sky), planes[export.PLANES[0]].shape[:2] + (3,)).copy()
for n in export.PLANES: a = planes[n]; img = img * (1 - a[..., 3:]) + a[..., :3] * a[..., 3:]
return img
def _open_to(L, first):
"""Pixels (window columns) that the layers from index `first` on leave open: no coverage within OCCLUDE_MARGIN_PX columns, so the plane's knock-out does not touch them."""
if first >= len(L): return np.ones((ridge.H, ridge.WIN), bool)
cov = ridge.win(1 - np.prod([1 - Ly['a'] for Ly in L[first:]], axis=0)); m = ridge.OCCLUDE_MARGIN_PX; pad = np.pad(cov, ((0, 0), (m, m)), mode='edge')
return np.lib.stride_tricks.sliding_window_view(pad, 2 * m + 1, axis=1).max(-1) < 1e-6
def test_the_far_plane_over_a_flat_sky_equals_the_opaque_relight_of_its_group():
"""The affine haze split is exact for one group: the far plane (floor + slot 0) over one flat colour equals relight of slot 0 alone with that colour as sky and haze (grain off, no shadows) within 1/255 mean and 4/255 max.
The planes carry no sky: above the ridge their alpha is 0."""
r, L = _three_slot_layers(); f = _statics_flat_grain(); sun = (200.0, 40.0); sky = export.SHEET_SKY
planes = ridge.relight_planes(L, *sun, *f, shadows=False, ref=sky); img = _over(dict(far=planes['far'], mid=0 * planes['mid'], near=0 * planes['near']), sky)
want = ridge.win(ridge.relight(L[:1], *sun, *f, shadows=False, flat=sky)); d = np.abs(img - want) * 255; d = d[_open_to(L, 1)] # a nearer layer hides the far plane where it covers (test_a_farther_plane_is_hidden_behind_the_nearer_layers_that_cover_it)
assert d.mean() < 1.0 and d.max() < 4.0, ('the far plane over a flat sky differs from its opaque relight', d.mean(), d.max())
assert planes['far'][0, :, 3].max() < 0.01 and planes['near'][0, :, 3].max() < 0.01, 'the top row (sky) is not transparent'
_VIENNA = {}
def _vienna_noon():
"""Real Vienna bake at noon: (planes over a flat sky as an error map in 1/255 per pixel, planes), cached for the tests that read it."""
if not _VIENNA:
saved = ridge.P; ridge.configure(ridge.load_preset('vienna')); d, A, Hh, _ = ridge.stage0(False); r = ridge.sweep(d, A, Hh); ridge.set_view(r['slots']); L = ridge.bake(r['slots']); f = _statics_flat_grain()
sun = export.sun_set(ridge.P, ridge.P['date'])['noon']; sky = export.SHEET_SKY; planes = ridge.relight_planes(L, sun['az'], sun['el'], *f, shadows=False, ref=sky)
_VIENNA['err'] = np.abs(_over(planes, sky) - ridge.win(ridge.relight(L, sun['az'], sun['el'], *f, shadows=False, flat=sky))).mean(-1) * 255; _VIENNA['planes'] = planes; ridge.P = saved
return _VIENNA['err'], _VIENNA['planes']
def test_stacked_planes_stay_close_to_the_opaque_relight_on_vienna_noon():
"""Real Vienna bake at noon, three planes over a flat sky vs relight(flat=that sky): the stacking loss (a nearer group's haze veils the farther plane instead of the sky) measured 4.9/255 mean over the frame before the farther planes were knocked out
behind the nearer layers, 1.8 after; the bound is 3, so a split that loses colour or alpha, or a knock-out that stops working, shows. The spec's 2/255 pin is met with 0.2 to spare; the loss is concentrated where planes overlap, see the next test."""
err, _ = _vienna_noon(); assert err.mean() < 3.0, ('stacked planes drift from the opaque relight', err.mean())
def test_stacked_planes_error_over_the_overlap_region_is_the_measured_leak():
"""Where a nearer plane covers a farther one (two or more planes with alpha above 1/100) the rest of the leak sits: measured 11.2/255 mean over 16.4% of the frame on Vienna noon (21.8 over 22.6% before the knock-out), bound 12.5. It is what the 48 px knock-out margin
and the easing leave visible (a soft darker blob beside the near plane's wedge), and the dissolving feet where a nearer layer is only partly opaque. Outside the overlap the planes are exact (0.005/255)."""
err, planes = _vienna_noon(); ov = sum((planes[n][..., 3] > 0.01).astype(int) for n in export.PLANES) >= 2
assert 0.10 < ov.mean() < 0.25, ('the overlap region is not the 16-ish percent the bound was measured on', ov.mean())
assert err[ov].mean() < 12.5, ('overlap-region error', err[ov].mean()); assert err[~ov].mean() < 0.1, ('error outside the overlap', err[~ov].mean())
def test_a_farther_plane_is_hidden_behind_the_nearer_layers_that_cover_it():
"""The opaque frame never shows a farther ridge through a nearer layer, but the stacked planes did (the nearer plane's haze share became transparency and the farther ridge showed in it: a slanted seam through the near plane on Vienna).
Right answer on the 3-slot fixture: where the nearer layers are opaque for OCCLUDE_MARGIN_PX columns around a pixel, the mid and far planes are transparent there; where nothing nearer is within the margin, the planes are exactly what they were without the knock-out;
and the knock-out eases in (a pixel just inside the covered region keeps most of its alpha), so no edge of its own is drawn."""
r, L = _three_slot_layers(); f = _statics_flat_grain(); on = ridge.relight_planes(L, 200.0, 40.0, *f, shadows=False); keep = ridge.most_open; ridge.most_open = lambda seen: np.ones_like(seen)
try: off = ridge.relight_planes(L, 200.0, 40.0, *f, shadows=False)
finally: ridge.most_open = keep
m = ridge.OCCLUDE_MARGIN_PX
for name, first in (('mid', 2), ('far', 1)):
cov = ridge.win(1 - np.prod([1 - Ly['a'] for Ly in L[first:]], axis=0)); reach = lambda w: np.lib.stride_tricks.sliding_window_view(np.pad(cov, ((0, 0), (w, w)), mode='edge'), 2 * w + 1, axis=1).min(-1)
deep = reach(3 * m) > 0.999 # the max filter looks m columns out and the easing another 1.5 m
assert deep.sum() > 2000 and (off[name][..., 3][deep] > 0.1).sum() > 500, (name, 'the fixture has no farther body under a nearer layer to hide')
assert on[name][..., 3][deep].max() < 0.03, (name, 'a farther plane shows through the layer in front of it', float(on[name][..., 3][deep].max()))
free = _open_to(L, first); assert np.array_equal(on[name][..., 3][free], off[name][..., 3][free]) and free.sum() > 2000, (name, 'the knock-out reached pixels no nearer layer covers')
edge = (cov > 0.999) & (reach(2) < 0.5) & (off[name][..., 3] > 0.1); assert edge.sum() > 50 and (on[name][..., 3][edge] / off[name][..., 3][edge]).mean() > 0.4, (name, 'the knock-out has a hard edge at the margin')
def test_the_nearest_layer_is_opaque_down_to_the_horizon_and_the_others_keep_their_dissolve():
"""Right answer: the nearest layer's alpha is 1 from its crest to the horizon row, whatever its strip's valley angle says (above the horizon a dissolved body shows the sky under a crest: the wedge of Vienna's near plane, whose valley angle jumps where the winning chain changes);
a farther layer keeps its dissolve (the far blue ridges fade into the haze above the horizon by design). Fixture: a 400 m block at 3 km (crest 5.7 deg, foot 210 px but 380 px to the horizon) and a 4000 m block at 20 km (a crest above the near one, so it is a ridge of its own)."""
r, L = _bake_view(lambda dk, az: np.where(in_arc(az, 100, 140) & (dk >= 3000) & (dk < 3600), 400.0, np.where(in_arc(az, 100, 140) & (dk >= 20000) & (dk < 24000), 4000.0, 0.0)), 120.0)
c = col_of(120); hz = int(np.argmax(ridge.rowang < 0)); assert len(L) == 2, [Ly['dist'] for Ly in L]
for Ly, solid in ((L[-1], True), (L[0], False)):
a = Ly['a'][:, c]; crest = int(np.argmax(a > 0.5)); body = a[crest + 3:hz]; assert body.size > 20, ('fixture crest is not above the horizon', crest, hz)
assert (body.min() > 0.999) if solid else (body.min() < 0.5), ('nearest' if solid else 'farther', 'layer alpha between crest and horizon', float(body.min()))
def test_near_plane_must_cover_every_column_and_leave_no_hole_under_its_crest():
"""check_near_cover: a near plane passes when every column has a crest and nothing between the crest and the horizon row is a hole; it refuses a fully transparent column, and a hole under a crest (the wedge: alpha 0 at the plane's right edge, rows 230-480 with a hard edge, in the committed Vienna set).
Holes below the horizon are the foot dissolving into the floor and pass."""
ok = np.zeros((60, 40, 4), np.uint8); ok[10:, :, 3] = 200; export.check_near_cover(ok, 30.0); export.check_near_cover(ok, 59.0)
cols = ok.copy(); cols[:, 33:, 3] = 0; wedge = ok.copy(); wedge[20:50, 30:, 3] = 0; below = ok.copy(); below[35:, 30:, 3] = 0
export.check_near_cover(below, 30.0)
for bad, why in ((cols, 'transparent'), (wedge, 'hole')):
try: export.check_near_cover(bad, 40.0)
except ValueError as e: assert why in str(e), (why, str(e))
else: assert False, ('a near plane with a ' + why + ' was accepted')
export.check_near_cover(ok, 30.0)
def test_write_bake_refuses_a_near_plane_with_a_wedge_and_lets_the_other_planes_have_empty_columns():
"""The refusal is at the writer, on the decoded near plane of every frame; the far and mid planes may have transparent columns (a place with no ridge at that distance in part of the window)."""
# ---------------------------------------------------------------------------------------- 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 _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
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
WALLED = terrain(block(0, 359.99, 9000, 10000, 300), block(0, 359.99, 38000, 40000, 2000))
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_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)
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())
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))
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)
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()
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."""
for d0, d1, sp in RECEDING:
j0, j1, cover = _alpha_jumps(d0, d1, sp); assert j0 < 0.35 and j1 < 0.35, ('a card appears or vanishes between neighbouring columns', (d0, d1, sp), j0, j1); assert cover > 0.999, ('the ridge body is not covered by the two cards together', (d0, d1, sp))
def test_far_card_keeps_terrain_hidden_behind_a_nearer_ridge():
"""Layered depth: a far ridge (20 km) lower in angle than the near ridge (3 km) in azimuth 0..36 and higher in 36..72. Where the near card is opaque in front of the far ridge (columns 100..500) the mid card still holds that ridge, at its distance;
where the far ridge shows above the near one (column 900) the near card is empty and the mid card holds it."""
b = _bake(terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 1500), block(36, 359.99, 20000, 21500, 2400)), [6]); c0, c1 = _canvas(b['cards'][0]), b['cards'][1]; a1 = _canvas(c1); ld1 = _canvas(c1, 'logd'); r = _row(theta(1500, 20000) - 0.2)
for x in (100, 300, 500):
assert c0[r, x] > 0.99, ('the near ridge does not cover the far one here', x); assert a1[r, x] > 0.99, ('the far card lost the terrain behind the near ridge', x); assert abs(math.exp(ld1[r, x]) - 20000) < 1500, (x, math.exp(ld1[r, x]))
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
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():
"""A plane with front slope s (north) and lateral slope l (east), seen towards azimuth 0: n = (-E s, -E l, 1) normalised, E the authored exaggeration (a dropped E fails)."""
s, l, E = 0.12, -0.08, 3.0; saved = ridge.PXDEG_V; ridge.PXDEG_V = E * ridge.HPX_DEG
try:
az = (np.arange(W) + 0.5) / W * 2 * math.pi; h = 300.0 + s * D[:, None] * np.cos(az)[None, :] + l * D[:, None] * np.sin(az)[None, :]; nr, nt, nu = ridge.normals(D, h); k = len(D) // 2; x = [0, 1, 2, W - 2, W - 1]
want = np.array([-E * s, -E * l, 1.0]); want /= np.linalg.norm(want); got = np.array([nr[k, x].mean(), nt[k, x].mean(), nu[k, x].mean()]); assert np.abs(got - want).max() < 2e-3, (got, want)
assert np.abs(nr ** 2 + nt ** 2 + nu ** 2 - 1).max() < 1e-9
finally: ridge.PXDEG_V = saved
def test_lateral_slope_uses_equal_distance_not_equal_row():
"""A plane with lateral slope l at 20 km, a 3 km ridge only for azimuth above 40 deg: at the 20 km samples, in the columns around the ridge's azimuth edge, the across-ray slope is the plane's own l (neighbouring columns at the same distance), not a step between the ridge and the plane."""
l = 0.05; saved = ridge.PXDEG_V; ridge.PXDEG_V = 2.0 * ridge.HPX_DEG
try:
az = (np.arange(W) + 0.5) / W * 360.0; A, Hh = rays(lambda dk, a: np.where(dk > 10000, GROUND + l * dk * np.radians(a), GROUND) + np.where((a > 40) & (dk >= 3000) & (dk < 3600), 400.0, 0.0))
nr, nt, nu = ridge.normals(D, Hh); k = int(np.searchsorted(D, 20000)); x0 = int(40 / 360 * W); want = -2.0 * l / math.sqrt(1 + 4 * l * l + (2.0 * 0.0) ** 2)
assert np.abs(nt[k, x0 - 20:x0 + 20] / nu[k, x0 - 20:x0 + 20] + 2.0 * l).max() < 5e-3, nt[k, x0 - 5:x0 + 5] / nu[k, x0 - 5:x0 + 5]
finally: ridge.PXDEG_V = saved
def test_prefilter_flattens_roofs_and_keeps_hills():
"""A 25 m bump 60 m wide at 2 km drops below 5 m; a 400 m hill (3 km scale) keeps at least 90% of its height."""
ridge.P.update(eye_m=EYE); roof = lambda dk, az: GROUND + np.where((az < 1.72) & (dk >= 2000) & (dk < 2060), 25.0, 0.0)
hill = lambda dk, az: GROUND + 400.0 * np.exp(-((dk - 10000.0) / 3000.0) ** 2 - ((np.radians(((az + 180) % 360) - 180) * dk) / 3000.0) ** 2)
for f, name in ((roof, 'roof'), (hill, 'hill')):
A, Hh = rays(f); a, h = ridge.prefilter(D, Hh, 100.0); k = int(np.argmin(np.abs(D - (2030 if name == 'roof' else 10000)))); x = int(np.argmax(Hh[k]))
if name == 'roof': assert h[k, x] - GROUND < 5.0 and Hh[k, x] - GROUND >= 24.9, ('the roof survives the low-pass', h[k, x] - GROUND)
else: assert h[k, x] - GROUND >= 0.9 * 400.0, ('the hill is flattened', h[k, x] - GROUND)
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]
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():
"""Alpha-over of all cards, last to first, equals the opaque march coverage within 0.02 everywhere, and where opaque the nearest solid card's distance is the first-hit distance of the march."""
for hf, sp in ((THREE, [6, 40]), (terrain(_receding), [6]), (terrain(block(0, 359.99, 3000, 3600, 350), block(0, 36, 20000, 21500, 700), block(36, 359.99, 20000, 21500, 1800)), [6])):
b = _bake(hf, sp); comp = 1 - np.prod([1 - _canvas(c) for c in b['cards']], axis=0); assert np.abs(comp - b['opaque']).max() < 0.02, np.abs(comp - b['opaque']).max()
rm = np.maximum.accumulate(b['a'], axis=0); col = 640; r = _row(float(b['a'][:, col].max()) - 0.5); k = int(np.searchsorted(rm[:, col], ridge.rowang[r], 'left')); first = None
for c in b['cards']:
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:
place, view, suns, planes = _fixture_bake()
for k in export.KEYS: planes[k]['mid'][:, 200:260, 3] = 0
export.write_bake(d + '/ok', place, view, suns, _encode_all(planes))
for k, ys, xs in (('dawn', slice(20, 80), slice(1200, 1280)), ('night', slice(0, 600), slice(600, 700))):
bad = {kk: {n: np.array(v) for n, v in vv.items()} for kk, vv in planes.items()}; bad[k]['near'][ys, xs, 3] = 0
_refuses(d + '/bad', place, view, suns, _encode_all(bad), 'a near plane with a transparent wedge in frame %s was written' % k)
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)
def test_plane_grouping_far_mid_near_and_refuses_fewer_than_three_slots():
"""far = slot 0, near = the last slot, mid = every slot between (the union); a 3-slot place fills all three planes; fewer than 3 slots are refused."""
assert ridge.group_slots(3) == dict(far=[0], mid=[1], near=[2]) and ridge.group_slots(6) == dict(far=[0], mid=[1, 2, 3, 4], near=[5])
for n in (0, 1, 2):
try: ridge.group_slots(n)
except ValueError: continue
assert False, ('a place with %d slots was accepted' % n)
r, L = _three_slot_layers(); f = _statics_flat_grain(); pl = ridge.relight_planes(L[:3], 200.0, 40.0, *f, shadows=False)
assert all(pl[n][..., 3].max() > 0.5 for n in export.PLANES), {n: float(pl[n][..., 3].max()) for n in export.PLANES}
try: ridge.relight_planes(L[:2], 200.0, 40.0, *f, shadows=False)
except ValueError: pass
else: assert False, 'a 2-slot place was relit into planes'
def test_straight_alpha_planes_unpremultiply_the_composite():
"""Planes carry straight (un-premultiplied) colour: the mid plane (slot 1, 16 km) and the near plane (slot 2, 5 km) each alone over a flat sky equal the opaque relight of that one slot over the same sky, on the rows
above the horizon (the floor belongs to the far plane). Their bodies are translucent (the haze share is alpha's deficit), so premultiplied colour would be darker by alpha and fail by tens of 1/255. u8() keeps colour and alpha apart."""
a = np.zeros((2, 2, 4), np.float32); a[0, 0] = (0.5, 0.25, 0.75, 0.5); b = export.u8(a); assert tuple(b[0, 0]) == (128, 64, 191, 128) and tuple(b[1, 1]) == (0, 0, 0, 0)
r, L = _three_slot_layers(); f = _statics_flat_grain(); sun = (200.0, 40.0); sky = export.SHEET_SKY; pl = ridge.relight_planes(L, *sun, *f, shadows=False, ref=sky); top = int((ridge.rowang >= 0).sum())
for name, i in (('mid', 1), ('near', 2)):
got = _over({n: (pl[n] if n == name else 0 * pl[n]) for n in export.PLANES}, sky)[:top]; want = ridge.win(ridge.relight(L[i:i + 1], *sun, *f, shadows=False, flat=sky))[:top]
body = pl[name][:top, :, 3] > 0.3; assert body.sum() > 1000 and pl[name][:top, :, 3][body].mean() < 0.97, (name, 'the fixture has no translucent body to test')
d = (np.abs(got - want) * 255)[_open_to(L, i + 1)[:top]]; assert d.mean() < 0.5 and d.max() < 4.0, (name, 'plane over a flat sky differs from its slot relight: colour is premultiplied or the haze split is wrong', d.mean(), d.max())
def _encode_all(planes): return {k: {n: export.encode(planes[k][n]) for n in export.PLANES} for k in export.KEYS}
def _fixture_bake():
r, L = _three_slot_layers(); f = _statics_flat_grain(); suns = {k: dict(az=100.0 + 20 * i, el=-10.0 + 15 * i, hour_utc=float(i)) for i, k in enumerate(export.KEYS)}
planes = {k: ridge.relight_planes(L, suns[k]['az'], max(suns[k]['el'], 5.0) if k != 'night' else 5.0, *f, shadows=False) for k in export.KEYS}
for k in export.KEYS: planes[k]['near'][..., 3] = np.maximum(planes[k]['near'][..., 3], 0.6) # the writer refuses a near plane with an empty column: the fixture's nearest ridge covers only 40 degrees, so its plane is lifted to cover the window
place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.1, tz_h=2, tz_name='CEST', date='2026-09-23')
view = dict(look_az_deg=120.0, plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=ridge.PXDEG_V, horizon_row=100.0, sky_row=24.0, near_row=396.0)
return place, view, suns, planes
def _sized(h, w, seed=0, noise=False):
"""the same plane for every key and name, h rows by w columns: a soft mid-grey ramp, or white noise when noise (a plane that does not compress)"""
rng = np.random.default_rng(seed); a = rng.random((h, w, 4)).astype(np.float32) if noise else np.dstack([np.full((h, w), 0.5), np.linspace(0, 1, w)[None].repeat(h, 0), np.full((h, w), 0.3), np.full((h, w), 0.4)]).astype(np.float32)
return {k: {n: export.encode(a) for n in export.PLANES} for k in export.KEYS}
def _refuses(out, place, view, suns, webp, why):
try: export.write_bake(out, place, view, suns, webp)
# ---------------------------------------------------------------------------------------- export: manifest v2, budget, cover
def _packed(b=None):
b = b or _bake(WIDE3, [20, 55]); return b, export.pack(b)
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)
except ValueError: assert not os.path.exists(out), ('a refused bake left files', why)
else: assert False, why
def test_manifest_validates_bake_id_is_deterministic_and_luma_is_recorded():
"""Two independent bakes (the relight and the encode each run twice, not one plane set encoded twice) give the same bytes and bake_id; the manifest validates against the schema, plane w/h are what the written files decode to, frame pairs fit the budget, luma min <= max in 0..1 per frame,
the index points at the dir, a rebake replaces the place's old dir, and nothing but the dir and index.json is left in the output."""
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."""
d = tempfile.mkdtemp()
try:
place, view, suns, planes = _fixture_bake(); webp = _encode_all(planes); again = _encode_all(_fixture_bake()[3]); assert webp == again, 'two independent bakes (relight and encode run twice) gave different plane bytes'
a = export.write_bake(d + '/a', place, view, suns, webp); b = export.write_bake(d + '/b', place, view, suns, again)
assert a.name == b.name and a.name == 'synthetic-' + export.bake_id(webp), (a.name, b.name); assert sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name]), os.listdir(d + '/a')
m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['bake_id'] == a.name.split('-')[1] and [f['key'] for f in m['frames']] == list(export.KEYS)
assert m['view']['plane_w'] <= export.PLANE_W_MAX and m['view']['window_deg'] == 72 and m['view']['plane_w'] == ridge.WIN and m['view']['plane_h'] == ridge.H
for f in m['frames']:
assert 0 <= f['luma']['min'] <= f['luma']['max'] <= 1, f['luma']; assert f['bytes'] == sum(p['bytes'] for p in f['planes'].values())
for p in f['planes'].values():
assert (a / p['file']).stat().st_size == p['bytes'] and export.decode((a / p['file']).read_bytes()).shape[:2] == (p['h'], p['w']) == (ridge.H, ridge.WIN), p
assert max(m['frames'][i]['bytes'] + m['frames'][i + 1]['bytes'] for i in range(5)) <= export.PAIR_BYTES_MAX
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})
webp2 = {k: dict(v) for k, v in webp.items()}; webp2['noon']['far'] = export.encode(np.full((ridge.H, ridge.WIN, 4), 0.5, np.float32) * np.array([1, 1, 1, 2], np.float32)); c = export.write_bake(d + '/a', place, view, suns, webp2)
assert c.name != a.name and not a.exists() and json.load(open(d + '/a/index.json'))['places']['synthetic'] == c.name, 'the old dir of the place survives a rebake'; assert sorted(os.listdir(d + '/a')) == sorted(['index.json', c.name])
bad = json.loads(json.dumps(m)); bad['frames'][0]['extra'] = 1
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'
committed = json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))); assert committed == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
finally: shutil.rmtree(d)
def test_index_default_keeps_the_first_place_and_follows_an_explicit_default():
"""A second place leaves the index default at the first; an explicit default names the default; a default naming no baked place falls back to the place just baked."""
d = tempfile.mkdtemp()
try:
place, view, suns, planes = _fixture_bake(); webp = _encode_all(planes); other = dict(place, id='other')
export.write_bake(d, place, view, suns, webp); export.write_bake(d, other, view, suns, webp); idx = json.load(open(d + '/index.json')); assert idx['default'] == 'synthetic' and sorted(idx['places']) == ['other', 'synthetic'], idx
export.write_bake(d, other, view, suns, webp, default='other'); assert json.load(open(d + '/index.json'))['default'] == 'other'
idx = json.load(open(d + '/index.json')); idx['default'] = 'gone'; open(d + '/index.json', 'w').write(json.dumps(idx)); export.write_bake(d, other, view, suns, webp); assert json.load(open(d + '/index.json'))['default'] == 'other'
finally: shutil.rmtree(d)
def test_bake_id_follows_the_plane_bytes_in_order():
"""bake_id = first 12 hex of sha256 over the plane bytes in key order, then far, mid, near: one changed byte in any plane changes it, swapping two planes changes it, and the value equals an independent hash."""
import hashlib
w = {k: {n: bytes([i, j]) * 5 for j, n in enumerate(export.PLANES)} for i, k in enumerate(export.KEYS)}; want = hashlib.sha256(b''.join(w[k][n] for k in export.KEYS for n in ('far', 'mid', 'near'))).hexdigest()[:12]
assert export.bake_id(w) == want
for k in export.KEYS:
v = {kk: dict(vv) for kk, vv in w.items()}; v[k]['near'] = v[k]['near'] + b'x'; assert export.bake_id(v) != want, k
v = {kk: dict(vv) for kk, vv in w.items()}; v[k]['far'], v[k]['mid'] = v[k]['mid'], v[k]['far']; assert export.bake_id(v) != want, k
def test_budget_refuses_a_pair_above_the_cap_and_a_plane_above_the_width():
"""Any two ADJACENT frames above PAIR_BYTES_MAX are refused (a heavy frame next to a light one at the cap passes), as is a plane wider than the cap, and nothing is written."""
cap = export.PAIR_BYTES_MAX; ok = [cap // 2] * 6; export.check_budget(ok, export.PLANE_W, ridge.H)
for i in range(6):
bad = [1000] * 6; bad[i] = cap // 2 + 1; bad[(i + 1) % 6] = cap // 2 + 1
try: export.check_budget(bad, export.PLANE_W, ridge.H)
except ValueError: pass
else: assert False, ('adjacent pair over the cap accepted', i)
try: export.check_budget([400_001, 1, 1, 1, 1, 400_000], export.PLANE_W, ridge.H)
except ValueError as e: assert 'night + dawn' in str(e), str(e)
else: assert False, 'night + dawn summing 800001 were accepted'
export.check_budget([400_000, 1, 1, 1, 1, 400_000], export.PLANE_W, ridge.H)
export.check_budget([cap - 1000, 1000, cap - 1000, 1000, cap - 1000, 1000], export.PLANE_W, ridge.H) # non-adjacent heavy frames are fine
export.check_budget(ok, export.PLANE_W_MAX, 100) # exactly the cap is fine
try: export.check_budget(ok, export.PLANE_W_MAX + 1, ridge.H)
except ValueError: pass
else: assert False, 'a plane wider than the cap was accepted'
d = tempfile.mkdtemp()
try:
place, view, suns, planes = _fixture_bake(); webp = _encode_all(planes); fat = {k: dict(v) for k, v in webp.items()}
fat['dusk']['mid'] = export.encode(np.random.default_rng(1).random((ridge.H, ridge.WIN, 4)).astype(np.float32)); assert len(fat['dusk']['mid']) > cap // 2, 'the noise plane does not weigh enough'
_refuses(d + '/o', place, view, suns, fat, 'an over-budget bake was written')
finally: shutil.rmtree(d)
def test_size_refusals_read_the_written_planes_not_constants():
"""write_bake measures the planes it was handed: a 5000 px plane is refused (cap 4096) and so are planes that disagree on size or with the view's plane_h; a frame pair decoding above 20 MB is refused (700 rows) and at 650 rows is written;
the manifest carries the measured w and h (1000 px planes say w=1000), never a constant."""
d = tempfile.mkdtemp()
try:
place, view, suns, _ = _fixture_bake(); v = lambda h: dict(view, plane_h=h)
_refuses(d + '/wide', place, v(100), suns, _sized(100, 5000), 'planes 5000 px wide were accepted')
mixed = _sized(100, 1000); mixed['noon']['mid'] = _sized(100, 900)['noon']['mid']; _refuses(d + '/mixed', place, v(100), suns, mixed, 'planes of two widths were accepted')
_refuses(d + '/rows', place, v(101), suns, _sized(100, 1000), 'planes whose height is not the view plane_h were accepted')
_refuses(d + '/heavy', place, v(700), suns, _sized(700, 1280), 'a frame pair decoding to 21.5 MB was accepted')
a = export.write_bake(d + '/ok', place, v(650), suns, _sized(650, 1280)); m = json.load(open(a / 'manifest.json')); assert m['view']['plane_w'] == 1280 and m['view']['plane_h'] == 650
b = export.write_bake(d + '/narrow', place, v(100), suns, _sized(100, 1000)); m = json.load(open(b / 'manifest.json'))
assert m['view']['plane_w'] == 1000 and all(p['w'] == 1000 and p['h'] == 100 for f in m['frames'] for p in f['planes'].values()), m['view']
finally: shutil.rmtree(d)
def test_the_shipped_manifest_carries_the_attribution_verbatim():
"""The Copernicus DEM licence obliges the credit line to ship with the planes: write_bake of the fixture bake (the shipped planes path) writes a manifest whose attribution is exactly the four pinned strings, each its own field:
credit_line, licence, dem_source and url (a blanked, shortened or swapped field fails by name)."""
d = tempfile.mkdtemp()
try:
place, view, suns, planes = _fixture_bake(); dest = export.write_bake(d, place, view, suns, _encode_all(planes)); a = json.load(open(dest / 'manifest.json'))['attribution']
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)'
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 sorted(a) == sorted(want), sorted(a)
for k in want: assert a[k] == want[k], (k, a[k])
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'
finally: shutil.rmtree(d)
def _srgb_y(c): c = np.asarray(c, float); lin = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4); return float(lin @ np.array([0.2126, 0.7152, 0.0722]))
def test_luma_range_is_the_far_mid_near_composite_over_a_grey_sky_where_coverage_is_at_least_half():
"""Hand-built 1x5 planes, none opaque anywhere (haze-as-alpha): px0 far white alpha 200 then near black alpha 128 (order matters, coverage .89); px1 far grey 128 alpha 128 (coverage .50, measured); px2 far white alpha 120
(coverage .47, NOT measured: it would be the brightest); px3 far and mid black alpha 100 each (coverage .63, measured); px4 nothing. min and max equal the arithmetic composite over the 0.5 grey sky to 1e-6."""
z = lambda: np.zeros((1, 5, 4), np.uint8); far, mid, near = z(), z(), z()
far[0, 0] = (255, 255, 255, 200); near[0, 0] = (0, 0, 0, 128); far[0, 1] = (128, 128, 128, 128); far[0, 2] = (255, 255, 255, 120); far[0, 3] = (0, 0, 0, 100); mid[0, 3] = (0, 0, 0, 100)
sky = np.full(3, 0.5); A, a, b = 200 / 255, 128 / 255, 100 / 255; p0 = (sky * (1 - A) + A) * (1 - a); p1 = sky * (1 - a) + 128 / 255 * a; p3 = sky * (1 - b) ** 2
want = sorted(_srgb_y(p) for p in (p0, p1, p3)); lo, hi = export.luma_range([far, mid, near]); assert abs(lo - want[0]) < 1e-6 and abs(hi - want[-1]) < 1e-6, ((lo, hi), want)
try: export.luma_range([z(), z(), z()])
except ValueError as e: assert 'coverage' in str(e), ('the refusal does not name the coverage', str(e))
else: assert False, 'a frame with no covered pixel was measured'
z2 = export.decode(export.encode(np.full((8, 8, 4), 1.0, np.float32))); assert z2.shape == (8, 8, 4) and (z2[..., 3] == 255).all(), 'an everywhere-opaque plane must read back as RGBA'
def _rt_error(planes, back):
sky = export.SHEET_SKY; return np.abs(_over({n: planes[n] for n in export.PLANES}, sky) - _over({n: back[n].astype(np.float32) / 255 for n in export.PLANES}, sky)) * 255
def test_encode_round_trips_the_shipped_planes_with_real_grain_and_the_default_reference():
"""The planes as shipped (default reference haze, the real grain, WebP quality 80) decode to the float planes: composited over a flat sky the round trip costs under 1.7/255 mean and 32/255 max (measured 1.47 and 28.6 on this hard-edged fixture; quality 50 measures 1.64 and 34, quality 5 measures 2.16 and 73), straight
colour (not premultiplied), alpha kept, rows not flipped; the real grain multiplies the colour exactly (the ratio to a grain-free bake is win(grain))."""
r, L = _three_slot_layers(); paperf, grain, fmot = ridge.statics(); sun = (200.0, 40.0)
shipped = ridge.relight_planes(L, *sun, paperf, grain, fmot, shadows=False); flat = ridge.relight_planes(L, *sun, paperf, np.ones_like(grain), fmot, shadows=False)
back = {n: export.decode(export.encode(shipped[n])) for n in export.PLANES}; assert all(back[n].shape == shipped[n].shape for n in export.PLANES), 'decode changed the plane shape'
e = _rt_error(shipped, back); assert e.mean() < 1.7 and e.max() < 32.0, ('encode/decode round trip', e.mean(), e.max())
for n in export.PLANES: assert abs(back[n][..., 3].astype(float) / 255 - shipped[n][..., 3]).max() < 0.1, ('alpha lost in the round trip', n)
g = ridge.win(grain); ok = (flat['near'][..., 3] > 0.2) & (flat['near'][..., :3].max(-1) * 1.03 < 1)
assert ok.sum() > 1000 and np.abs(shipped['near'][..., :3][ok] / flat['near'][..., :3][ok] - np.broadcast_to(g, ok.shape)[ok][:, None]).max() < 1e-3, 'the grain does not multiply the plane colour'
def test_default_reference_is_the_frames_own_haze_colour_and_shadows_darken_the_planes():
"""With no reference given the far plane over the frame's own haze colour equals the opaque relight of its group over that colour (<1 mean, 4 max in 1/255), not over the sky's horizon colour or a grey; cast shadows reach the planes:
a forced shadow of 1 darkens the far-group colour, a forced 0 equals shadows off."""
r, L = _three_slot_layers(); paperf, grain, fmot = ridge.statics(); f1 = (paperf, np.ones_like(grain), fmot); sun = (200.0, 40.0); st = ridge.sun_state(*sun); hz = ridge.haze_colour(ridge.sky_hz(st, paperf)[1])
far = ridge.relight_planes(L, *sun, *f1, shadows=False)['far']; sky = ridge.win(hz[None].astype(np.float32))[0]
img = _over(dict(far=far, mid=0 * far, near=0 * far), sky); want = ridge.win(ridge.relight(L[:1], *sun, *f1, shadows=False, flat=hz)); d = np.abs(img - want) * 255
assert d.mean() < 1.0 and d.max() < 4.0, ('the default reference is not the frame haze colour', d.mean(), d.max())
real = ridge.cast_shadows
try:
ridge.cast_shadows = lambda layers, az, el: [np.ones((3, W)) for _ in layers]; dark = ridge.relight_planes(L, *sun, *f1)
ridge.cast_shadows = lambda layers, az, el: [np.zeros((3, W)) for _ in layers]; lit = ridge.relight_planes(L, *sun, *f1)
finally: ridge.cast_shadows = real
off = ridge.relight_planes(L, *sun, *f1, shadows=False); body = off['near'][..., 3] > 0.5
assert body.sum() > 1000 and dark['near'][..., :3][body].mean() < off['near'][..., :3][body].mean() - 0.02, 'cast shadows do not reach the planes'
assert all(np.abs(lit[n] - off[n]).max() < 1e-4 for n in export.PLANES), 'a zero shadow differs from shadows off'
def test_sun_set_keys_sit_at_their_elevations_and_hours():
"""The six keys on Vienna's preset date: noon is the day's highest sun, golden at a geometric elevation of 6.0 deg after it, dusk -2.5 deg, night -12.0 deg (the schema's night frame), dawn just above the horizon a quarter hour after sunrise, morning at 9.5 h local;
hours increase dawn < morning < noon < golden < dusk < night. Elevations are re-read from sun.solar, not from the keys: the keys are geometric (solar()[2]) and the manifest's el is the apparent one (solar()[1], refraction added)."""
import sun; from datetime import datetime, timedelta, timezone
p = ridge.load_preset('vienna'); s = export.sun_set(p, p['date']); assert list(s) == list(export.KEYS)
day = datetime.fromisoformat(p['date']).replace(tzinfo=timezone.utc); el = lambda h: sun.solar(day + timedelta(hours=h), p['lat'], p['lon'])[1]
geo = lambda h: sun.solar(day + timedelta(hours=h), p['lat'], p['lon'])[2]
for k in s: assert abs(el(s[k]['hour_utc']) - s[k]['el']) < 1e-9, k
assert abs(geo(s['golden']['hour_utc']) - 6.0) < 0.01 and abs(geo(s['dusk']['hour_utc']) + 2.5) < 0.01 and abs(geo(s['night']['hour_utc']) + 12.0) < 0.01 and abs(s['night']['el'] + 12.0) < 0.01, {k: v['el'] for k, v in s.items()}
assert max(el(h / 100) for h in range(0, 2400, 5)) - s['noon']['el'] < 0.01 and abs(s['morning']['hour_utc'] - (9.5 - p['tz_h'])) < 1e-9
assert -0.833 < s['dawn']['el'] < 3.0, s['dawn']; hs = [s[k]['hour_utc'] for k in export.KEYS]; assert hs == sorted(hs), hs
def test_bake_place_manifest_fields_on_vienna():
"""bake_place on the real Vienna preset: altitude is the ground (km) without the eye height, horizon_row is the row where the elevation angle is 0 (inside the frame, between sky_row and near_row), px_per_deg_h is the ring's;
write_bake of its encoded planes gives finite luma for every frame, index default 'vienna', the full Copernicus credit line, and no temp dir left behind."""
saved = ridge.P
try:
place, view, suns, planes = export.bake_place('vienna', relight_keys=export.KEYS); P = ridge.P; rowang = ridge.rowang; pxv = ridge.PXDEG_V
finally: ridge.P = saved
assert abs(place['altitude_km'] * 1000 - P['ground_m']) < 1e-6 and P['eye_m'] > 0 and place['id'] == 'vienna' and place['date'] == P['date'] and place['lat'] == P['lat'] and place['lon'] == P['lon']
assert abs(view['sky_row'] - 0.04 * ridge.H) < 1e-9 and abs(view['near_row'] - 0.66 * ridge.H) < 1e-9, 'sky_row / near_row are rows (set_view anchors 4% and 66% of the frame)'
assert 0 < view['sky_row'] < view['horizon_row'] < view['near_row'] < ridge.H and abs(rowang[int(view['horizon_row'])]) <= 1.0 / pxv, (view, rowang[int(view['horizon_row'])])
assert view['look_az_deg'] == P['az_center'] and view['plane_h'] == ridge.H and view['px_per_deg_h'] == ridge.HPX_DEG and view['px_per_deg_v'] == pxv
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."""
d = tempfile.mkdtemp()
try:
dest = export.write_bake(d, place, view, suns, _encode_all(planes)); m = json.load(open(dest / 'manifest.json'))
assert all(math.isfinite(f['luma'][k]) and 0 <= f['luma']['min'] < f['luma']['max'] <= 1 for f in m['frames'] for k in ('min', 'max')), [f['luma'] for f in m['frames']]
assert json.load(open(d + '/index.json'))['default'] == 'vienna' and sorted(os.listdir(d)) == sorted(['index.json', dest.name]), os.listdir(d)
c = m['attribution']['credit_line']; assert c.startswith('Contains modified Copernicus data') and 'Airbus Defence and Space' in c and 'ESA' in c and m['attribution']['licence'] and m['attribution']['url'].startswith('https://'), m['attribution']
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))
finally: shutil.rmtree(d)
def _flat_card(top, h, w=WIN, seed=0, noise=False):
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)
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."""
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'))
try: ridge.load_preset('x', p)
except ValueError: pass
else: assert False, ('a preset with splits', bad, 'was accepted')
json.dump(dict(presets=[dict(id='x')]), open(os.path.join(d, 'q.json'), 'w'))
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)
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)."""
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)
finally: shutil.rmtree(d)
PLANES_TESTS = [v for k, v in sorted(globals().items()) if k.startswith('test_') and k not in _before]
TESTS = [v for k, v in sorted(globals().items()) if k.startswith('test_')]
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()
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'
assert partial_seen > 0, 'the fixture has no partial alpha'
finally: shutil.rmtree(d)
# ---------------------------------------------------------------------------------------- wall rows and the camera
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)]
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])):
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)
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)
want_alb = ridge.albedo(np.array([b['h'][k0[x], x]]), np.array([1.0]))[0]; assert np.abs(c['albedo'][rows, x] - want_alb).max() < 1e-5, ('wall albedo is not the ground material with the face up', x)
assert seen > 1000, 'the fixture has no wall'
for i in range(1, len(b['cards'])):
c = b['cards'][i]; steep += int((np.sqrt(np.clip(1 - c['n_r'] ** 2 - c['n_t'] ** 2, 0, 1))[c['wall']] < 0.93).sum())
assert steep > 1000, 'no wall pixel has a steep face under it: a wall lit by its own normal would pass'
b = _bake(NEARHILL, [20]); c0 = b['cards'][0]; lo = ridge.rowang - 0.5 / ridge.PXDEG_V; below = (lo[:, None] < b['a'][0][None, :])[c0['top']:c0['top'] + c0['alpha'].shape[0]]
assert below.sum() > 1000 and not c0['wall'].any(), ('card 0 has no wall, though rows lie below its first sample', int(below.sum()))
def test_the_sheet_lights_a_wall_with_the_face_up():
"""The contact sheet shades a wall pixel as an up-facing one whatever normal the card carries there, and a non-wall pixel by its normal."""
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."""
s = _bake(THREE, [6, 7])['seams']; assert (np.log(s[1]) - np.log(s[0]) >= 0.4 - 1e-9).all(), float((np.log(s[1]) - np.log(s[0])).min())
def test_elev_is_the_curved_refracted_angle():
"""elev(h, d) = atan2(h - eye - d^2 / 2R x (1 - k), d): at 80 km a 3000 m summit stands 0.3 deg lower than the flat angle, and curvature False gives the flat one."""
ridge.P.update(eye_m=EYE); d = 80000.0; want = math.degrees(math.atan2(3000.0 - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d)); flat = math.degrees(math.atan2(3000.0 - EYE, d))
assert abs(float(ridge.elev(3000.0, d)) - want) < 1e-9 and abs(float(ridge.elev(3000.0, d, curvature=False)) - flat) < 1e-9 and flat - want > 0.25, (want, flat)
assert ridge.elev(np.array([[1000.0, 1200.0]]), np.array([[d], [d / 2]])).shape == (2, 2)
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)
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]
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
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())
TESTS = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
if __name__ == '__main__':
fails = 0
for t in TESTS:
try: t(); print('PASS', t.__name__)
except Exception as e: fails += 1; print('FAIL', t.__name__, '|', repr(e)[:300])
print('failures:', fails); sys.exit(1 if fails else 0)
try: t(); print("PASS", t.__name__)
except Exception as e: fails += 1; print("FAIL", t.__name__, "|", repr(e)[:300])
print("failures:", fails); sys.exit(1 if fails else 0)

View file

@ -0,0 +1,121 @@
"""Pack the night sky's data into src/app/features/scene/ridge/nightSkyData.ts.
Usage (parse downloads with isolated mode):
python -I scripts/ridge-sky/build-night-sky.py BSC5.DAT.GZ CONSTELLATIONS.LINES.JSON OUT.ts [MAX_MAG]
Inputs, each in its own directory, never run from inside it:
bsc5.dat.gz Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991), public domain; CDS/VizieR V/50.
CDS was unreachable on 2026-11-20, so the file is the SAO Telescope Data Center's copy of the same
catalogue: http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (fixed-width, CDS V/50 `catalog` layout).
constellations.lines.json d3-celestial (Olaf Frohn), BSD-3-Clause:
https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json
GeoJSON MultiLineStrings of [RA, Dec] degrees, J2000.
Stars (stars cut to Vmag <= MAX_MAG, default 5.5), 6 bytes each: RA uint16 (360 deg / 65536), Dec uint16 ((dec + 90) / 180 * 65535),
Vmag uint8 ((V + 2) * 20), B-V uint8 ((B-V + 0.5) * 50; missing B-V stored as 0.65). Little endian, base64.
Lines: per chain a uint8 vertex count then that many (RA uint16, Dec uint16) pairs, same scaling; chains concatenated; base64.
"""
import base64
import gzip
import hashlib
import json
import struct
import sys
def sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
h.update(f.read())
return h.hexdigest()
def ra16(deg):
return int(round((deg % 360.0) / 360.0 * 65536.0)) % 65536
def dec16(deg):
return int(round((deg + 90.0) / 180.0 * 65535.0))
def stars(path, max_mag):
out = []
for line in gzip.open(path, "rt", encoding="latin-1"):
if len(line) < 114 or not line[75:77].strip():
continue # entries struck from the catalogue carry no position
try:
ra = (int(line[75:77]) + int(line[77:79]) / 60.0 + float(line[79:83]) / 3600.0) * 15.0
dec = int(line[84:86]) + int(line[86:88]) / 60.0 + int(line[88:90]) / 3600.0
dec = -dec if line[83] == "-" else dec
v = float(line[102:107])
except ValueError:
continue
if v > max_mag:
continue
bv_text = line[109:114].strip()
bv = float(bv_text) if bv_text else 0.65
out.append((ra, dec, v, bv))
out.sort(key=lambda s: s[2]) # brightest first: a prefix is the brighter stars
return out
def pack_stars(rows):
buf = bytearray()
for ra, dec, v, bv in rows:
vq = min(255, max(0, int(round((v + 2.0) * 20.0))))
bq = min(255, max(0, int(round((bv + 0.5) * 50.0))))
buf += struct.pack("<HHBB", ra16(ra), dec16(dec), vq, bq)
return bytes(buf)
def pack_lines(path):
with open(path, encoding="utf-8") as f:
gj = json.load(f)
buf = bytearray()
chains = 0
for feat in gj["features"]:
geom = feat["geometry"]
assert geom["type"] == "MultiLineString"
for chain in geom["coordinates"]:
assert 2 <= len(chain) < 256
buf.append(len(chain))
for lon, lat in chain:
buf += struct.pack("<HH", ra16(lon), dec16(lat))
chains += 1
return bytes(buf), chains
def wrap(b64, width=110):
return "\n".join(b64[i : i + width] for i in range(0, len(b64), width))
def main():
bsc, lines, out = sys.argv[1:4]
max_mag = float(sys.argv[4]) if len(sys.argv) > 4 else 5.5
rows = stars(bsc, max_mag)
star_bytes = pack_stars(rows)
line_bytes, chains = pack_lines(lines)
text = f"""/* eslint-disable */
// GENERATED by scripts/ridge-sky/build-night-sky.py: do not edit. The night sky's data, J2000.
// Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991; public domain), Vmag <= {max_mag}, {len(rows)} stars.
// source http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (copy of CDS/VizieR V/50), sha256 {sha256(bsc)}
// Constellation lines: d3-celestial constellations.lines.json (Olaf Frohn, BSD-3-Clause), {chains} chains.
// source https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json, sha256 {sha256(lines)}
// Layout: see the generator's docstring. Stars are sorted brightest first.
export const STAR_COUNT = {len(rows)};
export const STARS_B64 = `
{wrap(base64.b64encode(star_bytes).decode())}
`;
export const LINE_CHAINS = {chains};
export const LINES_B64 = `
{wrap(base64.b64encode(line_bytes).decode())}
`;
"""
with open(out, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
print(f"{len(rows)} stars, {chains} chains, {len(star_bytes)} + {len(line_bytes)} bytes")
main()

View file

@ -1,14 +1,14 @@
# Background scene
**Default: the ridge scene** (`ridge/`), no WebGL. `startBackgroundScene` runs it unless the client
**Default: the ridge scene** (`ridge/`): no per-frame WebGL (the baked cards are lit once per scene build, in a WebGL2 context that is released after). `startBackgroundScene` runs it unless the client
config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to `off`, and null still
means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene.
- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky? })` returns `{ login, dispose }` or
- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ login, dispose }` or
null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) on the host
canvas at the viewport's size in canvas pixels, then the stars baked into it, a twinkle overlay canvas for the swinging ones
(`ridge/stars.ts`), the baked ridge planes (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`).
With no planes (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms.
(`ridge/stars.ts`), the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`).
With no cards (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms.
The host canvas and its parent must be positioned and the canvas should fill the parent. A resize rebuilds it; so does a sky change
(`index.ts`).
- Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness.
@ -18,17 +18,23 @@ means "keep the CSS ground". Everything below this section describes the opt-in
and shows `n / median / p95` in a corner readout.
- `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host
passes `ridgeSkyFor` (skyForState.ts) instead.
- Ridge planes: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry,
unknown or absent: the index default), then the place's `manifest.json` (v1, written by `scripts/ridge-bake/export.py`; it is the one JSON
the backdrop reads). `ridge/frameChoice.ts` picks the two baked frames the sky's sun lies between and a blend weight; `ridge/Backdrop.ts`
decodes only those. `index.ts` `prepare()` loads manifest and planes with the scene chunk, so `createRidgeScene({ backdrop })` stays
synchronous, and a rebuild keeps the old scene up until the new one's planes have loaded, then swaps. The rig is one div of three plane groups (far, mid, near; DOM order is paint order; no z-index, no fixed position, nothing
outside the scene's parent), each drifting on `Element.animate` (transform only, 150 s loop, paused when the tab is hidden, motion is
reduced or the scene is still); a still draws the planes into the host canvas. Two frames are a true crossfade (`frameChoice.ts`
`crossfade`: a at 1 - w plus b at w, summed in an isolated group, `plus-lighter` in the rig and `lighter` in an offscreen for the still), because
the planes are haze as alpha and b laid over a would double the haze. A failure anywhere (404, bad manifest, an image that
will not decode) is the sky-only scene on `FALLBACK_VIEW`, told to the host by the live scene alone, through `onPlanesFail` when the live scene has no planes and `onPlanesOk` when a later one has them (never from a stale or disposed build); it is never `onCompileFail`.
`vite.config.js` copies `public/ridge` into `dist/public/`.
- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry,
unknown or absent: the index default), then the place's `manifest.json` (schema 2, written by `scripts/ridge-bake/export.py`; it is the one JSON
the backdrop reads): K G-buffer cards, nearest first, each a colour WebP (albedo, straight alpha) and a geometry WebP (the normal as 'rt8', the
log-distance, and the wall code R = G = 255 for the extruded face under a ridge). `index.ts` `prepare()` loads the manifest and, with the scene chunk,
`ridge/Backdrop.ts` `loadBackdrop`: every card's two files fetched and decoded straight (no premultiply, no colour management), then
`ridge/lightCards.ts` lights each card once in WebGL2 for the sky of this build (sun and ambient from the atmosphere, aerial perspective from the
geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas, and releases
the context. A sky change is a rebuild, so it lights again; nothing is lit per frame, and the host canvas is only ever asked for 2d.
`createRidgeScene({ backdrop })` stays synchronous, and a rebuild keeps the old scene up until the new one's cards are lit, then swaps. The rig
is one div of K card elements (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's parent),
each placed at its rows of the plane and moved by `view.ts` `cardMotion`: the camera turns through the baker's heading range (capped so every card still covers
the viewport) and card i pans `scale_i` x heading and is drawn `scale_i` times its bake, about the horizon centre, as a camera pushed forward on a circle
round the bake centre sees it (ruling ridge-camera-on-circle); the scales come from the manifest. It drifts on `Element.animate` (transform only, 150 s loop,
paused when the tab is hidden, motion is reduced or the scene is still); a still draws the same cards at heading 0 into the host canvas. A failure
anywhere (404, a manifest that is not schema 2, a card that will not decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`,
told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale
or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`.
- `harness/scene/bundle.cjs <out> ridge` builds a standalone page (`?tier=`, `?probe=1`).
- Not yet measured on a phone: see the PR description.

View file

@ -14,9 +14,11 @@ import {
import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '../../utils/keyboard';
import { useSkyState } from '../../hooks/useSkyState';
import { SKY_STATES, setSkyState, type SkyState } from './skyState';
import { SKY_STATES, pickSkyState, type SkyState } from './skyState';
import { loadManifest } from './ridge/manifest';
import {
LINES_CREDIT,
STARS_CREDIT,
terrainCredit,
WEATHER_CREDIT,
WEATHER_CREDIT_URL,
@ -87,7 +89,7 @@ export function SkyStateControl() {
role="menuitemradio"
aria-checked={state === s}
onClick={() => {
setSkyState(s);
pickSkyState(s);
setCords(undefined);
}}
after={state === s ? <Icon size="100" src={Icons.Check} /> : undefined}
@ -118,6 +120,12 @@ export function SkyStateControl() {
</a>
. {WEATHER_DATASET}.
</Text>
<Text size="T200" priority="300">
{STARS_CREDIT}.
</Text>
<Text size="T200" priority="300">
{LINES_CREDIT}.
</Text>
</Box>
)}
</Box>

View file

@ -2,21 +2,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit';
import type { Scene } from './Scene';
import { startBackgroundScene } from './index';
import { setSkyClock, setSkyState } from './skyState';
import { pickSkyState, setSkyClock, setSkyState } from './skyState';
import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
import { FALLBACK_VIEW } from './ridge/view';
import { frameChoice } from './ridge/frameChoice';
import { sunAt } from './ridge/sunAt';
import { ridgeWeather } from './ridge/weather';
import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed';
const { createRidgeScene, createScene } = vi.hoisted(() => ({
const { createRidgeScene, createScene, loadBackdrop } = vi.hoisted(() => ({
createRidgeScene: vi.fn(),
createScene: vi.fn(),
loadBackdrop: vi.fn(),
}));
vi.mock('./ridge/Ridge', () => ({ createRidgeScene }));
// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a loader it can hold, fail and count.
vi.mock('./ridge/Backdrop', () => ({ loadBackdrop }));
vi.mock('./Scene', () => ({ createScene }));
// The physical sky is baked per call (tens of ms: atmosphere LUTs) and the clock here is fixed, so a state always
// draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is
@ -49,6 +51,35 @@ const microtasks = (n: number) =>
(p) => p.then(() => undefined),
Promise.resolve()
);
/** A loader for `loadBackdrop` that waits on `ctl.hold` (queueing its settle in `ctl.pending`), then resolves a backdrop or, with `ctl.fail` as it stood when asked, null. `ctl.calls` is the sky each call was lit for. */
const loader = () => {
const ctl = {
pending: [] as Array<() => void>,
hold: false,
fail: false,
calls: [] as any[],
};
loadBackdrop.mockImplementation(
(manifest: unknown, physical: unknown) =>
new Promise((resolve) => {
const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
const settle = () => {
ctl.calls.push(physical);
resolve(fails ? null : { manifest, cards: [] });
};
if (ctl.hold) ctl.pending.push(settle);
else settle();
})
);
return {
ctl,
release: async () => {
ctl.hold = false;
ctl.pending.splice(0).forEach((s) => s());
await flush();
},
};
};
const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() });
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
@ -59,6 +90,7 @@ beforeEach(() => {
setSkyState('auto');
createRidgeScene.mockReset();
createScene.mockReset();
loadBackdrop.mockReset();
});
afterEach(() => {
setSkyClock();
@ -71,7 +103,9 @@ describe('startBackgroundScene follows the sky state', () => {
createRidgeScene.mockReturnValue(fakeScene());
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));
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
);
scene?.dispose();
});
@ -90,7 +124,9 @@ describe('startBackgroundScene follows the sky state', () => {
setSkyState('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));
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
);
scene?.dispose();
});
@ -102,7 +138,9 @@ describe('startBackgroundScene follows the sky state', () => {
setSkyState('day');
await flush();
expect(first.dispose).toHaveBeenCalledOnce();
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top));
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
);
scene?.dispose();
expect(second.dispose).toHaveBeenCalledOnce();
});
@ -115,7 +153,9 @@ describe('startBackgroundScene follows the sky state', () => {
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));
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
);
expect(a.dispose).toHaveBeenCalledOnce();
scene?.dispose();
expect(b.dispose).toHaveBeenCalledOnce();
@ -218,7 +258,9 @@ describe('startBackgroundScene follows the sky state', () => {
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));
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
);
scene?.dispose();
});
@ -311,44 +353,25 @@ describe('the ridge planes', () => {
)
);
};
const images = (reject = false) => {
const loaded: string[] = [];
vi.stubGlobal(
'Image',
class {
src = '';
decoding = '';
cloneNode = () => this;
decode = async () => {
if (reject) throw new Error('bad image');
loaded.push(this.src);
};
}
);
return loaded;
};
beforeEach(() => forgetManifests());
it('hands the scene the planes of the frame the sky was baked for, over the manifest view', async () => {
it('hands the scene the lit cards of its manifest, lit once for the sky it was given, over the manifest view', async () => {
served();
const loaded = images();
const { ctl } = loader();
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
const opts = createRidgeScene.mock.calls[0][0];
expect(opts.backdrop.manifest.view.place.id).toBe('vienna');
expect(opts.sky.physical.view).toBe(opts.backdrop.manifest.view);
// Midnight in Vienna: the night frame, three planes.
expect(loaded.sort()).toEqual([
'/public/ridge/vienna-abc123abc123/night-far.webp',
'/public/ridge/vienna-abc123abc123/night-mid.webp',
'/public/ridge/vienna-abc123abc123/night-near.webp',
]);
expect(ctl.calls).toHaveLength(1);
expect(ctl.calls[0]).toBe(opts.sky.physical); // the sky the cards were lit for is the sky the scene paints
expect(ctl.calls[0].state).toBe('night'); // midnight by the clock
scene?.dispose();
});
it('config place picks the index entry; an unknown id falls back to the default', async () => {
served();
images();
loader();
createRidgeScene.mockReturnValue(fakeScene());
(await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose();
expect(createRidgeScene.mock.calls[0][0].backdrop.manifest.view.place.id).toBe('graz');
@ -375,13 +398,13 @@ describe('the ridge planes', () => {
'fetch',
vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
);
images();
loader();
await skyOnly();
});
});
describe('the ridge planes failing', () => {
it('a rejecting image gives the same sky-only scene, and a rebuild does not report again', async () => {
describe('the ridge cards failing', () => {
it('a card that will not load gives the same sky-only scene, and a rebuild does not report again', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async (url: string) => ({
@ -390,14 +413,7 @@ describe('the ridge planes failing', () => {
json: async () => (url.endsWith('index.json') ? wireIndex : wireManifest()),
}))
);
vi.stubGlobal(
'Image',
class {
decode = async () => {
throw new Error('bad image');
};
}
);
loader().ctl.fail = true;
forgetManifests();
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
@ -413,7 +429,7 @@ describe('the ridge planes failing', () => {
});
});
describe('the ridge planes and the live scene', () => {
describe('the ridge cards and the live scene', () => {
const serve = (manifest: Record<string, unknown> = wireManifest()) =>
vi.stubGlobal(
'fetch',
@ -423,48 +439,11 @@ describe('the ridge planes and the live scene', () => {
json: async () => (url.endsWith('index.json') ? wireIndex : manifest),
}))
);
/** Image stub whose decode waits on `gate` (when given) and then resolves or rejects as `outcome` says now. */
const decoder = () => {
const ctl = {
pending: [] as Array<() => void>,
hold: false,
fail: false,
urls: [] as string[],
};
vi.stubGlobal(
'Image',
class {
src = '';
decoding = '';
cloneNode = () => this;
decode = () => {
const fails = ctl.fail; // the outcome belongs to the request, whenever it settles
return new Promise<void>((resolve, reject) => {
const settle = () => {
ctl.urls.push(this.src);
if (fails) reject(new Error('bad image'));
else resolve();
};
if (ctl.hold) ctl.pending.push(settle);
else settle();
});
};
}
);
return {
ctl,
release: async () => {
ctl.hold = false;
ctl.pending.splice(0).forEach((s) => s());
await flush();
},
};
};
beforeEach(() => forgetManifests());
it('says nothing about planes when they load', async () => {
it('says nothing about cards when they load', async () => {
serve();
decoder();
loader();
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
const onPlanesOk = vi.fn();
@ -478,27 +457,60 @@ describe('the ridge planes and the live scene', () => {
scene?.dispose();
});
it('chooses frames by the sun over the manifest place, not the fallback place', async () => {
const w = wireManifest() as any;
// A day where it is night by the clock, in the south, has the noon sun high and to the north; at Vienna it is low in the south: a different frame.
serve({ ...w, place: { ...w.place, lat: -33, lon: -163.65, tz_h: -11 } });
decoder();
setSkyState('day');
it('lights the cards again for the new sky on a sky-change rebuild, never otherwise', async () => {
serve();
const { ctl } = loader();
createRidgeScene.mockReturnValue(fakeScene());
(await startBackgroundScene(config, caps, { canvas }))?.dispose();
const opts = createRidgeScene.mock.calls[0][0];
const { manifest } = opts.backdrop;
const own = frameChoice(manifest.frames, opts.sky.physical.sun);
const fallbackSun = ridgeSkyFor('day', FALLBACK_VIEW).physical!.sun;
const theirs = frameChoice(manifest.frames, fallbackSun);
expect(own.a.key).not.toBe(theirs.a.key);
expect(opts.backdrop.choice.a.key).toBe(own.a.key);
expect(opts.backdrop.choice.b?.key ?? null).toBe(own.b?.key ?? null);
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');
await flush();
expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']);
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();
});
it('rebuilds the scene with the constellation lines when Night is re-picked while Night is the choice, and again to take them off', async () => {
serve();
loader();
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
await flush();
expect(createRidgeScene).toHaveBeenCalledTimes(2);
expect(createRidgeScene.mock.calls[1][0].lines).toBe(true);
pickSkyState('night');
await flush();
expect(createRidgeScene.mock.calls[2][0].lines).toBe(false);
scene?.dispose();
});
it('a lighting pass that throws (no WebGL2) is the sky alone, one onPlanesFail and never onCompileFail', async () => {
serve();
loadBackdrop.mockRejectedValue(new Error('ridge: no WebGL2'));
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
const onCompileFail = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined();
expect(createRidgeScene.mock.calls[0][0].sky.physical.view).toBe(FALLBACK_VIEW);
expect(onPlanesFail).toHaveBeenCalledOnce();
expect(onPlanesFail.mock.calls[0][0].message).toMatch(/WebGL2/);
expect(onCompileFail).not.toHaveBeenCalled();
scene?.dispose();
});
it("keys a rebuild by the manifest's place: the same sky state over a rebaked place rebuilds", async () => {
serve();
decoder();
loader();
const [a, b] = [fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
const w = wireManifest() as any;
@ -536,23 +548,31 @@ describe('the ridge planes and the live scene', () => {
ok: true,
status: 200,
json: async () =>
url.endsWith('weather.json') ? wx : url.endsWith('index.json') ? wireIndex : { ...w, place },
url.endsWith('weather.json')
? wx
: url.endsWith('index.json')
? wireIndex
: { ...w, place },
}))
);
decoder();
loader();
setSkyClock(() => now);
createRidgeScene.mockReturnValue(fakeScene());
(await startBackgroundScene(config, caps, { canvas }))?.dispose();
const file = parseWeatherFile(wx)!;
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)).elevation);
weatherFromFile(
file,
sunAt({ id: 'x', altitudeKm: 0, ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000))
.elevation
);
expect(at(FALLBACK_VIEW.place)).not.toBe(at(place));
expect(ridgeWeather()).toBe(at(place));
});
it('a failed load is the sky alone on the fallback view, never the manifest place', async () => {
serve();
const { ctl } = decoder();
const { ctl } = loader();
ctl.fail = true;
createRidgeScene.mockReturnValue(fakeScene());
const scene = await startBackgroundScene(config, caps, { canvas });
@ -564,7 +584,7 @@ describe('the ridge planes and the live scene', () => {
it('a rebuild keeps the old scene until the new planes have loaded, then swaps', async () => {
serve();
const d = decoder();
const d = loader();
const first = fakeScene();
const second = fakeScene();
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
@ -590,7 +610,7 @@ describe('the ridge planes and the live scene', () => {
it('a build that fails after the scene is disposed makes nothing and says nothing', async () => {
serve();
const d = decoder();
const d = loader();
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
@ -606,7 +626,7 @@ describe('the ridge planes and the live scene', () => {
it('a superseded build that fails does not speak for the live scene, which has planes', async () => {
serve();
const d = decoder();
const d = loader();
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
@ -617,7 +637,7 @@ describe('the ridge planes and the live scene', () => {
d.ctl.fail = false;
setSkyState('dusk'); // the live one: its decodes will succeed
await flush();
const stale = d.ctl.pending.splice(0, 6);
const stale = d.ctl.pending.splice(0, 1);
d.ctl.pending.length = 0;
d.ctl.hold = false;
stale.forEach((s) => s()); // the first six are day's, settled in order
@ -628,9 +648,12 @@ describe('the ridge planes and the live scene', () => {
it('a superseded build that finishes after the newer one touches nothing of the live scene', async () => {
serve();
const d = decoder();
const d = loader();
const [first, second, third] = [fakeScene(), fakeScene(), fakeScene()];
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second).mockReturnValueOnce(third);
createRidgeScene
.mockReturnValueOnce(first)
.mockReturnValueOnce(second)
.mockReturnValueOnce(third);
const onActive = vi.fn();
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
d.ctl.hold = true;
@ -661,7 +684,7 @@ describe('the ridge planes and the live scene', () => {
it('a build that finishes after dispose makes nothing, shows nothing and disposes nothing twice', async () => {
serve();
const d = decoder();
const d = loader();
const first = fakeScene();
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(fakeScene());
const onActive = vi.fn();
@ -678,7 +701,7 @@ describe('the ridge planes and the live scene', () => {
it('a rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => {
serve();
const d = decoder();
const d = loader();
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null);
const onPlanesFail = vi.fn();
const onInactive = vi.fn();
@ -693,7 +716,7 @@ describe('the ridge planes and the live scene', () => {
it('tells the host when the live scene loses its planes and when it gets them back', async () => {
serve();
const d = decoder();
const d = loader();
d.ctl.fail = true;
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();

View file

@ -1,14 +1,13 @@
import type { Scene, SceneOptions } from './Scene';
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
import { debugOverlaysAllowed } from './debugOverlays';
import { getSkyState, subscribe } from './skyState';
import { getConstellationLines, getSkyState, subscribe } from './skyState';
import type { SkyState } from './skyState';
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';
import { frameChoice } from './ridge/frameChoice';
export type { Scene, SceneStats } from './Scene';
export type { SceneStyle, SceneTier } from './tier';
@ -20,7 +19,7 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
onInactive?: () => void;
/** A rebuild made a scene again: the host lets it show. */
onActive?: () => void;
/** The live scene is the sky alone because the baked ridge planes did not load (no manifest, a missing image). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */
/** The live scene is the sky alone because the baked ridge cards did not load (no manifest, a missing or undecodable card, no WebGL2 to light them). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */
onPlanesFail?: (e: Error) => void;
/** The live scene has its planes after `onPlanesFail` said it had none: the host lets go of the ground it filled. */
onPlanesOk?: () => void;
@ -77,7 +76,8 @@ async function prepare(
const { createRidgeScene } = await import('./ridge/Ridge');
const { manifest, fail } = await manifestOf(config);
await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place);
// The planes load with the scene chunk and the weather: createRidgeScene stays synchronous. Any failure is the sky alone.
// 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.
let backdrop: Backdrop | null = null;
let sky: SkyColours | undefined;
let planesFail: Error | null = fail;
@ -85,13 +85,12 @@ async function prepare(
try {
const manifestSky = ridgeSkyFor(state, manifest.view);
sky = manifestSky;
const choice = frameChoice(
manifest.frames,
(manifestSky.physical as NonNullable<typeof manifestSky.physical>).sun
);
const { loadBackdrop } = await import('./ridge/Backdrop');
backdrop = await loadBackdrop(manifest, choice);
if (!backdrop) throw new Error('ridge planes did not load');
backdrop = await loadBackdrop(
manifest,
manifestSky.physical as NonNullable<typeof manifestSky.physical>
);
if (!backdrop) throw new Error('ridge cards did not load');
} catch (e) {
backdrop = null;
sky = undefined;
@ -103,6 +102,7 @@ async function prepare(
...options,
sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW),
backdrop: backdrop ?? undefined,
lines: getConstellationLines(),
})
);
return { ...made, planesFail };

View file

@ -1,44 +1,90 @@
import { describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { loadBackdrop } from './Backdrop';
import { frameChoice } from './frameChoice';
import type { LitCard } from './lightCards';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { PhysicalSky } from './physicalSky';
const sky = {} as PhysicalSky;
const manifest = parseManifest(wireManifest(), '/d/');
const img = (src: string) => ({ src } as unknown as HTMLImageElement);
const stubDecoder = () => {
const made: { url: string; opts: unknown; closed: boolean }[] = [];
vi.stubGlobal(
'createImageBitmap',
vi.fn(async (blob: Blob & { url: string }, opts: unknown) => {
if (blob.url.endsWith('card-2-geometry.webp') && fail.on) throw new Error('bad card');
const bmp = { url: blob.url, opts, closed: false, close: () => (bmp.closed = true) };
made.push(bmp);
return bmp;
})
);
return made;
};
const fail = { on: false };
const blobFor = async (url: string) => ({ url } as unknown as Blob);
const lit = (m: typeof manifest): LitCard[] =>
m.cards.map((c) => ({ canvas: {} as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale }));
afterEach(() => {
fail.on = false;
vi.unstubAllGlobals();
});
describe('loadBackdrop', () => {
it('loads the planes of the needed frames only, by manifest directory', async () => {
const load = vi.fn(async (u: string) => img(u));
const one = await loadBackdrop(
manifest,
frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }),
load
it('fetches and decodes both files of every card straight, lights once, and returns the cards nearest first', async () => {
const made = stubDecoder();
const light = vi.fn((m: typeof manifest) => lit(m));
const bd = await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light });
expect(bd?.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
expect(bd?.manifest).toBe(manifest);
expect(made.map((b) => b.url).sort()).toEqual(
[0, 1, 2].flatMap((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`]).sort()
);
expect(load.mock.calls.map((c) => c[0]).sort()).toEqual([
'/d/noon-far.webp',
'/d/noon-mid.webp',
'/d/noon-near.webp',
]);
expect(one?.b).toBeNull();
load.mockClear();
const two = await loadBackdrop(
manifest,
frameChoice(manifest.frames, { elevation: 10, azimuth: 130 }),
load
made.forEach((b) =>
expect(b.opts).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' })
);
expect(load).toHaveBeenCalledTimes(6);
expect(two?.b?.far.src).toBe('/d/morning-far.webp');
expect(two?.a.near.src).toBe('/d/dawn-near.webp');
expect(light).toHaveBeenCalledOnce();
// Handed over in manifest order, each card its own pair.
const given = light.mock.calls[0] as unknown as [
unknown,
{ colour: { url: string }; geometry: { url: string } }[],
unknown
];
expect(given[1].map((p) => [p.colour.url, p.geometry.url])).toEqual(
[0, 1, 2].map((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`])
);
expect(given[2]).toBe(sky);
});
it('is null, and does not throw, when any image rejects', async () => {
const load = vi.fn(async (u: string) => {
if (u.includes('mid')) throw new Error('decode');
return img(u);
});
await expect(
loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), load)
).resolves.toBeNull();
it('closes the decoded bitmaps once they are lit', async () => {
const made = stubDecoder();
await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: lit });
expect(made).toHaveLength(6);
expect(made.every((b) => b.closed)).toBe(true);
});
it('is null when any one card will not decode, lights nothing and closes what it decoded', async () => {
const made = stubDecoder();
fail.on = true;
const light = vi.fn(lit);
expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light })).toBeNull();
expect(light).not.toHaveBeenCalled();
expect(made.length).toBeGreaterThan(0);
expect(made.every((b) => b.closed)).toBe(true);
});
it('is null when a file is missing, and when the lighting pass throws', async () => {
const made = stubDecoder();
const gone = async (url: string) => {
if (url.endsWith('card-1-colour.webp')) throw new Error('ridge: 404');
return blobFor(url);
};
expect(await loadBackdrop(manifest, sky, { fetchBlob: gone, light: lit })).toBeNull();
const boom = () => {
throw new Error('no WebGL2');
};
expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: boom })).toBeNull();
expect(made.every((b) => b.closed)).toBe(true);
});
});

View file

@ -1,44 +1,55 @@
// The decoded planes the scene composes: only the frames the choice needs. Failure is a value (null), never a throw.
import type { FrameChoice } from './frameChoice';
import type { Frame, PlaneName, RidgeManifest } from './manifest';
import { PLANE_NAMES } from './manifest';
export type Planes = Record<PlaneName, HTMLImageElement>;
// The ridge cards the scene composes, lit: every card's two files fetched and decoded exactly as the baker wrote them, then lit once for the sky
// (`lightCards.ts`). Failure is a value (null), never a throw.
import type { RidgeManifest } from './manifest';
import type { PhysicalSky } from './physicalSky';
import { lightCards } from './lightCards';
import type { CardBitmaps, LitCard } from './lightCards';
export interface Backdrop {
manifest: RidgeManifest;
choice: FrameChoice;
/** Decoded planes of frame a, and of frame b when the choice has one. */
a: Planes;
b: Planes | null;
/** Nearest first, as the manifest lists them. */
cards: LitCard[];
}
export type ImageLoader = (url: string) => Promise<HTMLImageElement>;
export interface BackdropDeps {
fetchBlob: (url: string) => Promise<Blob>;
light: (manifest: RidgeManifest, bitmaps: CardBitmaps[], sky: PhysicalSky) => LitCard[];
}
/** The browser's decoder: an <img> that has decoded, so the first paint does not wait on it. */
export const loadImage: ImageLoader = async (url) => {
const img = new Image();
img.decoding = 'async';
img.src = url;
await img.decode();
return img;
const fetchBlob = async (url: string): Promise<Blob> => {
const res = await fetch(url);
if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`);
return res.blob();
};
/** Straight alpha and the file's own values: the colour card's alpha is coverage and the geometry card's channels are data, so neither may be premultiplied or colour-managed. */
const decode = (blob: Blob): Promise<ImageBitmap> =>
createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
export async function loadBackdrop(
manifest: RidgeManifest,
choice: FrameChoice,
load: ImageLoader = loadImage
sky: PhysicalSky,
deps: Partial<BackdropDeps> = {}
): Promise<Backdrop | null> {
const planes = async (f: Frame): Promise<Planes> => {
const [far, mid, near] = await Promise.all(
PLANE_NAMES.map((n) => load(`${manifest.dir}${f.planes[n]}`))
);
return { far, mid, near };
};
const get = deps.fetchBlob ?? fetchBlob;
const light = deps.light ?? lightCards;
const open: ImageBitmap[] = [];
try {
const [a, b] = await Promise.all([planes(choice.a), choice.b ? planes(choice.b) : null]);
return { manifest, choice, a, b };
const files = manifest.cards.flatMap((c) => [c.colour, c.geometry]);
const settled = await Promise.allSettled(
files.map(async (f) => decode(await get(`${manifest.dir}${f}`)))
);
settled.forEach((s) => s.status === 'fulfilled' && open.push(s.value));
const failed = settled.find((s) => s.status === 'rejected');
if (failed) throw (failed as PromiseRejectedResult).reason;
const bitmaps = manifest.cards.map((_, i) => ({
colour: open[2 * i],
geometry: open[2 * i + 1],
}));
return { manifest, cards: light(manifest, bitmaps, sky) };
} catch {
return null;
} finally {
open.forEach((b) => b.close?.());
}
}

View file

@ -3,14 +3,14 @@ import { createRidgeScene } from './Ridge';
import { valueNoise, hash2 } from './noise';
import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe';
import type { SkyColours } from './skyColour';
import { makeStars } from './stars';
import { nightBodies } from './nightBodies';
import { sunAt } from './sunAt';
import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky';
import { startBackgroundScene } from '../index';
import { frameChoice } from './frameChoice';
import { parseManifest } from './manifest';
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
import type { Backdrop } from './Backdrop';
import { FALLBACK_VIEW, windowFor } from './view';
import { cardMotion, FALLBACK_VIEW, windowFor } from './view';
describe('noise', () => {
it('is deterministic and in [0, 1)', () => {
@ -147,9 +147,20 @@ function ctx() {
draws.push('sky');
},
save() {},
restore() {},
restore() {
c.t = undefined;
c.k = undefined;
},
translate(x: number, y: number) {
c.t = [x, y];
},
scale(k: number) {
c.k = k;
},
rect() {},
clip() {},
rotate() {},
ellipse() {},
createImageData: (w: number, h: number) => ({
data: new Uint8ClampedArray(w * h * 4),
width: w,
@ -160,7 +171,9 @@ function ctx() {
},
beginPath() {},
moveTo() {},
stroke() {},
stroke() {
draws.push('line');
},
createRadialGradient: () => ({ addColorStop: vi.fn() }),
lineTo() {},
closePath() {},
@ -178,7 +191,10 @@ function ctx() {
else draws.push('fill');
},
drawImage(...a: unknown[]) {
images.push(Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation }));
draws.push('image');
images.push(
Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation, t: c.t, k: c.k })
);
},
globalAlpha: 1,
globalCompositeOperation: 'source-over',
@ -367,13 +383,15 @@ describe('the door', () => {
describe('the starfield in the scene', () => {
const count = (kind: string) => draws.filter((d) => d === kind).length;
const night = {
...DAY,
top: [10, 14, 40],
mid: [30, 34, 80],
horizon: [60, 50, 90],
} as SkyColours;
const N = makeStars(night, 400, 800).length;
// A moonless-horizon night over Vienna (the moon is 17 degrees below it): the real stars of that moment, and no moon to count as an arc.
const t = new Date('2026-12-04T00:00:00Z');
const physical = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t));
const night: SkyColours = { ...DAY, physical };
const N = nightBodies(
physical,
paintPhysicalSky(physical, 400, 800, windowFor(FALLBACK_VIEW, 400, 800).camera),
false
).stars.length;
const hear = (name: string) => {
const calls = motion.addEventListener.mock.calls.filter((c: any[]) => c[0] === name);
return calls[calls.length - 1][1] as () => void;
@ -385,7 +403,7 @@ describe('the starfield in the scene', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
expect(count('star')).toBe(N);
expect(count('sky')).toBe(1);
expect(painted).toHaveLength(1); // the physical sky's one grid
expect(parent.children[1].anims).toHaveLength(0); // the overlay, above the sky
expect(parent.children).toHaveLength(2);
const before = baked();
@ -393,8 +411,8 @@ describe('the starfield in the scene', () => {
expect(baked()).toBe(before);
expect(count('clear')).toBeGreaterThan(60);
expect(count('clear')).toBeLessThanOrEqual(101);
// each pass paints at most SLOTS stars
expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 32);
// each pass paints at most SLOTS stars, each as its cover and the star again
expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64);
expect(count('twinkle')).toBeGreaterThan(0);
s.dispose();
});
@ -525,25 +543,16 @@ describe('rain in the scene', () => {
});
});
describe('the ridge planes in the scene', () => {
const manifest = parseManifest(wireManifest(), '/d/');
const fakeImg = (src: string) => {
const el = fakeEl('img');
el.src = src;
el.cloneNode = () => fakeImg(src);
return el as unknown as HTMLImageElement;
};
const planes = (k: string) => ({
far: fakeImg(`${k}-far`),
mid: fakeImg(`${k}-mid`),
near: fakeImg(`${k}-near`),
describe('the ridge cards in the scene', () => {
const manifest = parseManifest(wireManifest(), '/d/'); // three cards, scales 1.2, 1.0167, 1.005, nearest first
const litCards = (): Backdrop => ({
manifest,
cards: manifest.cards.map((c, k) => {
const canvas = fakeEl('canvas');
canvas.id = `card-${k}`;
return { canvas: canvas as unknown as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale };
}),
});
const backdropAt = (elevation: number, azimuth: number): Backdrop => {
const choice = frameChoice(manifest.frames, { elevation, azimuth });
return { manifest, choice, a: planes(choice.a.key), b: choice.b ? planes(choice.b.key) : null };
};
const NOON = backdropAt(60, 180);
const BLEND = backdropAt(10, 130);
const night: SkyColours = {
...DAY,
top: [10, 14, 40],
@ -553,10 +562,40 @@ describe('the ridge planes in the scene', () => {
};
const rigOf = (parent: any) =>
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));
const win = windowFor(manifest.view, 400, 800);
const motion400 = cardMotion(manifest, win);
it('lays the night bodies (lines, stars, moon) in the sky before any card, so the cards occlude them', () => {
const { canvas } = host();
createRidgeScene({
canvas,
tier: 'still',
sky: { ...night },
backdrop: litCards(),
lines: true,
});
const bodies = draws.map((d, i) => (d === 'line' || d === 'star' ? i : -1)).filter((i) => i >= 0);
const images = draws.map((d, i) => (d === 'image' ? i : -1)).filter((i) => i >= 0);
expect(bodies.length).toBeGreaterThan(0);
expect(draws).toContain('line'); // the lines are drawn (the sky is a night one)
const cards = images.slice(-3); // the sky's upscale first, then the three cards, farthest first
expect(cards).toHaveLength(3);
expect(Math.max(...bodies)).toBeLessThan(Math.min(...cards));
});
it('keeps the live sky canvas, with every body baked into it, under the twinkle canvas and the rig', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: { ...night }, backdrop: litCards(), lines: true });
const rig = rigOf(parent);
const twinkle = parent.children.findIndex((c: any) => c.tag === 'canvas');
expect(twinkle).toBeGreaterThanOrEqual(0);
expect(parent.children.indexOf(rig)).toBeGreaterThan(twinkle);
expect(draws.filter((d) => d === 'image')).toHaveLength(1); // only the sky's own upscale is in the host canvas: the cards are DOM above it
});
it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: NOON })!;
const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!;
const kinds = parent.children.map((c: any) => c.tag);
expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']);
expect(parent.children[2].children).toHaveLength(3);
@ -568,23 +607,36 @@ describe('the ridge planes in the scene', () => {
expect(parent.children).toEqual([canvas]);
});
it('is three groups, far to near, each placed by windowFor and drifting by its depth of driftPx', () => {
it('is one element per card, farthest first, each at its rows of the plane and its origin on the horizon centre', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!;
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const rig = rigOf(parent);
const win = windowFor(manifest.view, 400, 800);
expect(rig.children).toHaveLength(3);
rig.children.forEach((g: any, k: number) => {
expect(g.style.width).toBe(`${win.plane.w}px`);
expect(g.style.height).toBe(`${win.plane.h}px`);
expect(g.style.bottom).toBe('0px');
expect(g.style.left).toBe(`${(400 - win.plane.w) / 2}px`);
expect(g.children.map((i: any) => i.src)).toEqual([`noon-${['far', 'mid', 'near'][k]}`]);
const { keyframes, options } = g.anims[0];
const reach = win.driftPx * [0.35, 0.7, 1][k];
expect(rig.children.map((c: any) => c.id)).toEqual(['card-2', 'card-1', 'card-0']);
const planeTop = 800 - win.plane.bottom - win.plane.h;
rig.children.forEach((el: any, j: number) => {
const card = manifest.cards[2 - j];
expect(el.style.left).toBe(`${(400 - win.plane.w) / 2}px`);
expect(el.style.width).toBe(`${win.plane.w}px`);
expect(el.style.top).toBe(`${planeTop + card.top * win.plane.scale}px`);
expect(el.style.height).toBe(`${card.h * win.plane.scale}px`);
expect(el.style.transformOrigin).toBe(
`${win.plane.w / 2}px ${(manifest.view.horizonRow - card.top) * win.plane.scale}px`
);
});
s.dispose();
});
it('pans card i by scale_i x heading and scales it by scale_i, to and fro on the compositor', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
rigOf(parent).children.forEach((el: any, j: number) => {
const k = 2 - j;
const { scale, reachPx } = motion400.cards[k];
const { keyframes, options } = el.anims[0];
expect(scale).toBe(manifest.cards[k].scale);
expect(keyframes).toEqual([
{ transform: `translate3d(${-reach}px,0,0)` },
{ transform: `translate3d(${reach}px,0,0)` },
{ transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
{ transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
]);
expect(options).toMatchObject({
duration: 75000,
@ -593,50 +645,23 @@ describe('the ridge planes in the scene', () => {
easing: 'ease-in-out',
});
});
s.dispose();
});
it('crossfades a into b: a at 1 - w, b added at w, in a group of its own', () => {
const { parent, canvas } = host();
const BLEND3 = backdropAt(4, 130); // w = 0.2, not the symmetric half
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: BLEND3 })!;
const { w } = BLEND3.choice;
expect(w).toBeCloseTo(0.2, 6);
const g = rigOf(parent).children[1];
expect(g.style.isolation).toBe('isolate');
expect(
g.children.map((i: any) => [i.src, i.style.opacity, i.style.mixBlendMode ?? null])
).toEqual([
['dawn-mid', String(1 - w), null],
['morning-mid', String(w), 'plus-lighter'],
]);
s.dispose();
});
it('a lone frame is drawn at full opacity with no blend mode', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!;
const g = rigOf(parent).children[1];
expect(
g.children.map((i: any) => [i.src, i.style.opacity, i.style.mixBlendMode ?? null])
).toEqual([['noon-mid', '1', null]]);
// The nearer the card, the further it travels.
const reach = (j: number) => motion400.cards[2 - j].reachPx;
expect(reach(2)).toBeGreaterThan(reach(1));
expect(reach(1)).toBeGreaterThan(reach(0));
s.dispose();
});
it('adds no rAF or timer callback of its own: the drift is Element.animate, the stars alone loop', () => {
const { canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!;
expect(rafQueue).toHaveLength(1); // the frame sampler, as without planes
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards
s.dispose();
const bare = host();
const b = createRidgeScene({ canvas: bare.canvas, tier: 'full', sky: DAY })!;
expect(rafQueue).toHaveLength(1);
b.dispose();
});
it('pauses the drift under reduced motion, in a hidden tab, and plays it again', () => {
const { parent, canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!;
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!;
const anims = rigOf(parent).children.map((g: any) => g.anims[0]);
anims.forEach((a: any) => expect(a.play).toHaveBeenCalled());
anims.forEach((a: any) => a.pause.mockClear());
@ -654,57 +679,36 @@ describe('the ridge planes in the scene', () => {
anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
});
it("a still sums each blended plane in an offscreen (a at 1 - w, then b lighter at w) and draws it at windowFor's placement", () => {
it("a still draws every card, farthest first, scaled by its own scale about the rig's origin, at heading 0", () => {
const { parent, canvas } = host();
const BLEND3 = backdropAt(4, 130);
createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: BLEND3 });
const { w } = BLEND3.choice;
const win = windowFor(manifest.view, 400, 800);
const planesDrawn = images.filter((a) => (a[0] as any).src) as any[];
expect(planesDrawn.map((a) => [a[0].src, a.alpha, a.op])).toEqual(
['far', 'mid', 'near'].flatMap((n) => [
[`dawn-${n}`, 1 - w, 'source-over'],
[`morning-${n}`, w, 'lighter'],
])
);
// Each sum then meets the host canvas once, plainly, at the plane's placement.
const summed = images.filter((a) => !(a[0] as any).src && (a[0] as any).width) as any[];
expect(summed).toHaveLength(3);
summed.forEach((a) => {
createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: litCards() });
const drawn = images.filter((a) => (a[0] as any).id) as any[];
expect(drawn.map((a) => a[0].id)).toEqual(['card-2', 'card-1', 'card-0']);
const dpr = 2;
const s = win.plane.scale * dpr;
const x0 = (800 - win.plane.w * dpr) / 2;
const planeTop = 1600 - (win.plane.h + win.plane.bottom) * dpr;
const origin = [x0 + (win.plane.w * dpr) / 2, planeTop + manifest.view.horizonRow * s];
drawn.forEach((a, j) => {
const card = manifest.cards[2 - j];
expect(a.k).toBe(card.scale);
expect(a.t).toEqual(origin);
expect([a[1], a[2], a[3], a[4]]).toEqual([
(800 - win.plane.w * 2) / 2,
1600 - win.plane.h * 2,
win.plane.w * 2,
win.plane.h * 2,
x0 - origin[0],
planeTop + card.top * s - origin[1],
win.plane.w * dpr,
card.h * s,
]);
expect([a.alpha, a.op]).toEqual([1, 'source-over']);
expect([a[0].width, a[0].height]).toEqual([win.plane.w * 2, win.plane.h * 2]);
});
expect(parent.children).toEqual([canvas]);
});
it('a lone frame in a still goes straight to the host canvas at full alpha', () => {
const { canvas } = host();
createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: NOON });
const win = windowFor(manifest.view, 400, 800);
const planesDrawn = images.filter((a) => (a[0] as any).src) as any[];
expect(planesDrawn.map((a) => [a[0].src, a.alpha, a.op])).toEqual(
['far', 'mid', 'near'].map((n) => [`noon-${n}`, 1, 'source-over'])
);
const [, x, y, dw, dh] = planesDrawn[0];
expect([x, y, dw, dh]).toEqual([
(800 - win.plane.w * 2) / 2,
1600 - win.plane.h * 2,
win.plane.w * 2,
win.plane.h * 2,
]);
});
it('settles to a still with the planes painted when the frame rate is poor', () => {
it('settles to a still with the cards painted when the frame rate is poor', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON });
createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() });
runFrames(100, 400);
expect(images.filter((a) => (a[0] as any).src)).toHaveLength(3);
expect(images.filter((a) => (a[0] as any).id)).toHaveLength(3);
expect(parent.children).toEqual([canvas]);
});
@ -712,7 +716,27 @@ describe('the ridge planes in the scene', () => {
const { parent, canvas } = host();
createRidgeScene({ canvas, tier: 'full', sky: DAY });
expect(parent.children).toEqual([canvas]);
expect(images.filter((a) => (a[0] as any).src)).toHaveLength(0);
expect(images.filter((a) => (a[0] as any).id)).toHaveLength(0);
});
it('asks the host canvas, and every canvas it makes, only for 2d: the cards arrive lit', () => {
const { canvas } = host();
const kinds: string[] = [];
const ask = (el: any) => {
const real = el.getContext;
el.getContext = vi.fn((k: string) => (kinds.push(k), real(k)));
};
ask(canvas);
const make = doc.createElement;
doc.createElement = (t: string) => {
const el = make(t);
ask(el);
return el;
};
const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!;
expect(kinds.length).toBeGreaterThan(0);
expect(kinds.every((k) => k === '2d')).toBe(true);
s.dispose();
});
});

View file

@ -3,12 +3,12 @@ import { overlayRequested } from '../debugOverlays';
import { FrameSampler, FrameStats } from './probe';
import { skyColours, SkyColours, Srgb } from './skyColour';
import { paintSky as paintPhysicalSky } from './physicalSky';
import { windowFor } from './view';
import { crossfade } from './frameChoice';
import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars';
import { cardMotion, windowFor } from './view';
import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars';
import { nightBodies, paintNightBodies } from './nightBodies';
import type { NightBodies } from './nightBodies';
import { drawRainTile, RAIN_TILES } from './rain';
import type { Backdrop, Planes } from './Backdrop';
import { PLANE_NAMES } from './manifest';
import type { Backdrop } from './Backdrop';
export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */
@ -19,8 +19,10 @@ export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
onProbe?: (s: FrameStats & { still: boolean }) => void;
/** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */
sky?: SkyColours;
/** The baked ridge planes, already decoded; none is the sky-only scene (`view.ts` FALLBACK_VIEW). */
/** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */
backdrop?: Backdrop;
/** Draw the constellation lines over the stars (a hidden extra, `skyState.ts`); only a night sky shows them. */
lines?: boolean;
};
const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`;
@ -57,9 +59,9 @@ function paintSky(
cssW: number,
cssH: number,
makeCanvas: () => HTMLCanvasElement
): boolean {
): { ok: boolean; px?: ReturnType<typeof paintPhysicalSky> } {
const ctx = context2d(canvas);
if (!ctx) return false;
if (!ctx) return { ok: false };
if (sky.physical) {
const px = paintPhysicalSky(
sky.physical,
@ -79,7 +81,7 @@ function paintSky(
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(small, 0, 0, canvas.width, canvas.height);
if (px.sunDisc) drawSun(ctx, px.sunDisc, canvas.width, canvas.height);
return true;
return { ok: true, px };
}
}
const g = ctx.createLinearGradient(0, 0, 0, canvas.height);
@ -89,7 +91,7 @@ function paintSky(
g.addColorStop(1, css(sky.horizon));
ctx.fillStyle = g;
ctx.fillRect(0, 0, canvas.width, canvas.height);
return true;
return { ok: true };
}
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
@ -97,7 +99,7 @@ const clock = (): number => (typeof performance !== 'undefined' ? performance.no
interface Built {
/** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */
twinkle?: HTMLCanvasElement;
/** The ridge planes' rig, over the twinkle canvas and under the rain; absent in 'still' (the planes are drawn into the host canvas). */
/** The ridge cards' rig, over the twinkle canvas and under the rain; absent in 'still' (the cards are drawn into the host canvas). */
rig?: { el: HTMLElement; anims: (Animation | undefined)[] };
/** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */
rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] };
@ -106,13 +108,13 @@ interface Built {
/** The twinkle overlay redraws at most this often: the swings are 2 to 7 s, no need for 60 fps. */
const TWINKLE_FRAME_MS = 50;
/** Far, mid and near slide this share of the drift room (`windowFor` driftPx); one leg of the back-and-forth takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */
const DRIFT_DEPTH = [0.35, 0.7, 1] as const;
/** One leg of the back-and-forth drift, a turn of the heading from one end of its range to the other, takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */
const DRIFT_LEG_S = 75;
/**
* The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS
* ground"), no WebGL. It draws the sky, the stars, the baked ridge planes when given a `backdrop` (none: the sky alone) and the rain. The host canvas holds the baked sky; it and
* ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` (none: the sky alone) and the rain. The scene itself
* requests no WebGL: the cards arrive lit (`lightCards.ts`, once per scene build) and only 2D contexts are asked of the host canvas. The host canvas holds the baked sky; it and
* its parent must be positioned, and the canvas should fill the parent.
*/
export function createRidgeScene(opts: RidgeOptions): Scene | null {
@ -210,12 +212,14 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
};
/**
* The ridge over the sky: one div holding a group per plane (far, mid, near: DOM order is paint order, stacking is by order alone), each the frame's
* image and, when the choice blends two frames, the second over it at the blend weight. A group slides sideways on the compositor by
* `driftPx` times its depth; the baker's pixels are never touched.
* The ridge over the sky: one element per lit card, farthest first (DOM order is paint order, stacking is by order alone), placed at the card's rows
* of the plane and scaled about the horizon's centre by the baker's `scale` (`view.ts` `cardMotion` owns every offset and scale). The camera
* turns through its heading range and back on the compositor: card i pans `scale` x heading, so a nearer card leads the far range.
*/
const startRig = (bd: Backdrop, w: number, h: number): NonNullable<Built['rig']> => {
const win = windowFor(bd.manifest.view, w, h);
const { view } = bd.manifest;
const win = windowFor(view, w, h);
const motion = cardMotion(bd.manifest, win);
const el = document.createElement('div');
el.setAttribute('aria-hidden', 'true');
Object.assign(el.style, {
@ -228,41 +232,26 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
pointerEvents: 'none',
});
const anims: (Animation | undefined)[] = [];
PLANE_NAMES.forEach((name, k) => {
const group = document.createElement('div');
Object.assign(group.style, {
const planeTop = h - win.plane.bottom - win.plane.h;
for (let k = bd.cards.length - 1; k >= 0; k -= 1) {
const card = bd.cards[k];
const { scale, reachPx } = motion.cards[k];
const node = card.canvas;
Object.assign(node.style, {
position: 'absolute',
left: `${(w - win.plane.w) / 2}px`,
bottom: `${win.plane.bottom}px`,
top: `${planeTop + card.top * win.plane.scale}px`,
width: `${win.plane.w}px`,
height: `${win.plane.h}px`,
height: `${card.h * win.plane.scale}px`,
transformOrigin: `${win.plane.w / 2}px ${(view.horizonRow - card.top) * win.plane.scale}px`,
willChange: 'transform',
});
const layer = (planes: Planes, opacity: number, blend?: string) => {
const img = planes[name].cloneNode() as HTMLImageElement;
Object.assign(img.style, {
position: 'absolute',
left: '0',
top: '0',
width: '100%',
height: '100%',
opacity: String(opacity),
});
if (blend) img.style.mixBlendMode = blend;
group.appendChild(img);
};
// One rule (`crossfade`): a at 1 - w, b added to it at w; the group is its own isolated backdrop, so the sum meets the sky once.
const fade = crossfade(bd.choice);
group.style.isolation = 'isolate';
layer(bd.a, fade.a);
if (bd.b) layer(bd.b, fade.b, 'plus-lighter');
el.appendChild(group);
const reach = win.driftPx * DRIFT_DEPTH[k];
el.appendChild(node);
anims.push(
group.animate?.(
node.animate?.(
[
{ transform: `translate3d(${-reach}px,0,0)` },
{ transform: `translate3d(${reach}px,0,0)` },
{ transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
{ transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
],
{
duration: DRIFT_LEG_S * 1000,
@ -272,43 +261,32 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
}
)
);
});
}
parent.appendChild(el);
return { el, anims };
};
/** Paint the ridge planes into the host canvas, a and b crossfaded, far to near: the still scene's one image. */
const paintPlanes = (bd: Backdrop) => {
/** Paint the lit cards into the host canvas, farthest first, each at its scale about the same origin as the rig, at heading 0: the still scene's one image. */
const paintCards = (bd: Backdrop) => {
const ctx = context2d(canvas);
if (!ctx) return;
const { view } = bd.manifest;
const { w, h, scale } = viewSize();
const win = windowFor(bd.manifest.view, w, h);
const win = windowFor(view, w, h);
const s = win.plane.scale * scale;
const dw = win.plane.w * scale;
const dh = win.plane.h * scale;
const x = (canvas.width - dw) / 2;
const y = canvas.height - dh - win.plane.bottom * scale;
const fade = crossfade(bd.choice);
// A blend is summed in an offscreen of its own, as the rig sums it in an isolated group: 'lighter' on the host canvas would add to the sky.
const sum = bd.b ? document.createElement('canvas') : null;
if (sum) {
sum.width = dw;
sum.height = dh;
const x0 = (canvas.width - dw) / 2;
const planeTop = canvas.height - (win.plane.h + win.plane.bottom) * scale;
const ox = x0 + dw / 2;
const oy = planeTop + view.horizonRow * s;
for (let k = bd.cards.length - 1; k >= 0; k -= 1) {
const card = bd.cards[k];
ctx.save();
ctx.translate(ox, oy);
ctx.scale(card.scale, card.scale);
ctx.drawImage(card.canvas, x0 - ox, planeTop + card.top * s - oy, dw, card.h * s);
ctx.restore();
}
const sctx = sum ? context2d(sum) : null;
PLANE_NAMES.forEach((name) => {
if (!bd.b || !sum || !sctx) {
ctx.drawImage(bd.a[name], x, y, dw, dh);
return;
}
sctx.clearRect(0, 0, dw, dh);
sctx.globalCompositeOperation = 'source-over';
sctx.globalAlpha = fade.a;
sctx.drawImage(bd.a[name], 0, 0, dw, dh);
sctx.globalCompositeOperation = 'lighter';
sctx.globalAlpha = fade.b;
sctx.drawImage(bd.b[name], 0, 0, dw, dh);
ctx.drawImage(sum, x, y, dw, dh);
});
};
/** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */
@ -319,12 +297,17 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
const { w, h, scale } = viewSize();
canvas.width = Math.round(w * scale);
canvas.height = Math.round(h * scale);
if (!paintSky(canvas, sky, w, h, () => document.createElement('canvas'))) return false;
// Every star is baked into the sky; the twinkling ones get their own canvas, which a per-frame
// pass clears and paints over. 'still' has no overlay.
const stars = makeStars(sky, w, h);
const painted = paintSky(canvas, sky, w, h, () => document.createElement('canvas'));
if (!painted.ok) return false;
// The real stars, the moon and (when asked) the constellation lines are baked into the sky; the twinkling stars get their own
// canvas, which a per-frame pass clears and paints over. 'still' has no overlay. A sky with no physical model has no bodies.
const bodies: NightBodies =
painted.px && sky.physical
? nightBodies(sky.physical, painted.px, opts.lines === true)
: { stars: [], lines: [] };
const stars = bodies.stars;
const skyCtx = context2d(canvas);
if (skyCtx) drawStars(skyCtx, stars, canvas.width, canvas.height, scale);
if (skyCtx) paintNightBodies(skyCtx, bodies, canvas.width, canvas.height, scale);
let twinkle: HTMLCanvasElement | undefined;
if (stars.length && tier !== 'still') {
twinkle = document.createElement('canvas');
@ -397,7 +380,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
teardown();
cancelAnimationFrame(raf);
raf = 0;
if (opts.backdrop) paintPlanes(opts.backdrop);
if (opts.backdrop) paintCards(opts.backdrop);
report(true);
};

View file

@ -1,7 +1,16 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { WEATHER_CREDIT, WEATHER_CREDIT_URL, WEATHER_DATASET, terrainCredit } from './credits';
import {
LINES_CREDIT,
LINES_SOURCE_URL,
STARS_CREDIT,
STARS_SOURCE_URL,
WEATHER_CREDIT,
WEATHER_CREDIT_URL,
WEATHER_DATASET,
terrainCredit,
} from './credits';
import { parseIndex, parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import { WEATHER_ATTRIBUTION } from './weatherFeed';
@ -39,3 +48,14 @@ describe('the terrain credit', () => {
expect(terrainCredit(undefined)).toBeUndefined();
});
});
describe('the night sky credits', () => {
const data = readFileSync(join(__dirname, 'nightSkyData.ts'), 'utf8');
it("name the sources the generated data's header names, with their licences", () => {
expect(data).toContain(STARS_SOURCE_URL);
expect(data).toContain(LINES_SOURCE_URL);
expect(data).toMatch(/BSD-3-Clause/);
expect(STARS_CREDIT).toMatch(/Yale Bright Star Catalogue.*public domain/);
expect(LINES_CREDIT).toMatch(/Olaf Frohn.*BSD-3-Clause/);
});
});

View file

@ -14,3 +14,13 @@ export const terrainCredit = (
manifest: Pick<RidgeManifest, 'attribution'> | undefined
): string | undefined =>
manifest ? `${manifest.attribution.creditLine} ${manifest.attribution.licence}` : undefined;
/** The stars: the Yale Bright Star Catalogue, public domain (CDS/VizieR V/50; the file is the SAO Telescope Data Center's copy, see `nightSkyData.ts`). */
export const STARS_CREDIT =
'Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit and Warren 1991), public domain, CDS VizieR V/50';
export const STARS_SOURCE_URL = 'http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz';
/** The constellation lines: d3-celestial by Olaf Frohn, BSD-3-Clause (the repository's LICENSE, 2015). The licence asks for its notice to travel with redistributions: the full text is in `THIRD_PARTY_NOTICES.md` at the repository root. */
export const LINES_CREDIT =
'Constellation lines: d3-celestial by Olaf Frohn (BSD-3-Clause, copyright 2015 Olaf Frohn), https://github.com/ofrohn/d3-celestial';
export const LINES_SOURCE_URL =
'https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json';

View file

@ -97,6 +97,11 @@ function sampleMedium(altKm: number, mieScale: number): Medium {
};
}
/** The air's extinction per km (per channel) at a height above sea level: a horizontal path of d km keeps exp(-extinction x d) of the light. */
export function extinctionAt(altKm: number, mieScale: number): Vec3 {
return sampleMedium(altKm, mieScale).extinction;
}
/** Nearest positive hit of a unit-direction ray with a sphere at the origin: its distance, or -1. */
function raySphere(
ox: number,

View file

@ -1,117 +0,0 @@
import { describe, expect, it } from 'vitest';
import { BLEND_EDGE, crossfade, frameChoice } from './frameChoice';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
const { frames } = parseManifest(wireManifest(), '/d/');
const at = (elevation: number, azimuth: number) => frameChoice(frames, { elevation, azimuth });
const keys = (c: ReturnType<typeof at>) => [c.a.key, c.b?.key ?? null];
describe('frameChoice', () => {
it('blends continuously with elevation inside a half', () => {
const ws = [3, 6, 9, 12, 15, 18].map((el) => at(el, 130).w);
ws.forEach((w, i) => i && expect(w).toBeGreaterThan(ws[i - 1]));
});
it('weights by the elevation between the bracketing keys, a at the lower', () => {
// Morning half: night -12, dawn 0, morning 20, noon 60. Sun 10 deg is half way from dawn to morning.
const c = at(10, 130);
expect(keys(c)).toEqual(['dawn', 'morning']);
expect(c.w).toBeCloseTo(0.5, 6);
});
it('uses the afternoon keys after the noon azimuth and the morning keys before', () => {
expect(keys(at(10, 130))).toEqual(['dawn', 'morning']);
expect(keys(at(-1, 250))).toEqual(['dusk', 'golden']);
expect(at(-1, 250).w).toBeCloseTo(1.5 / 8.5, 6);
});
it('noon is the same single frame from both halves', () => {
expect(keys(at(60, 170))).toEqual(['noon', null]);
expect(keys(at(60, 190))).toEqual(['noon', null]);
expect(keys(at(75, 190))).toEqual(['noon', null]);
});
it('is the night key alone at or below its elevation, in either half', () => {
expect(keys(at(-12, 10))).toEqual(['night', null]);
expect(keys(at(-40, 300))).toEqual(['night', null]);
});
it('blends night into dawn before sunrise and dusk into night after sunset', () => {
expect(keys(at(-6, 90))).toEqual(['night', 'dawn']);
expect(keys(at(-6, 270))).toEqual(['night', 'dusk']);
});
it('collapses a blend within 2% of either end to one frame, and w stays in 0..1', () => {
expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01
expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99
const els = Array.from({ length: 325 }, (_, i) => -30 + i * 0.37);
els.forEach((el) =>
[0, 100, 179, 181, 270].forEach((az) => {
const c = at(el, az);
expect(c.w).toBeGreaterThanOrEqual(0);
expect(c.w).toBeLessThanOrEqual(1);
expect(c.b === null).toBe(c.w === 0);
})
);
});
it("splits the halves at the noon frame's azimuth, wherever the bake put it", () => {
const w = wireManifest() as any;
const shifted = parseManifest(
{
...w,
frames: w.frames.map((f: any) =>
f.key === 'noon' ? { ...f, sun: { ...f.sun, az: 170 } } : f
),
},
'/d/'
);
const pick = (az: number) => frameChoice(shifted.frames, { elevation: 10, azimuth: az });
expect([pick(169).a.key, pick(169).b?.key]).toEqual(['dawn', 'morning']);
expect([pick(171).a.key, pick(171).b?.key]).toEqual(['golden', 'noon']);
});
it('collapses exactly at BLEND_EDGE and no further: a blend of 3% still has two frames', () => {
expect(BLEND_EDGE).toBe(0.02);
// Morning half dawn 0 .. morning 20: w = el / 20.
expect(keys(at(0.6, 130))).toEqual(['dawn', 'morning']); // w = 0.03
expect(keys(at(19.4, 130))).toEqual(['dawn', 'morning']); // w = 0.97
expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01
expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99
});
});
describe('crossfade: the one rule of a blend', () => {
// A baked plane is haze as alpha: no pixel opaque, the same alpha in every frame. Frames as (premultiplied) colour and alpha.
const planeA = { c: 0.2, alpha: 0.6 };
const planeB = { c: 0.5, alpha: 0.6 };
const sum = (c: ReturnType<typeof at>) => {
const f = crossfade(c);
const b = c.b ? planeB : { c: 0, alpha: 0 };
return { c: planeA.c * f.a + b.c * f.b, alpha: planeA.alpha * f.a + b.alpha * f.b };
};
it('is a lerp of the two frames: colour and haze alike, never denser than either', () => {
[0.03, 0.2, 0.5, 0.8, 0.97].forEach((w) => {
const c = { a: frames[0], b: frames[1], w };
const got = sum(c);
expect(got.c).toBeCloseTo(planeA.c * (1 - w) + planeB.c * w, 12);
expect(got.alpha).toBeCloseTo(0.6, 12); // equal alphas stay equal: the haze is not doubled
expect(got.alpha).toBeLessThanOrEqual(Math.max(planeA.alpha, planeB.alpha) + 1e-12);
});
});
it('has no jump where the choice collapses: the blend either side of an edge is within the edge of the lone frame', () => {
const gap = Math.abs(planeA.c - planeB.c);
const high = sum({ a: frames[0], b: frames[1], w: 1 - BLEND_EDGE });
const low = sum({ a: frames[0], b: frames[1], w: BLEND_EDGE });
expect(Math.abs(high.c - planeB.c)).toBeLessThanOrEqual(BLEND_EDGE * gap + 1e-12); // collapse shows b alone
expect(Math.abs(low.c - planeA.c)).toBeLessThanOrEqual(BLEND_EDGE * gap + 1e-12); // collapse shows a alone
expect(high.alpha).toBeCloseTo(planeB.alpha, 12);
});
it('a lone frame is full weight alone', () => {
expect(crossfade({ a: frames[0], b: null, w: 0 })).toEqual({ a: 1, b: 0 });
});
});

View file

@ -1,55 +0,0 @@
// Which baked frames the live sun lies between, and how far. Pure. The frames are ordered by the sun elevation they were baked for, a
// morning half rising from the night key through dawn and morning to noon, an afternoon half falling from noon through golden and dusk
// to night; the two halves share noon and the night key. The half is the live sun's side of the noon frame's azimuth.
import type { Frame, FrameKey } from './manifest';
export interface FrameChoice {
/** The frame shown alone when b is null, else weighted 1 - w. */
a: Frame;
/** The frame crossfaded in at `w`, or null when one frame stands alone. */
b: Frame | null;
/** Weight of b in 0..1; 0 when b is null. */
w: number;
}
/** Blends this close to either frame are not worth a second image. */
export const BLEND_EDGE = 0.02;
/**
* The one rule of a blend, for the rig and the still alike: a true crossfade, a at 1 - w plus b at w, summed (premultiplied) in a group of
* their own. The baked planes carry haze as alpha (no pixel is opaque), so b laid over a at opacity w would double the haze mid-blend
* and jump when the choice collapses to b alone; the sum is a lerp of the two frames and never denser than either.
*/
export function crossfade(choice: FrameChoice): { a: number; b: number } {
return choice.b ? { a: 1 - choice.w, b: choice.w } : { a: 1, b: 0 };
}
const MORNING: readonly FrameKey[] = ['night', 'dawn', 'morning', 'noon'];
const AFTERNOON: readonly FrameKey[] = ['night', 'dusk', 'golden', 'noon'];
export function frameChoice(
frames: readonly Frame[],
sun: { elevation: number; azimuth: number }
): FrameChoice {
const by = (k: FrameKey): Frame => {
const f = frames.find((x) => x.key === k);
if (!f) throw new Error(`frameChoice: no ${k} frame`);
return f;
};
const noon = by('noon');
const half = (sun.azimuth < noon.sun.az ? MORNING : AFTERNOON).map(by);
// Ascending in elevation along the half, whatever the bake's numbers: sort so a hand-made manifest cannot invert the order.
half.sort((p, q) => p.sun.el - q.sun.el);
const lowest = half[0];
const highest = half[half.length - 1];
if (sun.elevation <= lowest.sun.el) return { a: lowest, b: null, w: 0 };
if (sun.elevation >= highest.sun.el) return { a: highest, b: null, w: 0 };
let i = 0;
while (half[i + 1].sun.el < sun.elevation) i += 1;
const lo = half[i];
const hi = half[i + 1];
const w = (sun.elevation - lo.sun.el) / (hi.sun.el - lo.sun.el);
if (w < BLEND_EDGE) return { a: lo, b: null, w: 0 };
if (w > 1 - BLEND_EDGE) return { a: hi, b: null, w: 0 };
return { a: lo, b: hi, w };
}

View file

@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest';
import { inkContrast, themeInk } from './frameLuma';
import { luminance } from '../../../../sky/skyTokens.js';
describe('inkContrast', () => {
it('reads the ink from the themes: dark Noonday ink by day and dusk, light Midnight ink at night', () => {
expect(themeInk('day')).toBe('#342d25');
expect(themeInk('dusk')).toBe('#342d25');
expect(themeInk('night')).toBe('#aeccff');
});
it('gives the known ratios on a white and on a black ridge', () => {
const dark = luminance('#342d25');
const light = luminance('#aeccff');
const day = inkContrast({ min: 1, max: 1 }, 'day');
expect(day.atMax).toBeCloseTo(1.05 / (dark + 0.05), 10);
expect(day.atMax).toBeCloseTo(13.6, 0);
const night = inkContrast({ min: 0, max: 0 }, 'night');
expect(night.atMin).toBeCloseTo((light + 0.05) / 0.05, 10);
expect(night.atMin).toBeCloseTo(12.9, 0);
});
it('the worst contrast is where the range comes closest to the ink', () => {
const ink = luminance('#342d25');
const across = inkContrast({ min: 0, max: 1 }, 'day');
expect(across.worst).toBe(1);
expect(inkContrast({ min: ink + 0.2, max: 0.9 }, 'day').worst).toBeCloseTo(
(ink + 0.2 + 0.05) / (ink + 0.05),
10
);
});
});

View file

@ -1,33 +0,0 @@
// What a baked frame's recorded luma (manifest `frames[].luma`, WCAG linear relative luminance of the composited planes where they are
// solid enough, export.py) means for the text over it: the contrast of the state's theme ink against the ridge's own extremes, no scrim.
// Data for ridge-ad-legibility, which sizes the scrim from it and owns the 4.5:1 pass/fail; nothing here gates.
import { baked } from '../../../../sky/baked';
import { luminance } from '../../../../sky/skyTokens.js';
import type { FixedSkyState } from '../skyState';
export interface FrameLuma {
min: number;
max: number;
}
/** The theme text ink skyState.ts's `FixedSkyState` bands derive: Noonday Sky's for day and dusk, Midnight Sky's for night. */
export const themeInk = (state: FixedSkyState): string =>
(state === 'night' ? baked.midnight : baked.noonday).tokens.Surface.OnContainer;
const ratio = (a: number, b: number): number => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
/**
* WCAG contrast of the state's ink over a plain backdrop of the ridge's darkest and of its lightest luminance, and `worst`: the lowest
* contrast over every luminance between them (the ink's own luminance clamped into the range, where the two are closest).
*/
export function inkContrast(
luma: FrameLuma,
state: FixedSkyState
): { atMin: number; atMax: number; worst: number } {
const ink = luminance(themeInk(state));
return {
atMin: ratio(ink, luma.min),
atMax: ratio(ink, luma.max),
worst: ratio(ink, Math.min(luma.max, Math.max(luma.min, ink))),
};
}

View file

@ -0,0 +1,358 @@
import { describe, expect, it, vi } from 'vitest';
import {
decodeNormal,
DEFAULT_LOOK,
PHYSICAL_LOOK,
celShade,
celLevels,
FRAGMENT,
lightCards,
lightingOf,
skyLut,
SKY_LUT,
sunColumns,
sunInColumn,
WALL_RT2,
} from './lightCards';
import type { RidgeLook } from './lightCards';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { PhysicalSky } from './physicalSky';
import { ACES_FIT, ACES_IN, ACES_OUT, BLACK_LIFT, makeCurve } from './toneMap';
const manifest = parseManifest(wireManifest(), '/d/');
const RAD = Math.PI / 180;
const dot = (a: readonly number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
/** A display curve that is the straight line from the black lift to white: a fixture, the cards only need some curve to carry. */
const FLAT_CURVE = makeCurve(
[0, 0.25, 0.5, 0.75, 1],
[0, 0.25, 0.5, 0.75, 1].map((v) => BLACK_LIFT + (1 - BLACK_LIFT) * v)
);
describe("the sun in a column's frame", () => {
it.each([5, 30, 60, 89])(
'at elevation %i it lights an up-facing normal by sin e and a normal facing it by 1',
(e) => {
const s = sunInColumn({ azimuth: 130, elevation: e }, 130);
expect(dot([0, 0, 1], s)).toBeCloseTo(Math.sin(e * RAD), 12);
expect(dot([Math.cos(e * RAD), 0, Math.sin(e * RAD)], s)).toBeCloseTo(1, 12);
expect(Math.hypot(...s)).toBeCloseTo(1, 12);
}
);
it('turns with the column: a sun 90 degrees clockwise of the ray lights the across axis, one behind lights the back', () => {
const across = sunInColumn({ azimuth: 100, elevation: 0 }, 10);
expect(across[0]).toBeCloseTo(0, 12);
expect(across[1]).toBeCloseTo(1, 12);
expect(sunInColumn({ azimuth: 190, elevation: 0 }, 10)[0]).toBeCloseTo(-1, 12);
expect(sunInColumn({ azimuth: 10, elevation: 0 }, 100)[1]).toBeCloseTo(-1, 12);
});
it('is computed for every column of the window, from its own azimuth', () => {
const view = manifest.view;
const cols = sunColumns(view, { azimuth: 214, elevation: 20 });
expect(cols).toHaveLength(view.planeW * 4);
const at = (x: number) => Array.from(cols.slice(x * 4, x * 4 + 3));
const mid = at(view.planeW / 2);
expect(mid[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the middle column looks near the sun's azimuth
expect(at(0)[1]).toBeGreaterThan(0.1); // the left edge has the sun to its right
expect(at(view.planeW - 1)[1]).toBeLessThan(-0.1);
});
});
describe('the wall code', () => {
it('reads R = G = 255 as a wall and a real normal as a normal', () => {
expect(decodeNormal(255, 255)).toEqual({ wall: true });
const flat = decodeNormal(128, 128);
expect(flat.wall).toBe(false);
if (!flat.wall) expect(flat.n[2]).toBeGreaterThan(0.99);
// The steepest real normal of the Vienna bake (r2 + t2 = 0.998) still decodes as terrain.
const r8 = Math.round(((Math.sqrt(0.998) + 1) / 2) * 255);
const steep = decodeNormal(r8, 128);
expect(steep.wall).toBe(false);
if (!steep.wall) expect(Math.hypot(...steep.n)).toBeCloseTo(1, 1);
expect(0.998).toBeLessThan(WALL_RT2);
expect(2).toBeGreaterThan(WALL_RT2);
});
it('the shader carries the same threshold', () => {
expect(FRAGMENT).toContain(`const float WALL_RT2 = ${WALL_RT2};`);
});
});
describe('the lighting inputs', () => {
const atm = (sinLog: number[] = []) => ({
observerKm: 0.183,
mieScale: 1,
transmittanceToSpace: (mu: number, out: number[]) => {
sinLog.push(mu);
out[0] = 0.9 * mu;
out[1] = 0.8 * mu;
out[2] = 0.7 * mu;
},
irradiance: { direct: [0, 0, 0], ambient: [0.1, 0.2, 0.3] },
radiance: vi.fn((vz: number, cosSun: number, out: number[]) => {
out[0] = vz;
out[1] = cosSun;
out[2] = 1;
}),
});
const sky = (elevation: number, a = atm()): PhysicalSky =>
({
sun: { azimuth: 214, elevation },
atm: a,
fit: { display: { exposure: 12, curve: FLAT_CURVE } },
view: manifest.view,
} as unknown as PhysicalSky);
it("takes the display of the sky's own fit, so terrain and sky share one exposure", () => {
const l = lightingOf(manifest, sky(30));
expect([l.exposure, l.curve]).toEqual([12, FLAT_CURVE]);
[0.1, 0.2, 0.3].forEach((a, i) => expect(l.key.ambient[i]).toBeCloseTo(a, 6)); // plus the airglow's
expect(l.logDMin).toBe(4.6);
expect(l.logDSpan).toBeCloseTo(11.5 - 4.6, 12);
});
it("gives the ground the sun's transmittance at its elevation, and none with the sun below the atmosphere's cut-off", () => {
const l = lightingOf(manifest, sky(30));
expect(l.key.direct[0]).toBeCloseTo(0.9 * Math.sin(30 * RAD), 12);
expect(l.key.direct[2]).toBeCloseTo(0.7 * Math.sin(30 * RAD), 12);
expect(lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg - 1)).key.direct).toEqual([0, 0, 0]);
expect(
lightingOf(manifest, sky(DEFAULT_LOOK.sunCutoffDeg + 0.5)).key.direct[0]
).toBeGreaterThanOrEqual(0);
});
it("takes the haze's extinction from the atmosphere at the observer: more aerosol, more extinction", () => {
const clear = lightingOf(manifest, sky(30, { ...atm(), mieScale: 1 }));
const hazy = lightingOf(manifest, sky(30, { ...atm(), mieScale: 4 }));
expect(clear.extinction.every((e) => e > 0)).toBe(true);
hazy.extinction.forEach((e, k) => expect(e).toBeGreaterThan(clear.extinction[k]));
});
it("builds the haze lookup from the view direction of each texel, the horizon's below it", () => {
const a = atm();
const lut = skyLut(sky(30, a), manifest.view, SKY_LUT.w, SKY_LUT.h);
expect(lut).toHaveLength(SKY_LUT.w * SKY_LUT.h * 4);
const texel = (i: number, j: number) =>
Array.from(lut.slice((j * SKY_LUT.w + i) * 4, (j * SKY_LUT.w + i) * 4 + 3));
const { horizonRow, planeH, pxPerDegV } = manifest.view;
const rowAt = (j: number) => ((j + 0.5) / SKY_LUT.h) * planeH;
// A row above the horizon asks the sky for the sine of its elevation; a row below it asks for the horizon.
const above = Math.floor((horizonRow / planeH) * SKY_LUT.h) - 6;
expect(texel(0, above)[0]).toBeCloseTo(
Math.sin(((horizonRow - rowAt(above)) / pxPerDegV) * RAD),
7 // the airglow floor adds a few 1e-9
);
expect(texel(0, SKY_LUT.h - 1)[0]).toBeCloseTo(0, 7);
// The sun lies at 214 degrees, the middle of the window: the cosine from the sun is 1 there and falls to the sides.
const mid = texel(SKY_LUT.w / 2, above)[1];
expect(mid).toBeGreaterThan(0.999);
expect(texel(0, above)[1]).toBeLessThan(mid);
});
});
describe('the display of the shader', () => {
const g = (n: number) => (Number.isInteger(n) ? `${n}.0` : String(n));
it("writes toneMap.ts's ACES matrices and fit into the source", () => {
ACES_IN.forEach((row, i) =>
expect(FRAGMENT).toContain(`const vec3 IN_R${i} = vec3(${row.map(g).join(', ')});`)
);
ACES_OUT.forEach((row, i) =>
expect(FRAGMENT).toContain(`const vec3 OUT_R${i} = vec3(${row.map(g).join(', ')});`)
);
expect(FRAGMENT).toContain(`vec3(${g(ACES_FIT[0])}, ${g(ACES_FIT[1])}, 0.0)`);
expect(FRAGMENT).toContain(`vec3(${g(ACES_FIT[2])}, ${g(ACES_FIT[3])}, ${g(ACES_FIT[4])})`);
});
});
describe('the look reaches the shader', () => {
// A recording WebGL2: every uniform call is kept by the name of its location, nothing is drawn.
const run = (look?: Partial<RidgeLook>) => {
const uniforms: Record<string, number[]> = {};
const gl = new Proxy(
{
getUniformLocation: (_p: unknown, name: string) => name,
uniform1i: () => undefined,
getShaderParameter: () => true,
getProgramParameter: () => true,
getExtension: () => null,
} as Record<string, unknown>,
{
get: (t, k: string) =>
k in t
? t[k]
: k.startsWith('uniform')
? (name: string, ...v: number[]) => {
uniforms[name] = v;
}
: () => ({}),
}
);
const el = { width: 0, height: 0, getContext: () => gl };
vi.stubGlobal('document', { createElement: () => el });
const bmp = { width: 1, height: 1, close: () => undefined } as unknown as ImageBitmap;
const sky = {
sun: { azimuth: 214, elevation: 30 },
atm: {
observerKm: 0.183,
mieScale: 1,
transmittanceToSpace: (_m: number, o: number[]) => o.fill(1),
irradiance: { direct: [0, 0, 0], ambient: [0.1, 0.2, 0.3] },
radiance: (_a: number, _b: number, o: number[]) => o.fill(0),
},
fit: { display: { exposure: 1, curve: FLAT_CURVE } },
view: manifest.view,
} as unknown as PhysicalSky;
const one = { ...manifest, cards: manifest.cards.slice(0, 1) };
try {
lightCards(one, [{ colour: bmp, geometry: bmp }], sky, look && { ...DEFAULT_LOOK, ...look });
} finally {
vi.unstubAllGlobals();
}
return uniforms;
};
it('defaults to DEFAULT_LOOK', () => {
const u = run();
expect(u.uInkKeep).toEqual([0.45, 0.55, 0.8]);
expect(u.uInkGeometry).toEqual([0.35, 0.85]);
});
it('carries an ink override to the uniforms: edge keep 1 removes edge ink', () => {
const u = run({ inkKeep: { edge: 1, occlude: 0.55, crease: 0.8 } });
expect(u.uInkKeep[0]).toBe(1);
});
it('carries the art-pass axes: relief, fixed light, tint, tone, ink scale, noise', () => {
const u = run({
reliefWeight: 0.15,
reliefLight: { mix: 1, azimuthDeg: 0, elevationDeg: 90 },
hazeTint: [0, 0.1, 0.3],
nearWarm: 0.5,
contrastByDistance: 1.5,
cardToneStep: 0.2,
cardGradient: 0.3,
inkScale: 0,
groundNoise: 0.4,
cloudShadows: 0.6,
});
expect(u.uRelief).toEqual([0.15, 1]);
expect(u.uFixedLight[2]).toBeCloseTo(1, 12); // a light straight up
expect(u.uHazeTint).toEqual([0, 0.1, 0.3]);
expect(u.uDist).toEqual([0.5, 1.5]);
expect(u.uCard).toEqual([1, 0.3]); // a single card sits at the centre of the tone steps
expect(u.uInkScale).toEqual([0]);
expect(u.uGround).toEqual([0.4, 0.6]);
});
it('scales the haze optical depth and the ambient light, and moves the sun cut-off', () => {
const base = run();
const look = run({ hazeScale: 2 * DEFAULT_LOOK.hazeScale, ambientScale: 0.5 });
look.uExt.forEach((e, k) => expect(e).toBeCloseTo(2 * base.uExt[k], 12));
expect(look.uAmbient[2]).toBeCloseTo(0.15, 6); // plus the airglow's ambient
expect(
lightingOf(manifest, sky30(), { ...DEFAULT_LOOK, sunCutoffDeg: 45 }).key.direct
).toEqual([0, 0, 0]);
});
});
function sky30(): PhysicalSky {
return {
sun: { azimuth: 214, elevation: 30 },
atm: {
observerKm: 0.183,
mieScale: 1,
transmittanceToSpace: (_m: number, o: number[]) => o.fill(1),
irradiance: { direct: [0, 0, 0], ambient: [0, 0, 0] },
},
fit: { display: { exposure: 1, curve: FLAT_CURVE } },
} as unknown as PhysicalSky;
}
describe('night key light', () => {
const atmOf = (ambient: [number, number, number]) => ({
observerKm: 0.183,
mieScale: 1,
transmittanceToSpace: (_m: number, o: number[]) => o.fill(1),
irradiance: { direct: [0, 0, 0], ambient },
radiance: (_a: number, _b: number, o: number[]) => o.fill(0),
});
const night = (moonEl: number | undefined, state = 'night') =>
lightingOf(manifest, {
state,
sun: { azimuth: 0, elevation: -30 },
moon: { azimuth: 150, elevation: moonEl ?? -20 },
night:
moonEl === undefined
? {}
: { moon: { azimuth: 150, elevation: moonEl, ratio: 2.5e-6, atm: atmOf([0.4, 0.5, 0.8]) } },
atm: atmOf([0.001, 0.001, 0.002]),
fit: { display: { exposure: 1, curve: FLAT_CURVE } },
view: manifest.view,
} as unknown as PhysicalSky);
it('is the moon at night: its direction, its irradiance ratio times the transmittance, its ambient scaled by the ratio', () => {
const l = night(40);
expect([l.key.azimuth, l.key.elevation]).toEqual([150, 40]);
expect(l.key.direct[0]).toBeCloseTo(2.5e-6, 12);
expect(l.key.ambient[2]).toBeGreaterThan(0.002);
expect(l.key.ambient[2]).toBeCloseTo(0.002 + 0.8 * 2.5e-6, 4);
});
it('has no direct light with the moon down, and keeps the ambient (twilight and airglow)', () => {
const l = night(undefined);
expect(l.key.direct).toEqual([0, 0, 0]);
expect(l.key.ambient.every((a) => a > 0)).toBe(true);
});
it('fades the moon out over the horizon', () => {
expect(night(-0.5).key.direct[0]).toBe(0);
expect(night(0.5).key.direct[0]).toBeGreaterThan(0);
expect(night(0.5).key.direct[0]).toBeLessThan(night(5).key.direct[0]);
});
it('the sun lights the other states', () => {
const l = lightingOf(manifest, sky30());
expect(l.key.elevation).toBe(30);
});
});
describe('cel shading', () => {
const sweep = (bands: number, softness: number, levels?: number[]) => {
const out = new Set<number>();
for (let i = -20; i <= 100; i += 1) {
const x = i / 100;
// away from the band edges (i / bands), where a softened edge is between two levels
if (Array.from({ length: bands }, (_, k) => k / bands).some((e) => e > 0 && Math.abs(x - e) <= softness / 2 + 1e-9)) continue;
out.add(Math.round(celShade(x, bands, softness, levels) * 1e9));
}
return out;
};
it.each([1, 2, 3, 4, 6])('quantizes a normal sweep to exactly %i levels away from the edges', (n) => {
expect(sweep(n, 0.05).size).toBe(n);
expect(sweep(n, 0).size).toBe(n);
});
it('is monotone in n.s, from the lowest level to the highest, and softens an edge without a jump', () => {
let prev = -1;
let maxStep = 0;
for (let i = -20; i <= 100; i += 1) {
const v = celShade(i / 100, 3, 0.1);
expect(v).toBeGreaterThanOrEqual(prev - 1e-12);
if (prev >= 0) maxStep = Math.max(maxStep, v - prev);
prev = v;
}
expect(maxStep).toBeLessThan(0.3);
expect(celShade(-0.5, 3, 0)).toBe(0);
expect(celShade(1, 3, 0)).toBe(1);
});
it('takes the band levels it is given', () => {
expect(celLevels(3, [0.2, 0.5, 0.9]).slice(0, 3)).toEqual([0.2, 0.5, 0.9]);
expect(celShade(0.9, 3, 0, [0.2, 0.5, 0.9])).toBe(0.9);
expect(celShade(-1, 3, 0, [0.2, 0.5, 0.9])).toBe(0.2);
});
it('is on in the default look and off in the physical one; the shader carries the ramp', () => {
expect(DEFAULT_LOOK.celBands).toBeGreaterThan(0);
expect(PHYSICAL_LOOK.celBands).toBe(0);
expect(FRAGMENT).toContain('float cel(float x)');
expect(FRAGMENT).toContain('uBandLevels[6]');
});
});

View file

@ -0,0 +1,647 @@
// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card (colour with straight alpha, geometry with the
// 'rt8' normal and log-distance, `scripts/ridge-bake/export.py`) is lit once, for the sky this scene build was made for, in one WebGL2 context on a
// canvas of its own, and copied into a 2D canvas of the card's size. After the last card the context is released: there is no per-frame WebGL, and the
// host canvas stays 2D (`Ridge.ts`). A sky change rebuilds the scene and lights again; nothing patches the lit canvases.
//
// Per pixel: the normal from the geometry card in the column's frame (r along the ray, t across it, up), the sun brought into that frame per column;
// radiance = albedo x (sun transmittance x max(n.s, 0) + ambient irradiance) / pi; aerial perspective L T(d) + Lsky (1 - T(d)) with d from the
// geometry's log-distance and the sky's own extinction at the ground; contours; then the sky's own display (exposure, ACES with `toneMap.ts`'s
// constants written into the shader, the sky's fitted curve, sRGB), so terrain and sky share one exposure. Wall pixels (R = G = 255 in the geometry file, a code
// no real normal reaches) are the extruded face under a ridge: they are lit with the face up and wear no crease ink.
import { extinctionAt } from './earthAtmosphere';
import type { Vec3 } from './earthAtmosphere';
import type { RidgeManifest } from './manifest';
import type { PhysicalSky } from './physicalSky';
import { addNightRadiance, airglow } from './nightSky';
import { ACES_FIT, ACES_IN, ACES_OUT, KNOTS, SCOTOPIC } from './toneMap';
import type { Curve } from './toneMap';
import type { View } from './view';
export interface CardBitmaps {
colour: ImageBitmap;
geometry: ImageBitmap;
}
/** A lit card: its pixels, premultiplied by the card's alpha, at the card's own size, and where the card sits in the plane. */
export interface LitCard {
canvas: HTMLCanvasElement;
top: number;
h: number;
scale: number;
}
/** A real normal has r2 + t2 at most 0.998 (probe on the Vienna bake); the wall code is 2. A code of the data, not of the look. */
export const WALL_RT2 = 1.02;
/** The lookup of the sky's radiance for the haze: azimuth columns by plane rows, filtered in the shader. */
export const SKY_LUT = { w: 64, h: 64 } as const;
/**
* The look: every number of the art pass (ratatoskr:follow_up:ridge-art-quality-rework), the one owner of them. None is a rule of the machine.
* The shader reads them as uniforms, so one compiled program serves every look.
*/
export interface RidgeLook {
/** A neighbour farther by more than this many nats of distance draws occluding ink on this pixel. */
occludeLogD: number;
/** A normal turning past this cosine between two non-wall pixels draws crease ink. */
creaseCos: number;
/** How much each ink keeps of the radiance it falls on (1 = no ink). */
inkKeep: { edge: number; occlude: number; crease: number };
/** Below this sun elevation (degrees) no direct sun reaches the ground (the atmosphere's own cut-off, `earthAtmosphere.ts` irradiance). */
sunCutoffDeg: number;
/** Multiplies the optical depth of the aerial perspective: 1 is the sky's own extinction, 0 no haze. */
hazeScale: number;
/** Multiplies the ambient irradiance the terrain is lit by. */
ambientScale: number;
/** 0 = no normal shading (the flat card tone, as a horizontal surface), 1 = shaded by the normals. */
reliefWeight: number;
/** The relief light: `mix` 0 is the sun, 1 a fixed light; `azimuthDeg` is clockwise of the view ray (-45 = upper left, behind the ridge), `elevationDeg` above the horizon. */
reliefLight: { mix: number; azimuthDeg: number; elevationDeg: number };
/** Added to the sky radiance used for the haze, rgb in units of that radiance's own luminance (so it holds at every sky): positive blue = cool far. */
hazeTint: readonly [number, number, number];
/** Strength (0..1) of a warm tint on the near, fading out with the log-distance across the baked range. */
nearWarm: number;
/** The relief's contrast about the pixel's flat tone scales by exp(c (1 - 2 d)), d the log-distance across the baked range: c > 0 near contrasty, far flat. */
contrastByDistance: number;
/** Value of each card multiplies by 1 + step (index - centre); the nearest card is index 0, so a positive step makes near darkest. */
cardToneStep: number;
/** Value ramp inside each card: 1 + g (y - 1/2), y the fraction down the card; positive lightens toward the foot. */
cardGradient: number;
/** Multiplies each ink's darkening: 0 = no lines. */
inkScale: number;
/** Procedural albedo variation (a stand-in for land cover we do not bake): fbm in metres on the ground, so its screen frequency follows distance. 0 = none. */
groundNoise: number;
/** Low-frequency noise darkening of the direct sun (static). 0 = none. */
cloudShadows: number;
/** Cel shading: the lit side of the relief (n.s) in this many flat bands instead of Lambert's ramp (0 = Lambert; at most `CEL_MAX`). */
celBands: number;
/** Width of each band edge in n.s units (0 = hard). */
celSoftness: number;
/** The level of each band, 0..1, darkest first (default: evenly from 0 to 1). Length `celBands`. */
celBandLevels?: readonly number[];
/** The ambient is coarse too: surfaces facing the sky (the normal's up component past `celAmbientEdge`) keep it whole, the rest keep this fraction (1 = no step). */
celAmbientAway: number;
celAmbientEdge: number;
}
/** The first art pass's look: Lambert relief, no procedural variation, the sky's own haze, full ink. Kept for comparison in the look sheet. */
export const PHYSICAL_LOOK: RidgeLook = {
occludeLogD: 0.35,
creaseCos: 0.85,
inkKeep: { edge: 0.45, occlude: 0.55, crease: 0.8 },
sunCutoffDeg: -1,
hazeScale: 1,
ambientScale: 1,
reliefWeight: 1,
reliefLight: { mix: 0, azimuthDeg: -45, elevationDeg: 40 },
hazeTint: [0, 0, 0],
nearWarm: 0,
contrastByDistance: 0,
cardToneStep: 0,
cardGradient: 0,
inkScale: 1,
groundNoise: 0,
cloudShadows: 0,
celBands: 0,
celSoftness: 0,
celAmbientAway: 1,
celAmbientEdge: 0.7,
};
/** The default: painterly (ground variation, cloud shadows, warm near, moderate haze, light ink) with cel-shaded relief. */
export const DEFAULT_LOOK: RidgeLook = {
...PHYSICAL_LOOK,
groundNoise: 0.35,
cloudShadows: 0.5,
nearWarm: 0.6,
hazeScale: 2,
inkScale: 0.4,
celBands: 3,
celSoftness: 0.05,
celAmbientAway: 0.7,
};
/** Most bands the shader's uniform holds. */
export const CEL_MAX = 6;
/** The level of each of `bands` cel bands, darkest first: `custom` where given, else evenly 0..1 (one band is fully lit). Padded to `CEL_MAX`. */
export function celLevels(bands: number, custom?: readonly number[]): number[] {
const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands)));
return Array.from({ length: CEL_MAX }, (_, i) => {
const k = Math.min(i, n - 1);
return custom?.[k] ?? (n === 1 ? 1 : k / (n - 1));
});
}
const smooth = (a: number, b: number, v: number): number => {
const t = Math.min(1, Math.max(0, (v - a) / (b - a)));
return t * t * (3 - 2 * t);
};
/**
* The cel ramp: the light of a surface whose normal makes `ndl` with the sun, in `bands` flat bands, edges at i / bands (i = 1..bands-1), each
* edge `softness` wide. The lowest band holds the unlit side too (its level is what ambient light alone leaves). The shader writes the same.
*/
export function celShade(ndl: number, bands: number, softness: number, levels?: readonly number[]): number {
const n = Math.min(CEL_MAX, Math.max(1, Math.round(bands)));
const lv = celLevels(n, levels);
let out = lv[0];
for (let i = 1; i < n; i += 1) {
const e = i / n;
const w = softness / 2;
out += (lv[i] - lv[i - 1]) * (w > 0 ? smooth(e - w, e + w, ndl) : ndl >= e ? 1 : 0);
}
return out;
}
const RAD = Math.PI / 180;
/** The sun in the frame of a column looking at azimuth `columnAzDeg`: along the ray, across it (clockwise, +90 degrees), up. Unit length. */
export function sunInColumn(
sun: { azimuth: number; elevation: number },
columnAzDeg: number
): [number, number, number] {
const el = sun.elevation * RAD;
const d = (sun.azimuth - columnAzDeg) * RAD;
return [Math.cos(el) * Math.cos(d), Math.cos(el) * Math.sin(d), Math.sin(el)];
}
/** The azimuth of plane column `x` of `w` (the card is the whole baked window wide). */
export const columnAzimuth = (view: View, x: number, w: number): number =>
view.lookAzDeg + ((x + 0.5) / w - 0.5) * view.windowDeg;
/** A geometry texel's red and green bytes as the shader reads them: a wall, or the unit normal (along the ray, across it, up). */
export function decodeNormal(
r8: number,
g8: number
): { wall: true } | { wall: false; n: [number, number, number] } {
const r = (r8 / 255) * 2 - 1;
const t = (g8 / 255) * 2 - 1;
const rt2 = r * r + t * t;
return rt2 > WALL_RT2
? { wall: true }
: { wall: false, n: [r, t, Math.sqrt(Math.max(0, 1 - rt2))] };
}
/** Everything the lighting reads of the sky and the manifest, as the numbers the shader's uniforms hold. */
export interface Lighting {
planeW: number;
planeH: number;
logDMin: number;
logDSpan: number;
/** Per km of horizontal path, per channel. */
extinction: Vec3;
/** Where the key light is (the sun by day and dusk, the moon at night) and what of it reaches the ground. */
key: KeyLight;
exposure: number;
/** The sky's fitted curve (`toneMap.ts`), applied per channel after ACES. */
curve: Curve;
/** Weight of the scotopic grade (`toneMap.ts`), applied to the radiance before exposure. */
grade: number;
}
/**
* The key light of the ground and what it brings. Day and dusk: the sun, by its transmittance to the ground, cut off below `look.sunCutoffDeg`.
* Night: the moon, by its transmittance times its irradiance relative to the sun's (phase and distance, `nightSky.ts`), faded out over the
* horizon; it is the direction the cel bands are cut by, and what is left of it, the sun's twilight and the airglow, is the ambient.
* `direct` is per unit of sun irradiance, `ambient` the irradiance the sky and the airglow give a horizontal surface.
*/
export interface KeyLight {
azimuth: number;
elevation: number;
direct: Vec3;
ambient: Vec3;
}
export function keyLight(sky: PhysicalSky, look: RidgeLook = DEFAULT_LOOK): KeyLight {
const ambient = scale3(sky.atm.irradiance.ambient, look.ambientScale);
const glow = [0, 0, 0];
airglow(0.6, glow);
const base = add3(ambient, scale3([glow[0], glow[1], glow[2]], Math.PI));
const trans = [0, 0, 0];
if (sky.state === 'night') {
const m = sky.night.moon;
if (!m) return { azimuth: sky.moon.azimuth, elevation: sky.moon.elevation, direct: [0, 0, 0], ambient: base };
m.atm.transmittanceToSpace(Math.max(Math.sin(m.elevation * RAD), 0), trans);
const fade = smooth(-0.5, 1.5, m.elevation) * m.ratio;
return {
azimuth: m.azimuth,
elevation: m.elevation,
direct: [trans[0] * fade, trans[1] * fade, trans[2] * fade],
ambient: add3(base, scale3(scale3(m.atm.irradiance.ambient, look.ambientScale), m.ratio)),
};
}
sky.atm.transmittanceToSpace(Math.max(Math.sin(sky.sun.elevation * RAD), 0), trans);
const lit = sky.sun.elevation > look.sunCutoffDeg;
return {
azimuth: sky.sun.azimuth,
elevation: sky.sun.elevation,
direct: lit ? [trans[0], trans[1], trans[2]] : [0, 0, 0],
ambient: base,
};
}
const scale3 = (v: Vec3, k: number): Vec3 => [v[0] * k, v[1] * k, v[2] * k];
const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
export function lightingOf(
manifest: RidgeManifest,
sky: PhysicalSky,
look: RidgeLook = DEFAULT_LOOK
): Lighting {
return {
planeW: manifest.view.planeW,
planeH: manifest.view.planeH,
logDMin: manifest.encoding.logDMin,
logDSpan: manifest.encoding.logDMax - manifest.encoding.logDMin,
extinction: scale3(extinctionAt(sky.atm.observerKm, sky.atm.mieScale), look.hazeScale),
key: keyLight(sky, look),
exposure: sky.fit.display.exposure,
curve: sky.fit.display.curve,
grade: sky.fit.display.grade ?? 0,
};
}
/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `planeW`. */
export function sunColumns(view: View, sun: { azimuth: number; elevation: number }): Float32Array {
const out = new Float32Array(view.planeW * 4);
for (let x = 0; x < view.planeW; x += 1) {
const [r, t, u] = sunInColumn(sun, columnAzimuth(view, x, view.planeW));
out.set([r, t, u, 0], x * 4);
}
return out;
}
/**
* The sky's radiance (per unit of sun irradiance) as the haze needs it: a small grid over the window's azimuths and the plane's rows, the view
* direction of each texel's centre. Rows below the horizon take the horizon's radiance (the haze in front of a ridge is the air at its foot).
*/
export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Float32Array {
const out = new Float32Array(w * h * 4);
const rgb = [0, 0, 0];
for (let j = 0; j < h; j += 1) {
const elDeg = Math.max(0, (view.horizonRow - ((j + 0.5) / h) * view.planeH) / view.pxPerDegV);
for (let i = 0; i < w; i += 1) {
const az = columnAzimuth(view, ((i + 0.5) / w) * view.planeW - 0.5, view.planeW);
sky.atm.radiance(Math.sin(elDeg * RAD), Math.cos((az - sky.sun.azimuth) * RAD), rgb);
addNightRadiance(sky.night, Math.sin(elDeg * RAD), az * RAD, rgb);
out.set([rgb[0], rgb[1], rgb[2], 0], (j * w + i) * 4);
}
}
return out;
}
const glsl = (n: number): string => (Number.isInteger(n) ? `${n}.0` : String(n));
/** The fragment shader. `ACES_IN` and `ACES_OUT` are written as rows and applied with `dot`, so no transposition is in play. */
export const FRAGMENT = `#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uColour;
uniform sampler2D uGeo;
uniform sampler2D uSun;
uniform sampler2D uSky;
uniform ivec2 uSize;
uniform ivec2 uSkySize;
uniform int uTop;
uniform vec2 uPlane;
uniform vec2 uLogD;
uniform vec3 uExt;
uniform vec3 uTSun;
uniform vec3 uAmbient;
uniform float uExposure;
uniform float uGrade;
uniform vec3 uScotTint;
uniform float uCx[${KNOTS}];
uniform float uCy[${KNOTS}];
uniform float uCm[${KNOTS}];
uniform vec2 uInkGeometry; // occludeLogD, creaseCos
uniform vec3 uInkKeep; // edge, occlude, crease
uniform float uInkScale;
uniform vec2 uRelief; // weight, mix toward the fixed light
uniform vec3 uFixedLight; // in the column frame
uniform vec3 uHazeTint;
uniform vec2 uDist; // nearWarm, contrastByDistance
uniform vec2 uCard; // value of this card, gradient
uniform vec2 uGround; // groundNoise, cloudShadows
uniform vec4 uCel; // bands (0 = Lambert), softness, ambientAway, ambientEdge
uniform float uBandLevels[${CEL_MAX}];
uniform float uRadPerPx; // radians of azimuth per plane pixel
out vec4 outColor;
const float PI = 3.14159265358979;
const vec3 NEAR_WARM = vec3(1.0, 0.82, 0.62);
const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
const float WALL_RT2 = ${glsl(WALL_RT2)};
${[0, 1, 2]
.map((i) => `const vec3 IN_R${i} = vec3(${ACES_IN[i].map(glsl).join(', ')});`)
.join('\n')}
${[0, 1, 2]
.map((i) => `const vec3 OUT_R${i} = vec3(${ACES_OUT[i].map(glsl).join(', ')});`)
.join('\n')}
const vec3 FIT_AB = vec3(${glsl(ACES_FIT[0])}, ${glsl(ACES_FIT[1])}, 0.0);
const vec3 FIT_CDE = vec3(${glsl(ACES_FIT[2])}, ${glsl(ACES_FIT[3])}, ${glsl(ACES_FIT[4])});
// toneMap.ts scotopic: toward the rods' luminance (Jensen et al. 2001) in a blue-shifted grey, at weight w.
float scotLum(vec3 c) {
float X = dot(vec3(0.4124, 0.3576, 0.1805), c);
float Y = dot(vec3(0.2126, 0.7152, 0.0722), c);
float Z = dot(vec3(0.0193, 0.1192, 0.9505), c);
return max(0.0, Y * (1.33 * (1.0 + (Y + Z) / max(X, 1e-30)) - 1.68));
}
vec3 scotopic(vec3 c, float w) {
if (w <= 0.0) return c;
float k = scotLum(c) / scotLum(vec3(1.0));
return mix(c, k * uScotTint, w);
}
vec3 toLinear(vec3 c) {
return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), c));
}
vec3 toSrgb(vec3 c) {
c = clamp(c, 0.0, 1.0);
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), c));
}
vec3 fit(vec3 v) {
return (v * (v + FIT_AB.x) - FIT_AB.y) / (v * (FIT_CDE.x * v + FIT_CDE.y) + FIT_CDE.z);
}
vec3 aces(vec3 x) {
vec3 p = fit(max(vec3(dot(IN_R0, x), dot(IN_R1, x), dot(IN_R2, x)), 0.0));
return clamp(vec3(dot(OUT_R0, p), dot(OUT_R1, p), dot(OUT_R2, p)), 0.0, 1.0);
}
// toneMap.ts applyCurve: the monotone cubic Hermite through the sky's five knots.
float curve1(float v) {
float x = clamp(v, 0.0, 1.0);
int k = 0;
for (int i = 1; i < ${KNOTS - 1}; i++) if (x > uCx[i]) k = i;
float h = uCx[k + 1] - uCx[k];
float t = (x - uCx[k]) / h;
float t2 = t * t;
float t3 = t2 * t;
return (2.0 * t3 - 3.0 * t2 + 1.0) * uCy[k] + (t3 - 2.0 * t2 + t) * h * uCm[k]
+ (-2.0 * t3 + 3.0 * t2) * uCy[k + 1] + (t3 - t2) * h * uCm[k + 1];
}
vec3 curve(vec3 c) { return vec3(curve1(c.r), curve1(c.g), curve1(c.b)); }
// lightCards.ts celShade: flat bands of n.s, edges at i / bands.
float cel(float x) {
int n = int(uCel.x);
float w = uCel.y * 0.5;
float l = uBandLevels[0];
for (int i = 1; i < ${CEL_MAX}; i++) {
if (i >= n) break;
float e = float(i) / float(n);
l += (uBandLevels[i] - uBandLevels[i - 1]) * (w > 0.0 ? smoothstep(e - w, e + w, x) : step(e, x));
}
return l;
}
vec3 skyAt(vec2 uv) {
vec2 f = uv * vec2(uSkySize) - 0.5;
vec2 b = floor(f);
vec2 t = f - b;
ivec2 lo = clamp(ivec2(b), ivec2(0), uSkySize - 1);
ivec2 hi = clamp(ivec2(b) + 1, ivec2(0), uSkySize - 1);
vec3 a = mix(texelFetch(uSky, ivec2(lo.x, lo.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, lo.y), 0).rgb, t.x);
vec3 c = mix(texelFetch(uSky, ivec2(lo.x, hi.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, hi.y), 0).rgb, t.x);
return mix(a, c, t.y);
}
float hash2(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float vnoise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
f = f * f * (3.0 - 2.0 * f);
return mix(mix(hash2(i), hash2(i + vec2(1.0, 0.0)), f.x), mix(hash2(i + vec2(0.0, 1.0)), hash2(i + vec2(1.0, 1.0)), f.x), f.y);
}
float fbm(vec2 p) {
float a = 0.5;
float sum = 0.0;
for (int i = 0; i < 4; i++) { sum += a * vnoise(p); p *= 2.03; a *= 0.5; }
return sum / 0.9375;
}
struct Geo { vec3 n; float logD; bool wall; };
Geo geoAt(ivec2 p) {
vec4 g = texelFetch(uGeo, p, 0);
vec2 rt = g.rg * 2.0 - 1.0;
float rt2 = dot(rt, rt);
Geo o;
o.wall = rt2 > WALL_RT2;
o.logD = uLogD.x + g.b * uLogD.y;
o.n = o.wall ? vec3(0.0, 0.0, 1.0) : vec3(rt, sqrt(max(0.0, 1.0 - rt2)));
return o;
}
void main() {
ivec2 p = ivec2(int(gl_FragCoord.x), uSize.y - 1 - int(gl_FragCoord.y));
vec4 c = texelFetch(uColour, p, 0);
if (c.a <= 0.0) { outColor = vec4(0.0); return; }
Geo g = geoAt(p);
vec3 s = texelFetch(uSun, ivec2(p.x, 0), 0).xyz;
if (uRelief.y > 0.0) s = normalize(mix(s, uFixedLight, uRelief.y));
float dist = exp(g.logD);
vec2 world = vec2(float(p.x) * uRadPerPx, 1.0) * dist;
vec3 albedo = toLinear(c.rgb);
if (uGround.x > 0.0) albedo *= max(1.0 + uGround.x * (2.0 * fbm(world / 250.0) - 1.0), 0.0);
float cloud = uGround.y > 0.0 ? 1.0 - uGround.y * smoothstep(0.5, 0.72, fbm(world / 4000.0 + 17.0)) : 1.0;
float lit = uCel.x > 0.5 ? cel(dot(g.n, s)) : max(dot(g.n, s), 0.0);
float ndl = mix(max(s.z, 0.0), lit, uRelief.x);
float ambStep = uCel.x > 0.5 ? mix(uCel.z, 1.0, smoothstep(uCel.w - uCel.y * 0.5, uCel.w + uCel.y * 0.5 + 1e-4, g.n.z)) : 1.0;
vec3 radiance = albedo * (uTSun * ndl * cloud + uAmbient * mix(1.0, ambStep, uRelief.x)) / PI;
float dn = clamp((g.logD - uLogD.x) / uLogD.y, 0.0, 1.0);
if (uDist.y != 0.0) {
vec3 flatTone = albedo * (uTSun * max(s.z, 0.0) * cloud + uAmbient) / PI;
radiance = flatTone + (radiance - flatTone) * exp(uDist.y * (1.0 - 2.0 * dn));
}
radiance *= mix(vec3(1.0), NEAR_WARM, uDist.x * (1.0 - dn));
vec3 T = exp(-uExt * (dist / 1000.0));
vec2 uv = vec2((float(p.x) + 0.5) / uPlane.x, (float(uTop + p.y) + 0.5) / uPlane.y);
vec3 haze = skyAt(uv);
haze += uHazeTint * dot(haze, LUMA);
radiance = radiance * T + haze * (1.0 - T);
radiance *= max(uCard.x * (1.0 + uCard.y * ((float(p.y) + 0.5) / float(uSize.y) - 0.5)), 0.0);
float keep = 1.0;
ivec2 dirs[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1));
for (int k = 0; k < 4; k++) {
ivec2 q = p + dirs[k];
if (q.x < 0 || q.y < 0 || q.x >= uSize.x || q.y >= uSize.y) continue;
float an = texelFetch(uColour, q, 0).a;
Geo gn = geoAt(q);
if (c.a >= 0.5 && an < 0.5) keep = min(keep, uInkKeep.x);
else if (an >= 0.5 && gn.logD - g.logD > uInkGeometry.x) keep = min(keep, uInkKeep.y);
else if (an >= 0.5 && !g.wall && !gn.wall && dot(g.n, gn.n) < uInkGeometry.y) keep = min(keep, uInkKeep.z);
}
radiance *= 1.0 - (1.0 - keep) * uInkScale;
vec3 rgb = toSrgb(curve(aces(scotopic(radiance, uGrade) * uExposure)));
outColor = vec4(rgb * c.a, c.a);
}
`;
const VERTEX = `#version 300 es
void main() {
vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
`;
function compile(gl: WebGL2RenderingContext, type: number, source: string): WebGLShader {
const sh = gl.createShader(type);
if (!sh) throw new Error('ridge: no shader');
gl.shaderSource(sh, source);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS))
throw new Error(`ridge: shader did not compile: ${gl.getShaderInfoLog(sh) ?? ''}`);
return sh;
}
function program(gl: WebGL2RenderingContext): WebGLProgram {
const p = gl.createProgram();
if (!p) throw new Error('ridge: no program');
gl.attachShader(p, compile(gl, gl.VERTEX_SHADER, VERTEX));
gl.attachShader(p, compile(gl, gl.FRAGMENT_SHADER, FRAGMENT));
gl.linkProgram(p);
if (!gl.getProgramParameter(p, gl.LINK_STATUS))
throw new Error(`ridge: shader did not link: ${gl.getProgramInfoLog(p) ?? ''}`);
return p;
}
function texture(gl: WebGL2RenderingContext, unit: number): WebGLTexture {
const t = gl.createTexture();
if (!t) throw new Error('ridge: no texture');
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return t;
}
function floatTexture(
gl: WebGL2RenderingContext,
unit: number,
w: number,
h: number,
data: Float32Array
): WebGLTexture {
const t = texture(gl, unit);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, w, h, 0, gl.RGBA, gl.FLOAT, data);
return t;
}
function bitmapTexture(gl: WebGL2RenderingContext, unit: number, bmp: ImageBitmap): WebGLTexture {
const t = texture(gl, unit);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, bmp);
return t;
}
/**
* Light the cards of `manifest` for `sky`, nearest first, as the manifest lists them. Throws without WebGL2 or when the shader will not link;
* the caller (`loadBackdrop`) turns any throw into the sky alone. Closes the bitmaps, and releases the context after the last card.
*/
export function lightCards(
manifest: RidgeManifest,
bitmaps: CardBitmaps[],
sky: PhysicalSky,
look: RidgeLook = DEFAULT_LOOK
): LitCard[] {
const glCanvas = document.createElement('canvas');
const gl = glCanvas.getContext('webgl2', {
alpha: true,
premultipliedAlpha: true,
antialias: false,
depth: false,
stencil: false,
});
if (!gl) throw new Error('ridge: no WebGL2');
try {
const lit = lightingOf(manifest, sky, look);
const prog = program(gl);
gl.useProgram(prog);
const u = (name: string) => gl.getUniformLocation(prog, name);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
['uColour', 'uGeo', 'uSun', 'uSky'].forEach((n, i) => gl.uniform1i(u(n), i));
gl.uniform2f(u('uPlane'), lit.planeW, lit.planeH);
gl.uniform2f(u('uLogD'), lit.logDMin, lit.logDSpan);
gl.uniform3f(u('uExt'), ...lit.extinction);
gl.uniform3f(u('uTSun'), ...lit.key.direct);
gl.uniform3f(u('uAmbient'), ...lit.key.ambient);
gl.uniform1f(u('uGrade'), lit.grade);
gl.uniform3f(u('uScotTint'), ...SCOTOPIC.tint);
gl.uniform1f(u('uExposure'), lit.exposure);
gl.uniform1fv(u('uCx'), lit.curve.x);
gl.uniform1fv(u('uCy'), lit.curve.y);
gl.uniform1fv(u('uCm'), lit.curve.m);
gl.uniform2f(u('uInkGeometry'), look.occludeLogD, look.creaseCos);
gl.uniform3f(u('uInkKeep'), look.inkKeep.edge, look.inkKeep.occlude, look.inkKeep.crease);
gl.uniform1f(u('uInkScale'), look.inkScale);
gl.uniform2f(u('uRelief'), look.reliefWeight, look.reliefLight.mix);
const fl = look.reliefLight;
gl.uniform3f(
u('uFixedLight'),
Math.cos(fl.elevationDeg * RAD) * Math.cos(fl.azimuthDeg * RAD),
Math.cos(fl.elevationDeg * RAD) * Math.sin(fl.azimuthDeg * RAD),
Math.sin(fl.elevationDeg * RAD)
);
gl.uniform3f(u('uHazeTint'), ...look.hazeTint);
gl.uniform2f(u('uDist'), look.nearWarm, look.contrastByDistance);
gl.uniform2f(u('uGround'), look.groundNoise, look.cloudShadows);
gl.uniform4f(u('uCel'), look.celBands, look.celSoftness, look.celAmbientAway, look.celAmbientEdge);
gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels));
gl.uniform1f(u('uRadPerPx'), (manifest.view.windowDeg * RAD) / lit.planeW);
gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h);
const sunTex = floatTexture(gl, 2, lit.planeW, 1, sunColumns(manifest.view, lit.key));
const skyTex = floatTexture(
gl,
3,
SKY_LUT.w,
SKY_LUT.h,
skyLut(sky, manifest.view, SKY_LUT.w, SKY_LUT.h)
);
const out = manifest.cards.map((card, i): LitCard => {
const { colour, geometry } = bitmaps[i];
glCanvas.width = colour.width;
glCanvas.height = colour.height;
gl.viewport(0, 0, colour.width, colour.height);
const colourTex = bitmapTexture(gl, 0, colour);
const geoTex = bitmapTexture(gl, 1, geometry);
gl.uniform2i(u('uSize'), colour.width, colour.height);
gl.uniform1i(u('uTop'), card.top);
gl.uniform2f(
u('uCard'),
1 + look.cardToneStep * (i - (manifest.cards.length - 1) / 2),
look.cardGradient
);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);
const canvas = document.createElement('canvas');
canvas.width = colour.width;
canvas.height = colour.height;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('ridge: no 2D context for a lit card');
ctx.drawImage(glCanvas, 0, 0);
gl.deleteTexture(colourTex);
gl.deleteTexture(geoTex);
colour.close();
geometry.close();
return { canvas, top: card.top, h: card.h, scale: card.scale };
});
gl.deleteTexture(sunTex);
gl.deleteTexture(skyTex);
return out;
} finally {
gl.getExtension('WEBGL_lose_context')?.loseContext();
}
}

View file

@ -1,19 +1,16 @@
// A hand-written manifest v1 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder.
import { FRAME_KEYS } from './manifest';
// A hand-written manifest v2 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder.
import type { View } from './view';
const SUN: Record<typeof FRAME_KEYS[number], [number, number]> = {
dawn: [100, 0],
morning: [130, 20],
noon: [180, 60],
golden: [240, 6],
dusk: [262, -2.5],
night: [0, -12],
};
/** Card scales of the fixture, nearest first, as the baker derives them for a camera 200 m forward (distances 1.2 km, 12 km, 40 km). */
const SCALES = [1.2, 1.0167, 1.005] as const;
export const wireManifest = (over: Record<string, unknown> = {}): Record<string, unknown> => ({
schema: 1,
baker_version: 1,
/** A v2 manifest of `k` cards (1 to 6), nearest first, each a band of the 600-row plane. */
export const wireManifest = (
over: Record<string, unknown> = {},
k = 3
): Record<string, unknown> => ({
schema: 2,
baker_version: 2,
bake_id: 'abc123abc123',
place: {
id: 'vienna',
@ -21,9 +18,7 @@ export const wireManifest = (over: Record<string, unknown> = {}): Record<string,
lat: 48.19,
lon: 16.35,
altitude_km: 0.183,
tz_h: 1,
tz_name: 'CET',
date: '2026-06-21',
eye_m: 1.7,
},
view: {
look_az_deg: 214,
@ -31,24 +26,29 @@ export const wireManifest = (over: Record<string, unknown> = {}): Record<string,
plane_w: 1280,
plane_h: 600,
px_per_deg_h: 1280 / 72,
px_per_deg_v: 17.7,
px_per_deg_v: 177.8,
exaggeration: 10,
horizon_row: 314.5,
sky_row: 0,
near_row: 599,
sky_row: 24,
near_row: 396,
},
frames: FRAME_KEYS.map((key) => ({
key,
sun: { az: SUN[key][0], el: SUN[key][1] },
hour_utc: 0,
planes: Object.fromEntries(
['far', 'mid', 'near'].map((n) => [
n,
{ file: `${key}-${n}.webp`, bytes: 1, w: 1280, h: 600 },
])
),
bytes: 3,
luma: { min: 0.1, max: 0.5 },
curvature: { r_earth_m: 6371000, k_ref: 0.13 },
encoding: { log_d_min: 4.6, log_d_max: 11.5, normal: 'rt8' },
camera: { r_m: 200, heading_max_deg: 23 },
cards: Array.from({ length: k }, (_, i) => ({
top: 100 * i,
h: 600 - 100 * i,
near_m: i ? 1000 * i : null,
far_m: i < k - 1 ? 1000 * (i + 1) : null,
median_m: 1000 * (i + 1),
distance_m: 1000 * (i + 1),
scale: SCALES[i] ?? 1.001,
colour: { file: `card-${i}-colour.webp`, bytes: 1 },
geometry: { file: `card-${i}-geometry.webp`, bytes: 1 },
})),
w: 1280,
h: 600,
bytes: 2 * k,
attribution: {
credit_line: 'credit',
licence: 'licence',
@ -72,5 +72,6 @@ export const ELSEWHERE_VIEW: View = {
planeW: 1600,
planeH: 700,
pxPerDegH: 1600 / 90,
pxPerDegV: 100,
horizonRow: 250,
};

View file

@ -3,7 +3,7 @@ import { forgetManifests, loadManifest, parseManifest } from './manifest';
import { wireIndex, wireManifest } from './manifest.fixture';
describe('parseManifest', () => {
it('reads a v1 manifest into the View the sky and planes share', () => {
it('reads a v2 manifest into the View the sky and cards share, and K cards nearest first', () => {
const m = parseManifest(wireManifest(), '/public/ridge/v/');
expect(m.dir).toBe('/public/ridge/v/');
expect(m.view).toMatchObject({
@ -11,36 +11,85 @@ describe('parseManifest', () => {
windowDeg: 72,
planeW: 1280,
planeH: 600,
pxPerDegH: 1280 / 72, // not px_per_deg_v (17.7): a real bake's two differ 10x
pxPerDegH: 1280 / 72,
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.frames.map((f) => f.key)).toEqual([
'dawn',
'morning',
'noon',
'golden',
'dusk',
'night',
]);
expect(m.frames[2]).toMatchObject({
sun: { az: 180, el: 60 },
planes: { far: 'noon-far.webp', near: 'noon-near.webp' },
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]);
expect(m.cards[1]).toEqual({
top: 100,
h: 500,
scale: 1.0167,
colour: 'card-1-colour.webp',
geometry: 'card-1-geometry.webp',
});
expect(m.attribution.creditLine).toBe('credit');
});
it('rejects a missing field, a wrong schema, a plane wider than 4096 and fewer than 6 frames', () => {
it.each([1, 2, 3, 4, 5, 6])('parses a bake of %i cards', (k) => {
expect(parseManifest(wireManifest({}, k), '/').cards).toHaveLength(k);
});
it('keeps only what the runtime reads: no distances, no camera offset', () => {
const m = parseManifest(wireManifest(), '/') as unknown as Record<string, any>;
expect(JSON.stringify(m)).not.toMatch(/median|near_m|far_m|distance|rM|r_m/);
});
it('refuses schema 1, no cards, seven cards, a card past the plane, a scale that is not above 0, a missing camera', () => {
const w = wireManifest() as any;
expect(() => parseManifest({ ...w, schema: 1 }, '/')).toThrow(/schema/);
expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/);
expect(() => parseManifest(wireManifest({}, 7), '/')).toThrow(/cards/);
const card = w.cards[0];
const withCard = (c: unknown) => ({ ...w, cards: [c] });
expect(() => parseManifest(withCard({ ...card, top: 300, h: 301 }), '/')).toThrow(/rows/);
expect(() => parseManifest(withCard({ ...card, top: -1 }), '/')).toThrow(/rows/);
expect(() => parseManifest(withCard({ ...card, scale: 0 }), '/')).toThrow(/scale/);
expect(() => parseManifest(withCard({ ...card, scale: -1 }), '/')).toThrow(/scale/);
expect(() => parseManifest(withCard({ ...card, scale: Infinity }), '/')).toThrow(/scale/);
expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/);
expect(() => parseManifest({ ...w, camera: { heading_max_deg: 0 } }, '/')).toThrow(/heading/);
});
it('rejects a missing field, a plane wider than 4096, a normal that is not rt8 and a backwards encoding', () => {
const w = wireManifest() as any;
expect(() => parseManifest({ ...w, bake_id: undefined }, '/')).toThrow(/bake_id/);
expect(() => parseManifest({ ...w, schema: 2 }, '/')).toThrow(/schema/);
expect(() => parseManifest({ ...w, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/);
expect(() => parseManifest({ ...w, frames: w.frames.slice(1) }, '/')).toThrow(/frames/);
expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow(
/horizon_row/
);
expect(() => parseManifest({ ...w, encoding: { ...w.encoding, normal: 'oct' } }, '/')).toThrow(
/normal/
);
expect(() =>
parseManifest({ ...w, encoding: { ...w.encoding, log_d_max: w.encoding.log_d_min } }, '/')
).toThrow(/encoding/);
expect(() => parseManifest(null, '/')).toThrow();
});
it('never echoes a value it refused', () => {
const w = wireManifest() as any;
const refusal = (bad: unknown) => {
try {
parseManifest(bad, '/');
} catch (e) {
return String(e);
}
return '';
};
for (const bad of [
{ ...w, schema: 'SECRET-VALUE-42' },
{ ...w, camera: { heading_max_deg: 'SECRET-VALUE-42' } },
{ ...w, cards: [{ ...w.cards[0], scale: 'SECRET-VALUE-42' }] },
]) {
const msg = refusal(bad);
expect(msg).not.toBe('');
expect(msg).not.toContain('SECRET-VALUE-42');
}
});
});
const serve = (files: Record<string, unknown>) => {

View file

@ -1,20 +1,21 @@
// The ridge backdrop's one JSON boundary: a static asset between the offline Python baker (scripts/ridge-bake/export.py, whose SCHEMA is the
// contract) and the page; no daemon state. Main-chunk safe: types, a parser and fetch only. Wire names are snake_case; the parsed manifest is
// camelCase and its `view` is the View (`view.ts`) the sky and the planes share.
// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 2: K G-buffer cards, nearest first.
import type { View } from './view';
export const FRAME_KEYS = ['dawn', 'morning', 'noon', 'golden', 'dusk', 'night'] as const;
export type FrameKey = typeof FRAME_KEYS[number];
export const PLANE_NAMES = ['far', 'mid', 'near'] as const;
export type PlaneName = typeof PLANE_NAMES[number];
export const PLANE_W_MAX = 4096;
/** As export.py MAX_CARDS: the decode budget holds this many. */
export const MAX_CARDS = 6;
export interface Frame {
key: FrameKey;
/** The sun this frame was lit by: degrees. */
sun: { az: number; el: number };
/** File names inside the manifest's directory. */
planes: Record<PlaneName, string>;
/** One G-buffer card: its rows of the plane, how large it sits against the bake, and its two files (names inside the manifest's directory). */
export interface CardEntry {
/** First row of the card in the plane, and its height in rows. */
top: number;
h: number;
/** The card's pan rate per unit of heading and its static size, as the baker derived them from the camera and the card's distance (ruling ridge-camera-on-circle). */
scale: number;
colour: string;
geometry: string;
}
export interface RidgeManifest {
@ -24,8 +25,12 @@ export interface RidgeManifest {
/** Display name of the place. */
name: string;
view: View;
/** In `FRAME_KEYS` order. */
frames: Frame[];
/** How the geometry card's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */
encoding: { logDMin: number; logDMax: number };
/** The widest heading either side of the look azimuth the baked cards allow, degrees. */
camera: { headingMaxDeg: number };
/** Nearest first. */
cards: CardEntry[];
attribution: { creditLine: string; licence: string; demSource: string; url: string };
}
@ -57,31 +62,39 @@ export function parseIndex(raw: unknown): RidgeIndex {
return { default: str(r.default, 'index.default'), places: out };
}
/** `dir` is the URL of the directory the manifest was read from; the planes are read relative to it. */
/** `dir` is the URL of the directory the manifest was read from; the cards are read relative to it. */
export function parseManifest(raw: unknown, dir: string): RidgeManifest {
const r = rec(raw, 'manifest');
if (r.schema !== 1) fail('schema', 'must be 1');
if (r.schema !== 2) fail('schema', 'must be 2');
const p = rec(r.place, 'place');
const v = rec(r.view, 'view');
const planeW = num(v.plane_w, 'view.plane_w');
if (planeW > PLANE_W_MAX) fail('view.plane_w', `above ${PLANE_W_MAX}`);
if (!Array.isArray(r.frames) || r.frames.length < FRAME_KEYS.length)
fail('frames', `fewer than ${FRAME_KEYS.length}`);
const frames = FRAME_KEYS.map((key) => {
const f = (r.frames as unknown[])
.map((x, i) => rec(x, `frames[${i}]`))
.find((x) => x.key === key);
if (!f) return fail('frames', `no ${key} frame`);
const sun = rec(f.sun, `frames.${key}.sun`);
const planes = rec(f.planes, `frames.${key}.planes`);
const file = (n: PlaneName) =>
str(rec(planes[n], `frames.${key}.planes.${n}`).file, `frames.${key}.planes.${n}.file`);
const planeH = num(v.plane_h, 'view.plane_h');
if (!Array.isArray(r.cards) || r.cards.length < 1) fail('cards', 'none');
if ((r.cards as unknown[]).length > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`);
const cards = (r.cards as unknown[]).map((x, i): CardEntry => {
const c = rec(x, `cards[${i}]`);
const top = num(c.top, `cards[${i}].top`);
const h = num(c.h, `cards[${i}].h`);
if (top < 0 || h < 1 || top + h > planeH) fail(`cards[${i}]`, 'outside the plane rows');
const scale = num(c.scale, `cards[${i}].scale`);
if (!(scale > 0)) fail(`cards[${i}].scale`, 'not above 0');
return {
key,
sun: { az: num(sun.az, `frames.${key}.sun.az`), el: num(sun.el, `frames.${key}.sun.el`) },
planes: { far: file('far'), mid: file('mid'), near: file('near') },
top,
h,
scale,
colour: str(rec(c.colour, `cards[${i}].colour`).file, `cards[${i}].colour.file`),
geometry: str(rec(c.geometry, `cards[${i}].geometry`).file, `cards[${i}].geometry.file`),
};
});
const e = rec(r.encoding, 'encoding');
if (e.normal !== 'rt8') fail('encoding.normal', "must be 'rt8'");
const logDMin = num(e.log_d_min, 'encoding.log_d_min');
const logDMax = num(e.log_d_max, 'encoding.log_d_max');
if (!(logDMax > logDMin)) fail('encoding', 'log_d_max not above log_d_min');
const headingMaxDeg = num(rec(r.camera, 'camera').heading_max_deg, 'camera.heading_max_deg');
if (!(headingMaxDeg > 0)) fail('camera.heading_max_deg', 'not above 0');
const a = rec(r.attribution, 'attribution');
const id = str(p.id, 'place.id');
return {
@ -98,11 +111,14 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest {
lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'),
windowDeg: num(v.window_deg, 'view.window_deg'),
planeW,
planeH: num(v.plane_h, 'view.plane_h'),
planeH,
pxPerDegH: num(v.px_per_deg_h, 'view.px_per_deg_h'),
pxPerDegV: num(v.px_per_deg_v, 'view.px_per_deg_v'),
horizonRow: num(v.horizon_row, 'view.horizon_row'),
},
frames,
encoding: { logDMin, logDMax },
camera: { headingMaxDeg },
cards,
attribution: {
creditLine: str(a.credit_line, 'attribution.credit_line'),
licence: str(a.licence, 'attribution.licence'),

View file

@ -0,0 +1,155 @@
import { describe, expect, it } from 'vitest';
import { limbAngle, nightBodies, onScreen, paintNightBodies } from './nightBodies';
import { makePhysicalSky, paintSky } from './physicalSky';
import { sunAt } from './sunAt';
import { FALLBACK_VIEW } from './view';
import type { Camera } from './view';
import { MAG_LIMIT, starsAt } from './starCatalogue';
import { moonAt } from './nightSky';
const P = FALLBACK_VIEW.place;
// A camera that sees most of the sky, so the moon of any hour is in it (the app's own window looks 72 degrees wide over the south-west).
const camera: Camera = { azimuthDeg: 180, hfovDeg: 340, vfovDeg: 170, horizonAt: 0.92 };
const sky = (iso: string, state: 'day' | 'dusk' | 'night' = 'night') => {
const t = new Date(iso);
return makePhysicalSky(state, t, 0, FALLBACK_VIEW, sunAt(P, t));
};
const bodies = (iso: string, state: 'day' | 'dusk' | 'night' = 'night', lines = false) => {
const p = sky(iso, state);
return { p, nb: nightBodies(p, paintSky(p, 640, 360, camera), lines) };
};
// 2026-11-24 22:00 UTC: full moon high in the south over Vienna. 2026-12-09 20:00 UTC: new moon. 2026-12-04 00:00 UTC: no moon up.
const FULL = '2026-11-24T22:00:00Z';
const NEW = '2026-12-09T20:00:00Z';
const MOONLESS = '2026-12-04T00:00:00Z';
describe('the stars of a night sky', () => {
it('are the catalogue stars of the sky\'s own moment inside the camera, brightest drawn largest', () => {
const { nb } = bodies(MOONLESS);
expect(nb.stars.length).toBeGreaterThan(300);
const inView = starsAt(new Date(MOONLESS), P.lat, P.lon, MAG_LIMIT, -0.5).filter((s) => {
const a = onScreen(camera, s.azimuth, s.elevation);
return a.x > -0.02 && a.x < 1.02 && a.y > -0.02 && a.y < 1.02;
});
expect(nb.stars.length).toBeLessThanOrEqual(inView.length);
const radii = nb.stars.map((s) => s.r);
expect(Math.max(...radii)).toBeGreaterThan(1.2 * Math.min(...radii));
});
it('are hidden by the twilight that exposes the sky: none at dusk, none by day, more on a moonless night than a full-moon one', () => {
expect(bodies('2026-06-21T10:40:00Z', 'day').nb.stars).toHaveLength(0);
expect(bodies('2026-12-04T15:20:00Z', 'dusk').nb.stars.length).toBeLessThan(5);
expect(bodies(MOONLESS).nb.stars.length).toBeGreaterThan(bodies(FULL).nb.stars.length);
});
it('move with the clock: three hours later the field is a different one, rotated by 45 degrees about the pole', () => {
const a = bodies('2026-12-04T00:00:00Z').nb.stars.slice(0, 20).map((s) => s.x.toFixed(3)).join();
const b = bodies('2026-12-04T03:00:00Z').nb.stars.slice(0, 20).map((s) => s.x.toFixed(3)).join();
expect(a).not.toBe(b);
});
it('twinkle by flux: a star dimmed by its gain is closer to the sky behind it, brightened is lighter, base is its fill', () => {
const { nb } = bodies(MOONLESS);
const s = nb.stars[0];
const lum = (c: string) => c.match(/\d+/g)!.map(Number).reduce((a, b) => a + b, 0);
expect(s.shade(1)).toBe(s.fill);
expect(lum(s.shade(0.35))).toBeLessThanOrEqual(lum(s.fill));
expect(lum(s.shade(1.15))).toBeGreaterThanOrEqual(lum(s.fill));
expect(lum(s.cover)).toBeLessThan(lum(s.fill));
});
});
describe('the moon of a night sky', () => {
it('is drawn where the ephemeris puts it, with the real phase', () => {
const { p, nb } = bodies(FULL);
expect(nb.moon).toBeDefined();
expect(nb.moon!.illuminated).toBeGreaterThan(0.99);
const at = onScreen(camera, p.moon.azimuth, p.moon.elevation);
expect(nb.moon!.x).toBeCloseTo(at.x, 9);
expect(nb.moon!.y).toBeCloseTo(at.y, 9);
// 0.52 degrees across, vertical field of view a few tens of degrees
expect(nb.moon!.radius * camera.vfovDeg).toBeCloseTo((p.moon.radius * 180) / Math.PI, 6);
});
it('is a thin sliver near new moon and not drawn when it is below the horizon', () => {
expect(moonAt(P, new Date(NEW)).illuminated).toBeLessThan(0.05);
expect(bodies(MOONLESS).nb.moon).toBeUndefined();
});
it('points its bright limb at the sun: down and toward the sun at moonrise after sunset, up at moonset in the morning', () => {
// A moon due south at 30 degrees with the sun at the horizon due west: the limb leans to the right (east is left on screen looking south, west right).
const a = limbAngle({ azimuth: 180, elevation: 30 }, { azimuth: 270, elevation: 0 });
expect(Math.cos(a)).toBeGreaterThan(0.5);
expect(Math.sin(a)).toBeLessThan(0);
// Sun straight below the moon: the limb points down the screen.
expect(Math.sin(limbAngle({ azimuth: 180, elevation: 30 }, { azimuth: 180, elevation: -30 }))).toBeLessThan(-0.99);
});
it('is lighter than the sky around it, and its dark side lighter than the sky', () => {
const { nb } = bodies(FULL);
const lum = (c: string) => c.match(/\d+/g)!.map(Number).reduce((a, b) => a + b, 0);
expect(lum(nb.moon!.lit)).toBeGreaterThan(lum(nb.moon!.dark));
expect(lum(nb.moon!.lit)).toBeGreaterThan(450);
});
});
describe('the constellation lines', () => {
it('are absent unless asked for, and present for a night sky when they are', () => {
expect(bodies(MOONLESS, 'night', false).nb.lines).toHaveLength(0);
const on = bodies(MOONLESS, 'night', true).nb.lines;
expect(on.length).toBeGreaterThan(20);
expect(on.every((l) => l.points.length > 1)).toBe(true);
});
it('are not drawn in a day or dusk sky even when asked for', () => {
expect(bodies('2026-06-21T10:40:00Z', 'day', true).nb.lines).toHaveLength(0);
expect(bodies('2026-12-04T15:20:00Z', 'dusk', true).nb.lines).toHaveLength(0);
});
});
describe('painting', () => {
it('draws lines, stars and the moon in that order and builds the terminator from an ellipse', () => {
const calls: string[] = [];
const ctx = new Proxy(
{},
{
get: (_t, k) => (k === 'save' ? () => 0 : () => calls.push(String(k))),
set: () => true,
}
) as unknown as CanvasRenderingContext2D;
const { nb } = bodies(FULL, 'night', true);
paintNightBodies(ctx, nb, 1280, 720, 2);
expect(calls.indexOf('stroke')).toBeGreaterThanOrEqual(0);
expect(calls.indexOf('stroke')).toBeLessThan(calls.indexOf('arc'));
expect(calls).toContain('ellipse');
expect(calls.filter((c) => c === 'arc').length).toBeGreaterThanOrEqual(nb.stars.length + 2);
});
});
describe('the stars under the figures', () => {
it('carry every constellation-line vertex in the sky strip that the moon does not cover, even under a full moon, at the app framing', async () => {
const { windowFor } = await import('./view');
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 nb = nightBodies(p, paintSky(p, 1100, 619, cam), false);
let vertices = 0;
let carried = 0;
linesAt(t, P.lat, P.lon).forEach((chain) =>
chain.forEach((q) => {
const a = onScreen(cam, q.azimuth, q.elevation);
if (a.x < 0 || a.x > 1 || a.y < 0 || a.y > 0.8) return;
// The moon is drawn over the stars, and a star inside its disc is not placed.
if (nb.moon && Math.hypot((nb.moon.x - a.x) * 1100, (nb.moon.y - a.y) * 619) < Math.max(2, nb.moon.radius * 619)) return;
vertices += 1;
// Placement only: a catalogue star is drawn within a few px of the vertex. How bright it is is the look's.
if (nb.stars.some((s) => Math.hypot((s.x - a.x) * 1100, (s.y - a.y) * 619) < 4)) carried += 1;
})
);
expect(vertices).toBeGreaterThan(20);
expect(carried).toBe(vertices);
});
});

View file

@ -0,0 +1,268 @@
// The night's bodies on the sky canvas: the real stars (`starCatalogue.ts`, for the place and the moment the sky state draws, `sun.time`),
// the moon with its phase, and the constellation lines. Each body's radiance (`nightSky.ts`) is added to the sky's own radiance behind it
// (the dome's grid, `skyDome.ts`) and goes through the sky's display (exposure, scotopic grade, ACES, curve), so the twilight that brightens the sky
// hides them, as a camera's exposure would, and the cards share the display. A body's contrast is compressed (`NIGHT_LOOK`): see there.
import { display8 } from './toneMap';
import { blackbodyRgb, compressed, extinguished, NIGHT_LOOK, moonSurface, starRadiance, temperatureOfBV } from './nightSky';
import type { Dome } from './skyDome';
import type { PhysicalSky, SkyPixels } from './physicalSky';
import { linesAt, MAG_LIMIT, starsAt } from './starCatalogue';
import type { Star } from './stars';
const RAD = Math.PI / 180;
const luma = (c: ArrayLike<number>): number => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
const css = (c: ArrayLike<number>): string => `rgb(${c[0]},${c[1]},${c[2]})`;
const wrap180 = (d: number): number => ((((d + 180) % 360) + 360) % 360) - 180;
/** Where a direction is on the image (the camera's angle-linear mapping, `view.ts`), as fractions of its width and height (y down). */
export function onScreen(
camera: SkyPixels['camera'],
azimuth: number,
elevation: number
): { x: number; y: number } {
return {
x: 0.5 + wrap180(azimuth - camera.azimuthDeg) / camera.hfovDeg,
y: camera.horizonAt - elevation / camera.vfovDeg,
};
}
/** The dome's radiance behind a point of the image (fractions), bilinear between texel centres. */
export function domeAt(dome: Dome, x: number, y: number, out: number[]): void {
const fx = Math.min(dome.w - 1, Math.max(0, x * dome.w - 0.5));
const fy = Math.min(dome.h - 1, Math.max(0, y * dome.h - 0.5));
const i0 = Math.floor(fx);
const j0 = Math.floor(fy);
const i1 = Math.min(dome.w - 1, i0 + 1);
const j1 = Math.min(dome.h - 1, j0 + 1);
const tx = fx - i0;
const ty = fy - j0;
for (let k = 0; k < 3; k += 1) {
const at = (i: number, j: number) => dome.hdr[(j * dome.w + i) * 3 + k];
out[k] =
(at(i0, j0) * (1 - tx) + at(i1, j0) * tx) * (1 - ty) + (at(i0, j1) * (1 - tx) + at(i1, j1) * tx) * ty;
}
}
/** `bg` plus a body of radiance `add` on it, the contrast compressed to the power `exp` (1 physical), as linear rgb into `out`. */
function composite(bg: number[], add: number[], exp: number, out: number[]): void {
const total = luma(bg) + luma(add);
const k = total > 0 ? compressed(luma(bg), luma(add), exp) / total : 1;
for (let i = 0; i < 3; i += 1) out[i] = (bg[i] + add[i]) * k;
}
export interface MoonDraw {
x: number;
y: number;
/** Radius as a fraction of the image height. */
radius: number;
/** Lit fraction of the disc and the phase angle (0 full) in radians. */
illuminated: number;
phaseAngle: number;
/** Direction of the bright limb on the image, radians counter-clockwise from the right. */
limb: number;
lit: string;
dark: string;
}
export interface LineDraw {
/** Polyline in image fractions. */
points: { x: number; y: number }[];
}
export interface NightBodies {
stars: Star[];
moon?: MoonDraw;
lines: LineDraw[];
}
/** Unit vector (east, north, up) of a direction. */
const vec = (az: number, el: number): [number, number, number] => [
Math.cos(el * RAD) * Math.sin(az * RAD),
Math.cos(el * RAD) * Math.cos(az * RAD),
Math.sin(el * RAD),
];
/** The screen direction (radians, counter-clockwise from the right) from the moon toward `toward`, by the tangent of the great circle at the moon. */
export function limbAngle(moon: { azimuth: number; elevation: number }, toward: { azimuth: number; elevation: number }): number {
const m = vec(moon.azimuth, moon.elevation);
const s = vec(toward.azimuth, toward.elevation);
const d = m[0] * s[0] + m[1] * s[1] + m[2] * s[2];
const t = [s[0] - d * m[0], s[1] - d * m[1], s[2] - d * m[2]];
const az = moon.azimuth * RAD;
const el = moon.elevation * RAD;
const east = [Math.cos(az), -Math.sin(az), 0];
const up = [-Math.sin(el) * Math.sin(az), -Math.sin(el) * Math.cos(az), Math.cos(el)];
return Math.atan2(t[0] * up[0] + t[1] * up[1] + t[2] * up[2], t[0] * east[0] + t[1] * east[1] + t[2] * east[2]);
}
/** Great-circle subdivision of a chain's legs, as az/el. */
function slerp(a: { azimuth: number; elevation: number }, b: { azimuth: number; elevation: number }, n: number) {
const u = vec(a.azimuth, a.elevation);
const v = vec(b.azimuth, b.elevation);
const w = Math.acos(Math.min(1, Math.max(-1, u[0] * v[0] + u[1] * v[1] + u[2] * v[2])));
if (w < 1e-6) return [a];
return Array.from({ length: n + 1 }, (_, i) => {
const t = i / n;
const s0 = Math.sin((1 - t) * w) / Math.sin(w);
const s1 = Math.sin(t * w) / Math.sin(w);
const p = [0, 1, 2].map((k) => s0 * u[k] + s1 * v[k]);
return {
azimuth: ((Math.atan2(p[0], p[1]) / RAD) % 360 + 360) % 360,
elevation: Math.asin(Math.min(1, Math.max(-1, p[2]))) / RAD,
};
});
}
/**
* The stars, moon and (when asked, and only in the night state) constellation lines of a physical sky as seen through the camera of `px`
* (`paintSky`'s grid and the dome behind it). The moment is the sky's own, `p.sun.time`, so the bodies agree with the light.
*/
export function nightBodies(p: PhysicalSky, px: SkyPixels, withLines: boolean): NightBodies {
const { place } = p.view;
const { camera, dome } = px;
const display = p.fit.display;
const bg = [0, 0, 0];
const add = [0, 0, 0];
const tot = [0, 0, 0];
const out = [0, 0, 0];
let moon: MoonDraw | undefined;
const mo = p.moon;
const mAt = onScreen(camera, mo.azimuth, mo.elevation);
if (mo.elevation > -1 && mAt.x > -0.05 && mAt.x < 1.05 && mAt.y > -0.05 && mAt.y < 1.05) {
domeAt(dome, mAt.x, mAt.y, bg);
const trans = [0, 0, 0];
p.atm.transmittanceToSpace(Math.max(Math.sin(mo.elevation * RAD), 0), trans);
const top = Math.max(...trans, 1e-9);
const tint = [1, 0.96, 0.88];
const surface = moonSurface(mo);
for (let i = 0; i < 3; i += 1) add[i] = surface * tint[i] * (trans[i] / top) ** 0.6;
composite(bg, add, NIGHT_LOOK.moonContrastExp, tot);
display8(tot[0], tot[1], tot[2], display, out);
const lit = css(out);
// Earthshine: a fraction of the full moon's surface, the more the thinner the crescent.
const full = moonSurface({ ...mo, ratio: mo.ratio / Math.max(mo.illuminated, 0.02), illuminated: 1 });
for (let i = 0; i < 3; i += 1) add[i] = NIGHT_LOOK.earthshine * full * (1.1 - mo.illuminated) * [0.9, 1, 1.15][i];
composite(bg, add, NIGHT_LOOK.moonContrastExp, tot);
display8(tot[0], tot[1], tot[2], display, out);
moon = {
x: mAt.x,
y: mAt.y,
radius: ((mo.radius / RAD) * NIGHT_LOOK.moonScale) / camera.vfovDeg,
illuminated: mo.illuminated,
phaseAngle: mo.phaseAngleDeg * RAD,
limb: limbAngle(mo, p.sun),
lit,
dark: css(out),
};
}
const stars: Star[] = [];
for (const s of starsAt(p.sun.time, place.lat, place.lon, MAG_LIMIT, -0.5)) {
const at = onScreen(camera, s.azimuth, s.elevation);
if (at.x < -0.02 || at.x > 1.02 || at.y < -0.02 || at.y > 1.02) continue;
// The moon is painted over the stars: one inside its disc is never seen, and its twinkle would be painted over the moon.
if (moon && Math.hypot((at.x - moon.x) * px.w, (at.y - moon.y) * px.h) < Math.max(2, moon.radius * px.h)) continue;
const back = [0, 0, 0];
domeAt(dome, at.x, at.y, back);
const m = extinguished(s.mag, s.elevation);
const rgb = blackbodyRgb(temperatureOfBV(s.bv));
const lum = starRadiance(m);
// Each star owns its own scratch: `shade` outlives this loop.
const hdr = (gain: number, o: number[]) => {
const a = [rgb[0] * lum * gain, rgb[1] * lum * gain, rgb[2] * lum * gain];
const t = [0, 0, 0];
composite(back, a, NIGHT_LOOK.starContrastExp, t);
display8(t[0], t[1], t[2], display, o);
};
const base = [0, 0, 0];
hdr(1, base);
display8(back[0], back[1], back[2], display, out);
// A star the sky hides (within three 8-bit steps of it in every channel) is not drawn.
if (Math.max(Math.abs(base[0] - out[0]), Math.abs(base[1] - out[1]), Math.abs(base[2] - out[2])) < 3) continue;
const { base: r0, perMag } = NIGHT_LOOK.starRadius;
stars.push({
x: at.x,
y: at.y,
r: r0 + perMag * Math.max(0, MAG_LIMIT - m),
fill: css(base),
cover: css(out),
shade: (gain) => {
const o = [0, 0, 0];
hdr(gain, o);
return css(o);
},
});
}
const lines: LineDraw[] = [];
if (withLines && p.state === 'night') {
for (const chain of linesAt(p.sun.time, place.lat, place.lon)) {
const points: { x: number; y: number }[] = [];
const flush = () => {
if (points.length > 1) lines.push({ points: points.slice() });
points.length = 0;
};
chain.forEach((v, i) => {
const legs = i === 0 ? [v] : slerp(chain[i - 1], v, 6).slice(1);
legs.forEach((q) => {
const a = onScreen(camera, q.azimuth, q.elevation);
const prev = points[points.length - 1];
if (prev && Math.abs(a.x - prev.x) > 0.5) flush();
points.push(a);
});
});
flush();
}
}
return { stars, moon, lines };
}
/** Paint the lines, the stars and the moon onto the canvas (`w` x `h` device px, `scale` device px per CSS px), in that order. */
export function paintNightBodies(
ctx: CanvasRenderingContext2D,
nb: NightBodies,
w: number,
h: number,
scale: number
): void {
if (nb.lines.length) {
const [r, g, b] = NIGHT_LOOK.lines.rgb;
ctx.save();
ctx.strokeStyle = `rgba(${r},${g},${b},${NIGHT_LOOK.lines.alpha})`;
ctx.lineWidth = NIGHT_LOOK.lines.widthPx * scale;
ctx.lineJoin = 'round';
nb.lines.forEach((l) => {
ctx.beginPath();
l.points.forEach((q, i) => (i ? ctx.lineTo(q.x * w, q.y * h) : ctx.moveTo(q.x * w, q.y * h)));
ctx.stroke();
});
ctx.restore();
}
nb.stars.forEach((s) => {
ctx.fillStyle = s.fill;
ctx.beginPath();
ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI);
ctx.fill();
});
const m = nb.moon;
if (!m) return;
const R = Math.max(2 * scale, m.radius * h);
ctx.save();
ctx.translate(m.x * w, m.y * h);
ctx.rotate(-m.limb); // the bright limb to +x; canvas rotation is clockwise, `limb` counter-clockwise
ctx.fillStyle = m.dark;
ctx.beginPath();
ctx.arc(0, 0, R, 0, 2 * Math.PI);
ctx.fill();
if (m.illuminated > 0.004) {
// Lit: the half toward the sun, plus or minus the half-ellipse of the terminator, whose semi-axis along x is R |cos i|.
const cosI = Math.cos(m.phaseAngle);
ctx.fillStyle = m.lit;
ctx.beginPath();
ctx.arc(0, 0, R, -Math.PI / 2, Math.PI / 2, false);
ctx.ellipse(0, 0, Math.max(R * Math.abs(cosI), 1e-3), R, 0, Math.PI / 2, cosI > 0 ? (3 * Math.PI) / 2 : -Math.PI / 2, cosI <= 0);
ctx.closePath();
ctx.fill();
}
ctx.restore();
}

View file

@ -0,0 +1,190 @@
// The night's light and bodies, in the units of the day sky: radiance per unit of the sun's irradiance (`skyDome.ts`). The sun is 1; the moon
// is its brightness by phase (Krisciunas & Schaefer 1991) times the atmosphere's response to a light at the moon's elevation
// (`earthAtmosphere.ts`, the same sky-view LUT, baked for the moon instead of the sun); the airglow is a floor; a star is its illuminance
// over the point spread it is drawn with. Everything marked EYEBALLED is a knob of the look, tuned by eye, not a measurement.
import { moonPhase, moonPosition } from '../../../../sky/moon.js';
import type { Atmosphere, Vec3 } from './earthAtmosphere';
import type { Place } from './view';
const RAD = Math.PI / 180;
const clamp = (x: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, x));
/** Illuminance in lux of a source of apparent visual magnitude `m` above the atmosphere (V = 0 is 2.13e-6 lux; the sun, V = -26.74, 1.06e5). */
export const luxOfMagnitude = (m: number): number => 10 ** (-0.4 * (m + 14.18));
export const SUN_V = -26.74;
/** The sun's illuminance, the unit of every radiance of the ridge sky. */
export const SUN_LUX = luxOfMagnitude(SUN_V);
/** The look of the night's bodies. EYEBALLED knobs: the operator tunes these by eye. */
export const NIGHT_LOOK = {
/** Radius of the point spread a star's light is spread over, arcminutes: smaller is brighter and more of them saturate. */
starPsfArcmin: 1.5,
/** Atmospheric extinction in magnitudes per air mass (V band, a clean low site is 0.2). */
extinctionPerAirmass: 0.2,
/**
* Display contrast of a star over its sky is the physical contrast to this power (1 = physical): the eye and a camera cannot show a
* mag 0 star at the 1e4:1 it has over a dark sky. Brightest stars still saturate; the faintest keep a little.
*/
starContrastExp: 0.8,
/** The same for the moon's disc (physical contrast is 1e7 and more). */
moonContrastExp: 0.3,
/** Visible radius of a star, CSS px: `base` for the faintest, plus `perMag` for each magnitude brighter than 5.5. */
starRadius: { base: 0.65, perMag: 0.22 },
/** The moon's disc, as a multiple of its true angular size (1 is true; a viewer's eye sees it larger than a lens does). */
moonScale: 1,
/** Earthshine on the unlit part of the disc, as a fraction of the lit surface's radiance. */
earthshine: 4e-5,
/** Constellation lines: opacity of the stroke (a pale blue-white) and its width in CSS px. */
lines: { alpha: 0.22, widthPx: 0.9, rgb: [160, 185, 235] as const },
};
// ---- Airglow ----------------------------------------------------------------------------------
/** Natural night-sky radiance at the zenith without moon or town, cd/m^2 (about 22 V mag/arcsec^2: 2.5e-4). */
export const AIRGLOW_CD = 2.5e-4;
/** Its colour, linear, luminance 1 (a faint cool grey). EYEBALLED. */
const AIRGLOW_TINT: Vec3 = [0.95, 1, 1.1];
const AIRGLOW_NORM = 0.2126 * 0.95 + 0.7152 + 0.0722 * 1.1;
/** The airglow floor, per unit of sun irradiance, at view elevation sine `vz` (brighter toward the horizon, van Rhijn). */
export function airglow(vz: number, out: number[]): void {
const k = ((AIRGLOW_CD / SUN_LUX) * (0.6 + 1.4 * (1 - clamp(vz, 0, 1)))) / AIRGLOW_NORM;
out[0] += AIRGLOW_TINT[0] * k;
out[1] += AIRGLOW_TINT[1] * k;
out[2] += AIRGLOW_TINT[2] * k;
}
// ---- Moon --------------------------------------------------------------------------------------
/** The moon over a place at a moment, with its light. */
export interface MoonSample {
/** Degrees clockwise from north, and above the horizon (topocentric, no refraction). */
azimuth: number;
elevation: number;
time: Date;
/** Lit fraction of the disc, and the sun-moon-earth angle in degrees (0 full, 180 new). */
illuminated: number;
phaseAngleDeg: number;
waxing: boolean;
distanceKm: number;
/** Angular radius in radians. */
radius: number;
/** The moon's illuminance relative to the sun's: its light on the ground per unit of the sun's. */
ratio: number;
}
/** The moon's visual magnitude at phase angle `alphaDeg`: Krisciunas & Schaefer 1991 (the Allen / Lane & Irvine fit) plus the distance. */
export const moonMagnitude = (alphaDeg: number, distanceKm: number): number => {
const a = Math.abs(alphaDeg);
return -12.73 + 0.026 * a + 4e-9 * a ** 4 + 5 * Math.log10(distanceKm / 384400);
};
/** The moon's illuminance over the sun's. At full moon about 2.5e-6. */
export const moonIrradianceRatio = (alphaDeg: number, distanceKm: number): number =>
10 ** (-0.4 * (moonMagnitude(alphaDeg, distanceKm) - SUN_V));
export function moonAt(place: Place, time: Date): MoonSample {
const p = moonPosition(time, place.lat, place.lon) as { elevation: number; azimuth: number };
const ph = moonPhase(time) as {
illuminated: number;
phaseAngleDeg: number;
waxing: boolean;
distanceKm: number;
};
return {
...p,
time,
illuminated: ph.illuminated,
phaseAngleDeg: ph.phaseAngleDeg,
waxing: ph.waxing,
distanceKm: ph.distanceKm,
radius: Math.asin(1737.4 / ph.distanceKm),
ratio: moonIrradianceRatio(ph.phaseAngleDeg, ph.distanceKm),
};
}
/**
* The radiance of the moon's lit surface per unit of sun irradiance: its flux over the lit area of the disc. About 4000 cd/m^2 at full moon.
* `lit` is the lit fraction (at least a sliver, so a thin crescent's surface brightness stays finite).
*/
export const moonSurface = (m: MoonSample): number =>
m.ratio / (Math.max(m.illuminated, 0.02) * Math.PI * m.radius * m.radius);
// ---- The night's light, as the dome and the cards read it ------------------------------------
/** What lights the sky besides the sun: the moon (its own atmosphere bake, scaled by `ratio`) and the airglow. */
export interface NightLight {
moon?: { azimuth: number; elevation: number; atm: Atmosphere; ratio: number };
}
/**
* Add the night's radiance (the moon's scattered light and the airglow, per unit of sun irradiance) for a view ray: `vz` the sine of its
* elevation, `azRad` its azimuth in radians, written onto `out`.
*/
export function addNightRadiance(
n: NightLight | undefined,
vz: number,
azRad: number,
out: number[]
): void {
airglow(vz, out);
if (!n?.moon) return;
const m = n.moon;
const tmp = [0, 0, 0];
m.atm.radiance(vz, Math.cos(azRad - m.azimuth * RAD), tmp);
out[0] += tmp[0] * m.ratio;
out[1] += tmp[1] * m.ratio;
out[2] += tmp[2] * m.ratio;
}
// ---- Stars -------------------------------------------------------------------------------------
/** Relative air mass, Kasten & Young 1989. Elevation in degrees. */
export const airMass = (elDeg: number): number =>
1 / (Math.sin(Math.max(elDeg, 0) * RAD) + 0.50572 * Math.pow(Math.max(elDeg, 0) + 6.07995, -1.6364));
/** A star's magnitude after the air: extinction per air mass along its elevation. */
export const extinguished = (mag: number, elDeg: number): number =>
mag + NIGHT_LOOK.extinctionPerAirmass * airMass(elDeg);
/** Linear sRGB colour of a black body of temperature `t` kelvin at luminance 1 (Kim et al. 2002 Planckian locus, sRGB primaries). */
export function blackbodyRgb(t: number): Vec3 {
const T = clamp(t, 1700, 24000);
const x =
T <= 4000
? -0.2661239e9 / T ** 3 - 0.2343589e6 / T ** 2 + 0.8776956e3 / T + 0.17991
: -3.0258469e9 / T ** 3 + 2.1070379e6 / T ** 2 + 0.2226347e3 / T + 0.24039;
const y =
T <= 2222
? -1.1063814 * x ** 3 - 1.3481102 * x ** 2 + 2.18555832 * x - 0.20219683
: T <= 4000
? -0.9549476 * x ** 3 - 1.37418593 * x ** 2 + 2.09137015 * x - 0.16748867
: 3.081758 * x ** 3 - 5.8733867 * x ** 2 + 3.75112997 * x - 0.37001483;
const X = x / y;
const Z = (1 - x - y) / y;
const rgb = [
3.2406 * X - 1.5372 - 0.4986 * Z,
-0.9689 * X + 1.8758 + 0.0415 * Z,
0.0557 * X - 0.204 + 1.057 * Z,
].map((c) => Math.max(0, c));
const lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
return [rgb[0] / lum, rgb[1] / lum, rgb[2] / lum];
}
/** Effective temperature of a star from its B-V colour index (Ballesteros 2012). */
export const temperatureOfBV = (bv: number): number => {
const c = clamp(bv, -0.4, 2);
return 4600 * (1 / (0.92 * c + 1.7) + 1 / (0.92 * c + 0.62));
};
/** A star's radiance when seen through the point spread, per unit of sun irradiance: its illuminance over the spread's solid angle. */
export const starRadiance = (mag: number): number => {
const r = (NIGHT_LOOK.starPsfArcmin / 60) * RAD;
return luxOfMagnitude(mag) / (Math.PI * r * r) / SUN_LUX;
};
/** Perceptual compression of a body's contrast over the sky behind it: `bg` the sky's radiance, `add` the body's on top; the exponent 1 is physical. */
export const compressed = (bg: number, add: number, exp: number): number => {
const b = Math.max(bg, 1e-30);
return b * ((b + add) / b) ** exp;
};

View file

@ -0,0 +1,271 @@
/* eslint-disable */
// GENERATED by scripts/ridge-sky/build-night-sky.py: do not edit. The night sky's data, J2000.
// Stars: Yale Bright Star Catalogue, 5th revised ed. (Hoffleit & Warren 1991; public domain), Vmag <= 5.5, 2887 stars.
// source http://tdc-www.harvard.edu/catalogs/bsc5.dat.gz (copy of CDS/VizieR V/50), sha256 0471ced07fc241e625613baa689b2fa5f4b59fd733f731003e57d2d436036cdb
// Constellation lines: d3-celestial constellations.lines.json (Olaf Frohn, BSD-3-Clause), 150 chains.
// source https://github.com/ofrohn/d3-celestial/blob/master/data/constellations.lines.json, sha256 294f66bef5d5cf50b1e17f16d2efa1d97a15131612c68dd935adef6e7373e13c
// Layout: see the generator's docstring. Stars are sorted brightest first.
export const STAR_COUNT = 2887;
export const STARS_B64 = `
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
`;
export const LINE_CHAINS = 150;
export const LINES_B64 = `
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
6ih9V4pyPYjqc=
`;

View file

@ -3,13 +3,13 @@ import { FALLBACK_VIEW } from './view';
import { ELSEWHERE_VIEW } from './manifest.fixture';
import { sunForState } from './sunAt';
import { makePhysicalSky, paintSky } from './physicalSky';
import { skyBackdrop } from '../skyState';
import { ridgeDrawn } from '../skyForState';
import type { FixedSkyState } from '../skyState';
import { windowFor } from './view';
import type { PhysicalSky } from './physicalSky';
// The Aqua method on tonemapped pixels: paint the sky the way the host canvas does and measure the WCAG luminance of every 8-bit
// texel, against the bounds the page text was checked against (`skyBackdrop`, 4.5:1). Over the weather, the day of the year, and
// texel, against the display range the sky was fitted to (`ridgeDrawn`). Over the weather, the day of the year, and
// viewports of different shape (the fit is made on one 16:9 grid and the paint on another).
const lin = (v: number): number => {
const c = v / 255;
@ -35,10 +35,10 @@ const VIEWPORTS: [number, number][] = [
];
describe.each(['day', 'dusk', 'night'] as FixedSkyState[])(
'the %s sky stays inside its backdrop bounds',
'the %s sky stays inside its fitted display range',
(state) => {
it('over weather, season and viewport shape', () => {
const b = skyBackdrop(state);
const b = ridgeDrawn(state);
let lo = 2;
let hi = -1;
for (const day of DAYS) {
@ -89,23 +89,6 @@ describe('weather in the sky', () => {
});
describe('the sun disc', () => {
it('keeps the display floor the dark link was fitted to, at every hour it is drawn', () => {
const lin = (c: number) =>
c / 255 <= 0.04045 ? c / 255 / 12.92 : ((c / 255 + 0.055) / 1.055) ** 2.4;
let drawn = 0;
for (const state of ['day', 'dusk'] as FixedSkyState[]) {
for (let m = 0; m < 24 * 60; m += 10) {
const sky = makePhysicalSky(state, new Date(Date.UTC(2026, 10, 11, 0, m)), 0, FALLBACK_VIEW);
const d = paintSky(sky, 1280, 720, facingSun(sky, 1280, 720)).sunDisc;
if (!d) continue;
drawn += 1;
expect(
0.2126 * lin(d.rgb[0]) + 0.7152 * lin(d.rgb[1]) + 0.0722 * lin(d.rgb[2])
).toBeGreaterThanOrEqual(0.4744);
}
}
expect(drawn).toBeGreaterThan(0);
});
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', () => {

View file

@ -7,8 +7,10 @@ import type { Atmosphere } from './earthAtmosphere';
import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome';
import type { Dome } from './skyDome';
import type { Srgb } from './skyColour';
import { display8, fitDisplay, holdBudget, MARGIN } from './toneMap';
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';
@ -21,6 +23,10 @@ export interface PhysicalSky {
/** Where the observer stands and where the planes look: the camera of any viewport is `windowFor(view, w, h).camera`. */
view: View;
sun: SunSample;
/** The moon over the place at the sun's moment (`sun.time`): the night's key light, and a body in any sky it is above the horizon of. */
moon: MoonSample;
/** What lights the sky besides the sun: at night, the moon above the horizon with its own atmosphere bake. */
night: NightLight;
weather: Weather;
atm: Atmosphere;
/** The display fitted to this sky's budget. */
@ -53,10 +59,12 @@ export function makePhysicalSky(
state: FixedSkyState,
now: Date,
weatherValue: number,
view: View
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 {
const t0 = clock();
const sun = sunForState(view.place, state, now);
const sun = sunOverride ?? sunForState(view.place, state, now);
const weather = weatherOf(weatherValue);
const atm = bakeAtmosphere({
sunElevationDeg: sun.elevation,
@ -65,13 +73,33 @@ export function makePhysicalSky(
});
// A 16:9 viewport: the camera's fov and horizon fraction do not depend on its size, only on its shape.
const { camera } = windowFor(view, CANON.w, CANON.h);
const dome = renderDome(atm, sun, camera, CANON.w, CANON.h, weather.cover);
// The moon is the night's light: its own bake of the same atmosphere, for a light at its elevation (the transmittance and the
// multiple-scattering tables do not depend on it, but the bake is one function). Only in the night state, and only above -2 degrees.
const moon = moonAt(view.place, sun.time);
const night: NightLight =
state === 'night' && moon.elevation > -2
? {
moon: {
azimuth: moon.azimuth,
elevation: moon.elevation,
ratio: moon.ratio,
atm: bakeAtmosphere({
sunElevationDeg: moon.elevation,
mieScale: weather.mieScale,
observerKm: view.place.altitudeKm,
}),
},
}
: {};
const dome = renderDome(atm, sun, camera, CANON.w, CANON.h, weather.cover, night);
const fit = fitDisplay(state, dome.hdr, dome.meanLuma);
const at = (f: number) => rowMean(dome, fit.display, Math.round(f * CANON.h));
return {
state,
view,
sun,
moon,
night,
weather,
atm,
fit,
@ -94,10 +122,10 @@ export interface SkyPixels {
/** The sky for a viewport seen through `camera` (`windowFor(p.view, cssW, cssH).camera`), as a small RGBA grid the host canvas upscales smoothly. */
export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Camera): SkyPixels {
const { w, h } = domeSize(cssW, cssH);
const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover);
const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover, p.night);
const data = new Uint8ClampedArray(w * h * 4);
const out = [0, 0, 0];
const display = holdBudget(p.state, dome.hdr, p.fit.display);
const display = p.fit.display;
for (let i = 0; i < w * h; i += 1) {
display8(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], display, out);
data[i * 4] = out[0];
@ -108,8 +136,6 @@ export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Cam
return { w, h, data, dome, camera, sunDisc: sunDisc(p, camera) };
}
/** The luma the disc must keep: the day/dusk floor of toneMap's budget. */
const DISC_FLOOR = 0.4744 + MARGIN;
const smooth01 = (a: number, b: number, v: number): number => {
const t = Math.min(1, Math.max(0, (v - a) / (b - a)));
return t * t * (3 - 2 * t);
@ -127,13 +153,6 @@ function sunDisc(p: PhysicalSky, camera: Camera): SkyPixels['sunDisc'] {
p.atm.transmittanceToSpace(Math.max(Math.sin((p.sun.elevation * Math.PI) / 180), 0), trans);
const top = Math.max(...trans, 1e-9);
const rgb = trans.map((t) => Math.round(255 * (t / top) ** 0.6));
// The disc sits on the sky, so it keeps the display floor the dark link was fitted to: mix toward white until it does.
const lin = (c: number): number =>
c / 255 <= 0.04045 ? c / 255 / 12.92 : ((c / 255 + 0.055) / 1.055) ** 2.4;
const luma = (c: number[]): number =>
0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]);
for (let m = 0; luma(rgb) < DISC_FLOOR && m < 40; m += 1)
for (let i = 0; i < 3; i += 1) rgb[i] = Math.round(rgb[i] + (255 - rgb[i]) * 0.1);
return {
...at,
rgb: rgb as unknown as Srgb,

View file

@ -1,54 +1,50 @@
// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on
// (export.py PAIR_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each plane's own bytes, not the manifest's claims about
// them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the manifest's w and h,
// which the decode budget is computed from; and the bake id is re-derived from the plane bytes, as the baker derives it, so any
// corruption of a plane, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels.
// (export.py MAX_CARDS, TOTAL_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each card file's own bytes, not the manifest's
// claims about them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the card's
// width and band height, which the decode budget is computed from; and the bake id is re-derived from the card bytes as the baker derives it,
// so any corruption of a card, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels.
import { createHash } from 'node:crypto';
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { join, sep } from 'node:path';
import { describe, expect, it } from 'vitest';
import { FRAME_KEYS, PLANE_NAMES, parseIndex, parseManifest } from './manifest';
import { MAX_CARDS, parseIndex, parseManifest } from './manifest';
/** The same two constants as scripts/ridge-bake/export.py: two adjacent frames, fetched and decoded. */
export const PAIR_BYTES_MAX = 800_000;
/** The same constants as scripts/ridge-bake/export.py: every card file of a place, and the cards decoded (2 textures x w x band rows x 4 bytes each). */
export const TOTAL_BYTES_MAX = 1_500_000;
export const DECODE_BYTES_MAX = 20_000_000;
interface WirePlane {
interface WireFile {
file: string;
bytes: number;
w: number;
h: number;
}
interface WireFrame {
key: string;
planes: Record<string, WirePlane>;
luma: { min: number; max: number };
interface WireCard {
top: number;
h: number;
scale: number;
colour: WireFile;
geometry: WireFile;
}
export interface WireManifest {
bake_id: string;
frames: WireFrame[];
w: number;
cards: WireCard[];
camera?: { heading_max_deg?: number };
}
const planes = (f: WireFrame): WirePlane[] => PLANE_NAMES.map((n) => f.planes[n]);
const files = (c: WireCard): WireFile[] => [c.colour, c.geometry];
/** Why a manifest breaks the size gate, or undefined. Frames are taken in FRAME_KEYS order; the pairs are neighbours, and night meets dawn. */
/** Why a manifest breaks the size gate, or undefined: too many cards, too many bytes, or too many decoded bytes. */
export function sizeGate(m: WireManifest): string | undefined {
const byKey = FRAME_KEYS.map((k) => m.frames.find((f) => f.key === k) as WireFrame);
for (let i = 0; i < byKey.length; i += 1) {
const pair = [byKey[i], byKey[(i + 1) % byKey.length]];
const ps = pair.flatMap(planes);
const fetched = ps.reduce((a, p) => a + p.bytes, 0);
const decoded = ps.reduce((a, p) => a + p.w * p.h * 4, 0);
if (fetched > PAIR_BYTES_MAX) return `${pair[0].key}+${pair[1].key} fetches ${fetched}`;
if (decoded > DECODE_BYTES_MAX) return `${pair[0].key}+${pair[1].key} decodes ${decoded}`;
}
return undefined;
if (m.cards.length > MAX_CARDS) return `${m.cards.length} cards, above ${MAX_CARDS}`;
const bytes = m.cards.flatMap(files).reduce((a, f) => a + f.bytes, 0);
if (bytes > TOTAL_BYTES_MAX) return `the cards are ${bytes} bytes, above ${TOTAL_BYTES_MAX}`;
const decoded = m.cards.reduce((a, c) => a + 2 * m.w * c.h * 4, 0);
return decoded > DECODE_BYTES_MAX
? `the cards decode to ${decoded} bytes, above ${DECODE_BYTES_MAX}`
: undefined;
}
/**
* Why a buffer is not a well-formed WebP of `w` x `h`, or undefined. Checks the RIFF envelope (its size is the file's), that the chunks tile
* the file exactly, and the dimensions the container and the bitstream header each state.
*/
/** Why `b` is not the WebP of `w` x `h` pixels, or undefined: the RIFF container is walked, so a cut or padded file and a changed frame header fail. */
export function webpFault(b: Uint8Array, w: number, h: number): string | undefined {
const u32 = (o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
const u24 = (o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16);
@ -89,10 +85,16 @@ export function webpFault(b: Uint8Array, w: number, h: number): string | undefin
return bad ? `states ${bad}, the manifest ${w}x${h}` : undefined;
}
/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the plane bytes, frames in FRAME_KEYS order, planes far, mid, near. */
export function bakeIdOf(planeBytes: (frame: string, plane: string) => Uint8Array): string {
/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the card files in index order, colour then geometry. */
export function bakeIdOf(
cardBytes: (card: number, kind: 'colour' | 'geometry') => Uint8Array,
n: number
): string {
const h = createHash('sha256');
FRAME_KEYS.forEach((k) => PLANE_NAMES.forEach((n) => h.update(planeBytes(k, n))));
for (let i = 0; i < n; i += 1) {
h.update(cardBytes(i, 'colour'));
h.update(cardBytes(i, 'geometry'));
}
return h.digest('hex').slice(0, 12);
}
@ -109,121 +111,132 @@ describe('the committed ridge assets', () => {
dirs.forEach(([id, dir]) => {
describe(`${id} (${dir})`, () => {
const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest;
const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest & { schema: number };
const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file));
it('parses, and its directory ends in its bake id', () => {
it('is schema 2, parses, and its directory ends in its bake id', () => {
expect(raw.schema).toBe(2);
expect(() => parseManifest(raw, `${dir}/`)).not.toThrow();
expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true);
});
it('has every plane file, at the length the manifest states', () => {
raw.frames.flatMap(planes).forEach((p) => {
expect(statSync(join(ROOT, dir, p.file)).size, p.file).toBe(p.bytes);
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);
});
});
it('decodes every plane as the WebP of the size the manifest states', () => {
raw.frames.flatMap(planes).forEach((p) => {
expect(
webpFault(readFileSync(join(ROOT, dir, p.file)), p.w, p.h),
p.file
).toBeUndefined();
});
it('decodes every card file as the WebP of the width and band height the manifest states', () => {
raw.cards.forEach((c) =>
files(c).forEach((f) => {
expect(webpFault(read(f), raw.w, c.h), f.file).toBeUndefined();
})
);
});
it('holds the bytes its bake id was made from', () => {
const bytes = (frame: string, plane: string) =>
readFileSync(
join(
ROOT,
dir,
(raw.frames.find((f) => f.key === frame) as WireFrame).planes[plane].file
)
);
expect(bakeIdOf(bytes)).toBe(raw.bake_id);
const bytes = (i: number, kind: 'colour' | 'geometry') => read(raw.cards[i][kind]);
expect(bakeIdOf(bytes, raw.cards.length)).toBe(raw.bake_id);
});
it('keeps every adjacent pair of frames inside the fetch and decode budget', () => {
it('keeps the place inside the card, byte and decode budget', () => {
expect(sizeGate(raw)).toBeUndefined();
});
it('records a finite luma for every frame', () => {
expect(raw.frames).toHaveLength(FRAME_KEYS.length);
raw.frames.forEach((f) => {
expect(Number.isFinite(f.luma.min) && Number.isFinite(f.luma.max), f.key).toBe(true);
expect(f.luma.min, f.key).toBeLessThanOrEqual(f.luma.max);
});
it('carries its camera and a scale for every card', () => {
expect(Number.isFinite(raw.camera?.heading_max_deg)).toBe(true);
raw.cards.forEach((c) => expect(Number.isFinite(c.scale) && c.scale > 0).toBe(true));
});
});
});
it('shows Vienna from a camera pushed forward: no card is smaller than its bake', () => {
const vienna = index.places.vienna;
expect(vienna).toBeDefined();
const m = readJson(join(ROOT, vienna, 'manifest.json')) as WireManifest;
m.cards.forEach((c) => expect(c.scale).toBeGreaterThanOrEqual(1));
});
it('holds no file a manifest does not name', () => {
const named = new Set<string>(['index.json']);
dirs.forEach(([, dir]) => {
named.add(`${dir}/manifest.json`);
(readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).frames
.flatMap(planes)
.forEach((p) => named.add(`${dir}/${p.file}`));
(readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).cards
.flatMap(files)
.forEach((f) => named.add(`${dir}/${f.file}`));
});
const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true })
.filter((e) => e.isFile())
.map((e) => join(e.parentPath, e.name).slice(ROOT.length + 1));
.map((e) =>
join(e.parentPath, e.name)
.slice(ROOT.length + 1)
.split(sep)
.join('/')
);
expect(onDisk.filter((f) => !named.has(f))).toEqual([]);
expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]);
});
});
describe('the plane gates refuse a plane that is not what the manifest says', () => {
const real = readFileSync(join(ROOT, Object.values(index.places)[0], 'noon-mid.webp'));
const manifest = readJson(
join(ROOT, Object.values(index.places)[0], 'manifest.json')
) as WireManifest;
const { w, h } = manifest.frames[2].planes.mid;
const id = (b: Uint8Array) => bakeIdOf(() => b);
describe('the card gates refuse a card that is not what the manifest says', () => {
const dir = Object.values(index.places)[0];
const manifest = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest;
const real = readFileSync(join(ROOT, dir, manifest.cards[1].geometry.file));
const { h } = manifest.cards[1];
const w = manifest.w;
const id = (b: Uint8Array) => bakeIdOf(() => b, 1);
it('accepts the real plane at its size', () => {
it('accepts the real card at its size', () => {
expect(webpFault(real, w, h)).toBeUndefined();
});
it("refuses a manifest that lies about the plane's size, and a file cut short or padded", () => {
it("refuses a manifest that lies about the card's size, and a file cut short or padded", () => {
expect(webpFault(real, w, h + 1)).toMatch(/states/);
expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined();
expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined();
});
it('refuses a frame header whose dimensions are changed, and bytes that are not a WebP', () => {
const vp8 = Buffer.from(real);
const at = vp8.indexOf('VP8 ') + 8 + 6;
vp8[at] ^= 0x01;
expect(webpFault(vp8, w, h)).toMatch(/states/);
it('refuses bytes that are not a WebP', () => {
expect(webpFault(Buffer.from('not a webp, but long enough to try'), w, h)).toMatch(/RIFF/);
});
it('re-derives a different bake id from a plane with the same length and 8 bytes overwritten', () => {
it('re-derives a different bake id from a card with the same length and 8 bytes overwritten', () => {
const bad = Buffer.from(real);
bad.fill(0xab, 100, 108);
expect(bad.length).toBe(real.length);
expect(id(bad)).not.toBe(id(real));
});
it('derives the id from colour then geometry, in card order', () => {
const a = Buffer.from('a-colour');
const b = Buffer.from('b-geometry');
const order = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? a : b);
const swapped = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? b : a);
const want = createHash('sha256').update(a).update(b).update(b).update(b);
expect(bakeIdOf(order, 2)).toBe(want.digest('hex').slice(0, 12));
expect(bakeIdOf(swapped, 2)).not.toBe(bakeIdOf(order, 2));
});
});
describe('sizeGate', () => {
const plane = (bytes: number): WirePlane => ({ file: 'x.webp', bytes, w: 1280, h: 600 });
const frame = (key: string, bytes: number): WireFrame => ({
key,
planes: { far: plane(bytes), mid: plane(bytes), near: plane(bytes) },
luma: { min: 0, max: 1 },
const card = (bytes: number, h: number): WireCard => ({
top: 0,
h,
scale: 1,
colour: { file: 'c.webp', bytes },
geometry: { file: 'g.webp', bytes },
});
const set = (bytes: number): WireManifest => ({
const set = (n: number, bytes: number, h: number): WireManifest => ({
bake_id: 'x',
frames: FRAME_KEYS.map((k) => frame(k, bytes)),
w: 1280,
cards: Array.from({ length: n }, () => card(bytes, h)),
});
it('passes a pair at the budget and fails a 900 KB pair', () => {
expect(sizeGate(set(133_333))).toBeUndefined();
expect(sizeGate(set(150_000))).toMatch(/fetches 900000/);
it('passes a place at the byte budget and fails one a byte over', () => {
expect(sizeGate(set(3, 250_000, 100))).toBeUndefined();
expect(sizeGate(set(3, 250_001, 100))).toMatch(/1500006 bytes/);
});
it('fails a pair that decodes past the budget', () => {
const m = set(1);
m.frames[2].planes.far = { file: 'x.webp', bytes: 1, w: 4096, h: 1000 };
expect(sizeGate(m)).toMatch(/decodes/);
it('fails a seventh card, and cards that decode past the budget', () => {
expect(sizeGate(set(6, 1, 150))).toBeUndefined();
expect(sizeGate(set(7, 1, 150))).toMatch(/7 cards/);
expect(sizeGate(set(2, 1, 600))).toBeUndefined();
expect(sizeGate(set(4, 1, 600))).toMatch(/decode/);
});
});

View file

@ -5,6 +5,8 @@ import type { Atmosphere } from './earthAtmosphere';
import type { SunSample } from './sunAt';
import type { Camera } from './view';
import { cloudAmount, cloudRadiance } from './clouds';
import { addNightRadiance } from './nightSky';
import type { NightLight } from './nightSky';
const RAD = Math.PI / 180;
/** The sun's angular radius in radians (Hillaire's/Bruneton's `sun_angular_radius`). */
@ -25,7 +27,7 @@ export const domeSize = (cssW: number, cssH: number): { w: number; h: number } =
});
/**
* Render the HDR sky. Rays below the horizon take the horizon's radiance (the ridges cover them). The sun's disc is not here: it is smaller than a texel, so the host draws it on the upscaled canvas (`sunOnScreen`). `cover` (0..1, `weather.ts`) lays the cloud deck (`clouds.ts`) over it.
* Render the HDR sky: the sun's atmosphere, plus at night the moon's (`night`, scaled by its irradiance ratio) and the airglow. Rays below the horizon take the horizon's radiance (the ridges cover them). The sun's disc is not here: it is smaller than a texel, so the host draws it on the upscaled canvas (`sunOnScreen`). `cover` (0..1, `weather.ts`) lays the cloud deck (`clouds.ts`) over it.
*/
export function renderDome(
atm: Atmosphere,
@ -33,7 +35,8 @@ export function renderDome(
camera: Camera,
w: number,
h: number,
cover = 0
cover = 0,
night?: NightLight
): Dome {
const hdr = new Float32Array(w * h * 3);
const sunAz = sun.azimuth * RAD;
@ -47,6 +50,19 @@ export function renderDome(
const zenith = [0, 0, 0];
atm.radiance(1, 1, zenith);
cloudRadiance(sz, trans, zenith, cover, cloud);
if (night?.moon) {
// The deck is moonlit as it is sunlit: the moon's own light through the air, scaled by its irradiance.
const m = night.moon;
const moonCloud = [0, 0, 0];
const moonTrans = [0, 0, 0];
const moonZenith = [0, 0, 0];
m.atm.transmittanceToSpace(Math.max(Math.sin(m.elevation * RAD), 0), moonTrans);
m.atm.radiance(1, 1, moonZenith);
cloudRadiance(Math.sin(m.elevation * RAD), moonTrans, moonZenith, cover, moonCloud);
for (let i = 0; i < 3; i += 1) cloud[i] += moonCloud[i] * m.ratio;
}
// The airglow lights the deck too, at the zenith's strength.
addNightRadiance(undefined, 1, 0, cloud);
}
let logSum = 0;
for (let j = 0; j < h; j += 1) {
@ -57,6 +73,7 @@ export function renderDome(
const az = (camera.azimuthDeg + ((i + 0.5) / w - 0.5) * camera.hfovDeg) * RAD;
const cosFromSun = Math.cos(az - sunAz);
atm.radiance(vz, cosFromSun, rgb);
addNightRadiance(night, vz, az, rgb);
let r = rgb[0];
let g = rgb[1];
let b = rgb[2];

View file

@ -0,0 +1,117 @@
import { describe, expect, it } from 'vitest';
import { moonPosition } from '../../../../sky/moon.js';
import { catalogue, lineChains, linesAt, precess, starsAt } from './starCatalogue';
const DEG = 180 / Math.PI;
const VIENNA = { lat: 48.1929826, lon: 16.3534237 };
/**
* Reference altitude/azimuth (degrees, no refraction) from astropy 8.0.3 (ICRS to AltAz at Vienna 48.1929826 N 16.3534237 E, sea level,
* UTC, J2000 coordinates of the stars as Hipparcos lists them), computed once and pasted: an independent implementation of the transform.
*/
const REFERENCE: { t: string; name: string; ra: number; dec: number; alt: number; az: number }[] = [
{ t: '2026-01-15T21:00:00Z', name: 'Sirius', ra: 101.2875, dec: -16.7161, alt: 23.711, az: 164.391 },
{ t: '2026-01-15T21:00:00Z', name: 'Betelgeuse', ra: 88.7929, dec: 7.4071, alt: 49.164, az: 176.246 },
{ t: '2026-11-20T21:00:00Z', name: 'Vega', ra: 279.2347, dec: 38.7837, alt: 15.924, az: 311.197 },
{ t: '2026-11-20T21:00:00Z', name: 'Polaris', ra: 37.9546, dec: 89.2641, alt: 48.79, az: 0.26 },
{ t: '2026-06-01T23:00:00Z', name: 'Arcturus', ra: 213.9153, dec: 19.1824, alt: 47.976, az: 239.397 },
];
describe('the catalogue', () => {
it('is the Yale Bright Star Catalogue cut at naked-eye, brightest first, Sirius leading', () => {
const c = catalogue();
expect(c.length).toBeGreaterThan(2500);
expect(c.length).toBeLessThan(3200);
expect(c.every((s, i) => i === 0 || s.mag >= c[i - 1].mag - 1e-9)).toBe(true);
const sirius = c[0];
expect(sirius.mag).toBeCloseTo(-1.46, 1);
// Sirius, J2000: RA 6h45m09s = 101.287 deg, Dec -16d42'58" = -16.716 deg.
expect(sirius.ra * DEG).toBeCloseTo(101.287, 1);
expect(sirius.dec * DEG).toBeCloseTo(-16.716, 1);
expect(sirius.bv).toBeCloseTo(0.0, 1);
});
it('carries the figures: 150 chains of at least two vertices', () => {
const l = lineChains();
expect(l.length).toBe(150);
expect(l.every((ch) => ch.length >= 2)).toBe(true);
});
});
describe('precession', () => {
it('moves Polaris in declination by 20.04 arcsec a year times cos(RA): 0.118 degrees in 26.9 years, and nothing at the epoch', () => {
const polaris = catalogue().find((s) => Math.abs(s.dec * DEG - 89.264) < 0.05)!;
const [, dec] = precess(polaris.ra, polaris.dec, new Date('2026-11-20T00:00:00Z'));
expect(Math.abs(dec - polaris.dec) * DEG).toBeGreaterThan(0.1);
expect(Math.abs(dec - polaris.dec) * DEG).toBeLessThan(0.13);
const [ra0, dec0] = precess(polaris.ra, polaris.dec, new Date('2000-01-01T12:00:00Z'));
expect(Math.abs(ra0 - polaris.ra) * DEG).toBeLessThan(1e-3);
expect(Math.abs(dec0 - polaris.dec) * DEG).toBeLessThan(1e-3);
});
});
describe('star placement', () => {
it.each(REFERENCE)('puts $name at the reference altitude and azimuth at $t, within half a degree', (r) => {
const placed = starsAt(new Date(r.t), VIENNA.lat, VIENNA.lon, 6, -90);
// The catalogue's star nearest the reference position (the reference coordinates are rounded).
const star = catalogue().reduce(
(best, s, i) => {
const d = Math.hypot((s.ra * DEG - r.ra) * Math.cos(r.dec / DEG), s.dec * DEG - r.dec);
return d < best.d ? { d, i } : best;
},
{ d: 1e9, i: -1 }
);
expect(star.d).toBeLessThan(0.1);
const p = placed.find((s) => s.index === star.i)!;
expect(Math.abs(p.elevation - r.alt)).toBeLessThan(0.5);
// Azimuth error scales with 1/cos(alt); Polaris sits within 0.8 degree of the pole where azimuth swings fastest.
const dAz = Math.abs(((p.azimuth - r.az + 540) % 360) - 180);
expect(dAz * Math.cos(r.alt / DEG)).toBeLessThan(0.5);
});
it("puts Polaris at the observer's latitude in altitude, due north", () => {
for (const t of ['2026-11-20T21:00:00Z', '2026-11-21T02:13:00Z', '2026-06-01T23:00:00Z']) {
const polaris = starsAt(new Date(t), VIENNA.lat, VIENNA.lon).find(
(s) => s.mag > 1.9 && s.mag < 2.1 && s.elevation > 47 && s.elevation < 50
)!;
expect(Math.abs(polaris.elevation - VIENNA.lat)).toBeLessThan(0.8);
expect(Math.min(polaris.azimuth, 360 - polaris.azimuth)).toBeLessThan(2);
}
});
it('hides what is below the horizon and keeps stars brightest first', () => {
const placed = starsAt(new Date('2026-11-20T21:00:00Z'), VIENNA.lat, VIENNA.lon);
expect(placed.length).toBeGreaterThan(900);
expect(placed.length).toBeLessThan(1700);
expect(placed.every((s) => s.elevation >= -1)).toBe(true);
expect(placed.every((s, i) => i === 0 || s.mag >= placed[i - 1].mag - 1e-9)).toBe(true);
});
it('turns with the sky: a sidereal day later the same star is back within a quarter degree', () => {
const t0 = Date.parse('2026-11-20T21:00:00Z');
const a = starsAt(new Date(t0), VIENNA.lat, VIENNA.lon)[3];
const b = starsAt(new Date(t0 + 86164091), VIENNA.lat, VIENNA.lon).find((s) => s.index === a.index)!;
expect(Math.abs(a.elevation - b.elevation)).toBeLessThan(0.25);
});
});
describe('the moon at Vienna', () => {
it('is where astropy puts it, 2026-11-20 21:00 UTC (alt 42.576, az 215.016), within the series\' 0.5 degrees', () => {
const m = moonPosition('2026-11-20T21:00:00Z', VIENNA.lat, VIENNA.lon);
expect(Math.abs(m.elevation - 42.576)).toBeLessThan(0.5);
expect(Math.abs(m.azimuth - 215.016)).toBeLessThan(0.7);
});
it('and 2026-06-01 23:00 UTC (alt 11.48, az 164.748)', () => {
const m = moonPosition('2026-06-01T23:00:00Z', VIENNA.lat, VIENNA.lon);
expect(Math.abs(m.elevation - 11.48)).toBeLessThan(0.5);
expect(Math.abs(m.azimuth - 164.748)).toBeLessThan(0.7);
});
});
describe('constellation lines', () => {
it('place every vertex for the moment, in az/el, one chain per chain', () => {
const l = linesAt(new Date('2026-11-20T21:00:00Z'), VIENNA.lat, VIENNA.lon);
expect(l).toHaveLength(150);
expect(l[0].every((p) => p.azimuth >= 0 && p.azimuth < 360 && Math.abs(p.elevation) <= 90)).toBe(true);
});
});

View file

@ -0,0 +1,120 @@
// The real stars and constellation lines of the night sky, placed for a place and a moment. The data is nightSkyData.ts (generated, J2000;
// see its header for sources); the sidereal transform is the sun's own (`src/sky/sun.js` equatorialToHorizontal), after precessing the
// J2000 positions to the date. Proper motion and nutation are left out: both are under an arcminute here.
import { daysSinceJ2000, equatorialToHorizontal } from '../../../../sky/sun.js';
import { LINES_B64, LINE_CHAINS, STARS_B64, STAR_COUNT } from './nightSkyData';
const RAD = Math.PI / 180;
const ARCSEC = RAD / 3600;
/** Faintest star drawn, by catalogue Vmag. The data is cut at 5.5. */
export const MAG_LIMIT = 5.5;
export interface CatalogueStar {
/** J2000, radians. */
ra: number;
dec: number;
/** Visual magnitude. */
mag: number;
/** B-V colour index. */
bv: number;
}
const bytes = (b64: string): Uint8Array => {
const bin = atob(b64.replace(/\s+/g, ''));
return Uint8Array.from(bin, (c) => c.charCodeAt(0));
};
const raOf = (u16: number): number => (u16 / 65536) * 360 * RAD;
const decOf = (u16: number): number => ((u16 / 65535) * 180 - 90) * RAD;
let stars: CatalogueStar[] | undefined;
let chains: { ra: number; dec: number }[][] | undefined;
/** The catalogue, brightest first (decoded once). */
export function catalogue(): readonly CatalogueStar[] {
if (!stars) {
const b = bytes(STARS_B64);
const v = new DataView(b.buffer);
stars = Array.from({ length: STAR_COUNT }, (_, i) => ({
ra: raOf(v.getUint16(i * 6, true)),
dec: decOf(v.getUint16(i * 6 + 2, true)),
mag: b[i * 6 + 4] / 20 - 2,
bv: b[i * 6 + 5] / 50 - 0.5,
}));
}
return stars;
}
/** The constellation figures: chains of J2000 vertices (decoded once). */
export function lineChains(): readonly { ra: number; dec: number }[][] {
if (!chains) {
const b = bytes(LINES_B64);
const v = new DataView(b.buffer);
const out: { ra: number; dec: number }[][] = [];
let at = 0;
while (at < b.length) {
const n = b[at];
at += 1;
out.push(
Array.from({ length: n }, (_, k) => ({
ra: raOf(v.getUint16(at + k * 4, true)),
dec: decOf(v.getUint16(at + k * 4 + 2, true)),
}))
);
at += n * 4;
}
if (out.length !== LINE_CHAINS) throw new Error('nightSkyData: line chains do not match the header');
chains = out;
}
return chains;
}
/** J2000 right ascension and declination (radians) precessed to the date of `time` (IAU 1976, Meeus, "Astronomical Algorithms" 21.2). */
export function precess(ra: number, dec: number, time: Date | number): [number, number] {
const t = daysSinceJ2000(time) / 36525;
const zeta = (2306.2181 * t + 0.30188 * t * t + 0.017998 * t ** 3) * ARCSEC;
const z = (2306.2181 * t + 1.09468 * t * t + 0.018203 * t ** 3) * ARCSEC;
const theta = (2004.3109 * t - 0.42665 * t * t - 0.041833 * t ** 3) * ARCSEC;
const a = Math.cos(dec) * Math.sin(ra + zeta);
const b = Math.cos(theta) * Math.cos(dec) * Math.cos(ra + zeta) - Math.sin(theta) * Math.sin(dec);
const c = Math.sin(theta) * Math.cos(dec) * Math.cos(ra + zeta) + Math.cos(theta) * Math.sin(dec);
return [Math.atan2(a, b) + z, Math.asin(Math.max(-1, Math.min(1, c)))];
}
interface Horizontal {
azimuth: number;
elevation: number;
}
export interface PlacedStar extends CatalogueStar, Horizontal {
/** Index into the catalogue. */
index: number;
}
/** The stars at or above `minElevation` degrees (and no fainter than `magLimit`) for the moment and place, brightest first. Degrees; azimuth clockwise from north; no refraction. */
export function starsAt(
time: Date,
lat: number,
lon: number,
magLimit: number = MAG_LIMIT,
minElevation = -1
): PlacedStar[] {
const out: PlacedStar[] = [];
catalogue().forEach((s, index) => {
if (s.mag > magLimit) return;
const [ra, dec] = precess(s.ra, s.dec, time);
const h = equatorialToHorizontal(ra, dec, time, lat, lon) as Horizontal;
if (h.elevation >= minElevation) out.push({ ...s, index, azimuth: h.azimuth, elevation: h.elevation });
});
return out;
}
/** The constellation chains for the moment and place as azimuth and elevation (degrees), every vertex kept (the horizon is the ridge's to hide). */
export function linesAt(time: Date, lat: number, lon: number): Horizontal[][] {
return lineChains().map((chain) =>
chain.map((p) => {
const [ra, dec] = precess(p.ra, p.dec, time);
return equatorialToHorizontal(ra, dec, time, lat, lon) as Horizontal;
})
);
}

View file

@ -1,88 +1,23 @@
/* eslint-disable no-restricted-syntax, no-continue -- test loops over sample times */
import { describe, expect, it } from 'vitest';
import { skyColours } from './skyColour';
import {
MAX_STARS,
NIGHT_LUMA,
SLOTS,
TWINKLE_GAIN,
TWINKLE_PERIOD,
activeAt,
makeStars,
skyLuma,
slotCount,
slotOffset,
slotPeriod,
starCount,
twinkleGain,
} from './stars';
const DAY = {
...skyColours(),
top: [96, 150, 220],
mid: [150, 190, 235],
horizon: [240, 215, 190],
} as const;
const NIGHT = {
...skyColours(),
top: [10, 14, 40],
mid: [30, 34, 80],
horizon: [60, 50, 90],
} as const;
const N = makeStars(NIGHT, 390, 844).length;
/** A field the size of a night's visible stars. */
const N = 1200;
function hash2(a: number, b: number) {
return ((a * 7919 + b * 104729) % 1000) / 1000;
}
describe('star placement', () => {
it('is deterministic: the same sky and size give the identical field', () => {
expect(makeStars(NIGHT, 390, 844)).toEqual(makeStars(NIGHT, 390, 844));
expect(makeStars(skyColours(), 390, 844)).toEqual(makeStars(skyColours(), 390, 844));
});
it('draws none in a day sky or the lavender dusk, and some in a night one', () => {
expect(makeStars(DAY, 390, 844)).toHaveLength(0);
expect(makeStars(skyColours(), 390, 844)).toHaveLength(0);
expect(makeStars(NIGHT, 390, 844).length).toBeGreaterThan(50);
});
it('is a few hundred at most: bounded by MAX_STARS and by the viewport', () => {
for (const [w, h] of [
[390, 844],
[1920, 1080],
[100, 100],
] as const) {
expect(makeStars(NIGHT, w, h).length).toBeLessThanOrEqual(starCount(w, h));
expect(starCount(w, h)).toBeLessThanOrEqual(MAX_STARS);
}
expect(N).toBeGreaterThan(150);
});
it('thins toward the horizon: more than twice the stars in the top third than the bottom third of the sky', () => {
const all = makeStars(NIGHT, 390, 844);
expect(all.filter((s) => s.y < 0.26).length).toBeGreaterThan(
2 * all.filter((s) => s.y > 0.52).length
);
});
it('fades with the sky: every star sits where the sky is dark, alpha within bounds', () => {
for (const s of makeStars(NIGHT, 390, 844)) {
expect(skyLuma(NIGHT, s.y)).toBeLessThan(NIGHT_LUMA);
expect(s.alpha).toBeLessThanOrEqual(0.9);
expect(s.alpha).toBeGreaterThanOrEqual(0.05);
}
});
it('varies in size and brightness', () => {
const all = makeStars(NIGHT, 390, 844);
expect(new Set(all.map((s) => s.r.toFixed(2))).size).toBeGreaterThan(50);
expect(
Math.max(...all.map((s) => s.alpha)) - Math.min(...all.map((s) => s.alpha))
).toBeGreaterThan(0.3);
});
});
describe('twinkle schedule', () => {
const times = Array.from({ length: 400 }, (_, i) => i * 0.37);

View file

@ -1,22 +1,11 @@
// The Midnight starfield: placed once from a seeded PRNG and baked once into the sky canvas. A
// rolling window of them twinkles on an overlay canvas: SLOTS slots, each running back-to-back
// twinkles of one star at a time, so the active set is always SLOTS stars and every star gets its turn.
// The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs
// after the field is built, so any instant maps straight to the active set and its brightnesses.
// The twinkle of the real stars (`nightBodies.ts` places them from the catalogue for the place and moment). A rolling window of them twinkles
// on an overlay canvas: SLOTS slots, each running back-to-back twinkles of one star at a time, so the active set is always SLOTS stars and every
// star gets its turn. The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs, so any instant maps
// straight to the active set and its gains. A gain multiplies the star's radiance before the display (scintillation is flux), so a star
// the twilight hides stays hidden whatever it does.
/* eslint-disable no-bitwise -- the seeded PRNG and hash are 32-bit integer arithmetic */
import type { SkyColours, Srgb } from './skyColour';
/* eslint-disable no-bitwise -- the seeded hash is 32-bit integer arithmetic */
/**
* Stars show when the sky behind them is darker than this sRGB luma (0..255). The ridge scene has
* no night flag (the sky theme's Midnight/Noonday is a body class chosen by the app, not seen here),
* so night is the sky's own darkness: a star's alpha is 1 - luma/NIGHT_LUMA at its height in the
* gradient, and a sky whose zenith is lighter than this gets no stars at all.
*/
export const NIGHT_LUMA = 110;
/** The sky gradient runs from the top (0) through mid (0.5) to the horizon glow (0.78 and below). */
export const SKY_STOPS = { mid: 0.5, horizon: 0.78 };
export const MAX_STARS = 400;
/** Twinkling stars at any instant (fewer only if the field has fewer stars). */
export const SLOTS = 32;
export const TWINKLE_PERIOD = { min: 2, max: 7 } as const;
@ -30,43 +19,12 @@ export interface Star {
y: number;
/** Radius in CSS px. */
r: number;
/** Base alpha 0..0.9 (brightness times how dark the sky is there). */
alpha: number;
/** CSS colour, white tinted blue or warm. */
/** CSS colour of the star's centre at base brightness: the display of the sky behind it plus the star, through the sky's own display. */
fill: string;
/** The sky gradient's colour at this height: dimming paints it over the baked star. */
/** CSS colour of the sky behind it, through the same display: twinkling paints it over the baked star first. */
cover: string;
}
const luma = (c: Srgb) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
/** The baked gradient's colour at fraction t of the canvas height (the canvas interpolates in sRGB). */
function skyAt(sky: SkyColours, t: number): Srgb {
const mix = (a: Srgb, b: Srgb, k: number): Srgb => [
Math.round(lerp(a[0], b[0], k)),
Math.round(lerp(a[1], b[1], k)),
Math.round(lerp(a[2], b[2], k)),
];
if (t <= SKY_STOPS.mid) return mix(sky.top, sky.mid, t / SKY_STOPS.mid);
if (t <= SKY_STOPS.horizon)
return mix(sky.mid, sky.horizon, (t - SKY_STOPS.mid) / (SKY_STOPS.horizon - SKY_STOPS.mid));
return sky.horizon;
}
export const skyLuma = (sky: SkyColours, t: number): number => luma(skyAt(sky, t));
export const isNight = (sky: SkyColours): boolean => luma(sky.top) < NIGHT_LUMA;
/** mulberry32: 32-bit seeded PRNG, one float in [0, 1) per call. */
function prng(seed: number) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
/** The star's centre colour with its radiance multiplied by `gain` (scintillation). */
shade: (gain: number) => string;
}
/** Stateless seeded hash of up to three integers to [0, 1). */
@ -78,49 +36,6 @@ export function hash(a: number, b = 0, c = 0): number {
return (h >>> 0) / 4294967296;
}
/** How many stars a viewport carries: about one per 1100 CSS px squared, 150..MAX_STARS. */
export const starCount = (cssW: number, cssH: number): number =>
Math.min(MAX_STARS, Math.max(150, Math.round((cssW * cssH) / 1100)));
/**
* Seeded placement. Each candidate draws all its random numbers whether it is kept or not, so a
* given seed and sky always give the same field and the prefix does not shift with the count.
* Heights are squeezed toward the zenith (y = 0.78 u^1.7) and alpha falls with the sky's luma, so
* the stars thin out and fade into the horizon glow. None for a day sky.
*/
export function makeStars(sky: SkyColours, cssW: number, cssH: number): Star[] {
if (!isNight(sky)) return [];
const rnd = prng(SEED);
const n = starCount(cssW, cssH);
// Every candidate draws all its numbers, kept or not, so the prefix is stable.
const candidates = Array.from({ length: MAX_STARS }, () => ({
x: rnd(),
y: SKY_STOPS.horizon * rnd() ** 1.7,
r: 0.35 + 1.0 * rnd() ** 4,
bright: 0.35 + 0.65 * rnd() ** 1.5,
tint: rnd(),
})).slice(0, n);
return candidates.flatMap(({ x, y, r, bright, tint }) => {
const alpha = Math.min(0.9, bright * Math.max(0, 1 - skyLuma(sky, y) / NIGHT_LUMA));
if (alpha < 0.05) return [];
// White, pulled toward blue or toward warm by the tint draw.
const to: Srgb = tint < 0.5 ? [165, 195, 255] : [255, 222, 185];
const k = 0.55 * Math.abs(tint - 0.5) * 2;
const c = [255, 255, 255].map((v, j) => Math.round(lerp(v, to[j], k)));
const s = skyAt(sky, y);
return [
{
x,
y,
r,
alpha,
fill: `rgb(${c[0]},${c[1]},${c[2]})`,
cover: `rgb(${s[0]},${s[1]},${s[2]})`,
},
];
});
}
// ---- The schedule ---------------------------------------------------------------------------
export const slotCount = (stars: number): number => Math.min(SLOTS, stars);
@ -199,28 +114,9 @@ export function activeAt(stars: number, t: number): Twinkling[] {
// ---- Drawing --------------------------------------------------------------------------------
/** Bake `stars` into `ctx` (canvas `w` x `h` device px, `scale` device px per CSS px) at base alpha. */
export function drawStars(
ctx: CanvasRenderingContext2D,
stars: readonly Star[],
w: number,
h: number,
scale: number
) {
stars.forEach((s) => {
ctx.globalAlpha = s.alpha;
ctx.fillStyle = s.fill;
ctx.beginPath();
ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI);
ctx.fill();
});
ctx.globalAlpha = 1;
}
/**
* The overlay pass: clear, then for each active star whose gain is off base, paint over the baked
* star. Dimming covers it with the sky's own colour at (1 - gain), which leaves exactly
* alpha * gain of the star; brightening adds a second star on top. A star at base draws nothing.
* The overlay pass: clear, then for each active star whose gain is off base, cover the baked star with the sky behind it and draw it again
* at the gain. A star at base draws nothing.
*/
export function drawTwinkle(
ctx: CanvasRenderingContext2D,
@ -234,16 +130,13 @@ export function drawTwinkle(
active.forEach((a) => {
const s = stars[a.star];
if (!s || Math.abs(a.gain - 1) < 0.01) return;
if (a.gain < 1) {
ctx.globalAlpha = 1 - a.gain;
ctx.fillStyle = s.cover;
} else {
ctx.globalAlpha = Math.min(1, ((a.gain - 1) * s.alpha) / (1 - s.alpha));
ctx.fillStyle = s.fill;
}
ctx.fillStyle = s.cover;
ctx.beginPath();
ctx.arc(s.x * w, s.y * h, s.r * scale + (a.gain < 1 ? 1 : 0), 0, 2 * Math.PI);
ctx.arc(s.x * w, s.y * h, s.r * scale + 1, 0, 2 * Math.PI);
ctx.fill();
ctx.fillStyle = s.shade(a.gain);
ctx.beginPath();
ctx.arc(s.x * w, s.y * h, s.r * scale, 0, 2 * Math.PI);
ctx.fill();
});
ctx.globalAlpha = 1;
}

View file

@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import { FALLBACK_VIEW } from './view';
import { makePhysicalSky } from './physicalSky';
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';
const sweep = (c: ReturnType<typeof makeCurve>) =>
Array.from({ length: 401 }, (_, i) => applyCurve(c, i / 400));
describe('the tone curve', () => {
it('is monotone, starts at the black lift and ends at the top knot, for a spread of knots', () => {
const cases: [number[], number[]][] = [
[[0, 0.01, 0.2, 0.7, 1], [BLACK_LIFT, 0.12, 0.5, 0.9, 1]],
[[0, 0.0005, 0.003, 0.05, 1], [BLACK_LIFT, 0.0225, 0.04, 0.043, 0.043]],
[[0, 0.3, 0.31, 0.32, 1], [BLACK_LIFT, 0.2, 0.5, 0.8, 1]],
];
for (const [x, y] of cases) {
const c = makeCurve(x, y);
const v = sweep(c);
expect(v[0]).toBeCloseTo(BLACK_LIFT, 12);
expect(v[400]).toBeCloseTo(y[4], 12);
for (let i = 1; i < v.length; i += 1) expect(v[i]).toBeGreaterThanOrEqual(v[i - 1] - 1e-12);
}
});
});
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 { 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];
it('has the black lift constant at black and every texel inside the state budget', () => {
const c = sky.fit.display.curve;
expect(applyCurve(c, 0)).toBe(b.lift);
expect(b.lift).toBe(state === 'night' ? NIGHT_LIFT : BLACK_LIFT);
expect(sky.fit.lo).toBeGreaterThanOrEqual(b.floor);
expect(sky.fit.hi).toBeLessThanOrEqual(b.ceiling + 0.004);
const v = sweep(c);
for (let i = 1; i < v.length; i += 1) expect(v[i]).toBeGreaterThanOrEqual(v[i - 1] - 1e-12);
});
it('puts the sky percentiles on the targets (as far as the gain limit allows)', () => {
const n = dome.hdr.length / 3;
const ls: number[] = [];
for (let i = 0; i < n; i += 1)
ls.push(displayLumaOf(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], sky.fit.display));
ls.sort((p, q) => p - q);
const at = (q: number) => ls[Math.floor(q * n)];
const flat = fitDisplay(state, dome.hdr, dome.meanLuma);
expect(flat.display).toEqual(sky.fit.display);
// The curve is fitted on luminance and applied per channel, so the byte luminance is near its targets, not on them. The median is never limited; the outer two are at or below their targets by the gain limit only.
const p = b.partial;
const level = p ? Math.min(p.levelMax, Math.max(p.levelMin, (dome.meanLuma / p.ref) ** (1 - p.exponent))) : 1;
expect(at(0.5)).toBeGreaterThan(b.targets[1] * level * 0.75);
// The scotopic grade lifts the blue channel, which the per-channel curve takes up faster than the luminance it was fitted on: night reads up to twice its target.
const slack = p ? 2.5 : 1.25;
expect(at(0.5)).toBeLessThan(b.targets[1] * level * slack);
expect(at(0.95)).toBeLessThanOrEqual(b.targets[2] * level * slack + 0.004);
expect(at(0.05)).toBeLessThan(at(0.5));
});
});
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));
};
const fullMoon = night('2026-11-24T22:00:00Z');
const newMoon = night('2026-12-09T20:00:00Z');
it('adapts the exposure to the sky: a moonless night is exposed far brighter than a moonlit one', () => {
expect(fullMoon.moon.illuminated).toBeGreaterThan(0.99);
expect(newMoon.moon.illuminated).toBeLessThan(0.1);
expect(newMoon.fit.display.exposure).toBeGreaterThan(10 * fullMoon.fit.display.exposure);
});
it('reads the new-moon night darker than the full-moon night (partial adaptation), by the level of the budget', () => {
const med = (p: ReturnType<typeof night>) => applyCurve(p.fit.display.curve, p.fit.display.curve.x[2]); // the median of the sky
expect(med(newMoon)).toBeLessThan(0.6 * med(fullMoon));
});
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);
});
it('has no fixed night ceiling: the curve tops out at NIGHT_CEILING', () => {
expect(applyCurve(newMoon.fit.display.curve, 1)).toBe(NIGHT_CEILING);
expect(BUDGET.night.ceiling).toBe(NIGHT_CEILING);
});
});
describe('the scotopic grade', () => {
it('leaves a neutral grey alone in hue, moves colour toward blue and darkens red against blue', () => {
const o = [0, 0, 0];
scotopic(0.2, 0.2, 0.2, 1, o);
expect(o[0] / o[1]).toBeCloseTo(SCOTOPIC.tint[0] / SCOTOPIC.tint[1], 6);
scotopic(0.5, 0.1, 0.1, 1, o);
const red = [...o];
scotopic(0.1, 0.1, 0.5, 1, o);
expect(o[2]).toBeGreaterThan(red[2]);
expect(red[0]).toBeLessThan(0.5); // red is nearly black to the rods
scotopic(0.3, 0.2, 0.1, 0, o);
expect(o).toEqual([0.3, 0.2, 0.1]);
});
it('weighs 1 in the dark and 0 in daylight, falling through the mesopic range', () => {
expect(scotopicWeight(2e-9)).toBeCloseTo(1, 6);
expect(scotopicWeight(0.3)).toBe(0);
expect(scotopicWeight(1e-6)).toBeGreaterThan(scotopicWeight(1e-4));
});
});

View file

@ -3,25 +3,32 @@
// matrix), then the sRGB encode. A per-pixel function with no state, applied once to the baked sky (CPU: the scene is a 2D
// canvas, there is no float render target to fall back from).
//
// Exposure is chosen per sky state (`exposureFor`): the sky is physical radiance, so brightness is the camera's, not a
// shaping of the result. Day and dusk expose to the sky's own luminance (adaptation, as an eye or auto-exposure does) so the
// darkest of the sky stays where the state's dark ink needs a backdrop; night is fixed, the physical dark.
// Exposure adapts to the sky's own luminance in every state (the sky is physical radiance, so brightness is the camera's); night
// adapts only in part (`Budget.partial`), so a new-moon night reads darker than a full-moon one. Before exposure a scotopic grade
// (`scotopic`: desaturation and a blue shift as the adapted luminance falls through the mesopic range) carries the night read. After
// ACES comes one more curve, per channel in display-linear: a monotone cubic through five knots, fitted per sky from the luminance
// 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 { SUN_LUX } from './nightSky';
type Rgb = readonly [number, number, number];
const IN: readonly Rgb[] = [
export const ACES_IN: readonly Rgb[] = [
[0.59719, 0.35458, 0.04823],
[0.076, 0.90834, 0.01566],
[0.0284, 0.13383, 0.83777],
];
const OUT: readonly Rgb[] = [
export const ACES_OUT: readonly Rgb[] = [
[1.60475, -0.53108, -0.07367],
[-0.10208, 1.10813, -0.00605],
[-0.00327, -0.07276, 1.07602],
];
/** Hill's rational fit, `(v (v + a) - b) / (v (c v + d) + e)`: the display the lit cards share (`lightCards.ts` writes the same into its shader). */
export const ACES_FIT = [0.0245786, 0.000090537, 0.983729, 0.432951, 0.238081] as const;
const fit = (v: number): number =>
(v * (v + 0.0245786) - 0.000090537) / (v * (0.983729 * v + 0.432951) + 0.238081);
(v * (v + ACES_FIT[0]) - ACES_FIT[1]) / (v * (ACES_FIT[2] * v + ACES_FIT[3]) + ACES_FIT[4]);
const encode = (l: number): number => {
const c = Math.min(1, Math.max(0, l));
return 255 * (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
@ -32,9 +39,51 @@ export function acesLinear(r: number, g: number, b: number, exposure: number, ou
const x = r * exposure;
const y = g * exposure;
const z = b * exposure;
const p = [0, 1, 2].map((i) => fit(Math.max(0, IN[i][0] * x + IN[i][1] * y + IN[i][2] * z)));
const p = [0, 1, 2].map((i) =>
fit(Math.max(0, ACES_IN[i][0] * x + ACES_IN[i][1] * y + ACES_IN[i][2] * z))
);
for (let i = 0; i < 3; i += 1)
out[i] = Math.min(1, Math.max(0, OUT[i][0] * p[0] + OUT[i][1] * p[1] + OUT[i][2] * p[2]));
out[i] = Math.min(
1,
Math.max(0, ACES_OUT[i][0] * p[0] + ACES_OUT[i][1] * p[1] + ACES_OUT[i][2] * p[2])
);
}
/** Scotopic luminance of linear sRGB (Jensen et al. 2001, from CIE XYZ): the response of the rods, which see red as nearly black. */
export const scotopicLuminance = (r: number, g: number, b: number): number => {
const X = 0.4124 * r + 0.3576 * g + 0.1805 * b;
const Y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const Z = 0.0193 * r + 0.1192 * g + 0.9505 * b;
return Math.max(0, Y * (1.33 * (1 + (Y + Z) / Math.max(X, 1e-30)) - 1.68));
};
/**
* The scotopic grade of linear radiance `r, g, b` at weight `w` (0 photopic .. 1 scotopic): toward the rods' luminance in a blue-shifted grey. A neutral grey keeps its luminance, so the grade moves colour more than brightness. Written into `out`.
* `lightCards.ts` writes the same into its shader.
*/
export function scotopic(r: number, g: number, b: number, w: number, out: number[]): void {
if (w <= 0) {
out[0] = r;
out[1] = g;
out[2] = b;
return;
}
const v = scotopicLuminance(r, g, b);
// Scale the rods' grey to the cones' luminance for a neutral, so only the colour is graded.
const grey = scotopicLuminance(1, 1, 1);
const k = v / grey;
for (let i = 0; i < 3; i += 1) {
const target = k * SCOTOPIC.tint[i];
out[i] = [r, g, b][i] + (target - [r, g, b][i]) * w;
}
}
/** How scotopic a sky is, 0..1, from its log-mean luminance per unit of sun irradiance: through the mesopic range (`SCOTOPIC`). */
export function scotopicWeight(meanLuma: number): number {
const lg = Math.log10(Math.max(meanLuma * SUN_LUX, 1e-12));
const [lo, hi] = SCOTOPIC.mesopic;
const t = Math.min(1, Math.max(0, (lg - lo) / (hi - lo)));
return SCOTOPIC.strength * (1 - t * t * (3 - 2 * t));
}
/** The 8-bit sRGB of linear radiance, exposed and tone-mapped. */
@ -49,46 +98,127 @@ export function toneMap8(r: number, g: number, b: number, exposure: number, out:
export const displayLuma = (c: ArrayLike<number>): number =>
0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
/** What a sky state needs of its backdrop's display luminance, from the ink it wears (skyState.ts, skyInk.ts). */
/** What a sky state needs of its backdrop's display luminance, and the targets its curve is fitted to. */
export interface Budget {
/** The darkest texel may not be darker than this (dark ink needs a light backdrop). 0: no floor. */
/** The darkest texel the curve can draw (its black lift, less one 8-bit step). */
floor: number;
/** The lightest texel may not be lighter than this (light ink needs a dark one). 1: no ceiling. */
/** What black is drawn as, display-linear: the curve's first knot. */
lift: number;
/** The lightest texel may not be lighter than this (light ink needs a dark one); it is the curve's top knot. 1: white. */
ceiling: number;
/** Display luminance the log-mean of the sky is exposed to, before the budget is applied; undefined: a fixed exposure. */
/** Display luminance the log-mean of the sky is exposed to before the curve; undefined: a fixed exposure. */
key?: number;
/** Exposure range, in multiples of scene radiance (per unit sun irradiance). */
min: number;
max: number;
/** Display luminance the 5th, 50th and 95th percentile of the sky's luminance are mapped to. */
targets: readonly [number, number, number];
/**
* Partial adaptation: the targets are scaled by `(meanLuma / ref) ^ (1 - exponent)` (clamped to `levelMin`..`levelMax`) where `meanLuma` is the sky's
* log-mean luminance per unit of sun irradiance and `ref` the one the targets were set at. Exponent 1 is full adaptation (day, dusk).
*/
partial?: { ref: number; exponent: number; levelMin: number; levelMax: number };
/** The most the curve may steepen the sky's own spread about its median (display luminance per unit of ACES output): a nearly flat overcast sky is not blown up into a gradient. */
maxGain: number;
}
/** Display luminance slack for the 8-bit rounding and the smooth upscale of the baked grid. */
export const MARGIN = 0.004;
/** The one absolute lift of day and dusk: what black is drawn as, display-linear. The rest of the range is made by the curve. */
export const BLACK_LIFT = 0.02;
/** Night's black lift: a little lower than day's, the darks stay soft rather than crushed. */
export const NIGHT_LIFT = 0.004;
/** The night's ceiling, display-linear: the top of its curve (1 is white). EYEBALLED: the operator tunes it by eye; the moon and the stars are drawn through the same display and need the room. */
export const NIGHT_CEILING = 1;
/**
* Day and Dusk wear the same dark ink, so one floor: its bound plus margin, 0.4744, which is what the dark link needs (about 0.4554 for 4.5:1, skyTheme.test.ts); a lower day floor (0.317 was tried) leaves the link at 3.3:1. Night wears light ink, and its
* dimmer foldout headers (L 0.386 on screen, rat-crest-a7c95ce-20261111) need a backdrop of at most 0.047.
* The scotopic grade (Thompson, Shirley & Ferwerda 2002; Kirk & O'Brien 2011; Jensen et al. 2001): `strength` scales it (EYEBALLED, 0 off),
* the mesopic range is log10 of the adapted luminance in cd/m^2 from `mesopic[0]` (fully scotopic) to `mesopic[1]` (fully photopic),
* and `tint` is the blue shift of the scotopic luminance (Jensen et al.).
*/
export const BUDGET: Record<FixedSkyState, Budget> = {
day: { floor: 0.4744 + MARGIN, ceiling: 1, key: 0.45, min: 4, max: 60 },
dusk: { floor: 0.4744 + MARGIN, ceiling: 1, key: 0.5, min: 4, max: 400 },
night: { floor: 0, ceiling: 0.047 - MARGIN, key: 0.03, min: 8, max: 3000 },
export const SCOTOPIC = {
strength: 1,
mesopic: [-2, 0.5] as const,
tint: [1.05, 0.97, 1.27] as const,
};
/** The luma one 8-bit code moves at the day floor (about 0.0037): a lift step smaller than this can leave the encoded luma where it was, so the floor search never steps less. */
const CODE_STEP = 0.0045;
export const BUDGET: Record<FixedSkyState, Budget> = {
day: { floor: BLACK_LIFT - 0.001, lift: BLACK_LIFT, ceiling: 1, key: 0.45, min: 4, max: 60, targets: [0.22, 0.58, 0.9], maxGain: 4 },
dusk: { floor: BLACK_LIFT - 0.001, lift: BLACK_LIFT, ceiling: 1, key: 0.5, min: 4, max: 400, targets: [0.12, 0.45, 0.85], maxGain: 4 },
night: {
floor: NIGHT_LIFT - 0.001,
lift: NIGHT_LIFT,
ceiling: NIGHT_CEILING,
// The key sits at the targets (not day's 0.45): the sky is exposed to where the curve wants it, so the curve is near the identity over it and
// the per-channel curve does not blow a small colour difference (the scotopic blue shift) up into a saturated sky.
key: 0.03,
min: 4,
max: 1e13,
targets: [0.012, 0.03, 0.07],
maxGain: 4,
// A full-moon sky is about 2e-7 of the sun's irradiance in radiance; a moonless one about 2e-9. Partial adaptation of 0.7 puts
// the second at about a quarter of the first.
partial: { ref: 2e-7, exponent: 0.7, levelMin: 0.2, levelMax: 1.3 },
},
};
/** The display transform of a sky: exposure, then ACES, then a black lift (veiling glare) in display-linear. */
/** Knots of the curve: black, the 5th, 50th, 95th percentile, white. */
export const KNOTS = 5;
/** A monotone piecewise-cubic Hermite curve over display-linear 0..1: knot positions, values and slopes. */
export interface Curve {
x: number[];
y: number[];
m: number[];
}
/** The monotone cubic (Fritsch-Carlson, Brodlie's weighted harmonic mean) through strictly increasing `x` and non-decreasing `y`. */
export function makeCurve(x: number[], y: number[]): Curve {
const n = x.length;
const h = x.slice(1).map((v, i) => v - x[i]);
const d = h.map((hk, i) => (y[i + 1] - y[i]) / hk);
const m = new Array<number>(n).fill(0);
m[0] = d[0];
m[n - 1] = d[n - 2];
for (let k = 1; k < n - 1; k += 1) {
if (d[k - 1] * d[k] <= 0) continue;
const w1 = 2 * h[k] + h[k - 1];
const w2 = h[k] + 2 * h[k - 1];
m[k] = (w1 + w2) / (w1 / d[k - 1] + w2 / d[k]);
}
return { x, y, m };
}
/** The curve at `v` (clamped to 0..1). `lightCards.ts` writes the same evaluation into its shader. */
export function applyCurve(c: Curve, v: number): number {
const t0 = Math.min(1, Math.max(0, v));
let k = 0;
for (let i = 1; i < c.x.length - 1; i += 1) if (t0 > c.x[i]) k = i;
const h = c.x[k + 1] - c.x[k];
const t = (t0 - c.x[k]) / h;
const t2 = t * t;
const t3 = t2 * t;
return (
(2 * t3 - 3 * t2 + 1) * c.y[k] +
(t3 - 2 * t2 + t) * h * c.m[k] +
(-2 * t3 + 3 * t2) * c.y[k + 1] +
(t3 - t2) * h * c.m[k + 1]
);
}
/** The display transform of a sky: exposure, then ACES, then the fitted curve in display-linear. */
export interface Display {
exposure: number;
/** Added to every channel after the curve, then rescaled so white stays white: out = lift + (1 - lift) * aces. */
lift: number;
curve: Curve;
/** Weight of the scotopic grade before exposure, 0 (photopic, the default) .. 1 (`scotopicWeight`). */
grade?: number;
}
/** The 8-bit sRGB of linear radiance through a display. */
export function display8(r: number, g: number, b: number, d: Display, out: number[]): void {
acesLinear(r, g, b, d.exposure, out);
for (let i = 0; i < 3; i += 1) out[i] = Math.round(encode(d.lift + (1 - d.lift) * out[i]));
if (d.grade) {
scotopic(r, g, b, d.grade, out);
acesLinear(out[0], out[1], out[2], d.exposure, out);
} else acesLinear(r, g, b, d.exposure, out);
for (let i = 0; i < 3; i += 1) out[i] = Math.round(encode(applyCurve(d.curve, out[i])));
}
const decode = (v: number): number => {
@ -112,15 +242,16 @@ export interface Fit {
/** Darkest and lightest display luminance of the grid under `display`. */
lo: number;
hi: number;
/** The exposure before the budget moved it, and what the budget took (for the numbers a report cites). */
/** The exposure the state's key chose (the curve does the rest). */
keyExposure: number;
}
/**
* Choose the display of a sky, the one place brightness is decided. `hdr` is the grid's radiance (3 floats a texel) and
* `meanLuma` its log-mean luminance. Exposure starts at the state's key (adaptation); a ceiling lowers it until the
* lightest texel is inside the budget (bisection: luminance is monotone in exposure); a floor raises the black lift until the
* darkest is (luminance is monotone in lift, and linear: the lift needed is solved in one step).
* Choose the display of a sky, the one place brightness is decided. `hdr` is the grid's radiance (3 floats a texel) and `meanLuma` its
* log-mean luminance. Exposure is the state's key (adaptation); the targets of a state with partial adaptation are scaled by the sky's level. The scotopic grade's weight comes from the sky's luminance. The curve is then fitted: the 5th, 50th and 95th percentile of the
* grid's luminance after ACES go to the state's targets (the outer two held to the budget's `maxGain` times the sky's own spread about the median),
* between a black lift below and white (or the night ceiling) above. Monotone by construction, so the ceiling holds for every texel
* of every grid and card, and no pass over another viewport's grid is needed.
*/
export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: number): Fit {
const b = BUDGET[state];
@ -129,83 +260,47 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu
? b.min
: Math.min(b.max, Math.max(b.min, (b.key * 1.6) / Math.max(meanLuma, 1e-9)));
const n = hdr.length / 3;
const tmp = [0, 0, 0];
const xs: number[] = [];
const grade = scotopicWeight(meanLuma);
for (let i = 0; i < n; i += 1) {
scotopic(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], grade, tmp);
acesLinear(tmp[0], tmp[1], tmp[2], keyExposure, tmp);
xs.push(displayLuma(tmp));
}
xs.sort((p, q) => p - q);
const pct = (q: number) => xs[Math.min(n - 1, Math.floor(q * n))];
const x = [0, pct(0.05), pct(0.5), pct(0.95), 1];
x[1] = Math.max(x[1], 1e-7);
x[2] = Math.max(x[2], x[1] * 1.001 + 1e-7);
x[3] = Math.max(x[3], x[2] * 1.001 + 1e-7);
if (x[3] > 0.97) {
x[3] = 0.97;
x[2] = Math.min(x[2], 0.965);
x[1] = Math.min(x[1], 0.96);
}
const p = b.partial;
const level = p
? Math.min(p.levelMax, Math.max(p.levelMin, (Math.max(meanLuma, 1e-30) / p.ref) ** (1 - p.exponent)))
: 1;
const [t0, t1, t2] = b.targets.map((t) => t * level);
const y = [
b.lift,
Math.max(b.lift + 1e-4, t0, t1 - b.maxGain * (x[2] - x[1])),
t1,
Math.min(b.ceiling - 1e-4, t2, t1 + b.maxGain * (x[3] - x[2])),
b.ceiling,
];
y[1] = Math.min(y[1], y[2] - 1e-4);
y[3] = Math.max(y[3], y[2] + 1e-4);
const display: Display = { exposure: keyExposure, curve: makeCurve(x, y), grade };
let lo = 2;
let hi = -1;
const stride = Math.max(1, Math.floor(n / 4000));
const tmp = [0, 0, 0];
const range = (d: Display) => {
let lo = 2;
let hi = -1;
for (let i = 0; i < n; i += stride) {
const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], d, tmp);
if (l < lo) lo = l;
if (l > hi) hi = l;
}
return { lo, hi };
};
let exposure = keyExposure;
let r = range({ exposure, lift: 0 });
if (r.hi > b.ceiling) {
let lo = 0;
let hiE = exposure;
for (let k = 0; k < 24; k += 1) {
const mid = (lo + hiE) / 2;
if (range({ exposure: mid, lift: 0 }).hi > b.ceiling) hiE = mid;
else lo = mid;
}
exposure = lo;
r = range({ exposure, lift: 0 });
for (let i = 0; i < n; i += stride) {
const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], display, tmp);
if (l < lo) lo = l;
if (l > hi) hi = l;
}
let lift = 0;
if (r.lo < b.floor) {
// Linear in the displayed linear luminance: L' = lift + (1 - lift) L, but through the 8-bit encode; solve in linear then check once.
lift = (b.floor - r.lo) / (1 - r.lo);
let probe = range({ exposure, lift });
for (let k = 0; k < 6 && probe.lo < b.floor; k += 1) {
lift += Math.max((b.floor - probe.lo) * 1.05, CODE_STEP);
probe = range({ exposure, lift });
}
r = probe;
}
return { display: { exposure, lift }, lo: r.lo, hi: r.hi, keyExposure };
}
/**
* The display, moved only as far as the budget needs, for a grid other than the one it was fitted on (another viewport's shape,
* its own texels): the fit is made once on a canonical grid so that resizing repaints the same sky, and this keeps a texel the canonical
* grid did not have inside the state's bounds. A display that already holds them is returned as it is.
*/
export function holdBudget(state: FixedSkyState, hdr: Float32Array, d: Display): Display {
const b = BUDGET[state];
const n = hdr.length / 3;
const tmp = [0, 0, 0];
const range = (x: Display) => {
let lo = 2;
let hi = -1;
for (let i = 0; i < n; i += 1) {
const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], x, tmp);
if (l < lo) lo = l;
if (l > hi) hi = l;
}
return { lo, hi };
};
let cur = d;
let r = range(cur);
if (r.hi > b.ceiling) {
let lo = 0;
let hiE = cur.exposure;
for (let k = 0; k < 20; k += 1) {
const mid = (lo + hiE) / 2;
if (range({ exposure: mid, lift: cur.lift }).hi > b.ceiling) hiE = mid;
else lo = mid;
}
cur = { exposure: lo, lift: cur.lift };
r = range(cur);
}
for (let k = 0; k < 8 && r.lo < b.floor; k += 1) {
cur = {
exposure: cur.exposure,
lift: cur.lift + ((b.floor - r.lo) / (1 - r.lo)) * 1.05 + 1e-4,
};
r = range(cur);
}
return cur;
return { display, lo, hi, keyExposure };
}

View file

@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
import { sunOnScreen } from './skyDome';
import { DRIFT_FRAC, FALLBACK_VIEW, windowFor } from './view';
import { cardMotion, DRIFT_FRAC, FALLBACK_VIEW, HORIZON_AT, windowFor } from './view';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { View } from './view';
const VIEWPORTS: [number, number][] = [
@ -10,27 +12,69 @@ const VIEWPORTS: [number, number][] = [
];
describe('windowFor', () => {
it.each(VIEWPORTS)('%i x %i: the planes cover the viewport, the camera sees only baked sky, the horizon is the plane\'s', (w, h) => {
const v = FALLBACK_VIEW;
const win = windowFor(v, w, h);
expect(win.driftPx).toBeGreaterThanOrEqual(0);
expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6);
expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway
// Angle seen never exceeds the baked window minus the drift margin on both sides.
expect(win.camera.hfovDeg).toBeLessThanOrEqual(v.windowDeg / (1 + 2 * DRIFT_FRAC) + 1e-9);
// The plane is anchored to the bottom; its horizon row lands at the camera's horizon fraction of the viewport.
const horizonY = h - win.plane.bottom - win.plane.h + win.plane.scale * v.horizonRow;
expect(Math.abs(horizonY - win.camera.horizonAt * h)).toBeLessThan(0.5);
expect(win.camera.azimuthDeg).toBe(v.lookAzDeg);
expect(win.camera.vfovDeg / win.camera.hfovDeg).toBeCloseTo(h / w, 9); // one scale on both axes
it.each(VIEWPORTS)(
"%i x %i: the planes cover the viewport, the camera sees only baked sky, the horizon is the plane's",
(w, h) => {
const v = FALLBACK_VIEW;
const win = windowFor(v, w, h);
expect(win.driftPx).toBeGreaterThanOrEqual(0);
expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6);
expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway
// Angle seen never exceeds the baked window minus the drift margin on both sides.
expect(win.camera.hfovDeg).toBeLessThanOrEqual(v.windowDeg / (1 + 2 * DRIFT_FRAC) + 1e-9);
// The plane's horizon row lands at the camera's horizon fraction of the viewport.
const horizonY = h - win.plane.bottom - win.plane.h + win.plane.scale * v.horizonRow;
expect(Math.abs(horizonY - win.camera.horizonAt * h)).toBeLessThan(0.5);
expect(win.camera.azimuthDeg).toBe(v.lookAzDeg);
expect(win.camera.vfovDeg / win.camera.hfovDeg).toBeCloseTo(h / w, 9); // one scale on both axes
}
);
it('puts the horizon at one fraction of the height, whatever the viewport, the view or the sky state', () => {
const wide: View = { ...FALLBACK_VIEW, lookAzDeg: 10, windowDeg: 144, planeW: 2560, horizonRow: 200 };
for (const v of [FALLBACK_VIEW, wide])
for (const [w, h] of [...VIEWPORTS, [1024, 768], [375, 812], [1100, 619]] as [number, number][])
expect(windowFor(v, w, h).camera.horizonAt).toBe(HORIZON_AT);
expect(HORIZON_AT).toBeGreaterThan(0.5);
expect(HORIZON_AT).toBeLessThan(1);
});
it('is shaped by the View alone: another window, plane and horizon give another camera', () => {
const wide: View = { ...FALLBACK_VIEW, lookAzDeg: 10, windowDeg: 144, planeW: 2560, horizonRow: 200 };
it('shows about 31 degrees of sky above the horizon in a 16:9 desktop cell', () => {
const { camera } = windowFor(FALLBACK_VIEW, 1100, 619);
const sky = camera.horizonAt * camera.vfovDeg;
expect(sky).toBeGreaterThan(29);
expect(sky).toBeLessThan(34);
});
it.each([
[1024, 768],
[1920, 1080],
[375, 812],
[1100, 619],
])('%i x %i: the plane covers the viewport bottom and sides, drift included, with baked ground to spare below the horizon', (w, h) => {
const win = windowFor(FALLBACK_VIEW, w, h);
expect(win.plane.bottom).toBeLessThanOrEqual(0); // the foot of the plane is at or below the viewport's bottom edge
expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6);
expect(win.driftPx).toBeGreaterThanOrEqual(0);
// The baked ground below the horizon row that the viewport crops to: more than the viewport needs.
const needed = (1 - HORIZON_AT) * h;
const baked = win.plane.scale * (FALLBACK_VIEW.planeH - FALLBACK_VIEW.horizonRow);
expect(baked).toBeGreaterThanOrEqual(needed);
});
it('is shaped by the View alone: another window and plane give another camera (azimuth and field of view; the horizon stays put)', () => {
const wide: View = {
...FALLBACK_VIEW,
lookAzDeg: 10,
windowDeg: 144,
planeW: 2560,
horizonRow: 200,
};
const a = windowFor(FALLBACK_VIEW, 1920, 1080).camera;
const b = windowFor(wide, 1920, 1080).camera;
expect(b.azimuthDeg).toBe(10);
expect(b.horizonAt).not.toBeCloseTo(a.horizonAt, 2);
expect(windowFor(FALLBACK_VIEW, 1920, 1080).camera.hfovDeg).not.toBeCloseTo(windowFor(wide, 1920, 1080).camera.hfovDeg, 2);
expect(b.horizonAt).toBe(a.horizonAt);
});
it('registration: a sun 10 degrees right of the look azimuth sits where the plane puts that azimuth', () => {
@ -58,3 +102,54 @@ describe('windowFor', () => {
expect(windowFor(FALLBACK_VIEW, 1280, 720).camera.azimuthDeg).toBe(FALLBACK_VIEW.lookAzDeg);
});
});
describe('cardMotion', () => {
const manifest = parseManifest(wireManifest(), '/d/'); // scales 1.2, 1.0167, 1.005; heading range 23 deg; 1280 px plane, 17.78 px per degree
const motion = (w: number, h: number) => cardMotion(manifest, windowFor(manifest.view, w, h));
it('turns the whole baked range on a phone and is capped by coverage on a wide screen', () => {
expect(motion(390, 844).headingDeg).toBe(23);
expect(motion(1920, 1080).headingDeg).toBeCloseTo(3.4, 1);
expect(motion(768, 1024).headingDeg).toBeLessThan(23);
expect(motion(768, 1024).headingDeg).toBeGreaterThan(motion(1920, 1080).headingDeg);
});
it.each([
[390, 844],
[768, 1024],
[1920, 1080],
[3440, 1440],
])(
'%i x %i: every card still covers the viewport at the end of the drift, and the cap is exact for the card that gives out first',
(w, h) => {
const win = windowFor(manifest.view, w, h);
const { headingDeg } = cardMotion(manifest, win);
const half = w / 2 / win.plane.scale;
const slack = manifest.cards.map(
(c) => manifest.view.planeW / 2 - half / c.scale - headingDeg * manifest.view.pxPerDegH
);
slack.forEach((s) => expect(s).toBeGreaterThanOrEqual(-1e-6));
if (headingDeg < manifest.camera.headingMaxDeg) expect(Math.min(...slack)).toBeCloseTo(0, 6);
}
);
it('pans card i by scale_i x heading and keeps the scales the manifest gave', () => {
const win = windowFor(manifest.view, 390, 844);
const m = cardMotion(manifest, win);
expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
m.cards.forEach((c) =>
expect(c.reachPx).toBeCloseTo(c.scale * 23 * manifest.view.pxPerDegH * win.plane.scale, 6)
);
// The nearer a card, the faster it pans.
expect(m.cards[0].reachPx).toBeGreaterThan(m.cards[1].reachPx);
expect(m.cards[1].reachPx).toBeGreaterThan(m.cards[2].reachPx);
});
it('a wider baker range moves a phone further, a narrower one less', () => {
const win = windowFor(manifest.view, 390, 844);
const at = (deg: number) => cardMotion({ ...manifest, camera: { headingMaxDeg: deg } }, win);
expect(at(10).headingDeg).toBe(10);
expect(at(40).headingDeg).toBeLessThan(40); // the phone's coverage gives out first
expect(at(10).cards[0].reachPx).toBeLessThan(at(20).cards[0].reachPx);
});
});

View file

@ -1,5 +1,5 @@
// The one View: where the sky's camera stands and looks, and where the ridge planes sit against it. A baked place's manifest
// (`view` and `place`, manifest v1) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the
// The one View: where the sky's camera stands and looks, and where the ridge cards sit against it. A baked place's manifest
// (`view` and `place`, manifest v2) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the
// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. Nothing else
// chooses a field of view, a horizon row or an azimuth.
@ -20,6 +20,8 @@ export interface ManifestView {
planeW: number;
planeH: number;
pxPerDegH: number;
/** Plane pixels per degree of elevation (the baker draws the vertical exaggerated: it is not `pxPerDegH`). */
pxPerDegV: number;
/** Row of the horizon in the plane, from its top. */
horizonRow: number;
}
@ -41,7 +43,7 @@ export interface Camera {
horizonAt: number;
}
/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the six-key Vienna bake. */
/** 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 },
lookAzDeg: 214,
@ -49,16 +51,23 @@ export const FALLBACK_VIEW: View = {
planeW: 1280,
planeH: 600,
pxPerDegH: 1280 / 72,
pxPerDegV: 177.8,
horizonRow: 314.5,
};
/** The share of the viewport height the plane's height is at least scaled to, and the slack each side of the viewport kept for drift. Authored, tunable by eye. */
export const RIDGE_BAND_FRAC = 0.6;
export const DRIFT_FRAC = 0.05;
/**
* Where the horizon sits down the viewport, as a fraction of its height: one constant for every sky state and every viewport (ruling
* ridge-frame-more-sky-fixed-pitch: the camera pitch never changes between day and night). The plane extends below the viewport bottom and
* the near plain is cropped. 0.85 (operator, 2026-11-20) shows about 31 degrees of sky above the horizon in a 16:9 cell. Authored, tunable by eye.
*/
export const HORIZON_AT = 0.85;
export interface Window {
camera: Camera;
/** The planes in viewport pixels: scaled size, anchored to the viewport's bottom edge and centred on `lookAzDeg`. */
/** The planes in viewport pixels: scaled size, centred on `lookAzDeg`, placed so the horizon row lands at `HORIZON_AT` of the height. `bottom` is the distance of the plane's foot above the viewport's bottom edge: negative, the plane runs on below it. */
plane: { scale: number; w: number; h: number; bottom: number };
/** How far the plane may slide sideways from centre and still cover the viewport. */
driftPx: number;
@ -75,9 +84,49 @@ export function windowFor(view: View, viewportW: number, viewportH: number): Win
azimuthDeg: view.lookAzDeg,
hfovDeg,
vfovDeg: (hfovDeg * viewportH) / viewportW,
horizonAt: (viewportH - scale * (view.planeH - view.horizonRow)) / viewportH,
horizonAt: HORIZON_AT,
},
plane: {
scale,
w: scale * view.planeW,
h: scale * view.planeH,
bottom: (1 - HORIZON_AT) * viewportH - scale * (view.planeH - view.horizonRow),
},
plane: { scale, w: scale * view.planeW, h: scale * view.planeH, bottom: 0 },
driftPx: (scale * view.planeW - viewportW) / 2,
};
}
/** What `cardMotion` reads of a manifest: the cards' scales, the baker's heading range and the View. */
interface CardRig {
view: View;
camera: { headingMaxDeg: number };
cards: readonly { scale: number }[];
}
export interface CardMotion {
/** The heading either side of the look azimuth the drift turns through, degrees. */
headingDeg: number;
/** Per card, in manifest order (nearest first): the static scale the baker derived and how far it pans, in viewport px, at the end of the drift. */
cards: { scale: number; reachPx: number }[];
}
/**
* Where each card goes on a viewport: the single owner of pan reach and heading range (ruling ridge-camera-on-circle). The heading is the baker's
* `headingMaxDeg` unless a card could no longer cover the viewport at it, so it is capped by the card that would uncover first: card i is `scale` times
* wider on screen, and shown at heading delta d it needs `half viewport / scale + d x pxPerDegH` of its half width. Card i pans `scale` x heading x
* `pxPerDegH` plane pixels, at the plane's scale. One scale per card on both axes; nothing is reprojected inside a card (ruling ridge-cards-per-card-slide).
*/
export function cardMotion(m: CardRig, win: Window): CardMotion {
const half = (win.plane.w - 2 * win.driftPx) / (2 * win.plane.scale); // half the viewport, in plane px
const cap = Math.min(
...m.cards.map((c) => (m.view.planeW / 2 - half / c.scale) / m.view.pxPerDegH)
);
const headingDeg = Math.max(0, Math.min(m.camera.headingMaxDeg, cap));
return {
headingDeg,
cards: m.cards.map((c) => ({
scale: c.scale,
reachPx: c.scale * headingDeg * m.view.pxPerDegH * win.plane.scale,
})),
};
}

View file

@ -2,43 +2,17 @@ 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 { baked } from '../../../sky/baked';
import { AA, luminance } from '../../../sky/skyTokens.js';
import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
import { DAY_FROM, setSkyClock, skyBackdrop } from './skyState';
import type { FixedSkyState } from './skyState';
import { skyThemeId } from './skyTheme';
import { DAY_FROM, setSkyClock } from './skyState';
import { BUDGET } from './ridge/toneMap';
const STATES = ['day', 'dusk', 'night'] as const;
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
/**
* The band each state needs, from the ink itself: dark ink needs a backdrop of at least
* AA * (L + 0.05) - 0.05, light ink at most (L + 0.05) / AA - 0.05. Day 0.2983, night 0.0931; dusk is bound by its
* link (0.4554), the darker ink to clear, whose floor also holds the text.
*/
const needs = (state: FixedSkyState) => {
const sky = SKY[skyThemeId(state)];
const l = luminance(sky.tokens.Background.OnContainer);
const link = luminance(sky.link);
return state === 'night'
? { floor: 0, ceiling: (l + 0.05) / AA - 0.05 }
: { floor: AA * ((state === 'dusk' ? link : l) + 0.05) - 0.05, ceiling: 1 };
};
afterEach(() => {
setSkyClock();
vi.unstubAllGlobals();
});
describe('the bands the text ink needs', () => {
it('are the numbers the shaping was set from', () => {
expect(needs('day').floor).toBeCloseTo(0.2983, 3);
expect(needs('dusk').floor).toBeCloseTo(0.4554, 3);
expect(needs('night').ceiling).toBeCloseTo(0.0931, 3);
});
});
describe('ridgeSkyFor', () => {
it('carries the physical sky of the state', () => {
for (const state of STATES) {
@ -91,26 +65,17 @@ describe('ridgeSkyFor', () => {
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('night', FALLBACK_VIEW, 0.3));
});
it.each(STATES)('%s: the display is fitted to the budget its text ink needs', (state) => {
const { floor, ceiling } = needs(state);
// 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).toBeGreaterThanOrEqual(floor);
expect(r.lightest).toBeLessThanOrEqual(ceiling);
expect(r.darkest).toBe(BUDGET[state].floor);
expect(r.lightest).toBeLessThanOrEqual(BUDGET[state].ceiling);
const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit;
expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9);
expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9);
});
});
describe('skyBackdrop holds the ridge sky', () => {
it.each(STATES)('%s: the backdrop bound contains the ridge display budget', (state) => {
const r = ridgeDrawn(state);
const b = skyBackdrop(state);
expect(b.darkest).toBeLessThanOrEqual(r.darkest);
expect(b.lightest).toBeGreaterThanOrEqual(r.lightest);
});
});
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 () => ({}) }));
@ -124,3 +89,18 @@ describe('loadWeather', () => {
vi.unstubAllGlobals();
});
});
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.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);
});
});

View file

@ -1,18 +1,17 @@
// 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). `skyBackdrop` bounds what comes out, and the login text was
// checked against that bound.
// state's luminance budget (ridge/toneMap.ts).
import type { SkyColours } from './ridge/skyColour';
import { makePhysicalSky } from './ridge/physicalSky';
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 { resolveSkyState, skyNow } from './skyState';
import { getConstellationLines, resolveSkyState, skyNow } from './skyState';
import type { SkyState } from './skyState';
/**
* What a rebuild of the ridge scene is for: the fixed state it draws and the weather. The sun moves with the clock inside a state and
* 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.
*/
export const ridgeSkyKey = (
@ -20,7 +19,10 @@ export const ridgeSkyKey = (
view: View,
weather: number = ridgeWeather(),
now: Date = skyNow()
): string => `ridge:${resolveSkyState(state, now)}:${weather}:${view.place.id}`;
): string => {
const fixed = resolveSkyState(state, now);
return `ridge:${fixed}:${weather}:${view.place.id}${fixed === 'night' && getConstellationLines() ? ':lines' : ''}`;
};
const WEATHER_REFRESH_MS = 10 * 60_000;
let weatherAt = -Infinity;

View file

@ -1,7 +1,7 @@
import chroma from 'chroma-js';
import { describe, expect, it } from 'vitest';
import { baked } from '../../../sky/baked';
import { AA, NIGHT_SKY_LIGHTEST, luminance } from '../../../sky/skyTokens.js';
import { AA, luminance } from '../../../sky/skyTokens.js';
import { indexColorMXID } from '../../../util/colorMXID';
import type { FixedSkyState } from './skyState';
import {
@ -115,8 +115,6 @@ describe('inkForState', () => {
expect(chroma(aqua).oklch()[0]).toBeLessThanOrEqual(NIGHT_INK_MAX_L);
expect(chroma(aqua).oklch()[1]).toBeGreaterThan(0.08);
expect(patchRatio(aqua, 'night', true)).toBeGreaterThan(3.9);
// The one-patch figure is what the cap gives up; against the sky's own lightest (skyBackdrop) it clears AA.
expect((luminance(aqua) + 0.05) / (NIGHT_SKY_LIGHTEST + 0.05)).toBeGreaterThanOrEqual(AA);
});
it('leaves a colour that already clears its patch untouched, and a non-colour alone', () => {

View file

@ -8,8 +8,8 @@
// until it clears 4.5:1 (WCAG) against the LIGHTEST 24x12 patch of terrain under the timeline in that state
// and viewport. Measured 2026-11-10 on the demo's terrain scene at 1920x1080 and 390x844 (Chrome, SwiftShader,
// not a GPU; ratatoskr-sidebar-contrast-20261110/results.md, T3). These are the scene's own patches, not
// `skyBackdrop` (skyState.ts): that is the bare sky's extreme (day 0.90, dusk 0.97), which the terrain under the
// timeline never shows, and at night the terrain's snow (0.103, phone 0.149) is lighter than the sky (0.0816).
// the bare sky: the terrain under the timeline is what the ink sits on, and at night its snow (0.103, phone 0.149) is
// lighter than the sky was when these were measured (0.0816).
// Only a person whose theme is the sky's (no explicit theme of their own, sceneThemeId) wears this ink.
import chroma from 'chroma-js';
import { AA, luminance } from '../../../sky/skyTokens.js';

View file

@ -1,13 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit';
import { baked } from '../../../sky/baked';
import { luminance } from '../../../sky/skyTokens.js';
import {
SKY_STATES,
SKY_STATE_KEY,
resolveSkyState,
setSkyClock,
skyBackdrop,
type SkyState,
} from './skyState';
@ -106,39 +101,6 @@ describe('sky state', () => {
});
});
describe('skyBackdrop', () => {
it('puts night below day and dusk', () => {
expect(skyBackdrop('night').lightest).toBeLessThan(skyBackdrop('day').darkest);
expect(skyBackdrop('night').lightest).toBeLessThan(skyBackdrop('dusk').lightest);
expect(skyBackdrop('dusk').lightest).toBeGreaterThanOrEqual(skyBackdrop('day').lightest);
});
it('holds the baked gradients for day and night', () => {
const lum = (g: readonly string[]) => g.map(luminance);
expect(skyBackdrop('day').lightest).toBeGreaterThanOrEqual(
Math.max(...lum(baked.noonday.gradient)) - 1e-9
);
expect(skyBackdrop('night').darkest).toBeLessThanOrEqual(
Math.min(...lum(baked.midnight.gradient)) + 1e-9
);
});
it('is the band of the sky auto resolves to, not the union of all three', () => {
const at = (h: number) => setSkyClock(() => atStandardTime(h, 0));
at(12);
expect(skyBackdrop('auto')).toEqual(skyBackdrop('day'));
at(0);
expect(skyBackdrop('auto')).toEqual(skyBackdrop('night'));
setSkyClock();
});
it('never has darkest above lightest', () => {
SKY_STATES.forEach((s) =>
expect(skyBackdrop(s).darkest).toBeLessThanOrEqual(skyBackdrop(s).lightest)
);
});
});
describe('auto follows the clock', () => {
const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock
let storage: ReturnType<typeof fakeStorage>;
@ -215,3 +177,69 @@ describe('auto follows the clock', () => {
expect(cb.mock.calls).toEqual([['night'], ['day']]);
});
});
describe('the constellation lines toggle', () => {
let storage: ReturnType<typeof fakeStorage>;
beforeEach(() => {
storage = fakeStorage();
vi.stubGlobal('localStorage', storage);
});
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');
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');
const cb = vi.fn();
m.subscribe(cb);
m.pickSkyState('night');
expect(m.getConstellationLines()).toBe(true);
expect(cb.mock.calls).toEqual([['night']]);
expect(m.getSkyState()).toBe('night');
m.pickSkyState('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 () => {
const m = await fresh();
m.pickSkyState('day');
m.pickSkyState('day');
expect(m.getConstellationLines()).toBe(false);
m.setSkyClock(() => new Date('2026-12-04T00:00:00Z'));
m.pickSkyState('auto');
m.pickSkyState('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');
expect(storage.data.get(m.SKY_LINES_KEY)).toBe('on');
const again = await fresh();
expect(again.getConstellationLines()).toBe(true);
});
it('survive a refused storage: they hold for the page and read as off from a broken store', async () => {
vi.stubGlobal('localStorage', {
getItem: () => {
throw new Error('denied');
},
setItem: () => {
throw new Error('denied');
},
});
const m = await fresh();
expect(m.getConstellationLines()).toBe(false);
m.pickSkyState('night');
m.pickSkyState('night');
expect(m.getConstellationLines()).toBe(true);
});
});

View file

@ -1,8 +1,7 @@
// 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, and
// `skyBackdrop` says how light or dark the sky behind the login text can be in each state, so the
// text colours can be checked against it. '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.
// 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';
export type SkyState = 'auto' | 'day' | 'dusk' | 'night';
@ -51,6 +50,22 @@ export function resolveSkyState(s: SkyState, now: Date = clock()): FixedSkyState
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';
let lines: boolean | undefined;
/** Whether the constellation lines are on: the stored choice of this viewer. They are drawn over the real stars of a night sky only. */
export const getConstellationLines = (): boolean => {
if (lines === undefined) {
try {
lines = localStorage.getItem(SKY_LINES_KEY) === 'on';
} catch {
lines = false;
}
}
return lines;
};
let current: SkyState | undefined;
const listeners = new Set<(s: FixedSkyState) => void>();
let timer: ReturnType<typeof setTimeout> | undefined;
@ -109,6 +124,24 @@ export function setSkyState(s: SkyState): void {
}
}
/**
* A pick in the sky menu. Picking a state 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') {
lines = !getConstellationLines();
try {
localStorage.setItem(SKY_LINES_KEY, lines ? 'on' : 'off');
} catch {
// Storage is refused: the lines hold for this page load only.
}
emit();
return;
}
setSkyState(s);
}
/** 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();
@ -119,25 +152,3 @@ export function subscribe(cb: (s: FixedSkyState) => void): () => void {
sync();
};
}
/**
* Relative luminance (WCAG, 0..1) of the lightest and darkest sky the state can show behind the
* page. Light ink is worst against `lightest`, dark ink against `darkest`. 'auto' is the band of
* the sky it resolves to now.
*/
export interface SkyBackdrop {
readonly darkest: number;
readonly lightest: number;
}
// What the ridge sky can show behind the page in each state (its display budget, ridge/toneMap.ts `BUDGET`, holds whatever the
// sun's elevation; physicalSky.test.ts sweeps the sun's year against these). Held as constants so this module, which the main chunk
// loads, does not pull in the sky generator. The bounds are at least as wide as the budgets: the login text was checked against them.
// Bounds what the 8-bit screen shows too (one step each way for rounding and dither), rounded outward to six places.
const BACKDROPS: Record<FixedSkyState, SkyBackdrop> = {
day: { darkest: 0.461063, lightest: 1 },
dusk: { darkest: 0.460352, lightest: 1 },
night: { darkest: 0, lightest: 0.081642 },
};
export const skyBackdrop = (state: SkyState): SkyBackdrop => BACKDROPS[resolveSkyState(state)];

View file

@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import { atStandardTime } from './standardTime.testkit';
import { baked } from '../../../sky/baked';
import { AA, NIGHT_SKY_LIGHTEST, contrast, luminance } from '../../../sky/skyTokens.js';
import { AA, contrast } from '../../../sky/skyTokens.js';
import { Editor } from '../../components/editor/Editor.css';
import { PageContent, PageNavContent } from '../../components/page/style.css';
import { CallStatus } from '../call-status/styles.css';
@ -12,30 +12,17 @@ import { SkyPlate, plateRegions } from './skyPlate.css';
import {
getResolvedSkyState,
setSkyClock,
skyBackdrop,
subscribe as subscribeSky,
} from './skyState';
import type { FixedSkyState, SkyBackdrop } from './skyState';
import { sceneThemeId, skyThemeId } from './skyTheme';
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
const r2 = (n: number) => n.toFixed(2);
const fixed = (['day', 'dusk', 'night'] as const).flatMap((s) => {
const id = skyThemeId(s);
return id ? [[s, id] as const] : [];
});
// WCAG contrast of an ink against the sky it is worst on, measured as skyState.test.ts does: the
// sky can show any luminance between its darkest and lightest, and contrast is lowest where the
// backdrop is closest to the ink, which is the ink's own luminance clamped into that range.
const against = (ink: string, bg: number) => {
const li = luminance(ink);
const [hi, lo] = li > bg ? [li, bg] : [bg, li];
return (hi + 0.05) / (lo + 0.05);
};
const ratio = (ink: string, b: SkyBackdrop) =>
against(ink, Math.min(b.lightest, Math.max(b.darkest, luminance(ink))));
const r2 = (n: number) => n.toFixed(2);
describe('skyThemeId', () => {
it('picks a theme for each explicit state', () => {
expect(skyThemeId('day')).toBe('noonday-sky');
@ -102,61 +89,6 @@ describe('skyThemeId', () => {
});
});
describe('ink of the theme a state picks, on bare sky', () => {
// Per state: the picked theme, its text ink and link, and their WCAG ratios on the sky the scenes
// draw (skyBackdrop, the worst case over its band). Text clears 4.5 in every state. Link clears
// in every state: the links are derived in src/sky/skyTokens.js, outside the band, and these numbers are recorded as
// they are measured. Midnight's link is brightened in its own hue until it clears the lightest Night sky
// (NIGHT_SKY_LIGHTEST); Dusk's dark link needs a backdrop of about 0.4554, which the dusk floor is set above.
// 'auto' resolves from the clock to one of these three and has the same numbers.
const cells: [FixedSkyState, string, string, string, string, string][] = [
['day', 'noonday-sky', '#342d25', '6.60', '#2a4f27', '4.55'],
['dusk', 'noonday-sky', '#342d25', '6.59', '#2a4f27', '4.54'],
['night', 'midnight-sky', '#aeccff', '4.89', '#8ad1bd', '4.53'],
];
it.each(cells)(
'%s with %s: text %s is %s, link %s is %s',
(state, id, ink, want, link, wantLink) => {
const sky = SKY[id as keyof typeof SKY];
expect(sky.tokens.Background.OnContainer).toBe(ink);
expect(sky.link).toBe(link);
expect(r2(ratio(ink, skyBackdrop(state)))).toBe(want);
expect(r2(ratio(link, skyBackdrop(state)))).toBe(wantLink);
}
);
it.each(cells)('%s: text clears AA', (state, _id, ink) => {
expect(ratio(ink, skyBackdrop(state))).toBeGreaterThanOrEqual(AA);
});
it('link clears AA in every state', () => {
const link = (s: FixedSkyState, id: keyof typeof SKY) => ratio(SKY[id].link, skyBackdrop(s));
expect(link('day', 'noonday-sky')).toBeGreaterThanOrEqual(AA);
expect(link('dusk', 'noonday-sky')).toBeGreaterThanOrEqual(AA);
expect(link('night', 'midnight-sky')).toBeGreaterThanOrEqual(AA);
});
it('keeps the lightest Night sky the link was fitted to equal to the Night backdrop (no drift)', () => {
expect(NIGHT_SKY_LIGHTEST).toBe(skyBackdrop('night').lightest);
});
it.each([
[12, 'day'],
[18, 'dusk'],
[0, 'night'],
] as const)('auto at %s:00 has the numbers of %s', (hour, state) => {
setSkyClock(() => atStandardTime(hour, hour === 18 ? 10 : 0));
const id = skyThemeId(getResolvedSkyState()) as keyof typeof SKY;
expect(id).toBe(skyThemeId(state));
const { tokens, link } = SKY[id];
const text = tokens.Background.OnContainer;
expect(r2(ratio(text, skyBackdrop('auto')))).toBe(r2(ratio(text, skyBackdrop(state))));
expect(r2(ratio(link, skyBackdrop('auto')))).toBe(r2(ratio(link, skyBackdrop(state))));
setSkyClock();
});
});
describe('the plate, where text cannot rest on bare sky', () => {
// Each theme's plate: fill, ink, link and the WCAG ratios of ink and link on the fill.
const plates = [
@ -217,7 +149,7 @@ describe('regions that sit on the plate', () => {
describe('the sign-in footer band', () => {
// The footer line is the plate's ink on a band that mixes FOOTER_TINT of the plate's fill over the blurred scene,
// as the browser does: per channel, in encoded sRGB (not in linear light, which flatters dark scenes). The scene
// behind it is the scene, taken as grey: as dark as 0, as light as the sky state's lightest backdrop. Ink
// behind it is the scene, taken as grey: as dark as 0 or as light as 1 (a sky's range is whatever the look draws). Ink
// contrast is lowest at one of those two ends, so both are checked.
const encode = (l: number) => (l <= 0.0031308 ? 12.92 * l : 1.055 * l ** (1 / 2.4) - 0.055);
const channels = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
@ -235,7 +167,7 @@ describe('the sign-in footer band', () => {
'%s: the ink clears AA over the darkest and the lightest scene behind it',
(state, id) => {
const { Other, OtherText } = SKY[id].bubbles;
[0, skyBackdrop(state).lightest].forEach((behind) => {
[0, 1].forEach((behind) => {
expect(contrast(OtherText, bandOver(Other, behind))).toBeGreaterThanOrEqual(AA);
});
}

View file

@ -16,7 +16,7 @@ export interface Capabilities {
}
/**
* 'ridge': baked parallax ridges, no WebGL (default). 'raymarch': the sphere-traced world with its tree and
* 'ridge': baked ridge cards lit once per sky in WebGL2, no per-frame WebGL (default). 'raymarch': the sphere-traced world with its tree and
* clouds.
*/
export type SceneStyle = 'ridge' | 'raymarch';

88
src/sky/moon.js Normal file
View file

@ -0,0 +1,88 @@
// The moon for a place and a moment. Dependency-free ES module beside sun.js, whose sidereal transform it shares.
//
// moonEquatorial(time) -> { ra, dec, distanceKm, lambda, beta } radians, of date
// moonPhase(time) -> { elongationDeg, phaseAngleDeg, illuminated, waxing }
// moonPosition(time, lat, lon) -> { elevation, azimuth } degrees, topocentric, no refraction
//
// Position is the low-precision series of the Astronomical Almanac (section D, "Low precision formulae for the Moon", T in Julian
// centuries from J2000.0): about 0.3 degrees in longitude and 0.2 in latitude, a few hundred km in distance, for 1950..2050.
// Phase is the elongation from the sun (sun.js) and the phase angle of Meeus, "Astronomical Algorithms", 2nd ed., eq. 48.3.
import { daysSinceJ2000, equatorialToHorizontal, sunEquatorial } from './sun.js';
const RAD = Math.PI / 180;
const EARTH_RADIUS_KM = 6378.14;
const AU_KM = 149597870.7;
const sinD = (deg) => Math.sin(deg * RAD);
const cosD = (deg) => Math.cos(deg * RAD);
/** The moon's ecliptic longitude and latitude (radians), horizontal parallax (radians) and distance (km), of date. */
function moonEcliptic(time) {
const T = daysSinceJ2000(time) / 36525;
const lambda =
218.32 +
481267.881 * T +
6.29 * sinD(135.0 + 477198.87 * T) -
1.27 * sinD(259.3 - 413335.36 * T) +
0.66 * sinD(235.7 + 890534.22 * T) +
0.21 * sinD(269.9 + 954397.74 * T) -
0.19 * sinD(357.5 + 35999.05 * T) -
0.11 * sinD(186.5 + 966404.03 * T);
const beta =
5.13 * sinD(93.3 + 483202.02 * T) +
0.28 * sinD(228.2 + 960400.89 * T) -
0.28 * sinD(318.3 + 6003.15 * T) -
0.17 * sinD(217.6 - 407332.21 * T);
const parallax =
0.9508 +
0.0518 * cosD(135.0 + 477198.87 * T) +
0.0095 * cosD(259.3 - 413335.36 * T) +
0.0078 * cosD(235.7 + 890534.22 * T) +
0.0028 * cosD(269.9 + 954397.74 * T);
return {
lambda: lambda * RAD,
beta: beta * RAD,
parallax: parallax * RAD,
distanceKm: EARTH_RADIUS_KM / Math.sin(parallax * RAD),
};
}
/** Right ascension, declination (radians, of date), distance (km) and ecliptic coordinates (radians) of the moon at a UTC moment. */
export function moonEquatorial(time) {
const { lambda, beta, distanceKm } = moonEcliptic(time);
const l = Math.cos(beta) * Math.cos(lambda);
const m = 0.9175 * Math.cos(beta) * Math.sin(lambda) - 0.3978 * Math.sin(beta);
const n = 0.3978 * Math.cos(beta) * Math.sin(lambda) + 0.9175 * Math.sin(beta);
return { ra: Math.atan2(m, l), dec: Math.asin(n), distanceKm, lambda, beta };
}
/**
* The phase at a UTC moment. `elongationDeg` is the geocentric angle sun-earth-moon side: 0 new, 90 first quarter, 180 full, 270 last quarter
* (by the longitude difference, so it runs the whole circle). `phaseAngleDeg` is the angle sun-moon-earth: 0 full, 180 new. `illuminated` is
* the lit fraction of the disc, (1 + cos i) / 2.
*/
export function moonPhase(time) {
const moon = moonEquatorial(time);
const sun = sunEquatorial(time);
const sunDistanceKm = AU_KM;
const cosPsi = Math.cos(moon.beta) * Math.cos(moon.lambda - sun.lambda);
const psi = Math.acos(Math.min(1, Math.max(-1, cosPsi)));
const i = Math.atan2(sunDistanceKm * Math.sin(psi), moon.distanceKm - sunDistanceKm * Math.cos(psi));
const elongationDeg = ((((moon.lambda - sun.lambda) / RAD) % 360) + 360) % 360;
return {
elongationDeg,
phaseAngleDeg: i / RAD,
illuminated: (1 + Math.cos(i)) / 2,
waxing: elongationDeg < 180,
distanceKm: moon.distanceKm,
};
}
/** Elevation and azimuth of the moon in degrees at a UTC moment and place, topocentric (the parallax lowers it up to a degree), no refraction. Azimuth clockwise from north. */
export function moonPosition(time, lat, lon) {
const m = moonEquatorial(time);
const { elevation, azimuth } = equatorialToHorizontal(m.ra, m.dec, time, lat, lon);
const parallaxDeg = Math.asin(EARTH_RADIUS_KM / m.distanceKm) / RAD;
return { elevation: elevation - parallaxDeg * cosD(elevation), azimuth };
}

50
src/sky/moon.test.ts Normal file
View file

@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import { moonEquatorial, moonPhase, moonPosition } from './moon.js';
import { sunPosition } from './sun.js';
const DEG = 180 / Math.PI;
describe('moon position', () => {
it('matches Meeus, Astronomical Algorithms ex. 47.a (1992 April 12, 0h TD) within the series\' 0.3 degrees', () => {
// Meeus: ra 134.688470, dec +13.768368, distance 368409.7 km (full series).
const m = moonEquatorial(Date.UTC(1992, 3, 12, 0, 0, 0));
expect(Math.abs(m.ra * DEG - 134.68847)).toBeLessThan(0.3);
expect(Math.abs(m.dec * DEG - 13.768368)).toBeLessThan(0.3);
expect(Math.abs(m.distanceKm - 368409.7)).toBeLessThan(1500);
});
it('is opposite the sun at full moon, with the parallax of a few tenths of a degree at most', () => {
// Total lunar eclipse of 2026-03-03, greatest eclipse 11:33 UTC: the moon sits opposite the sun.
const t = '2026-03-03T11:33:00Z';
const moon = moonPosition(t, 48.19, 16.35);
const sun = sunPosition(t, 48.19, 16.35);
expect(Math.abs(moon.elevation + sun.elevation)).toBeLessThan(1.5);
const dAz = Math.abs(((moon.azimuth - sun.azimuth + 360) % 360) - 180);
expect(dAz).toBeLessThan(2);
});
});
describe('moon phase', () => {
// US Naval Observatory phases of January 2000 and the lunar eclipse of March 2026 (UTC); the series is good to ~0.5 degree of
// elongation, which is an hour of the moon's 12.2 degrees a day relative to the sun, so these hold to a degree and a half.
const phases: [string, number][] = [
['2000-01-06T18:14:00Z', 0],
['2000-01-14T13:34:00Z', 90],
['2000-01-21T04:40:00Z', 180],
['2000-01-28T07:57:00Z', 270],
['2026-03-03T11:38:00Z', 180],
];
it.each(phases)('elongation at %s is %d degrees', (t, e) => {
const d = ((moonPhase(t).elongationDeg - e + 540) % 360) - 180;
expect(Math.abs(d)).toBeLessThan(1.5);
});
it('lit fraction: dark at new, half at the quarters, full at full; waxing between new and full', () => {
expect(moonPhase('2000-01-06T18:14:00Z').illuminated).toBeLessThan(0.01);
expect(moonPhase('2000-01-14T13:34:00Z').illuminated).toBeCloseTo(0.5, 1);
expect(moonPhase('2000-01-21T04:40:00Z').illuminated).toBeGreaterThan(0.99);
expect(moonPhase('2000-01-10T00:00:00Z').waxing).toBe(true);
expect(moonPhase('2000-01-25T00:00:00Z').waxing).toBe(false);
expect(moonPhase('2000-01-21T04:40:00Z').phaseAngleDeg).toBeLessThan(2);
});
});

View file

@ -19,8 +19,8 @@ const luma = (c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
export const GRADIENT_STOPS = 7;
export const AA = 4.5; // WCAG 2.x AA, normal text
// The lightest the Night sky draws behind the page (src/app/features/scene/skyState.ts, `skyBackdrop('night')`; a test in
// skyTheme.test.ts fails if the two drift). Midnight Sky's link also sits on bare sky, so it must clear AA against this.
// The Night sky's luminance the Midnight Sky link was fitted against (a derivation input, not a bound the scene is held to:
// the look is tuned by eye). The link is brightened in its own hue until it clears AA against this.
export const NIGHT_SKY_LIGHTEST = 0.081642;
// Where and when the theme is lit. Equinox, 45N on the prime meridian: noon sun at 45 degrees.

View file

@ -29,17 +29,32 @@ const mix = (a, b, t) => a + (b - a) * t;
const toMs = (time) => (time instanceof Date ? time.getTime() : typeof time === 'string' ? Date.parse(time) : Number(time));
/** Sun elevation and azimuth in degrees at a UTC moment and place. Azimuth runs clockwise from north. */
export function sunPosition(time, lat, lon) {
const d = toMs(time) / 86400000 - 10957.5; // days since J2000.0 (2000-01-01 12:00 UTC)
/** Days since J2000.0 (2000-01-01 12:00 UTC) at a UTC moment. */
export const daysSinceJ2000 = (time) => toMs(time) / 86400000 - 10957.5;
/** Greenwich mean sidereal time in radians (unreduced) at `d` days since J2000.0. */
export const gmstRad = (d) => (280.46061837 + 360.98564736629 * d) * RAD;
/** The sun's right ascension and declination of date, in radians, and its ecliptic longitude `lambda`, at a UTC moment. */
export function sunEquatorial(time) {
const d = daysSinceJ2000(time);
const L = (280.46 + 0.9856474 * d) * RAD; // mean longitude
const g = (357.528 + 0.9856003 * d) * RAD; // mean anomaly
const lambda = L + (1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD; // ecliptic longitude
const eps = (23.439 - 0.0000004 * d) * RAD; // obliquity
const dec = Math.asin(Math.sin(eps) * Math.sin(lambda));
const ra = Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda));
const gmst = (280.46061837 + 360.98564736629 * d) * RAD;
const hourAngle = gmst + lon * RAD - ra;
return {
dec: Math.asin(Math.sin(eps) * Math.sin(lambda)),
ra: Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda)),
lambda,
};
}
/**
* Elevation and azimuth in degrees of a point of the sky at a UTC moment and place, from its right ascension and declination of date
* (radians): the one sidereal transform of the sun, the moon and the stars. Azimuth runs clockwise from north; no refraction.
*/
export function equatorialToHorizontal(ra, dec, time, lat, lon) {
const hourAngle = gmstRad(daysSinceJ2000(time)) + lon * RAD - ra;
const phi = lat * RAD;
const sinEl = Math.sin(phi) * Math.sin(dec) + Math.cos(phi) * Math.cos(dec) * Math.cos(hourAngle);
// Hour angle is westward-positive, so atan2 gives azimuth from south, westward; +180 turns it into
@ -51,6 +66,12 @@ export function sunPosition(time, lat, lon) {
};
}
/** Sun elevation and azimuth in degrees at a UTC moment and place. Azimuth runs clockwise from north. */
export function sunPosition(time, lat, lon) {
const { ra, dec } = sunEquatorial(time);
return equatorialToHorizontal(ra, dec, time, lat, lon);
}
/** Sun elevation in degrees at a UTC moment and place. */
export const sunElevation = (time, lat, lon) => sunPosition(time, lat, lon).elevation;