Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 36373d8ba6 | |||
|
|
6524621ead | ||
| d62be29fd4 | |||
|
|
8567439786 | ||
|
|
e4ae831b5a | ||
| 8f4d935346 | |||
|
|
248839974b | ||
| f562f8fae9 | |||
|
|
d84a31ce79 | ||
|
|
01d74b8188 | ||
|
|
0089cd956a | ||
|
|
53910b1e5b | ||
|
|
3185ea90c1 | ||
|
|
0fd1ec45ae | ||
|
|
9d0764f23a | ||
|
|
5e64e83389 | ||
|
|
c18d3e3e9d | ||
|
|
52a085143b | ||
|
|
bf71489968 | ||
|
|
05cff53959 | ||
|
|
fe12e10f7c | ||
|
|
8c377b58ec | ||
|
|
18ad84aff5 | ||
|
|
d44bf032ca | ||
|
|
3232c866ca | ||
|
|
fa8f2a163b | ||
|
|
d4be09c2b2 | ||
|
|
9adcd6fe63 | ||
| 967d987eac | |||
|
|
2e3e9133c0 | ||
|
|
3b5c2a2487 | ||
|
|
e48a2bf76b | ||
|
|
32c127cd2a | ||
|
|
53b0394f89 | ||
|
|
6a31b716b3 | ||
|
|
8ed2088a21 | ||
|
|
19be8ec492 | ||
| 030a4a9231 | |||
|
|
a9eb9acbf9 | ||
|
|
a320f17431 | ||
|
|
14ad4d14f9 | ||
|
|
37b40c89b0 | ||
|
|
4c9064d50e | ||
|
|
1e52bd3e68 | ||
|
|
f0f7263e9e | ||
|
|
1df9222e28 | ||
|
|
f2c10ff798 | ||
|
|
9bcd7f0db7 | ||
|
|
568f6c19d3 | ||
|
|
0766f107ab | ||
| 5544fcfd6c | |||
|
|
e8e9cbbcb8 | ||
|
|
a1fdfee3cc | ||
| 829c94de63 | |||
|
|
b36173005b | ||
|
|
02f3bc0f2f | ||
|
|
c1628468a3 | ||
|
|
87993ad36e | ||
|
|
d7ed9ffb43 | ||
| 77e95c2826 | |||
|
|
c2cdde1ee7 | ||
| b30ddac052 | |||
| 786b41ddf1 | |||
|
|
eefaa8716d | ||
| 5b7b4c2eeb | |||
| 39c9924042 | |||
|
|
c6fb57d9f9 | ||
|
|
5310f606cd | ||
| 934f82386d | |||
|
|
1455988a83 | ||
| 08bf515997 | |||
| 683d3b92f8 |
126 changed files with 8228 additions and 7552 deletions
6
.github/workflows/build-pull-request.yml
vendored
6
.github/workflows/build-pull-request.yml
vendored
|
|
@ -18,10 +18,14 @@ jobs:
|
||||||
- name: Setup node
|
- name: Setup node
|
||||||
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
with:
|
with:
|
||||||
node-version-file: ".node-version"
|
node-version-file: '.node-version'
|
||||||
package-manager-cache: false
|
package-manager-cache: false
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
- name: Ridge asset gate
|
||||||
|
run: |
|
||||||
|
npx vitest run src/app/features/scene/ridge/ridgeAssets.test.ts
|
||||||
|
echo "ridge assets: $(find public/ridge -type f | wc -l) files, $(du -sb public/ridge | cut -f1) bytes"
|
||||||
- name: Build app
|
- name: Build app
|
||||||
env:
|
env:
|
||||||
NODE_OPTIONS: '--max_old_space_size=4096'
|
NODE_OPTIONS: '--max_old_space_size=4096'
|
||||||
|
|
|
||||||
21
THIRD_PARTY_NOTICES.md
Normal file
21
THIRD_PARTY_NOTICES.md
Normal 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.```
|
||||||
|
|
@ -26,7 +26,7 @@
|
||||||
"enabled": false
|
"enabled": false
|
||||||
},
|
},
|
||||||
"fileZoneShare": {
|
"fileZoneShare": {
|
||||||
"enabled": false
|
"enabled": true
|
||||||
},
|
},
|
||||||
"push": {
|
"push": {
|
||||||
"vapidPublicKey": "",
|
"vapidPublicKey": "",
|
||||||
|
|
|
||||||
34
deployment/idunn/recipe.toml
Normal file
34
deployment/idunn/recipe.toml
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
schema = "gamecult.idunn.target_declaration.v1"
|
||||||
|
target = "ratatoskr"
|
||||||
|
# Idunn stamps the source commit into the build environment under this name. The release is not built from source: the
|
||||||
|
# dist tarball below is built by scripts the release owner runs (build-prod-dist.sh) and enters pinned by sha256, so
|
||||||
|
# each release is a recipe commit whose pin is its provenance. The stamp the served index carries is the commit the
|
||||||
|
# tarball was built from, which is not this commit.
|
||||||
|
source_stamp_environment = "RATATOSKR_BUILD_COMMIT"
|
||||||
|
|
||||||
|
# Release dist d62be29fd4b245bd1303454022ace86c4f762d02: 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-d62be29f/ratatoskr-d62be29f-dist.tar.gz"
|
||||||
|
sha256 = "dd04634f82d081004941c71545ba43b8d5c40dbf97fb5643d9f4f24940b6afe8"
|
||||||
|
runner = "unpack"
|
||||||
|
destination = "release/dist.tar.gz"
|
||||||
|
|
||||||
|
[[steps]]
|
||||||
|
id = "unpack-dist"
|
||||||
|
phase = "prepare"
|
||||||
|
runner = "unpack"
|
||||||
|
argv = ["tar", "-xzf", "release/dist.tar.gz", "-C", "release"]
|
||||||
|
|
||||||
|
[[artifacts]]
|
||||||
|
id = "dist"
|
||||||
|
source_kind = "runner-output"
|
||||||
|
runner = "unpack"
|
||||||
|
source = "release/dist"
|
||||||
|
destination = "dist"
|
||||||
|
|
||||||
|
[static_release]
|
||||||
|
artifact = "dist"
|
||||||
|
|
@ -118,9 +118,9 @@ Under A the paused service is not built, and most of its list disappears:
|
||||||
|
|
||||||
## Cuts under A
|
## Cuts under A
|
||||||
|
|
||||||
Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. **Not built: the Commons entry row** (item 1 below, found by `#commons:gamecult.org` or the carried `media.commons` id through `lookupMediaRoom`, behind a dark `filesDesk.enabled` flag; neither the row nor the flag exists in the code). It waits on Eureka's Commons room.
|
Status 2026-11-14 (dev da822e9e plus the size-refusal cut): built: folders by album title path with navigation and breadcrumb (#147), pagination (#148), version folding (#149), add-to-album with named refusals (#150), Stop for a send in flight, replaces loops shown, freshest last event on add (#151), and the pre-send size refusal: a file larger than the server's `m.upload.size` is named and left unsent before any upload or album root, and a server stating no cap refuses nothing. The Commons entry row is built (item 1): `useCommons` in `MediaRow.tsx` finds the room by the alias `#commons:<server>` (provisioning records no id for it), through `lookupZoneRoom` (the one lookup `lookupMediaRoom` also uses); `EstateNavigator` shows it above the tiers as a Commons link when joined, a join row when invited or not joined, and nothing when the room is absent, the lookup failed or is out. It is gated on the existing `fileZoneShare.enabled`, not a new `filesDesk.enabled` flag. The album view and ShareSet work there because provisioning creates the Commons with the `org.gamecult.file_zone` create type. Members can share only once the room's power levels let them post: provisioning gives the poster level to the Minds alone.
|
||||||
|
|
||||||
1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias or carried id), opening the room's album view. Flagged, no new data layer.
|
1. **Commons entry**: a Commons row in the navigator (like `MediaRow`, found by alias), opening the room's album view. Flagged, no new data layer.
|
||||||
2. **Pagination** of albums and files in `useAlbums` (done, PR #148).
|
2. **Pagination** of albums and files in `useAlbums` (done, PR #148).
|
||||||
3. **Folders by title path** and the album list grouped by it.
|
3. **Folders by title path** and the album list grouped by it.
|
||||||
4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149).
|
4. **Versions**: read `org.gamecult.publish.replaces`, show the latest of a chain with the earlier versions folded under it (done, PR #149).
|
||||||
|
|
|
||||||
|
|
@ -113,9 +113,8 @@ Hard-refresh to clear `sw.js`. Do not delete the failed release; leave it for di
|
||||||
|
|
||||||
## Open
|
## Open
|
||||||
|
|
||||||
- The served config (checked 2026-11-12) is not the repo's: it says `backgroundScene.style`
|
- Release a5 (2026-11-20, dist `a1fdfee3`, receipt `/opt/commons/handoff/rat146-a5-receipt-20261120.md`)
|
||||||
`terrain` where the repo says `ridge` (#106, Meta 2026-11-11), lacks the repo's `dings`,
|
replaced the carried config with the repo's `config.json` (ridge, `fileZoneShare` on; ruling
|
||||||
`fileZoneShare` and `registration` blocks (all off in the repo), and has no trailing newline.
|
`ratatoskr:ruling:ridge-only-scene-terrain-cut`). The carried file and the build pin are equal, so a
|
||||||
The new keys default off or inert when absent, so only the style is a decision. Meta says which
|
handoff build passes its live check without `ALLOW_CONFIG_DRIFT=1`. A release that changes
|
||||||
style ships. Until the served file is replaced, every handoff build stops at the live check
|
`config.json` changes the carried file deliberately, as a5's `carry.sh` did.
|
||||||
unless `ALLOW_CONFIG_DRIFT=1` is set (section 1).
|
|
||||||
|
|
|
||||||
16
docs/gamecult/ridge-backdrop-target.md
Normal file
16
docs/gamecult/ridge-backdrop-target.md
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
# Ridge backdrop target
|
||||||
|
|
||||||
|
The scene's bottom silhouette is replaced by baked A+D ridge planes. The baker is Python and offline; the browser composes pre-lit planes over the live physical sky. Typed state for this campaign (ideas, questions, rulings, cuts) lives in the instance mind `nibu`, campaign `ratatoskr-backdrop`; this file keeps only the ends.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
The live noise ridge is nearly invisible on a phone (about 1.35:1 against the darkest sky) because every ridge pixel is lifted to the text-contrast floor, and the star dots show between nav and header glyphs because the shell is transparent. Meta, 2026-11-13: do not polish the old backdrop; ship the A+D ridge pipeline (round 2 mockup: https://minds.gamecult.org/nibu/ridge-mockups-ad/).
|
||||||
|
|
||||||
|
## Ends
|
||||||
|
- One owner per decision: the baker owns ridge geometry and shading; the runtime owns only frame choice, blending, camera drift and compositing. No ridge geometry is computed in the browser.
|
||||||
|
- Nothing from the scene paints above app content: the scene is one stacking context at the back of the app, and nothing it creates has its own z-index or lives outside it.
|
||||||
|
- Phone cost is bounded: no per-frame script for the ridge, decoded size and fetched size gated in CI.
|
||||||
|
- The baker has fixtures with known right answers (the far-plateau spike, chain-end taper, slot union, seam) and a mutation runner that must kill each re-introduced cause.
|
||||||
|
- A baked asset names its baker version, DEM source and licence in a validated manifest; the credits shown in the Sky menu come from the manifest.
|
||||||
|
|
||||||
|
## Not in scope
|
||||||
|
Button size (Void's). Patching the old noise-ridge path. Cone sampling. Live DEM access from the browser.
|
||||||
|
|
@ -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
|
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.
|
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).
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
|
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
|
||||||
// tier, `?probe=1` shows the rAF median/p95 readout. The bake record (each chunk's cost, from
|
// tier, `?probe=1` shows the rAF median/p95 readout. The long tasks the page saw are on `window.longTasks`
|
||||||
// the scene's `onBake`) and the long tasks the page saw are on `window.bakes` and `window.longTasks`
|
|
||||||
// for a driver to read. Not shipped.
|
// for a driver to read. Not shipped.
|
||||||
import { startBackgroundScene } from '../../src/app/features/scene';
|
import { startBackgroundScene } from '../../src/app/features/scene';
|
||||||
import type { SceneTier } from '../../src/app/features/scene';
|
import type { SceneTier } from '../../src/app/features/scene';
|
||||||
|
|
@ -8,8 +7,7 @@ import type { SceneTier } from '../../src/app/features/scene';
|
||||||
const q = new URLSearchParams(location.search);
|
const q = new URLSearchParams(location.search);
|
||||||
const tier = (q.get('tier') ?? 'full') as SceneTier;
|
const tier = (q.get('tier') ?? 'full') as SceneTier;
|
||||||
const canvas = document.getElementById('c') as HTMLCanvasElement;
|
const canvas = document.getElementById('c') as HTMLCanvasElement;
|
||||||
const w = window as unknown as { scene: unknown; bakes: unknown[]; longTasks: number[]; firstViewMs: number };
|
const w = window as unknown as { scene: unknown; longTasks: number[]; firstViewMs: number };
|
||||||
w.bakes = [];
|
|
||||||
w.longTasks = [];
|
w.longTasks = [];
|
||||||
try {
|
try {
|
||||||
new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({
|
new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({
|
||||||
|
|
@ -21,7 +19,6 @@ try {
|
||||||
const t0 = performance.now();
|
const t0 = performance.now();
|
||||||
startBackgroundScene({ tier }, {}, {
|
startBackgroundScene({ tier }, {}, {
|
||||||
canvas,
|
canvas,
|
||||||
onBake: (b: unknown) => w.bakes.push(b),
|
|
||||||
} as never).then((scene) => {
|
} as never).then((scene) => {
|
||||||
w.firstViewMs = performance.now() - t0;
|
w.firstViewMs = performance.now() - t0;
|
||||||
w.scene = scene;
|
w.scene = scene;
|
||||||
|
|
|
||||||
8
harness/scene/ridgeSheet.html
Normal file
8
harness/scene/ridgeSheet.html
Normal 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
282
harness/scene/ridgeSheet.ts
Normal 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}`;
|
||||||
|
});
|
||||||
7
public/ridge/index.json
Normal file
7
public/ridge/index.json
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
{
|
||||||
|
"schema": 1,
|
||||||
|
"default": "vienna",
|
||||||
|
"places": {
|
||||||
|
"vienna": "vienna-6815bb9dca99"
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
public/ridge/vienna-6815bb9dca99/card-0-colour.webp
Normal file
BIN
public/ridge/vienna-6815bb9dca99/card-0-colour.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.5 KiB |
BIN
public/ridge/vienna-6815bb9dca99/card-0-geometry.webp
Normal file
BIN
public/ridge/vienna-6815bb9dca99/card-0-geometry.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 94 KiB |
BIN
public/ridge/vienna-6815bb9dca99/card-1-colour.webp
Normal file
BIN
public/ridge/vienna-6815bb9dca99/card-1-colour.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.2 KiB |
BIN
public/ridge/vienna-6815bb9dca99/card-1-geometry.webp
Normal file
BIN
public/ridge/vienna-6815bb9dca99/card-1-geometry.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 128 KiB |
BIN
public/ridge/vienna-6815bb9dca99/card-2-colour.webp
Normal file
BIN
public/ridge/vienna-6815bb9dca99/card-2-colour.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.5 KiB |
BIN
public/ridge/vienna-6815bb9dca99/card-2-geometry.webp
Normal file
BIN
public/ridge/vienna-6815bb9dca99/card-2-geometry.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 116 KiB |
100
public/ridge/vienna-6815bb9dca99/manifest.json
Normal file
100
public/ridge/vienna-6815bb9dca99/manifest.json
Normal 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,123 +0,0 @@
|
||||||
#!/usr/bin/env python3
|
|
||||||
"""Bake the 360 degree horizon seen from the ridge viewpoint (src/app/features/scene/ridge/vienna.ts: VIENNA) into
|
|
||||||
src/app/features/scene/ridge/viennaHorizon.json: per azimuth, the highest elevation angle the terrain subtends, the distance and
|
|
||||||
height of the point that sets it, and the surface slope there (the normal). The source is Copernicus DEM GLO-30, a DSM (it
|
|
||||||
includes buildings and trees, which is what a horizon is made of). Source, licence and attribution go beside the bake, in its
|
|
||||||
`source` block, so the file cannot travel without them.
|
|
||||||
|
|
||||||
python3 scripts/bake-horizon.py <dir with the nine Copernicus_DSM_COG_10_N{47..49}_00_E{015..017}_00_DEM.tif> [out.json]
|
|
||||||
|
|
||||||
Needs numpy, tifffile, imagecodecs (pip, in a venv: this is a build-time tool, the bake is committed).
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import tifffile
|
|
||||||
|
|
||||||
LAT, LON = 48.1929826, 16.3534237 # the server location Meta gave, 2026-11-11; keep equal to VIENNA in vienna.ts
|
|
||||||
STEP_DEG = 0.5
|
|
||||||
RADIUS_KM = 60.0
|
|
||||||
EARTH_R = 6_371_000.0
|
|
||||||
REFRACTION_K = 0.13 # standard terrestrial refraction: effective radius R / (1 - k)
|
|
||||||
EYE_ABOVE_GROUND = 0.0 # the viewpoint is the DSM surface at the point (a roof, in a city); the page lifts it with VIENNA.altitudeKm
|
|
||||||
MIN_KM = 1.0 # the DSM at 30 m cannot resolve neighbouring buildings as a horizon; nearer than this is not ridge
|
|
||||||
|
|
||||||
|
|
||||||
class Mosaic:
|
|
||||||
def __init__(self, folder: Path):
|
|
||||||
self.tiles = {}
|
|
||||||
for p in sorted(folder.glob("Copernicus_DSM_COG_10_N*_E*_DEM.tif")):
|
|
||||||
lat0 = int(p.name.split("_N")[1][:2])
|
|
||||||
lon0 = int(p.name.split("_E")[1][:3])
|
|
||||||
with tifffile.TiffFile(p) as t:
|
|
||||||
self.tiles[(lat0, lon0)] = t.pages[0].asarray()
|
|
||||||
|
|
||||||
def height(self, lat: float, lon: float) -> float:
|
|
||||||
key = (math.floor(lat), math.floor(lon))
|
|
||||||
a = self.tiles.get(key)
|
|
||||||
if a is None:
|
|
||||||
return float("nan")
|
|
||||||
n = a.shape[0]
|
|
||||||
# Tile origin is the north-west corner; pixels are 1/n degree, pixel-is-area (centre at +0.5).
|
|
||||||
y = (key[0] + 1 - lat) * n - 0.5
|
|
||||||
x = (lon - key[1]) * n - 0.5
|
|
||||||
y0, x0 = int(math.floor(y)), int(math.floor(x))
|
|
||||||
y0 = min(max(y0, 0), n - 2)
|
|
||||||
x0 = min(max(x0, 0), n - 2)
|
|
||||||
fy, fx = min(max(y - y0, 0), 1), min(max(x - x0, 0), 1)
|
|
||||||
top = a[y0, x0] * (1 - fx) + a[y0, x0 + 1] * fx
|
|
||||||
bot = a[y0 + 1, x0] * (1 - fx) + a[y0 + 1, x0 + 1] * fx
|
|
||||||
return float(top * (1 - fy) + bot * fy)
|
|
||||||
|
|
||||||
|
|
||||||
def offset(lat: float, lon: float, az_deg: float, d_m: float):
|
|
||||||
az = math.radians(az_deg)
|
|
||||||
dlat = d_m * math.cos(az) / 111_320.0
|
|
||||||
dlon = d_m * math.sin(az) / (111_320.0 * math.cos(math.radians(lat)))
|
|
||||||
return lat + dlat, lon + dlon
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
|
||||||
folder = Path(sys.argv[1])
|
|
||||||
out = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("src/app/features/scene/ridge/viennaHorizon.json")
|
|
||||||
m = Mosaic(folder)
|
|
||||||
h0 = m.height(LAT, LON) + EYE_ABOVE_GROUND
|
|
||||||
az_count = int(360 / STEP_DEG)
|
|
||||||
elev, dist, peak, east, north = [], [], [], [], []
|
|
||||||
for i in range(az_count):
|
|
||||||
az = i * STEP_DEG
|
|
||||||
best, best_d, best_h, best_pt = -90.0, 0.0, h0, (LAT, LON)
|
|
||||||
d = MIN_KM * 1000
|
|
||||||
while d <= RADIUS_KM * 1000:
|
|
||||||
lat, lon = offset(LAT, LON, az, d)
|
|
||||||
h = m.height(lat, lon)
|
|
||||||
if not math.isnan(h):
|
|
||||||
drop = d * d / (2 * EARTH_R) * (1 - REFRACTION_K)
|
|
||||||
ang = math.degrees(math.atan2(h - h0 - drop, d))
|
|
||||||
if ang > best:
|
|
||||||
best, best_d, best_h, best_pt = ang, d, h, (lat, lon)
|
|
||||||
d += 30.0 if d < 5000 else 60.0 if d < 20000 else 120.0
|
|
||||||
# Surface slope at the peak (rise per metre, east and north), central difference over 60 m.
|
|
||||||
la, lo = best_pt
|
|
||||||
dl, dn = 60.0 / 111_320.0, 60.0 / (111_320.0 * math.cos(math.radians(la)))
|
|
||||||
ge = (m.height(la, lo + dn) - m.height(la, lo - dn)) / 120.0
|
|
||||||
gn = (m.height(la + dl, lo) - m.height(la - dl, lo)) / 120.0
|
|
||||||
elev.append(round(best, 3))
|
|
||||||
dist.append(round(best_d / 1000, 2))
|
|
||||||
peak.append(round(best_h, 1))
|
|
||||||
east.append(round(ge, 3))
|
|
||||||
north.append(round(gn, 3))
|
|
||||||
doc = {
|
|
||||||
"viewpoint": {"lat": LAT, "lon": LON, "groundM": round(h0, 1)},
|
|
||||||
"stepDeg": STEP_DEG,
|
|
||||||
"radiusKm": RADIUS_KM,
|
|
||||||
"minKm": MIN_KM,
|
|
||||||
"curvature": f"drop d^2/2R*(1-{REFRACTION_K}), R={int(EARTH_R)} m",
|
|
||||||
"source": {
|
|
||||||
"dataset": "Copernicus DEM GLO-30 (COP-DEM_GLO-30-DGED), a DSM, EGM2008 heights, 1 arc-second grid",
|
|
||||||
"tiles": sorted(f"N{a:02d}_00_E{b:03d}_00" for a, b in m.tiles),
|
|
||||||
"tileBytesEach": "about 42-44 MB (Cloud Optimized GeoTIFF); nine tiles, about 380 MB, read once, not committed",
|
|
||||||
"url": "https://copernicus-dem-30m.s3.amazonaws.com/ (AWS Open Data, eu-central-1, no account)",
|
|
||||||
"licence": "Copernicus DEM licence: free of charge for any use incl. commercial, attribution required, no warranty "
|
|
||||||
"(https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model, Licencing)",
|
|
||||||
"attribution": "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.",
|
|
||||||
"bakedBy": "scripts/bake-horizon.py",
|
|
||||||
},
|
|
||||||
"elevationDeg": elev,
|
|
||||||
"distanceKm": dist,
|
|
||||||
"peakHeightM": peak,
|
|
||||||
"slopeEast": east,
|
|
||||||
"slopeNorth": north,
|
|
||||||
}
|
|
||||||
out.write_text(json.dumps(doc, separators=(",", ":")) + "\n")
|
|
||||||
top = int(np.argmax(elev))
|
|
||||||
print(f"ground {h0:.1f} m; {az_count} azimuths; highest {elev[top]:.2f} deg at az {top * STEP_DEG}, {dist[top]} km, {peak[top]} m")
|
|
||||||
print(f"wrote {out} ({out.stat().st_size} bytes)")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
1
scripts/ridge-bake/.gitignore
vendored
Normal file
1
scripts/ridge-bake/.gitignore
vendored
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
__pycache__/
|
||||||
48
scripts/ridge-bake/README.md
Normal file
48
scripts/ridge-bake/README.md
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
# ridge-bake
|
||||||
|
|
||||||
|
Offline baker for the ridge backdrop: it turns a Copernicus DEM into K+1 G-buffer cards per place, split by K authored seams, plus a `manifest.json` (schema 2) and an `index.json` that the runtime reads. Each card is a colour WebP (albedo and coverage) and a geometry WebP (normal and log-distance). The baker is not shipped; `public/ridge/` holds its output. The client owns lighting, haze and ink: no sun, haze or shadow is baked.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 -I scripts/ridge-bake/export.py <place-id> --tiles DIR --out public/ridge/ [--work DIR] [--sheet contact.png]
|
||||||
|
```
|
||||||
|
|
||||||
|
Needs Python 3 with `numpy`, `tifffile` and `imagecodecs`. `--tiles` is a directory of Copernicus GLO-30 tiles (never committed); `--work` caches the mosaic and rays (default `$TMPDIR/ridge-bake-work`); `--sheet` writes the contact sheet (the composite, every card alone and the depth image with every seam, lit by one fixed light). `python3 -I scripts/ridge-bake/export.py --write-schema` rewrites `ridge-bake.schema.json`, which the tests pin.
|
||||||
|
|
||||||
|
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`)
|
||||||
|
|
||||||
|
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`.
|
||||||
|
|
||||||
|
| place id | tiles |
|
||||||
|
|---|---|
|
||||||
|
| vienna | N47E015 N47E016 N47E017 N48E015 N48E016 N48E017 N49E015 N49E016 |
|
||||||
|
| matterhorn | N45E007 N45E008 N46E007 N46E008 |
|
||||||
|
| fuji | N34E138 N34E139 N35E137 N35E138 N35E139 |
|
||||||
|
| halfdome | N37W121 N37W120 N38W120 |
|
||||||
|
| amadablam | N27E086 N27E087 N28E086 N28E087 |
|
||||||
|
| trecime | N46E011 N46E012 |
|
||||||
|
|
||||||
|
## Cards
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
Elevation: Copernicus DEM GLO-30. The credit line is written into every manifest (`attribution`) and must be shown with any rendering:
|
||||||
|
|
||||||
|
> 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: free, full and open access, with the credit line shown (https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model).
|
||||||
206
scripts/ridge-bake/export.py
Normal file
206
scripts/ridge-bake/export.py
Normal file
|
|
@ -0,0 +1,206 @@
|
||||||
|
"""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 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 pathlib import Path
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
sys.path.insert(0, str(HERE))
|
||||||
|
import numpy as np, imagecodecs
|
||||||
|
|
||||||
|
BAKER_VERSION = 2
|
||||||
|
WINDOW_DEG = 72
|
||||||
|
PLANE_W = 1280 # every card is the whole 72 deg window wide
|
||||||
|
PLANE_W_MAX = 4096
|
||||||
|
MAX_CARDS = 6 # per place; a full-frame card decodes to 2 textures x 1280 x 600 x 4 B = 6.1 MB, the decode budget below holds 3 of them and cropping to the row band is what lets a livelier place have more
|
||||||
|
TOTAL_BYTES_MAX = 1_500_000 # every card file of a place together
|
||||||
|
DECODE_BYTES_MAX = 20_000_000 # the cards decoded: sum over cards of 2 textures x w x band h x 4 bytes
|
||||||
|
COVER_TOL = 0.02 # the composite of the cards may differ from the opaque view by this much of a pixel, nowhere more
|
||||||
|
CAMERA_R_M = 200.0 # ruling ridge-camera-on-circle: the camera sits on a circle of this radius round the bake centre, signed, + forward along its heading and - backward; places.json may set camera_r_m per place. The steward's calibration for feel, tuned in the art pass
|
||||||
|
HEADING_MAX_DEG = 23.0 # the drift's heading range each side of look_az: today's phone sweep, 409 card px (the runtime caps it by what a viewport can cover)
|
||||||
|
R_FRAC_MAX = 0.5 # |r| stays under this share of the nearest card's distance: the offset must stay well inside the nearest cylinder
|
||||||
|
REST_SCALE_MIN = 1 / 1.1 # a 16:9 viewport is width-bound and the runtime's plane is 1.1 viewport widths wide (view.ts windowFor, DRIFT_FRAC 0.05 a side): a card scaled below this leaves the viewport's edge bare at rest
|
||||||
|
WEBP_QUALITY = 80
|
||||||
|
SHEET_SKY = (0.80, 0.86, 0.94) # the flat sky of the contact sheet
|
||||||
|
SHEET_LIGHT = (-0.35, 0.55, 0.76) # the fixed light of the contact sheet in (along ray, across ray, up); the sheet is a look at the cards, the client lights the real thing
|
||||||
|
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',
|
||||||
|
dem_source='Copernicus DEM GLO-30 (30 m)',
|
||||||
|
url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------------ 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}
|
||||||
|
_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)
|
||||||
|
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 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 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}')
|
||||||
|
for k, v in x.items():
|
||||||
|
if k in props: validate(v, props[k], f'{path}.{k}')
|
||||||
|
elif extra is False: raise ValueError(f'{path}: extra key {k}')
|
||||||
|
elif isinstance(extra, dict): validate(v, extra, f'{path}.{k}')
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------------ 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 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 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(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 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 colour, geometry in cards: h.update(colour); h.update(geometry)
|
||||||
|
return h.hexdigest()[:12]
|
||||||
|
|
||||||
|
def write_bake(out, place, view, meta, cards, opaque, default=None):
|
||||||
|
"""Write out/<place>-<bake_id>/ (card WebPs + manifest.json), rewrite out/index.json, delete the place's previous dir. cards: [dict(top, colour bytes, geometry bytes, near_m, far_m, median_m, distance_m, scale)], nearest first; opaque (h, w) is
|
||||||
|
the opaque view's coverage. Refuses before writing a bake whose files decode to different sizes, leave the frame or the view's plane_h, break the budget or composite away from the opaque view. meta: dict(curvature, encoding, camera dict(r_m, heading_max_deg)). Returns the directory."""
|
||||||
|
dec = [(decode(c['colour']), decode(c['geometry'])) for c in cards]; shapes = {a.shape[:2] for pair in dec for a in pair}; bands = [a.shape[0] for a, _ in dec]
|
||||||
|
if any(c.shape[:2] != g.shape[:2] for c, g in dec): raise ValueError('a card colour and geometry are not one size')
|
||||||
|
if len({a.shape[1] for pair in dec for a in pair}) != 1: raise ValueError(f'the cards are not one width: {sorted(shapes)}')
|
||||||
|
w = dec[0][0].shape[1]; h = view['plane_h']
|
||||||
|
if any(band < 1 or c['top'] < 0 or c['top'] + band > h for c, band in zip(cards, bands)): raise ValueError(f'a card leaves the {h} rows of the frame')
|
||||||
|
if opaque.shape != (h, w): raise ValueError(f'the opaque view is {opaque.shape}, the frame {(h, w)}')
|
||||||
|
sizes = [len(c['colour']) + len(c['geometry']) for c in cards]; check_budget(sizes, w, bands)
|
||||||
|
check_cover([(c['top'], col[..., 3] / 255.0) for c, (col, _) in zip(cards, dec)], opaque); check_camera([c['scale'] for c in cards], [c['top'] for c in cards], bands, view)
|
||||||
|
bid = bake_id([(c['colour'], c['geometry']) for c in cards]); name = f"{place['id']}-{bid}"; out = Path(out); dest = out / name
|
||||||
|
manifest = dict(schema=2, baker_version=BAKER_VERSION, bake_id=bid, place=place, view=dict(view, window_deg=WINDOW_DEG, plane_w=w), curvature=meta['curvature'], encoding=dict(meta['encoding'], normal='rt8'), camera=dict(r_m=meta['camera']['r_m'], heading_max_deg=meta['camera']['heading_max_deg']),
|
||||||
|
cards=[dict(top=c['top'], h=band, near_m=c['near_m'], far_m=c['far_m'], median_m=c['median_m'], distance_m=c['distance_m'], scale=c['scale'], colour=dict(file=f'card-{i}-colour.webp', bytes=len(c['colour'])), geometry=dict(file=f'card-{i}-geometry.webp', bytes=len(c['geometry'])))
|
||||||
|
for i, (c, band) in enumerate(zip(cards, bands))], w=w, h=h, bytes=sum(sizes), attribution=ATTRIBUTION)
|
||||||
|
validate(manifest, SCHEMA['$defs']['manifest']); out.mkdir(parents=True, exist_ok=True); tmp = Path(tempfile.mkdtemp(dir=out, prefix='.bake-'))
|
||||||
|
for i, c in enumerate(cards): (tmp / f'card-{i}-colour.webp').write_bytes(c['colour']); (tmp / f'card-{i}-geometry.webp').write_bytes(c['geometry'])
|
||||||
|
(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'])
|
||||||
|
validate(idx, SCHEMA['$defs']['index'])
|
||||||
|
if dest.exists(): shutil.rmtree(dest)
|
||||||
|
os.rename(tmp, dest); (out / '.index.tmp').write_text(json.dumps(idx, indent=1) + '\n'); os.replace(out / '.index.tmp', idx_path)
|
||||||
|
if old and old != name: shutil.rmtree(out / old, ignore_errors=True)
|
||||||
|
return dest
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------------ the bake
|
||||||
|
def bake_place(pid):
|
||||||
|
"""stage 0, prefilter, set_view, coverage, seams, cards: dict(place, view, meta, cards (ridge.cards arrays), seams (K, w) in m, cov (bins, w), opaque (h, w) coverage). Needs RIDGE_TILES / RIDGE_WORK."""
|
||||||
|
import ridge
|
||||||
|
assert ridge.WIN == PLANE_W and ridge.H > 0
|
||||||
|
p = ridge.configure(ridge.load_preset(pid)); ridge.mosaic(p); d, _, Hh, _ = ridge.stage0(False); a, h = ridge.prefilter(d, Hh, p.get('prefilter_m', 0)); v = ridge.set_view(a.max(0))
|
||||||
|
nrm = tuple(ridge.win(x) for x in ridge.normals(d, h)); aw, hw = ridge.win(a), ridge.win(h); cov = ridge.coverage(d, aw); sm = ridge.seams(cov, [k * 1000.0 for k in p['card_split_km']], d)
|
||||||
|
place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'])
|
||||||
|
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 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')
|
||||||
|
a = ap.parse_args(argv)
|
||||||
|
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)
|
||||||
|
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())
|
||||||
637
scripts/ridge-bake/places.json
Normal file
637
scripts/ridge-bake/places.json
Normal file
|
|
@ -0,0 +1,637 @@
|
||||||
|
{
|
||||||
|
"_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",
|
||||||
|
"name": "Vienna, looking SW to Rax/Schneeberg",
|
||||||
|
"kind": "far range over a flat foreground",
|
||||||
|
"lat": 48.1929826,
|
||||||
|
"lon": 16.3534237,
|
||||||
|
"eye_h_m": 30.0,
|
||||||
|
"ground_override_m": 183.3,
|
||||||
|
"az_deg": 214.0,
|
||||||
|
"rmax_km": 95,
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "matterhorn",
|
||||||
|
"name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)",
|
||||||
|
"kind": "lone horn, close, 27 deg of relief",
|
||||||
|
"lat": 45.983139,
|
||||||
|
"lon": 7.782466,
|
||||||
|
"eye_h_m": 1.6,
|
||||||
|
"look_at": [
|
||||||
|
45.97666,
|
||||||
|
7.65678
|
||||||
|
],
|
||||||
|
"rmax_km": 60,
|
||||||
|
"initial_guess_not_used": {
|
||||||
|
"lat": 45.9856,
|
||||||
|
"lon": 7.7452
|
||||||
|
},
|
||||||
|
"viewpoint_source": {
|
||||||
|
"status": "sourced",
|
||||||
|
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
|
||||||
|
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 3600-12000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
|
||||||
|
"files_found": 5003,
|
||||||
|
"in_range": 3241,
|
||||||
|
"with_exif_heading": 205,
|
||||||
|
"facing_the_peak": 52,
|
||||||
|
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
|
||||||
|
"rule": "densest 1 km cell of photos 3000-12000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
|
||||||
|
"median_camera_heading_deg": 245.8,
|
||||||
|
"photos_in_cell": 7,
|
||||||
|
"cells_tried": [
|
||||||
|
{
|
||||||
|
"n_facing": 7,
|
||||||
|
"lat": 45.98314,
|
||||||
|
"lon": 7.78247,
|
||||||
|
"peak_visible": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"distance_to_peak_m": 9749,
|
||||||
|
"bearing_to_peak_deg": 265.8,
|
||||||
|
"dem_ground_m": 3090.7,
|
||||||
|
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
|
||||||
|
"sample_files": [
|
||||||
|
{
|
||||||
|
"title": "File:Gornergrat-04.jpg",
|
||||||
|
"lat": 45.983061,
|
||||||
|
"lon": 7.782031,
|
||||||
|
"heading": 256.0,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-04.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Gornergrat-03.jpg",
|
||||||
|
"lat": 45.983058,
|
||||||
|
"lon": 7.782038,
|
||||||
|
"heading": 245.8,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-03.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Gornergrat-07.jpg",
|
||||||
|
"lat": 45.982653,
|
||||||
|
"lon": 7.782466,
|
||||||
|
"heading": 250.2,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AGornergrat-07.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Gornergratsee 2021 10.jpg",
|
||||||
|
"lat": 45.986958,
|
||||||
|
"lon": 7.780303,
|
||||||
|
"heading": 243.4,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AGornergratsee_2021_10.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Early morning Eiger.jpg",
|
||||||
|
"lat": 45.983242,
|
||||||
|
"lon": 7.783361,
|
||||||
|
"heading": 254.7,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AEarly_morning_Eiger.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Klein Matterhorn mit Wolken an Theodulhorn und Furgghorn \u00fcber dem Oberen Theodulgletscher- a view from Gornergrat 2021 02 (cropped).jpg",
|
||||||
|
"lat": 45.983139,
|
||||||
|
"lon": 7.784172,
|
||||||
|
"heading": 242.1,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AKlein_Matterhorn_mit_Wolken_an_Theodulhorn_und_Furgghorn_%C3%BCber_dem_Oberen_Theodulgletscher-_a_view_from_Gornergrat_2021_02_%28cropped%29.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Breithorn and neighbours from Gornergrat 2021 02.jpg",
|
||||||
|
"lat": 45.983139,
|
||||||
|
"lon": 7.784172,
|
||||||
|
"heading": 242.1,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3ABreithorn_and_neighbours_from_Gornergrat_2021_02.jpg"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"exif_headings": [
|
||||||
|
{
|
||||||
|
"title": "File:Gornergrat-04.jpg",
|
||||||
|
"heading": 256.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Gornergrat-03.jpg",
|
||||||
|
"heading": 245.8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Gornergrat-07.jpg",
|
||||||
|
"heading": 250.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Gornergratsee 2021 10.jpg",
|
||||||
|
"heading": 243.4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Early morning Eiger.jpg",
|
||||||
|
"heading": 254.7
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Klein Matterhorn mit Wolken an Theodulhorn und Furgghorn \u00fcber dem Oberen Theodulgletscher- a view from Gornergrat 2021 02 (cropped).jpg",
|
||||||
|
"heading": 242.1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Breithorn and neighbours from Gornergrat 2021 02.jpg",
|
||||||
|
"heading": 242.1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"n_with_exif_heading": 7,
|
||||||
|
"summit_dem_m": 4324.9,
|
||||||
|
"summit_nominal": [
|
||||||
|
45.97639,
|
||||||
|
7.65833
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fuji",
|
||||||
|
"name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)",
|
||||||
|
"kind": "lone cone, smooth",
|
||||||
|
"lat": 35.312467222222494,
|
||||||
|
"lon": 138.587223194445,
|
||||||
|
"eye_h_m": 1.6,
|
||||||
|
"look_at": [
|
||||||
|
35.36061,
|
||||||
|
138.72731
|
||||||
|
],
|
||||||
|
"rmax_km": 60,
|
||||||
|
"initial_guess_not_used": {
|
||||||
|
"lat": 35.4994,
|
||||||
|
"lon": 138.7686
|
||||||
|
},
|
||||||
|
"viewpoint_source": {
|
||||||
|
"status": "sourced",
|
||||||
|
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
|
||||||
|
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 9000-30000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
|
||||||
|
"files_found": 6494,
|
||||||
|
"in_range": 4280,
|
||||||
|
"with_exif_heading": 588,
|
||||||
|
"facing_the_peak": 132,
|
||||||
|
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
|
||||||
|
"rule": "densest 1 km cell of photos 8000-30000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
|
||||||
|
"median_camera_heading_deg": 64.4,
|
||||||
|
"photos_in_cell": 8,
|
||||||
|
"cells_tried": [
|
||||||
|
{
|
||||||
|
"n_facing": 15,
|
||||||
|
"lat": 35.36248,
|
||||||
|
"lon": 138.86287,
|
||||||
|
"peak_visible": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"n_facing": 8,
|
||||||
|
"lat": 35.31247,
|
||||||
|
"lon": 138.58722,
|
||||||
|
"peak_visible": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"distance_to_peak_m": 13808,
|
||||||
|
"bearing_to_peak_deg": 67.2,
|
||||||
|
"dem_ground_m": 486.9,
|
||||||
|
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
|
||||||
|
"sample_files": [
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 03.JPG",
|
||||||
|
"lat": 35.31114,
|
||||||
|
"lon": 138.5886,
|
||||||
|
"heading": 48.0,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_03.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Mount Fuji, view from Shiraito no Taki.jpg",
|
||||||
|
"lat": 35.313589,
|
||||||
|
"lon": 138.588394,
|
||||||
|
"heading": 68.8,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AMount_Fuji%2C_view_from_Shiraito_no_Taki.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 02.JPG",
|
||||||
|
"lat": 35.313248055556,
|
||||||
|
"lon": 138.58760805556,
|
||||||
|
"heading": 64.2,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_02.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 07.JPG",
|
||||||
|
"lat": 35.312428055556,
|
||||||
|
"lon": 138.58723138889,
|
||||||
|
"heading": 88.8,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_07.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 08.JPG",
|
||||||
|
"lat": 35.312418055556,
|
||||||
|
"lon": 138.587215,
|
||||||
|
"heading": 64.0,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_08.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 04.JPG",
|
||||||
|
"lat": 35.312478055556,
|
||||||
|
"lon": 138.58717805556,
|
||||||
|
"heading": 62.2,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_04.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 06.JPG",
|
||||||
|
"lat": 35.312456388889,
|
||||||
|
"lon": 138.58715805556,
|
||||||
|
"heading": 65.2,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_06.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 05.JPG",
|
||||||
|
"lat": 35.312479722222,
|
||||||
|
"lon": 138.58714138889,
|
||||||
|
"heading": 64.5,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A%E5%AF%8C%E5%A3%AB%E5%B1%B1%EF%BC%88%E3%81%B5%E3%81%98%E3%81%95%E3%82%93%E3%80%81%E8%8B%B1%E8%AA%9E%EF%BC%9AMount_Fuji%EF%BC%89_05.JPG"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"exif_headings": [
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 03.JPG",
|
||||||
|
"heading": 48.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Mount Fuji, view from Shiraito no Taki.jpg",
|
||||||
|
"heading": 68.8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 02.JPG",
|
||||||
|
"heading": 64.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 07.JPG",
|
||||||
|
"heading": 88.8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 08.JPG",
|
||||||
|
"heading": 64.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 04.JPG",
|
||||||
|
"heading": 62.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 06.JPG",
|
||||||
|
"heading": 65.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:\u5bcc\u58eb\u5c71\uff08\u3075\u3058\u3055\u3093\u3001\u82f1\u8a9e\uff1aMount Fuji\uff09 05.JPG",
|
||||||
|
"heading": 64.5
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"n_with_exif_heading": 8,
|
||||||
|
"summit_dem_m": 3765.5,
|
||||||
|
"summit_nominal": [
|
||||||
|
35.36061,
|
||||||
|
138.72731
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "halfdome",
|
||||||
|
"name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)",
|
||||||
|
"kind": "granite wall across a valley",
|
||||||
|
"lat": 37.745833333333,
|
||||||
|
"lon": -119.592606,
|
||||||
|
"eye_h_m": 1.6,
|
||||||
|
"look_at": [
|
||||||
|
37.74435,
|
||||||
|
-119.53426
|
||||||
|
],
|
||||||
|
"rmax_km": 40,
|
||||||
|
"initial_guess_not_used": {
|
||||||
|
"lat": 37.7305,
|
||||||
|
"lon": -119.5734
|
||||||
|
},
|
||||||
|
"viewpoint_source": {
|
||||||
|
"status": "sourced",
|
||||||
|
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
|
||||||
|
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 2700-9000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
|
||||||
|
"files_found": 2505,
|
||||||
|
"in_range": 1788,
|
||||||
|
"with_exif_heading": 181,
|
||||||
|
"facing_the_peak": 64,
|
||||||
|
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
|
||||||
|
"rule": "densest 1 km cell of photos 2000-9000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
|
||||||
|
"median_camera_heading_deg": 91.6,
|
||||||
|
"photos_in_cell": 9,
|
||||||
|
"cells_tried": [
|
||||||
|
{
|
||||||
|
"n_facing": 9,
|
||||||
|
"lat": 37.73853,
|
||||||
|
"lon": -119.57124,
|
||||||
|
"peak_visible": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"n_facing": 9,
|
||||||
|
"lat": 37.74583,
|
||||||
|
"lon": -119.59261,
|
||||||
|
"peak_visible": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"distance_to_peak_m": 5138,
|
||||||
|
"bearing_to_peak_deg": 91.8,
|
||||||
|
"dem_ground_m": 1209.2,
|
||||||
|
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
|
||||||
|
"sample_files": [
|
||||||
|
{
|
||||||
|
"title": "File:Yosemite National Park - 51700634719.jpg",
|
||||||
|
"lat": 37.746606,
|
||||||
|
"lon": -119.590317,
|
||||||
|
"heading": 87.0,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AYosemite_National_Park_-_51700634719.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome, Yosemite National Park - 53324601178.jpg",
|
||||||
|
"lat": 37.748264,
|
||||||
|
"lon": -119.592606,
|
||||||
|
"heading": 98.8,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome%2C_Yosemite_National_Park_-_53324601178.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome, Yosemite National Park - 53324824955.jpg",
|
||||||
|
"lat": 37.748322,
|
||||||
|
"lon": -119.592736,
|
||||||
|
"heading": 90.1,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome%2C_Yosemite_National_Park_-_53324824955.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:2013-09-19 18 35 25 Half Dome and the Merced River in Yosemite National Park.JPG",
|
||||||
|
"lat": 37.7435,
|
||||||
|
"lon": -119.58966666667,
|
||||||
|
"heading": 91.6,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A2013-09-19_18_35_25_Half_Dome_and_the_Merced_River_in_Yosemite_National_Park.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome from the Yosemite Valley floor in mid-Spring.jpeg",
|
||||||
|
"lat": 37.745833333333,
|
||||||
|
"lon": -119.59233333333,
|
||||||
|
"heading": 92.0,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_from_the_Yosemite_Valley_floor_in_mid-Spring.jpeg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Sentinel Bridge & Half Dome.jpg",
|
||||||
|
"lat": 37.743419,
|
||||||
|
"lon": -119.590562,
|
||||||
|
"heading": 86.8,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3ASentinel_Bridge_%26_Half_Dome.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome pre Super moon 2.jpg",
|
||||||
|
"lat": 37.745769,
|
||||||
|
"lon": -119.592972,
|
||||||
|
"heading": 106.5,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_pre_Super_moon_2.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome pre Super moon.jpg",
|
||||||
|
"lat": 37.745747,
|
||||||
|
"lon": -119.593033,
|
||||||
|
"heading": 97.1,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AHalf_Dome_pre_Super_moon.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Yosemite National Park 003.jpg",
|
||||||
|
"lat": 37.750814,
|
||||||
|
"lon": -119.598664,
|
||||||
|
"heading": 80.1,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AYosemite_National_Park_003.jpg"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"exif_headings": [
|
||||||
|
{
|
||||||
|
"title": "File:Yosemite National Park - 51700634719.jpg",
|
||||||
|
"heading": 87.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome, Yosemite National Park - 53324601178.jpg",
|
||||||
|
"heading": 98.8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome, Yosemite National Park - 53324824955.jpg",
|
||||||
|
"heading": 90.1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:2013-09-19 18 35 25 Half Dome and the Merced River in Yosemite National Park.JPG",
|
||||||
|
"heading": 91.6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome from the Yosemite Valley floor in mid-Spring.jpeg",
|
||||||
|
"heading": 92.0
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Sentinel Bridge & Half Dome.jpg",
|
||||||
|
"heading": 86.8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome pre Super moon 2.jpg",
|
||||||
|
"heading": 106.5
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Half Dome pre Super moon.jpg",
|
||||||
|
"heading": 97.1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Yosemite National Park 003.jpg",
|
||||||
|
"heading": 80.1
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"n_with_exif_heading": 9,
|
||||||
|
"summit_dem_m": 2669.1,
|
||||||
|
"summit_nominal": [
|
||||||
|
37.74597,
|
||||||
|
-119.5329
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "amadablam",
|
||||||
|
"name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)",
|
||||||
|
"kind": "far high range behind a near spire",
|
||||||
|
"lat": 27.822000000000003,
|
||||||
|
"lon": 86.722666666667,
|
||||||
|
"eye_h_m": 1.6,
|
||||||
|
"look_at": [
|
||||||
|
27.8617,
|
||||||
|
86.86079
|
||||||
|
],
|
||||||
|
"rmax_km": 60,
|
||||||
|
"initial_guess_not_used": {
|
||||||
|
"lat": 27.8369,
|
||||||
|
"lon": 86.7643
|
||||||
|
},
|
||||||
|
"viewpoint_source": {
|
||||||
|
"status": "sourced",
|
||||||
|
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
|
||||||
|
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 4800-16000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
|
||||||
|
"files_found": 1398,
|
||||||
|
"in_range": 1143,
|
||||||
|
"with_exif_heading": 54,
|
||||||
|
"facing_the_peak": 13,
|
||||||
|
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
|
||||||
|
"rule": "densest 1 km cell of photos 4000-16000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
|
||||||
|
"median_camera_heading_deg": 79.6,
|
||||||
|
"photos_in_cell": 2,
|
||||||
|
"cells_tried": [
|
||||||
|
{
|
||||||
|
"n_facing": 2,
|
||||||
|
"lat": 27.822,
|
||||||
|
"lon": 86.72267,
|
||||||
|
"peak_visible": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"distance_to_peak_m": 14299,
|
||||||
|
"bearing_to_peak_deg": 72.0,
|
||||||
|
"dem_ground_m": 3782.0,
|
||||||
|
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
|
||||||
|
"sample_files": [
|
||||||
|
{
|
||||||
|
"title": "File:Thamserku (6).JPG",
|
||||||
|
"lat": 27.822666666667,
|
||||||
|
"lon": 86.722666666667,
|
||||||
|
"heading": 73.6,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AThamserku_%286%29.JPG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Thamserku (7).JPG",
|
||||||
|
"lat": 27.821333333333,
|
||||||
|
"lon": 86.722666666667,
|
||||||
|
"heading": 85.7,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3AThamserku_%287%29.JPG"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"exif_headings": [
|
||||||
|
{
|
||||||
|
"title": "File:Thamserku (6).JPG",
|
||||||
|
"heading": 73.6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Thamserku (7).JPG",
|
||||||
|
"heading": 85.7
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"n_with_exif_heading": 2,
|
||||||
|
"summit_dem_m": 6659.6,
|
||||||
|
"summit_nominal": [
|
||||||
|
27.8617,
|
||||||
|
86.8614
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "trecime",
|
||||||
|
"name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)",
|
||||||
|
"kind": "cirque wall, spires",
|
||||||
|
"lat": 46.636906,
|
||||||
|
"lon": 12.310064,
|
||||||
|
"eye_h_m": 1.6,
|
||||||
|
"look_at": [
|
||||||
|
46.61806,
|
||||||
|
12.29583
|
||||||
|
],
|
||||||
|
"rmax_km": 40,
|
||||||
|
"initial_guess_not_used": {
|
||||||
|
"lat": 46.5833,
|
||||||
|
"lon": 12.2536
|
||||||
|
},
|
||||||
|
"viewpoint_source": {
|
||||||
|
"status": "sourced",
|
||||||
|
"source": "Wikimedia Commons geosearch (namespace 6), geotagged photos",
|
||||||
|
"query": "geosearch ns=6 gslimit=500 gsradius=10000 around 25 centres (peak + 3 rings x 8 bearings, radii 3000-10000 m), then EXIF GPSImgDirection of every file in range via prop=imageinfo&iiprop=commonmetadata",
|
||||||
|
"files_found": 2028,
|
||||||
|
"in_range": 763,
|
||||||
|
"with_exif_heading": 207,
|
||||||
|
"facing_the_peak": 33,
|
||||||
|
"pool": "photos whose camera heading is within 30 deg of the bearing to the summit",
|
||||||
|
"rule": "densest 1 km cell of photos 1500-10000 m from the summit whose EXIF camera heading faces the summit (within 30 deg) with the summit visible on the DEM (straight line, first 250 m ignored, 8 m clutter allowed); viewpoint = median coordinate of the cell",
|
||||||
|
"median_camera_heading_deg": 194.6,
|
||||||
|
"photos_in_cell": 5,
|
||||||
|
"cells_tried": [
|
||||||
|
{
|
||||||
|
"n_facing": 5,
|
||||||
|
"lat": 46.63691,
|
||||||
|
"lon": 12.31006,
|
||||||
|
"peak_visible": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"distance_to_peak_m": 2363,
|
||||||
|
"bearing_to_peak_deg": 207.4,
|
||||||
|
"dem_ground_m": 2403.0,
|
||||||
|
"eye_height_rule": "DEM ground at the viewpoint + 1.6 m (the source gives no eye height)",
|
||||||
|
"sample_files": [
|
||||||
|
{
|
||||||
|
"title": "File:Cime e Nuvole.jpg",
|
||||||
|
"lat": 46.63605,
|
||||||
|
"lon": 12.310064,
|
||||||
|
"heading": 200.3,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3ACime_e_Nuvole.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:DreiZinnenP.jpg",
|
||||||
|
"lat": 46.636770555556,
|
||||||
|
"lon": 12.310305555556,
|
||||||
|
"heading": 180.1,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3ADreiZinnenP.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Soffio di sguardo.jpg",
|
||||||
|
"lat": 46.636906,
|
||||||
|
"lon": 12.311142,
|
||||||
|
"heading": 194.6,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3ASoffio_di_sguardo.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:2405-DreizinnenH.jpg",
|
||||||
|
"lat": 46.637782777778,
|
||||||
|
"lon": 12.309966388889,
|
||||||
|
"heading": 178.4,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3A2405-DreizinnenH.jpg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Dolomiten-Fingerkraut in den Sextener Dolomiten - N\u00e4he Drei-Zinnen-H\u00fctte (9801216636).jpg",
|
||||||
|
"lat": 46.642352,
|
||||||
|
"lon": 12.30829,
|
||||||
|
"heading": 200.0,
|
||||||
|
"url": "https://commons.wikimedia.org/wiki/File%3ADolomiten-Fingerkraut_in_den_Sextener_Dolomiten_-_N%C3%A4he_Drei-Zinnen-H%C3%BCtte_%289801216636%29.jpg"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"exif_headings": [
|
||||||
|
{
|
||||||
|
"title": "File:Cime e Nuvole.jpg",
|
||||||
|
"heading": 200.3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:DreiZinnenP.jpg",
|
||||||
|
"heading": 180.1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Soffio di sguardo.jpg",
|
||||||
|
"heading": 194.6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:2405-DreizinnenH.jpg",
|
||||||
|
"heading": 178.4
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "File:Dolomiten-Fingerkraut in den Sextener Dolomiten - N\u00e4he Drei-Zinnen-H\u00fctte (9801216636).jpg",
|
||||||
|
"heading": 200.0
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"n_with_exif_heading": 5,
|
||||||
|
"summit_dem_m": 2746.9,
|
||||||
|
"summit_nominal": [
|
||||||
|
46.6186,
|
||||||
|
12.3025
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
307
scripts/ridge-bake/ridge-bake.schema.json
Normal file
307
scripts/ridge-bake/ridge-bake.schema.json
Normal file
|
|
@ -0,0 +1,307 @@
|
||||||
|
{
|
||||||
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
|
"title": "ridge-bake manifest v2 and index v1",
|
||||||
|
"$defs": {
|
||||||
|
"manifest": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"schema",
|
||||||
|
"baker_version",
|
||||||
|
"bake_id",
|
||||||
|
"place",
|
||||||
|
"view",
|
||||||
|
"curvature",
|
||||||
|
"encoding",
|
||||||
|
"camera",
|
||||||
|
"cards",
|
||||||
|
"w",
|
||||||
|
"h",
|
||||||
|
"bytes",
|
||||||
|
"attribution"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"schema": {
|
||||||
|
"const": 2
|
||||||
|
},
|
||||||
|
"baker_version": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"bake_id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"place": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"id",
|
||||||
|
"name",
|
||||||
|
"lat",
|
||||||
|
"lon",
|
||||||
|
"altitude_km",
|
||||||
|
"eye_m"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"lat": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"lon": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"altitude_km": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"eye_m": {
|
||||||
|
"type": "number"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"view": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"look_az_deg",
|
||||||
|
"window_deg",
|
||||||
|
"plane_w",
|
||||||
|
"plane_h",
|
||||||
|
"px_per_deg_h",
|
||||||
|
"px_per_deg_v",
|
||||||
|
"exaggeration",
|
||||||
|
"horizon_row",
|
||||||
|
"sky_row",
|
||||||
|
"near_row"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"look_az_deg": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"window_deg": {
|
||||||
|
"const": 72
|
||||||
|
},
|
||||||
|
"plane_w": {
|
||||||
|
"type": "integer",
|
||||||
|
"maximum": 4096
|
||||||
|
},
|
||||||
|
"plane_h": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"px_per_deg_h": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"px_per_deg_v": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"exaggeration": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"horizon_row": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"sky_row": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"near_row": {
|
||||||
|
"type": "number"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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": 1,
|
||||||
|
"maxItems": 6,
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"top",
|
||||||
|
"h",
|
||||||
|
"near_m",
|
||||||
|
"far_m",
|
||||||
|
"median_m",
|
||||||
|
"distance_m",
|
||||||
|
"scale",
|
||||||
|
"colour",
|
||||||
|
"geometry"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"top": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"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": [
|
||||||
|
"file",
|
||||||
|
"bytes"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"file": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"bytes": {
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"geometry": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"file",
|
||||||
|
"bytes"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"file": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"bytes": {
|
||||||
|
"type": "integer"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "nearest first; the runtime paints the list last to first. top and h place the card back at its rows of the frame; near_m and far_m are the median seam depths, null at the ends; median_m and distance_m are the median distance of the card's solid pixels that are not wall; scale = distance_m / (distance_m - camera.r_m) is the card's pan rate per unit of heading and its static size."
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"w": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"h": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"bytes": {
|
||||||
|
"type": "integer"
|
||||||
|
},
|
||||||
|
"attribution": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"credit_line",
|
||||||
|
"licence",
|
||||||
|
"dem_source",
|
||||||
|
"url"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"credit_line": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"licence": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"dem_source": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"url": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"index": {
|
||||||
|
"type": "object",
|
||||||
|
"required": [
|
||||||
|
"schema",
|
||||||
|
"default",
|
||||||
|
"places"
|
||||||
|
],
|
||||||
|
"additionalProperties": false,
|
||||||
|
"properties": {
|
||||||
|
"schema": {
|
||||||
|
"const": 1
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"places": {
|
||||||
|
"type": "object",
|
||||||
|
"additionalProperties": {
|
||||||
|
"type": "string"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
267
scripts/ridge-bake/ridge.py
Normal file
267
scripts/ridge-bake/ridge.py
Normal file
|
|
@ -0,0 +1,267 @@
|
||||||
|
"""Ridge baker: the ray march of a place, cut into K+1 layered-depth G-buffer cards by K authored seams (places.json), no painter, no sun.
|
||||||
|
Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it.
|
||||||
|
|
||||||
|
load_preset(id) -> configure() : observer, tiles, mosaic origin, ring radius, window azimuth, card splits and prefilter from places.json
|
||||||
|
stage0(detail) : ray march of all 6400 azimuth columns (curvature+refraction), optional authored sub-DEM foreground detail, cached
|
||||||
|
prefilter(d, h, sigma_m) : Gaussian low-pass of the sampled heights (along each ray, across rays at equal distance), angles recomputed with elev
|
||||||
|
set_view(skyline) : authored Y mapping from the march skyline: angle -> row, see set_view
|
||||||
|
coverage(d, a) / seams(cov, ..) : visible rows per log-distance bin; one forward-energy seam per authored split, per column
|
||||||
|
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
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import numpy as np, tifffile
|
||||||
|
|
||||||
|
def _env_dir(name, what):
|
||||||
|
v = os.environ.get(name)
|
||||||
|
if not v: raise RuntimeError(f"{name} is not set: it must name {what} (no default location is assumed)")
|
||||||
|
return Path(v)
|
||||||
|
B = _env_dir('RIDGE_WORK', 'the work directory (the mosaic / ray caches)')
|
||||||
|
COP = _env_dir('RIDGE_TILES', 'the directory of Copernicus GLO-30 tiles (Copernicus_DSM_COG_10_*_DEM.tif)')
|
||||||
|
W = 6400 # ring columns: 360 deg at 17.78 px/deg
|
||||||
|
WIN = 1280 # window = 72 deg of the ring
|
||||||
|
HPX_DEG = W / 360.0
|
||||||
|
H = 600 # frame rows
|
||||||
|
COLW = math.radians(360.0 / W)
|
||||||
|
R_EARTH, KREF = 6371000.0, 0.13
|
||||||
|
|
||||||
|
P = {} # configured preset
|
||||||
|
rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4
|
||||||
|
|
||||||
|
def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'):
|
||||||
|
"""The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march."""
|
||||||
|
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):
|
||||||
|
lat, lon, r = p['lat'], p['lon'], p['rmax_km']; dl = r / 111.32; dn = r / (111.32 * math.cos(math.radians(lat))); out = []
|
||||||
|
for la in range(math.floor(lat - dl), math.floor(lat + dl) + 1):
|
||||||
|
for lo in range(math.floor(lon - dn), math.floor(lon + dn) + 1):
|
||||||
|
cy = min(max(lat, la), la + 1); cx = min(max(lon, lo), lo + 1)
|
||||||
|
if math.hypot((cy - lat) * 111.32, (cx - lon) * 111.32 * math.cos(math.radians(lat))) <= r: out.append((la, lo))
|
||||||
|
return out
|
||||||
|
def tile_path(la, lo): return COP / f"Copernicus_DSM_COG_10_{'N' if la >= 0 else 'S'}{abs(la):02d}_00_{'E' if lo >= 0 else 'W'}{abs(lo):03d}_00_DEM.tif"
|
||||||
|
|
||||||
|
def cache_key(*parts):
|
||||||
|
"""Short digest of everything a cached array was computed from. A cache file is read only under the key of its own inputs, so a changed preset field, tile list or baker constant never meets a stale file."""
|
||||||
|
h = hashlib.sha256()
|
||||||
|
for q in parts: h.update(q.tobytes() if isinstance(q, np.ndarray) else repr(q).encode()); h.update(b'|')
|
||||||
|
return h.hexdigest()[:12]
|
||||||
|
def mosaic_key(p): return cache_key('mosaic.v1', sorted(tiles_for(p)), 3600)
|
||||||
|
|
||||||
|
_mos = {}
|
||||||
|
def mosaic(p):
|
||||||
|
"""Tile grid covering the circle (bounding rows/cols), cached as .npy per preset. Missing tiles (open sea has no GLO-30 tile) are zero."""
|
||||||
|
key = (p['id'], mosaic_key(p))
|
||||||
|
if key in _mos: return _mos[key]
|
||||||
|
ts = tiles_for(p); las = [t[0] for t in ts]; los = [t[1] for t in ts]; lat_top = max(las) + 1; lon_left = min(los)
|
||||||
|
c = B / f"mosaic-{p['id']}-{key[1]}.npy"
|
||||||
|
if c.exists(): m = np.load(c, mmap_mode='r')
|
||||||
|
else:
|
||||||
|
rows = []
|
||||||
|
for la in range(max(las), min(las) - 1, -1):
|
||||||
|
rows.append(np.concatenate([tifffile.imread(tile_path(la, lo)) if tile_path(la, lo).exists() else np.zeros((3600, 3600), np.float32) for lo in range(min(los), max(los) + 1)], axis=1))
|
||||||
|
m = np.concatenate(rows, axis=0).astype(np.float32); np.save(c, m)
|
||||||
|
_mos[key] = (m, lat_top, lon_left); return _mos[key]
|
||||||
|
|
||||||
|
def bil(a, lat_top, lon_left, lat, lon):
|
||||||
|
y = (lat_top - lat) * 3600 - 0.5; x = (lon - lon_left) * 3600 - 0.5
|
||||||
|
y0 = np.clip(np.floor(y).astype(int), 0, a.shape[0] - 2); x0 = np.clip(np.floor(x).astype(int), 0, a.shape[1] - 2)
|
||||||
|
fy = np.clip(y - y0, 0, 1); fx = np.clip(x - x0, 0, 1)
|
||||||
|
return (a[y0, x0] * (1 - fx) * (1 - fy) + a[y0, x0 + 1] * fx * (1 - fy) + a[y0 + 1, x0] * (1 - fx) * fy + a[y0 + 1, x0 + 1] * fx * fy)
|
||||||
|
|
||||||
|
def configure(p):
|
||||||
|
"""Set the module state for a preset: observer, eye elevation (DEM ground + eye height, or ground_override), window azimuth."""
|
||||||
|
global P
|
||||||
|
P = p; m, lt, ll = mosaic(p)
|
||||||
|
ground = p['ground_override_m'] if 'ground_override_m' in p else float(bil(m, lt, ll, np.array(p['lat']), np.array(p['lon'])))
|
||||||
|
P['ground_m'] = ground; P['eye_m'] = ground + p['eye_h_m']
|
||||||
|
if 'look_at' in p:
|
||||||
|
la, lo = p['look_at']; P['az_center'] = (math.degrees(math.atan2((lo - p['lon']) * math.cos(math.radians(p['lat'])), la - p['lat'])) + 360) % 360
|
||||||
|
else: P['az_center'] = p['az_deg']
|
||||||
|
P['win0'] = int(round(P['az_center'] / 360 * W - WIN / 2)) % W
|
||||||
|
return P
|
||||||
|
|
||||||
|
def win(img): return np.take(img, (P['win0'] + np.arange(WIN)) % W, axis=1)
|
||||||
|
|
||||||
|
# ====================================================================== authored sub-DEM foreground detail (Aetheria / CultMath ridged multifractal)
|
||||||
|
def _frac(v): return v - np.floor(v)
|
||||||
|
def _hash2(x, y): return _frac(np.sin(x * 127.1 + y * 311.7) * 43758.5453) # cultmath_hash(vec2), as Ratatoskr noise.ts
|
||||||
|
def _vnoise2(x, y): # cultmath_value_noise: 4 hashed corners, smoothstep blend
|
||||||
|
cx, cy = np.floor(x), np.floor(y); u = x - cx; v = y - cy; u = u * u * (3 - 2 * u); v = v * v * (3 - 2 * v)
|
||||||
|
a, b, c, d = _hash2(cx, cy), _hash2(cx + 1, cy), _hash2(cx, cy + 1), _hash2(cx + 1, cy + 1)
|
||||||
|
return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v
|
||||||
|
LACUN, WEIGHT_GAIN, AMP_GAIN, CRAG = 2.07, 2.0, 0.5, 0.5 # ridgeWorld.ts constants
|
||||||
|
DETAIL = dict(cell_m=60.0, octaves=4, amp_m=24.0, fade_from_m=500.0, fade_to_m=4000.0, seed=17)
|
||||||
|
def detail_height(E, N, dist):
|
||||||
|
"""Ridged multifractal (ridgeWorld.ts `profile`, folded value noise weighted by the previous octave) in WORLD metres (east, north of the observer),
|
||||||
|
so it is automatically periodic around the ring. First octave wavelength = 60 m = two GLO-30 cells (nothing coarser than the DEM can resolve is
|
||||||
|
touched), then x2.07. Amplitude fades to zero between fade_from and fade_to metres of distance. Seeded, deterministic, authored."""
|
||||||
|
cfg = DETAIL; e = 0.03 + (1 - CRAG) * 0.4; top = math.sqrt(1 + e * e); s = 0.0; nrm = 0.0; amp = 1.0; f = 1.0 / cfg['cell_m']; w = 1.0
|
||||||
|
for k in range(cfg['octaves']):
|
||||||
|
v = 2 * _vnoise2(E * f + cfg['seed'] * 7.31, N * f + cfg['seed'] * 3.17 + k * 13) - 1
|
||||||
|
sig = (1 - np.sqrt(v * v + e * e) / top) ** 2 * w; w = np.minimum(1.0, sig * WEIGHT_GAIN); s = s + sig * amp; nrm += amp; amp *= AMP_GAIN; f *= LACUN
|
||||||
|
t = np.clip((dist - cfg['fade_from_m']) / (cfg['fade_to_m'] - cfg['fade_from_m']), 0, 1); fade = 1 - t * t * (3 - 2 * t)
|
||||||
|
return cfg['amp_m'] * fade * (s / nrm - 0.3)
|
||||||
|
|
||||||
|
# ====================================================================== stage 0: march
|
||||||
|
def schedule(detail):
|
||||||
|
d = [500.0]
|
||||||
|
while d[-1] < P['rmax_km'] * 1000:
|
||||||
|
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)
|
||||||
|
for k, dk in enumerate(d):
|
||||||
|
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)
|
||||||
|
A[k] = elev(h, dk, curvature); Hh[k] = h
|
||||||
|
return d, A, Hh
|
||||||
|
|
||||||
|
def rays_key(detail):
|
||||||
|
"""Inputs of the ray march: observer, eye elevation, range, the DEM mosaic, the sample schedule (hashed as the array it produces), the Earth / refraction constants, the ring width, and (detail) the foreground detail noise."""
|
||||||
|
return cache_key('rays.v1', P['lat'], P['lon'], P['rmax_km'], round(float(P['eye_m']), 3), mosaic_key(P), schedule(detail), R_EARTH, KREF, W, bool(detail),
|
||||||
|
(sorted(DETAIL.items()), LACUN, WEIGHT_GAIN, AMP_GAIN, CRAG) if detail else None)
|
||||||
|
def stage0(detail=False, force=False):
|
||||||
|
c = B / f"rays-{P['id']}{'-detail' if detail else ''}-{rays_key(detail)}.npz"
|
||||||
|
if c.exists() and not force:
|
||||||
|
z = np.load(c); return z['d'], z['ang'], z['h'], None
|
||||||
|
t0 = time.time(); mosaic(P); t1 = time.time(); d, A, Hh = march(detail); t2 = time.time(); np.savez(c, d=d, ang=A, h=Hh)
|
||||||
|
return d, A, Hh, dict(mosaic=t1 - t0, march=t2 - t1, samples=len(d))
|
||||||
|
|
||||||
|
# ====================================================================== periodic helpers
|
||||||
|
def blurw(a, s):
|
||||||
|
r = int(3 * s) + 1; k = np.exp(-0.5 * (np.arange(-r, r + 1) / s) ** 2); k /= k.sum()
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ====================================================================== 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 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(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
|
||||||
|
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, low_deg=low, sky_row=sky_row, near_row=near_row)
|
||||||
|
|
||||||
|
# ====================================================================== 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 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 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 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
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# ====================================================================== 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 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
|
||||||
60
scripts/ridge-bake/tests/mutate.py
Normal file
60
scripts/ridge-bake/tests/mutate.py
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
"""Mutation check: re-introduce a cause into a COPY of the baker, run the fixtures against it, and require that at least one fails.
|
||||||
|
venv/bin/python tests/mutate.py (prints one line per mutant; exit 1 if a mutant survives)"""
|
||||||
|
import os, shutil, subprocess, sys, tempfile
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__)); SRC = os.path.join(HERE, '..')
|
||||||
|
MUTANTS = { # name -> (text in ridge.py or export.py, replacement)
|
||||||
|
'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 = 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')]
|
||||||
|
line = ('KILLED ' if r.returncode else 'SURVIVED ') + name + ' -> ' + (', '.join(fails) or 'no fixture failed'); print(line, file=sys.stderr, flush=True) # progress: a killed run keeps what finished
|
||||||
|
return line, r.returncode == 0
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
with ThreadPoolExecutor(int(os.environ.get('MUTATE_JOBS', '6'))) as ex: res = list(ex.map(run, [(n, v) for n, v in MUTANTS.items() if n not in EQUIVALENT]))
|
||||||
|
for line, _ in res: print(line, flush=True)
|
||||||
|
for n, why in EQUIVALENT.items(): print('EQUIVALENT ' + n + ' -> ' + why)
|
||||||
|
sys.exit(1 if any(sv for _, sv in res) else 0)
|
||||||
7
scripts/ridge-bake/tests/run.sh
Executable file
7
scripts/ridge-bake/tests/run.sh
Executable file
|
|
@ -0,0 +1,7 @@
|
||||||
|
#!/bin/sh
|
||||||
|
# Usage: RIDGE_PY=<venv python> RIDGE_TILES=<tiles dir> tests/run.sh [test_ridge.py|mutate.py]
|
||||||
|
# RIDGE_WORK (cache dir) defaults to a fresh directory under $TMPDIR.
|
||||||
|
: "${RIDGE_PY:?RIDGE_PY must name the python of the baker venv}"
|
||||||
|
export RIDGE_WORK="${RIDGE_WORK:-${TMPDIR:-/tmp}/ridge-bake-work}"; mkdir -p "$RIDGE_WORK"
|
||||||
|
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
exec "$RIDGE_PY" -I "$HERE/${1:-test_ridge.py}"
|
||||||
385
scripts/ridge-bake/tests/test_ridge.py
Normal file
385
scripts/ridge-bake/tests/test_ridge.py
Normal file
|
|
@ -0,0 +1,385 @@
|
||||||
|
"""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 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, 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=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
|
||||||
|
|
||||||
|
def rays(hfun):
|
||||||
|
az = (np.arange(W) + 0.5) / W * 360.0; A = np.zeros((len(D), W), np.float32); Hh = np.zeros_like(A)
|
||||||
|
for k, dk in enumerate(D):
|
||||||
|
h = hfun(dk, az); Hh[k] = h; A[k] = np.degrees(np.arctan2(h - EYE - dk * dk / (2 * ridge.R_EARTH) * (1 - ridge.KREF), dk))
|
||||||
|
return A, Hh
|
||||||
|
def theta(h, d): return math.degrees(math.atan2(h - EYE - d * d / (2 * ridge.R_EARTH) * (1 - ridge.KREF), d))
|
||||||
|
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 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
|
||||||
|
try:
|
||||||
|
base = dict(id='k1', lat=47.0, lon=11.0, rmax_km=40, eye_m=2000.0); ridge.P = dict(base); k0 = (ridge.rays_key(False), ridge.rays_key(True), ridge.mosaic_key(ridge.P))
|
||||||
|
ridge.P = dict(base, id='other'); assert (ridge.rays_key(False), ridge.rays_key(True), ridge.mosaic_key(ridge.P)) == k0, 'the preset id changed the key'
|
||||||
|
for fld, v in (('eye_m', 2010.0), ('rmax_km', 41), ('lon', 11.001), ('lat', 47.001)):
|
||||||
|
ridge.P = dict(base, **{fld: v}); assert ridge.rays_key(False) != k0[0], ('rays key ignores', fld)
|
||||||
|
ridge.P = dict(base, lat=47.0, lon=13.5); assert ridge.mosaic_key(ridge.P) != k0[2], 'mosaic key ignores the tile list'
|
||||||
|
ridge.P = dict(base); old = ridge.KREF; ridge.KREF = 0.2
|
||||||
|
try: assert ridge.rays_key(False) != k0[0], 'rays key ignores the refraction constant'
|
||||||
|
finally: ridge.KREF = old
|
||||||
|
old = ridge.DETAIL; ridge.DETAIL = dict(old, amp_m=30.0)
|
||||||
|
try: assert ridge.rays_key(True) != k0[1] and ridge.rays_key(False) == k0[0], 'detail key ignores the noise settings (or the plain key follows them)'
|
||||||
|
finally: ridge.DETAIL = old
|
||||||
|
finally: ridge.P = saved
|
||||||
|
def test_paths_come_from_the_environment_with_no_default():
|
||||||
|
"""Importing the baker without RIDGE_WORK / RIDGE_TILES fails with a message naming the variable (no location is assumed)."""
|
||||||
|
import subprocess; env = {k: v for k, v in os.environ.items() if not k.startswith('RIDGE_')}
|
||||||
|
for var in ('RIDGE_WORK', 'RIDGE_TILES'):
|
||||||
|
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:])
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------------------- 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:
|
||||||
|
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)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------------------- 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_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:
|
||||||
|
b, pk = _packed(); b2, pk2 = _packed(_bake(WIDE3, [20, 55])); assert [(c['colour'], c['geometry']) for c in pk] == [(c['colour'], c['geometry']) for c in pk2], 'two independent bakes gave different bytes'
|
||||||
|
a = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque']); assert a.name == 'synthetic-' + export.bake_id([(c['colour'], c['geometry']) for c in pk]); assert sorted(os.listdir(d + '/a')) == sorted(['index.json', a.name])
|
||||||
|
m = json.load(open(a / 'manifest.json')); export.validate(m, export.SCHEMA['$defs']['manifest']); assert m['schema'] == 2 and m['baker_version'] == export.BAKER_VERSION and len(m['cards']) == 3 and m['w'] == WIN and m['h'] == H
|
||||||
|
assert m['camera'] == dict(r_m=export.CAMERA_R_M, heading_max_deg=17.0) and all(c['scale'] == c['distance_m'] / (c['distance_m'] - export.CAMERA_R_M) and c['distance_m'] == c['median_m'] for c in m['cards']), m['camera']
|
||||||
|
assert m['cards'][0]['near_m'] is None and m['cards'][-1]['far_m'] is None and m['cards'][0]['far_m'] == m['cards'][1]['near_m'] and m['cards'][0]['median_m'] < m['cards'][1]['median_m'] < m['cards'][2]['median_m']
|
||||||
|
for c in m['cards']:
|
||||||
|
for kind in ('colour', 'geometry'): f = a / c[kind]['file']; assert f.stat().st_size == c[kind]['bytes'] and export.decode(f.read_bytes()).shape[:2] == (c['h'], WIN), c
|
||||||
|
assert m['bytes'] == sum(c[k]['bytes'] for c in m['cards'] for k in ('colour', 'geometry')) and m['encoding']['normal'] == 'rt8' and m['curvature'] == dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF)
|
||||||
|
idx = json.load(open(d + '/a/index.json')); export.validate(idx, export.SCHEMA['$defs']['index']); assert idx == dict(schema=1, default='synthetic', places={'synthetic': a.name})
|
||||||
|
pk3 = [dict(c) for c in pk]; pk3[1]['geometry'] = pk3[1]['geometry'] + b'x'; assert export.bake_id([(c['colour'], c['geometry']) for c in pk3]) != export.bake_id([(c['colour'], c['geometry']) for c in pk]), 'a changed byte kept the bake_id'
|
||||||
|
import hashlib; want = hashlib.sha256(b''.join(c['colour'] + c['geometry'] for c in pk)).hexdigest()[:12]; assert export.bake_id([(c['colour'], c['geometry']) for c in pk]) == want, 'bake_id is not the sha256 of the card files, colour then geometry, in index order'
|
||||||
|
assert export.bake_id([(c['geometry'], c['colour']) for c in pk]) != want and export.bake_id([(c['colour'], c['geometry']) for c in pk[::-1]]) != want, 'bake_id ignores the file order'
|
||||||
|
bad = json.loads(json.dumps(m)); bad['cards'][0]['extra'] = 1
|
||||||
|
try: export.validate(bad, export.SCHEMA['$defs']['manifest'])
|
||||||
|
except ValueError: pass
|
||||||
|
else: assert False, 'an extra key passed the schema'
|
||||||
|
assert json.load(open(os.path.join(SRC, 'ridge-bake.schema.json'))) == json.loads(json.dumps(export.SCHEMA)), 'ridge-bake.schema.json is stale (export.py --write-schema)'
|
||||||
|
want = dict(credit_line='Contains modified Copernicus data: DEM © DLR e.V. 2010-2014 and © Airbus Defence and Space GmbH 2014-2018 provided under COPERNICUS by the European Union and ESA; all rights reserved.',
|
||||||
|
licence='Copernicus DEM licence: free, full and open access, with the credit line shown', dem_source='Copernicus DEM GLO-30 (30 m)', url='https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model')
|
||||||
|
assert m['attribution'] == want, m['attribution']
|
||||||
|
c = export.write_bake(d + '/a', b['place'], b['view'], b['meta'], pk, b['opaque'])
|
||||||
|
assert c.name == a.name; other = dict(b['place'], id='other'); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'synthetic'
|
||||||
|
export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque'], default='other'); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
|
||||||
|
idx = json.load(open(d + '/a/index.json')); idx['default'] = 'gone'; open(d + '/a/index.json', 'w').write(json.dumps(idx)); export.write_bake(d + '/a', other, b['view'], b['meta'], pk, b['opaque']); assert json.load(open(d + '/a/index.json'))['default'] == 'other'
|
||||||
|
finally: shutil.rmtree(d)
|
||||||
|
def test_cover_and_size_refusals_write_nothing():
|
||||||
|
"""write_bake measures the files it is handed: a card with a hole (alpha zeroed in a band of columns) fails the cover check, a card leaving the frame, cards of two widths and a colour/geometry size mismatch are refused, and nothing is written."""
|
||||||
|
d = tempfile.mkdtemp()
|
||||||
|
try:
|
||||||
|
b, pk = _packed(); c1 = b['cards'][1]; hole = c1['alpha'].copy(); hole[:, 200:260] = 0
|
||||||
|
holed = [dict(c) for c in pk]; holed[1]['colour'] = export.encode_colour(c1['albedo'], hole); holed[2] = dict(pk[2], colour=export.encode_colour(b['cards'][2]['albedo'], b['cards'][2]['alpha'] * 0)); _refuses(d + '/hole', b, holed, 'a bake whose cards leave a hole was written')
|
||||||
|
_refuses(d + '/off', b, [dict(c, top=H - 5) if i == 0 else c for i, c in enumerate(pk)], 'a card leaving the frame was written')
|
||||||
|
narrow = [dict(c) for c in pk]; narrow[0]['colour'] = export.encode_colour(b['cards'][0]['albedo'][:, :1000], b['cards'][0]['alpha'][:, :1000]); _refuses(d + '/wide', b, narrow, 'cards of two widths were written')
|
||||||
|
_refuses(d + '/rows', b, pk, 'view plane_h disagreeing with the opaque view was written', view=dict(b['view'], plane_h=H + 1))
|
||||||
|
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)
|
||||||
|
|
||||||
|
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)
|
||||||
121
scripts/ridge-sky/build-night-sky.py
Normal file
121
scripts/ridge-sky/build-night-sky.py
Normal 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()
|
||||||
|
|
@ -133,7 +133,7 @@ const NavItemBase = style({
|
||||||
backgroundColor: ContainerHover,
|
backgroundColor: ContainerHover,
|
||||||
},
|
},
|
||||||
// While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint
|
// While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint
|
||||||
// wash of the theme's own surface: the terrain stays visible, the text stays readable.
|
// wash of the theme's own surface: the scene stays visible, the text stays readable.
|
||||||
// Hover, the selected row and a press each strengthen it a step.
|
// Hover, the selected row and a press each strengthen it a step.
|
||||||
':root[data-scene] &': {
|
':root[data-scene] &': {
|
||||||
backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`,
|
backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`,
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ import { searchModalAtom } from '../../state/searchModal';
|
||||||
import { getCanonicalAliasOrRoomId } from '../../utils/matrix';
|
import { getCanonicalAliasOrRoomId } from '../../utils/matrix';
|
||||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||||
import { MINDS } from '../../components/message/pose/poses';
|
import { MINDS } from '../../components/message/pose/poses';
|
||||||
import { MediaLink, MediaNote, useMindMedia } from './MediaRow';
|
import { MediaLink, MediaNote, useCommons, useMindMedia } from './MediaRow';
|
||||||
import { MediaRow as MediaRowState } from './mediaRoom';
|
import { MediaRow as MediaRowState } from './mediaRoom';
|
||||||
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
|
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
|
||||||
import { useCallEmbed } from '../../hooks/useCallEmbed';
|
import { useCallEmbed } from '../../hooks/useCallEmbed';
|
||||||
|
|
@ -194,6 +194,15 @@ function MindMedia({ media }: { media: MediaRowState }) {
|
||||||
return <JoinRow room={media.room} icon={Icons.Photo} />;
|
return <JoinRow room={media.room} icon={Icons.Photo} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The shared Commons room above the tiers: a link when joined, a join row otherwise, nothing when there is none. */
|
||||||
|
function CommonsEntry() {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const room = useCommons();
|
||||||
|
if (!room) return null;
|
||||||
|
if (room.state === 'joined') return <MediaLink to={estateRoomPath(mx, room)} label="Commons" />;
|
||||||
|
return <JoinRow room={room} icon={Icons.Photo} />;
|
||||||
|
}
|
||||||
|
|
||||||
function GroupSection({ tierId, group }: { tierId: string; group: EstateGroup }) {
|
function GroupSection({ tierId, group }: { tierId: string; group: EstateGroup }) {
|
||||||
const media = useMindMedia(group.mind, group.rooms);
|
const media = useMindMedia(group.mind, group.rooms);
|
||||||
const hasMedia = MINDS.includes(group.mind);
|
const hasMedia = MINDS.includes(group.mind);
|
||||||
|
|
@ -345,6 +354,7 @@ function EstateTiers({ rootId }: { rootId: string }) {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<CommonsEntry />
|
||||||
{tiers.map((tier) => (
|
{tiers.map((tier) => (
|
||||||
<Tier key={tier.id} tier={tier} />
|
<Tier key={tier.id} tier={tier} />
|
||||||
))}
|
))}
|
||||||
|
|
|
||||||
|
|
@ -26,4 +26,14 @@ describe('Media row', () => {
|
||||||
expect(text(html)).toBe('Media');
|
expect(text(html)).toBe('Media');
|
||||||
expect(html).toContain('href="/home/%23void-files%3Agamecult.org/"');
|
expect(html).toContain('href="/home/%23void-files%3Agamecult.org/"');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('the Commons link reads "Commons" and opens the room', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<MemoryRouter>
|
||||||
|
<MediaLink to="/home/%23commons%3Agamecult.org/" label="Commons" />
|
||||||
|
</MemoryRouter>
|
||||||
|
);
|
||||||
|
expect(text(html)).toBe('Commons');
|
||||||
|
expect(html).toContain('href="/home/%23commons%3Agamecult.org/"');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,10 @@ import { useEstateRootId } from './useEstate';
|
||||||
import {
|
import {
|
||||||
STEWARDSHIPS_KEY,
|
STEWARDSHIPS_KEY,
|
||||||
MediaRow as MediaRowState,
|
MediaRow as MediaRowState,
|
||||||
|
commonsAlias,
|
||||||
|
commonsRow,
|
||||||
lookupMediaRoom,
|
lookupMediaRoom,
|
||||||
|
lookupZoneRoom,
|
||||||
mediaRoomIdFromStewardships,
|
mediaRoomIdFromStewardships,
|
||||||
mediaRow,
|
mediaRow,
|
||||||
typedMediaRoom,
|
typedMediaRoom,
|
||||||
|
|
@ -44,7 +47,7 @@ export function MediaNote({ note, title }: { note: string; title?: string }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The joined Media row: opens the room, which shows its album view. */
|
/** The joined Media row: opens the room, which shows its album view. */
|
||||||
export function MediaLink({ to }: { to: string }) {
|
export function MediaLink({ to, label = 'Media' }: { to: string; label?: string }) {
|
||||||
return (
|
return (
|
||||||
<NavItem variant="Background" radii="400">
|
<NavItem variant="Background" radii="400">
|
||||||
<NavLink to={to}>
|
<NavLink to={to}>
|
||||||
|
|
@ -52,7 +55,7 @@ export function MediaLink({ to }: { to: string }) {
|
||||||
<Box as="span" grow="Yes" alignItems="Center" gap="200">
|
<Box as="span" grow="Yes" alignItems="Center" gap="200">
|
||||||
<NavGutter>{mediaIcon}</NavGutter>
|
<NavGutter>{mediaIcon}</NavGutter>
|
||||||
<Text className={NavLabel} as="span" size="Inherit" truncate>
|
<Text className={NavLabel} as="span" size="Inherit" truncate>
|
||||||
Media
|
{label}
|
||||||
</Text>
|
</Text>
|
||||||
</Box>
|
</Box>
|
||||||
</NavItemContent>
|
</NavItemContent>
|
||||||
|
|
@ -105,3 +108,23 @@ export const useMindMedia = (mind: string, rooms: readonly EstateRoom[]): MediaR
|
||||||
if (typed) return { kind: 'room', room: { ...typed, name: 'Media' } };
|
if (typed) return { kind: 'room', room: { ...typed, name: 'Media' } };
|
||||||
return mediaRow(lookup.data, membership);
|
return mediaRow(lookup.data, membership);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** The shared Commons room as the navigator sees it right now: undefined means no row. Dark unless fileZoneShare.enabled. */
|
||||||
|
export const useCommons = (): EstateRoom | undefined => {
|
||||||
|
const mx = useMatrixClient();
|
||||||
|
const joined = useAtomValue(allRoomsAtom);
|
||||||
|
const invited = useAtomValue(allInvitesAtom);
|
||||||
|
const enabled = !!useClientConfig().fileZoneShare?.enabled;
|
||||||
|
const server = mx.getDomain() ?? '';
|
||||||
|
// Provisioning records no id for the Commons (only per-Mind zones under @rooms.file_zones): the alias is the one way in.
|
||||||
|
const lookup = useQuery({
|
||||||
|
queryKey: ['commons-room', server],
|
||||||
|
queryFn: () => lookupZoneRoom(mx, commonsAlias(server), server),
|
||||||
|
staleTime: 60_000,
|
||||||
|
enabled,
|
||||||
|
});
|
||||||
|
const membership = new Map<string, 'join' | 'invite'>();
|
||||||
|
invited.forEach((id) => membership.set(id, 'invite'));
|
||||||
|
joined.forEach((id) => membership.set(id, 'join'));
|
||||||
|
return commonsRow(enabled, lookup.data, membership);
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,13 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import {
|
import {
|
||||||
|
commonsAlias,
|
||||||
|
commonsRow,
|
||||||
lookupMediaRoom,
|
lookupMediaRoom,
|
||||||
|
lookupZoneRoom,
|
||||||
mediaAlias,
|
mediaAlias,
|
||||||
mediaRoomIdFromStewardships,
|
mediaRoomIdFromStewardships,
|
||||||
mediaRow,
|
mediaRow,
|
||||||
|
MediaLookup,
|
||||||
typedMediaRoom,
|
typedMediaRoom,
|
||||||
} from './mediaRoom';
|
} from './mediaRoom';
|
||||||
|
|
||||||
|
|
@ -132,3 +136,51 @@ describe('the Media row of a Mind', () => {
|
||||||
expect(typedMediaRoom(rooms, () => false)).toBeUndefined();
|
expect(typedMediaRoom(rooms, () => false)).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('the Commons row', () => {
|
||||||
|
const none = new Map<string, 'join' | 'invite'>();
|
||||||
|
|
||||||
|
it('is found by the alias #commons:<server>', async () => {
|
||||||
|
const { mx, asked } = clientFor(async () => ({ room_id: '!c:gamecult.org' }));
|
||||||
|
const lookup = await lookupZoneRoom(mx, commonsAlias('gamecult.org'), 'gamecult.org');
|
||||||
|
expect(asked).toEqual(['#commons:gamecult.org']);
|
||||||
|
expect(commonsRow(true, lookup, new Map([['!c:gamecult.org', 'join']]))).toMatchObject({
|
||||||
|
roomId: '!c:gamecult.org',
|
||||||
|
name: 'Commons',
|
||||||
|
state: 'joined',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows no row when the room is absent, the lookup failed or is still out', async () => {
|
||||||
|
const missing = await lookupZoneRoom(
|
||||||
|
clientFor(async () => {
|
||||||
|
throw notFound;
|
||||||
|
}).mx,
|
||||||
|
commonsAlias('gamecult.org'),
|
||||||
|
'gamecult.org'
|
||||||
|
);
|
||||||
|
const failed = await lookupZoneRoom(
|
||||||
|
clientFor(async () => {
|
||||||
|
throw new Error('down');
|
||||||
|
}).mx,
|
||||||
|
commonsAlias('gamecult.org'),
|
||||||
|
'gamecult.org'
|
||||||
|
);
|
||||||
|
expect(commonsRow(true, missing, none)).toBeUndefined();
|
||||||
|
expect(commonsRow(true, failed, none)).toBeUndefined();
|
||||||
|
expect(commonsRow(true, undefined, none)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows no row with the flag off, even for a found room', () => {
|
||||||
|
const found: MediaLookup = { found: true, roomId: '!c:gamecult.org', via: ['gamecult.org'] };
|
||||||
|
expect(commonsRow(false, found, new Map([['!c:gamecult.org', 'join']]))).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('offers a join to a viewer who has not joined, and an accept to an invited one', () => {
|
||||||
|
const found: MediaLookup = { found: true, roomId: '!c:gamecult.org', via: ['gamecult.org'] };
|
||||||
|
expect(commonsRow(true, found, none)?.state).toBe('joinable');
|
||||||
|
expect(commonsRow(true, found, new Map([['!c:gamecult.org', 'invite']]))?.state).toBe(
|
||||||
|
'invited'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,9 @@ export const ROOMS_KEY = '@rooms';
|
||||||
|
|
||||||
export const mediaAlias = (mind: string, server: string): string => `#${mind}-files:${server}`;
|
export const mediaAlias = (mind: string, server: string): string => `#${mind}-files:${server}`;
|
||||||
|
|
||||||
|
/** The shared Commons room's alias (gamecult-ops synapse-accounts-hand-managed.py COMMONS_ALIAS). */
|
||||||
|
export const commonsAlias = (server: string): string => `#commons:${server}`;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The room id the stewardships state names for a Mind's media room, under `@rooms.file_zones[<mind>]`.
|
* The room id the stewardships state names for a Mind's media room, under `@rooms.file_zones[<mind>]`.
|
||||||
* The state's mind-to-repos lists are not read here.
|
* The state's mind-to-repos lists are not read here.
|
||||||
|
|
@ -46,16 +49,16 @@ export type MediaLookup =
|
||||||
| { found: true; roomId: string; via: string[] }
|
| { found: true; roomId: string; via: string[] }
|
||||||
| { found: false; reason: 'unset' | 'error'; message?: string };
|
| { found: false; reason: 'unset' | 'error'; message?: string };
|
||||||
|
|
||||||
/** Resolve a Mind's media room: a carried id if there is one, else the alias. A 404 means it is not set up. */
|
/** Resolve a file-zone room (a Mind's media room, or Commons): a carried id if there is one, else the alias. A 404 means it is not set up. */
|
||||||
export const lookupMediaRoom = async (
|
export const lookupZoneRoom = async (
|
||||||
mx: MediaClient,
|
mx: MediaClient,
|
||||||
mind: string,
|
alias: string,
|
||||||
server: string,
|
server: string,
|
||||||
carriedId?: string
|
carriedId?: string
|
||||||
): Promise<MediaLookup> => {
|
): Promise<MediaLookup> => {
|
||||||
if (carriedId) return { found: true, roomId: carriedId, via: [server] };
|
if (carriedId) return { found: true, roomId: carriedId, via: [server] };
|
||||||
try {
|
try {
|
||||||
const r = await mx.getRoomIdForAlias(mediaAlias(mind, server));
|
const r = await mx.getRoomIdForAlias(alias);
|
||||||
return { found: true, roomId: r.room_id, via: r.servers?.length ? r.servers : [server] };
|
return { found: true, roomId: r.room_id, via: r.servers?.length ? r.servers : [server] };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const err = e as {
|
const err = e as {
|
||||||
|
|
@ -75,6 +78,14 @@ export const lookupMediaRoom = async (
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Resolve a Mind's media room. */
|
||||||
|
export const lookupMediaRoom = (
|
||||||
|
mx: MediaClient,
|
||||||
|
mind: string,
|
||||||
|
server: string,
|
||||||
|
carriedId?: string
|
||||||
|
): Promise<MediaLookup> => lookupZoneRoom(mx, mediaAlias(mind, server), server, carriedId);
|
||||||
|
|
||||||
export type MediaRow =
|
export type MediaRow =
|
||||||
| { kind: 'checking' }
|
| { kind: 'checking' }
|
||||||
| { kind: 'unset' }
|
| { kind: 'unset' }
|
||||||
|
|
@ -86,7 +97,8 @@ const MEMBERSHIP_STATE = { join: 'joined', invite: 'invited', none: 'joinable' }
|
||||||
/** What the Media row shows: the lookup result joined to the user's own membership. */
|
/** What the Media row shows: the lookup result joined to the user's own membership. */
|
||||||
export const mediaRow = (
|
export const mediaRow = (
|
||||||
lookup: MediaLookup | undefined,
|
lookup: MediaLookup | undefined,
|
||||||
membership: ReadonlyMap<string, 'join' | 'invite'>
|
membership: ReadonlyMap<string, 'join' | 'invite'>,
|
||||||
|
name = 'Media'
|
||||||
): MediaRow => {
|
): MediaRow => {
|
||||||
if (!lookup) return { kind: 'checking' };
|
if (!lookup) return { kind: 'checking' };
|
||||||
if (!lookup.found) {
|
if (!lookup.found) {
|
||||||
|
|
@ -99,7 +111,7 @@ export const mediaRow = (
|
||||||
kind: 'room',
|
kind: 'room',
|
||||||
room: {
|
room: {
|
||||||
roomId: lookup.roomId,
|
roomId: lookup.roomId,
|
||||||
name: 'Media',
|
name,
|
||||||
state: MEMBERSHIP_STATE[m ?? 'none'],
|
state: MEMBERSHIP_STATE[m ?? 'none'],
|
||||||
via: lookup.via,
|
via: lookup.via,
|
||||||
parentId: null,
|
parentId: null,
|
||||||
|
|
@ -107,3 +119,18 @@ export const mediaRow = (
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Commons row: the shared room, or nothing. Off with the share flag; not set up, still looking and a failed lookup
|
||||||
|
* show no row (the room is shared furniture, not a per-Mind promise like Media). A found room is joined, invited or
|
||||||
|
* joinable, as for Media.
|
||||||
|
*/
|
||||||
|
export const commonsRow = (
|
||||||
|
enabled: boolean,
|
||||||
|
lookup: MediaLookup | undefined,
|
||||||
|
membership: ReadonlyMap<string, 'join' | 'invite'>
|
||||||
|
): EstateRoom | undefined => {
|
||||||
|
if (!enabled) return undefined;
|
||||||
|
const row = mediaRow(lookup, membership, 'Commons');
|
||||||
|
return row.kind === 'room' ? row.room : undefined;
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,12 @@
|
||||||
import React, { useEffect, useMemo, useRef } from 'react';
|
import React, { useEffect, useRef } from 'react';
|
||||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||||
import { getFallbackSession } from '../../state/sessions';
|
import { getFallbackSession } from '../../state/sessions';
|
||||||
import { mountBackgroundScene } from './host';
|
import { mountBackgroundScene } from './host';
|
||||||
|
import { setSceneDrawn } from './sceneDrawn';
|
||||||
import { readCapabilities, resolveTier } from './tier';
|
import { readCapabilities, resolveTier } from './tier';
|
||||||
import { getSceneStyleOverride } from './sceneStyle';
|
|
||||||
import './sceneShell.css';
|
import './sceneShell.css';
|
||||||
import './sceneButtons.css';
|
import './sceneButtons.css';
|
||||||
|
|
||||||
/** Set on <html> while a scene runs, so signed-out screens can let it show through. */
|
|
||||||
export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The one host for the background scene, mounted once at the app root. Fixed behind everything
|
* The one host for the background scene, mounted once at the app root. Fixed behind everything
|
||||||
* (z-index -1 sits above the body's background and below all normal content; the signed-out
|
* (z-index -1 sits above the body's background and below all normal content; the signed-out
|
||||||
|
|
@ -18,28 +15,23 @@ export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene';
|
||||||
* Tier 'off' renders nothing and loads nothing.
|
* Tier 'off' renders nothing and loads nothing.
|
||||||
*/
|
*/
|
||||||
export function BackgroundScene() {
|
export function BackgroundScene() {
|
||||||
const configured = useClientConfig().backgroundScene;
|
const config = useClientConfig().backgroundScene;
|
||||||
const config = useMemo(() => {
|
|
||||||
const style = getSceneStyleOverride();
|
|
||||||
return configured && style ? { ...configured, style } : configured;
|
|
||||||
}, [configured]);
|
|
||||||
const enabled = resolveTier(config, readCapabilities(navigator)) !== 'off';
|
const enabled = resolveTier(config, readCapabilities(navigator)) !== 'off';
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const canvas = canvasRef.current;
|
const canvas = canvasRef.current;
|
||||||
if (!enabled || !canvas) return undefined;
|
if (!enabled || !canvas) return undefined;
|
||||||
const root = document.documentElement;
|
|
||||||
const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, {
|
const dispose = mountBackgroundScene(config, readCapabilities(navigator), canvas, {
|
||||||
loggedIn: !!getFallbackSession(),
|
loggedIn: !!getFallbackSession(),
|
||||||
onActive: () => root.setAttribute(SCENE_ACTIVE_ATTRIBUTE, ''),
|
onActive: () => setSceneDrawn(true),
|
||||||
onInactive: () => root.removeAttribute(SCENE_ACTIVE_ATTRIBUTE),
|
onInactive: () => setSceneDrawn(false),
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
onFail: (e) => console.warn('Background scene unavailable:', e),
|
onFail: (e) => console.warn('Background scene unavailable:', e),
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
dispose();
|
dispose();
|
||||||
root.removeAttribute(SCENE_ACTIVE_ATTRIBUTE);
|
setSceneDrawn(false);
|
||||||
};
|
};
|
||||||
}, [config, enabled]);
|
}, [config, enabled]);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,40 +1,40 @@
|
||||||
# Background scene
|
# 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
|
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.
|
means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene.
|
||||||
|
|
||||||
- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, onBake?, 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). Each of four ridge layers is a function of world-x (`ridge/ridgeWorld.ts` `profile`:
|
null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) on the host
|
||||||
ridged multifractal value noise, each octave folded at its crest and weighted by the previous one, domain-warped; one
|
canvas at the viewport's size in canvas pixels, then the stars baked into it, a twinkle overlay canvas for the swinging ones
|
||||||
function, a parameter row per layer; nothing repeats). World-x is baked in chunks (1.2 viewport widths, integer pixels)
|
(`ridge/stars.ts`), the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`).
|
||||||
onto plain 2D canvases over a baked sky gradient on the host canvas. Per layer a track holds three chunk canvases: two
|
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 window can reach and one ahead. The first view bakes only the first chunk of each layer; the others are baked in
|
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
|
||||||
tasks of about 6 ms (`setTimeout`; a chunk is baked, put on a canvas with its in-scatter, and blurred in column bands, each sized from the last band's time). Per frame the only motion is the
|
(`index.ts`).
|
||||||
compositor sliding the track with a CSS transform (a Web Animation of `translate3d`, one chunk long, `fill: forwards`,
|
- Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness.
|
||||||
150-420 s per viewport width, farther is slower); when it finishes the chunks move one slot left and the track restarts
|
`tier: 'still'` paints the sky and stars and adds no overlay, no rain and no loop.
|
||||||
at 0 in the same task (no jump), and the canvas that left is baked with the next stretch of world. A second animation
|
|
||||||
sways the whole rig (up to 5% of the width sideways, 3% of the height down, 150 s loop): the slow yaw and pitch.
|
|
||||||
No script runs per frame. The host canvas and the layers' parent must be positioned and the canvas should fill the parent.
|
|
||||||
- `ridge/ridgeBake.ts` is the pixel function (pure, no DOM): per column the crest's slope gives a normal, lit against the
|
|
||||||
sun (`sunDirection`: x = 0.9 sin(2 pi \* `sunAzimuth`), so the sun is toward +x for azimuth 0 to 0.5, strongest at 0.25, toward -x for 0.5 to 1; with no `sunAzimuth` the face lighting falls back to 0.3 and the in-scatter is off); the face under it has a light-to-haze gradient, erosion
|
|
||||||
streaks (a folded noise at gully width, darker with steepness) and a lit rim on the crest. Contrast scales with
|
|
||||||
`transmittance`; the base colour, haze and blur are the aerial perspective below, not redone.
|
|
||||||
- Paused when the tab is hidden; under `prefers-reduced-motion` the layers are painted but never played.
|
|
||||||
`tier: 'still'` flattens sky and layers into the host canvas at once and leaves no extra elements.
|
|
||||||
- Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over
|
- Cadence guard: for the first 2 s after start (after 5 warm-up frames) rAF intervals are sampled; if their p95 is over
|
||||||
33 ms the scene flattens to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling
|
33 ms the scene settles to a still image (`ridge/probe.ts`) and stops. `?probe=1` (or `probe: true`) keeps sampling
|
||||||
and shows `n / median / p95` in a corner readout.
|
and shows `n / median / p95` in a corner readout.
|
||||||
- `ridge/skyColour.ts` `skyColours()` is the one place sky colours come from: a fixed dusk placeholder until Void's
|
- `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host
|
||||||
`src/sky/sun.js` `light()` lands (PR #20); replace its body, keep the signature.
|
passes `ridgeSkyFor` (skyForState.ts) instead.
|
||||||
- Aerial perspective (`ridge/ridgeWorld.ts` `AERIAL`, `transmittance`, `layerColour`, `edgeBlur`, `scatterAlpha`) is applied
|
- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry,
|
||||||
once while the layers are baked, from the `SkyColours` the one seam returns (`sunAzimuth` optional: omit it for no
|
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
|
||||||
in-scatter). Layer distance d = 1 - depth; transmittance T = exp(-1.6 d) (0.24 / 0.37 / 0.58 / 1.00 far to near); colour is
|
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
|
||||||
`T * ground + (1 - T) * haze`, then chroma drops by `0.5 (1 - T)`; the edge is blurred up to 2 px (canvas pixels at DPR 1,
|
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,
|
||||||
via the 2D `filter`, skipped where unsupported, e.g. Safari); a faint warm in-scatter (at most 0.16 alpha) peaks at the
|
`ridge/Backdrop.ts` `loadBackdrop`: every card's two files fetched and decoded straight (no premultiply, no colour management), then
|
||||||
sun's azimuth in world-x (two incommensurate cosines, so not periodic). Nothing runs per frame. The in-scatter lobe is
|
`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
|
||||||
painted into each chunk, so it drifts with the layer rather than staying fixed under the sun; that is a known
|
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
|
||||||
approximation until the sun is a real, fixed light.
|
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`).
|
- `harness/scene/bundle.cjs <out> ridge` builds a standalone page (`?tier=`, `?probe=1`).
|
||||||
- Not yet measured on a phone: see the PR description.
|
- Not yet measured on a phone: see the PR description.
|
||||||
|
|
||||||
|
|
@ -48,43 +48,10 @@ Integration (a canvas under the app, `startBackgroundScene`, `login()` when the
|
||||||
are later cuts. This PR is the render core plus the contract the host needs: flag, tier, failure
|
are later cuts. This PR is the render core plus the contract the host needs: flag, tier, failure
|
||||||
callbacks and the creature sizing rule. Nothing has drawn a creature.
|
callbacks and the creature sizing rule. Nothing has drawn a creature.
|
||||||
|
|
||||||
## Terrain scene (`style: 'terrain'`): the baked sky
|
## Ridge scene: Vienna and the weather
|
||||||
|
|
||||||
`terrain/` draws a Phacelle-displaced grid under a sky read from Void's bake (`src/sky/baked.ts`, layout in
|
|
||||||
`src/sky/README.md`); nothing is vendored. `terrainSky.ts` reads each moment's `sun.{elevation_deg, azimuth_deg,
|
|
||||||
color_linear}`, `ambient_linear` and `horizon_hex`; `terrainScatter.ts` decodes `baked.scatter` and uploads `sky_view` as an
|
|
||||||
RGB16F 3D texture (the transmittance table stays on the CPU, for the sun's colour at an elevation the bake does not hold).
|
|
||||||
Both fragment shaders sample it: `SKY_FRAG` for the sky, `GRID_FRAG` for the haze, which is the sky's colour at the horizon in the
|
|
||||||
fragment's azimuth, so far ground fades into the sky behind it at dusk too.
|
|
||||||
|
|
||||||
Page URL: `?sky=midnight|noonday` picks a bake; `?sun=<elevation deg>&az=<deg from north>` puts the sun anywhere between them
|
|
||||||
(`skyAtSun`: baked transmittance for the sun's colour, ambient and horizon blended from the midnight bake to the noonday one as
|
|
||||||
the sun climbs from -8 to 25 degrees). `?sun=` wins over `?sky=`.
|
|
||||||
|
|
||||||
Without WebGL2 (`createTerrainScene` returns null) the door mounts `terrain/TerrainSky2D.ts` on the same canvas: the sky alone, painted once on a
|
|
||||||
96 px wide 2D canvas from `skyColour` (the CPU twin of `SKY_FRAG`, same `?sky=` `?sun=` `?az=` choice via `chooseSky`), the star layer on
|
|
||||||
top when the sky is dark, nothing moving, no sun disc. Below the horizon the image continues in the horizon's colour. A canvas that already
|
|
||||||
holds a GL context gives no 2D one, so a GL failure after context creation (compile, framebuffer) still ends in the CSS ground.
|
|
||||||
|
|
||||||
- Sky: `1 - exp(-SKY_EXPOSURE * radiance)` plus a night glow (the midnight horizon colour, `nightness` 1 below -4 degrees, 0 above 4), a
|
|
||||||
sun disc from the sun's colour, and a +-0.5/255 dither on the 8-bit output. The table is single scattering only (no ground bounce,
|
|
||||||
no multiple scattering), so the noon horizon is pale yellow-green and a sun just under the horizon colours the whole sky orange,
|
|
||||||
where the real one keeps a blue-violet zenith. Within `HORIZON_FLOOR` (1.5 degrees) of the horizon the sky takes one flat colour,
|
|
||||||
because the table dips toward the ground there and would draw a seam against the haze.
|
|
||||||
- Stars: faded by the sun's elevation, `starGain` 1 below -12 degrees (where the table goes dark), 0 above -6, smooth between;
|
|
||||||
the field is placed against the midnight gradient and no longer gated on the sky being dark. At a baked sky that is the same as
|
|
||||||
before (midnight shows, noonday does not).
|
|
||||||
- Changed numbers: haze colour (was the gradient's horizon stop; now the scattered sky), ambient (was the gradient's zenith stop
|
|
||||||
x `AMBIENT_GAIN` 0.25 x `NIGHT_LIFT` up to 4; now `ambient_linear` as baked, so midnight's fill is about 2.5 to 3.5 times darker than
|
|
||||||
the lifted one). `HAZE_K` (0.0004 per metre) is unchanged.
|
|
||||||
|
|
||||||
## Ridge scene: Vienna, the real horizon and the weather
|
|
||||||
|
|
||||||
The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E
|
The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E
|
||||||
(`ridge/vienna.ts`). Its farthest layer is the real horizon of that viewpoint, standing still under the sun: `ridge/viennaHorizon.json`,
|
(`ridge/vienna.ts`).
|
||||||
baked by `scripts/bake-horizon.py` from Copernicus DEM GLO-30 (nine 1 degree tiles, about 380 MB, kept out of the repo). The file carries its
|
|
||||||
own `source` block with the dataset, tiles, licence and the attribution the licence requires. Its elevation range is 2.1 degrees, so the
|
|
||||||
layer draws the shape of the ring stretched to a fixed relief, not its scale.
|
|
||||||
|
|
||||||
The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear.
|
The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear.
|
||||||
The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit
|
The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit
|
||||||
|
|
@ -92,7 +59,7 @@ The browser never calls a weather service. `weather.json` is written by Eureka's
|
||||||
glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file fetched more than 30 minutes ago, or holding an observation more than 40 minutes old, or from another station, is a clear
|
glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file fetched more than 30 minutes ago, or holding an observation more than 40 minutes old, or from another station, is a clear
|
||||||
sky. Rain is the gauge; cloud is an estimate from the global radiation against Haurwitz's clear-sky value, cross-checked by the sunshine
|
sky. Rain is the gauge; cloud is an estimate from the global radiation against Haurwitz's clear-sky value, cross-checked by the sunshine
|
||||||
duration, with the humidity as the fallback when the sun is low (`ridge/weatherFeed.ts`). The weather draws a cloud deck in the sky
|
duration, with the humidity as the fallback when the sun is low (`ridge/weatherFeed.ts`). The weather draws a cloud deck in the sky
|
||||||
(`ridge/clouds.ts`), thickens the layers' valley mist, and lays tiled rain streaks over everything (`ridge/rain.ts`, compositor-driven, none in a still).
|
(`ridge/clouds.ts`) and lays tiled rain streaks over the sky (`ridge/rain.ts`, compositor-driven, none in a still).
|
||||||
|
|
||||||
## Entry points
|
## Entry points
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import React, { MouseEventHandler, useState } from 'react';
|
import React, { MouseEventHandler, useEffect, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Box,
|
Box,
|
||||||
config,
|
config,
|
||||||
|
|
@ -14,24 +14,19 @@ import {
|
||||||
import FocusTrap from 'focus-trap-react';
|
import FocusTrap from 'focus-trap-react';
|
||||||
import { stopPropagation } from '../../utils/keyboard';
|
import { stopPropagation } from '../../utils/keyboard';
|
||||||
import { useSkyState } from '../../hooks/useSkyState';
|
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 {
|
import {
|
||||||
HORIZON_CREDIT,
|
LINES_CREDIT,
|
||||||
|
STARS_CREDIT,
|
||||||
|
terrainCredit,
|
||||||
WEATHER_CREDIT,
|
WEATHER_CREDIT,
|
||||||
WEATHER_CREDIT_URL,
|
WEATHER_CREDIT_URL,
|
||||||
WEATHER_DATASET,
|
WEATHER_DATASET,
|
||||||
} from './ridge/credits';
|
} from './ridge/credits';
|
||||||
import { useClientConfig } from '../../hooks/useClientConfig';
|
import { useClientConfig } from '../../hooks/useClientConfig';
|
||||||
import {
|
|
||||||
getSceneStyleOverride,
|
|
||||||
SERVED_SCENE_STYLES,
|
|
||||||
setSceneStyle,
|
|
||||||
type ServedSceneStyle,
|
|
||||||
} from './sceneStyle';
|
|
||||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||||
|
|
||||||
const STYLE_LABEL: Record<ServedSceneStyle, string> = { terrain: 'Terrain', ridge: 'Ridges' };
|
|
||||||
|
|
||||||
const LABEL: Record<SkyState, string> = {
|
const LABEL: Record<SkyState, string> = {
|
||||||
auto: 'Auto',
|
auto: 'Auto',
|
||||||
day: 'Day',
|
day: 'Day',
|
||||||
|
|
@ -47,10 +42,21 @@ export function SkyStateControl() {
|
||||||
const state = useSkyState();
|
const state = useSkyState();
|
||||||
const [cords, setCords] = useState<RectCords>();
|
const [cords, setCords] = useState<RectCords>();
|
||||||
const backgroundScene = useClientConfig().backgroundScene;
|
const backgroundScene = useClientConfig().backgroundScene;
|
||||||
const configuredStyle = backgroundScene?.style;
|
|
||||||
const sceneStyle: ServedSceneStyle =
|
|
||||||
getSceneStyleOverride() ?? (configuredStyle === 'terrain' ? 'terrain' : 'ridge');
|
|
||||||
|
|
||||||
|
const place = backgroundScene?.place;
|
||||||
|
const [credit, setCredit] = useState<string>();
|
||||||
|
const ridgeOn = !!backgroundScene && backgroundScene.style !== 'raymarch';
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ridgeOn) return undefined;
|
||||||
|
let live = true;
|
||||||
|
loadManifest(import.meta.env.BASE_URL, place).then(
|
||||||
|
(m) => live && setCredit(terrainCredit(m)),
|
||||||
|
() => live && setCredit(undefined)
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
live = false;
|
||||||
|
};
|
||||||
|
}, [ridgeOn, place]);
|
||||||
const open: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
const open: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||||
setCords(evt.currentTarget.getBoundingClientRect());
|
setCords(evt.currentTarget.getBoundingClientRect());
|
||||||
};
|
};
|
||||||
|
|
@ -83,7 +89,7 @@ export function SkyStateControl() {
|
||||||
role="menuitemradio"
|
role="menuitemradio"
|
||||||
aria-checked={state === s}
|
aria-checked={state === s}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setSkyState(s);
|
pickSkyState(s);
|
||||||
setCords(undefined);
|
setCords(undefined);
|
||||||
}}
|
}}
|
||||||
after={state === s ? <Icon size="100" src={Icons.Check} /> : undefined}
|
after={state === s ? <Icon size="100" src={Icons.Check} /> : undefined}
|
||||||
|
|
@ -93,37 +99,7 @@ export function SkyStateControl() {
|
||||||
</Box>
|
</Box>
|
||||||
</MenuItem>
|
</MenuItem>
|
||||||
))}
|
))}
|
||||||
{backgroundScene && (
|
{ridgeOn && (
|
||||||
<>
|
|
||||||
<Text
|
|
||||||
size="L400"
|
|
||||||
priority="300"
|
|
||||||
style={{ padding: `${config.space.S200} ${config.space.S200} 0` }}
|
|
||||||
>
|
|
||||||
Background
|
|
||||||
</Text>
|
|
||||||
{SERVED_SCENE_STYLES.map((st) => (
|
|
||||||
<MenuItem
|
|
||||||
key={st}
|
|
||||||
size="300"
|
|
||||||
variant="Surface"
|
|
||||||
radii="300"
|
|
||||||
role="menuitemradio"
|
|
||||||
aria-checked={sceneStyle === st}
|
|
||||||
onClick={() => {
|
|
||||||
setCords(undefined);
|
|
||||||
if (st !== sceneStyle) setSceneStyle(st);
|
|
||||||
}}
|
|
||||||
after={sceneStyle === st ? <Icon size="100" src={Icons.Check} /> : undefined}
|
|
||||||
>
|
|
||||||
<Box grow="Yes">
|
|
||||||
<Text size="T300">{STYLE_LABEL[st]}</Text>
|
|
||||||
</Box>
|
|
||||||
</MenuItem>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{backgroundScene && sceneStyle === 'ridge' && (
|
|
||||||
<Box
|
<Box
|
||||||
direction="Column"
|
direction="Column"
|
||||||
gap="100"
|
gap="100"
|
||||||
|
|
@ -132,6 +108,11 @@ export function SkyStateControl() {
|
||||||
<Text size="L400" priority="300">
|
<Text size="L400" priority="300">
|
||||||
Data
|
Data
|
||||||
</Text>
|
</Text>
|
||||||
|
{credit && (
|
||||||
|
<Text size="T200" priority="300">
|
||||||
|
{credit}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
<Text size="T200" priority="300">
|
<Text size="T200" priority="300">
|
||||||
Datenquelle: GeoSphere Austria -{' '}
|
Datenquelle: GeoSphere Austria -{' '}
|
||||||
<a href={WEATHER_CREDIT_URL} target="_blank" rel="noreferrer noopener">
|
<a href={WEATHER_CREDIT_URL} target="_blank" rel="noreferrer noopener">
|
||||||
|
|
@ -140,7 +121,10 @@ export function SkyStateControl() {
|
||||||
. {WEATHER_DATASET}.
|
. {WEATHER_DATASET}.
|
||||||
</Text>
|
</Text>
|
||||||
<Text size="T200" priority="300">
|
<Text size="T200" priority="300">
|
||||||
{HORIZON_CREDIT}
|
{STARS_CREDIT}.
|
||||||
|
</Text>
|
||||||
|
<Text size="T200" priority="300">
|
||||||
|
{LINES_CREDIT}.
|
||||||
</Text>
|
</Text>
|
||||||
</Box>
|
</Box>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -2,14 +2,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { atStandardTime } from './standardTime.testkit';
|
import { atStandardTime } from './standardTime.testkit';
|
||||||
import type { Scene } from './Scene';
|
import type { Scene } from './Scene';
|
||||||
import { startBackgroundScene } from './index';
|
import { startBackgroundScene } from './index';
|
||||||
import { setSkyClock, setSkyState } from './skyState';
|
import { pickSkyState, setSkyClock, setSkyState } from './skyState';
|
||||||
import { ridgeSkyFor } from './skyForState';
|
import { ridgeSkyFor } from './skyForState';
|
||||||
|
import { forgetManifests } from './ridge/manifest';
|
||||||
|
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
|
||||||
|
import { FALLBACK_VIEW } from './ridge/view';
|
||||||
|
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(),
|
createRidgeScene: vi.fn(),
|
||||||
createScene: vi.fn(),
|
createScene: vi.fn(),
|
||||||
|
loadBackdrop: vi.fn(),
|
||||||
}));
|
}));
|
||||||
vi.mock('./ridge/Ridge', () => ({ createRidgeScene }));
|
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 }));
|
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
|
// 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
|
// draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is
|
||||||
|
|
@ -20,9 +29,11 @@ vi.mock('./skyForState', async (importOriginal) => {
|
||||||
return {
|
return {
|
||||||
...actual,
|
...actual,
|
||||||
ridgeSkyFor: (...args: Parameters<typeof actual.ridgeSkyFor>) => {
|
ridgeSkyFor: (...args: Parameters<typeof actual.ridgeSkyFor>) => {
|
||||||
if (args.length !== 1) return actual.ridgeSkyFor(...args);
|
const [state, view] = args;
|
||||||
if (!baked.has(args[0])) baked.set(args[0], actual.ridgeSkyFor(args[0]));
|
// One bake per state and place; the view is the one owner of the place, so it is part of what a sky is.
|
||||||
return baked.get(args[0]) as ReturnType<typeof actual.ridgeSkyFor>;
|
const key = `${state}@${JSON.stringify(view.place)}`;
|
||||||
|
if (!baked.has(key)) baked.set(key, actual.ridgeSkyFor(...args));
|
||||||
|
return baked.get(key) as ReturnType<typeof actual.ridgeSkyFor>;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
@ -40,6 +51,35 @@ const microtasks = (n: number) =>
|
||||||
(p) => p.then(() => undefined),
|
(p) => p.then(() => undefined),
|
||||||
Promise.resolve()
|
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 fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() });
|
||||||
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
|
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
|
||||||
|
|
||||||
|
|
@ -50,6 +90,7 @@ beforeEach(() => {
|
||||||
setSkyState('auto');
|
setSkyState('auto');
|
||||||
createRidgeScene.mockReset();
|
createRidgeScene.mockReset();
|
||||||
createScene.mockReset();
|
createScene.mockReset();
|
||||||
|
loadBackdrop.mockReset();
|
||||||
});
|
});
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
setSkyClock();
|
setSkyClock();
|
||||||
|
|
@ -62,7 +103,9 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
createRidgeScene.mockReturnValue(fakeScene());
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
const scene = await startBackgroundScene(config, caps, { canvas });
|
const scene = await startBackgroundScene(config, caps, { canvas });
|
||||||
expect(createRidgeScene).toHaveBeenCalledOnce();
|
expect(createRidgeScene).toHaveBeenCalledOnce();
|
||||||
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night').top));
|
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
|
||||||
|
hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
|
||||||
|
);
|
||||||
scene?.dispose();
|
scene?.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -81,7 +124,9 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
setSkyState('night');
|
setSkyState('night');
|
||||||
createRidgeScene.mockReturnValue(fakeScene());
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
const scene = await startBackgroundScene(config, caps, { canvas });
|
const scene = await startBackgroundScene(config, caps, { canvas });
|
||||||
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night').top));
|
expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(
|
||||||
|
hex(ridgeSkyFor('night', FALLBACK_VIEW).top)
|
||||||
|
);
|
||||||
scene?.dispose();
|
scene?.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -93,7 +138,9 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
setSkyState('day');
|
setSkyState('day');
|
||||||
await flush();
|
await flush();
|
||||||
expect(first.dispose).toHaveBeenCalledOnce();
|
expect(first.dispose).toHaveBeenCalledOnce();
|
||||||
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day').top));
|
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
|
||||||
|
hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
|
||||||
|
);
|
||||||
scene?.dispose();
|
scene?.dispose();
|
||||||
expect(second.dispose).toHaveBeenCalledOnce();
|
expect(second.dispose).toHaveBeenCalledOnce();
|
||||||
});
|
});
|
||||||
|
|
@ -106,7 +153,9 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
const scene = await started;
|
const scene = await started;
|
||||||
await flush();
|
await flush();
|
||||||
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day').top));
|
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
|
||||||
|
hex(ridgeSkyFor('day', FALLBACK_VIEW).top)
|
||||||
|
);
|
||||||
expect(a.dispose).toHaveBeenCalledOnce();
|
expect(a.dispose).toHaveBeenCalledOnce();
|
||||||
scene?.dispose();
|
scene?.dispose();
|
||||||
expect(b.dispose).toHaveBeenCalledOnce();
|
expect(b.dispose).toHaveBeenCalledOnce();
|
||||||
|
|
@ -186,7 +235,7 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
// The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else.
|
// The sky last built is dusk's, and it is the live scene: a login reaches it and nothing else.
|
||||||
const built = createRidgeScene.mock.calls.length;
|
const built = createRidgeScene.mock.calls.length;
|
||||||
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe(
|
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top)).toBe(
|
||||||
hex(ridgeSkyFor('dusk').top)
|
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
|
||||||
);
|
);
|
||||||
const live = scenes[built - 1];
|
const live = scenes[built - 1];
|
||||||
scene?.login();
|
scene?.login();
|
||||||
|
|
@ -209,12 +258,14 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
await flush();
|
await flush();
|
||||||
// The initial build and one rebuild, for dusk; day's rebuild stood down before building anything.
|
// The initial build and one rebuild, for dusk; day's rebuild stood down before building anything.
|
||||||
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('dusk').top));
|
expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(
|
||||||
|
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
|
||||||
|
);
|
||||||
scene?.dispose();
|
scene?.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
// A second sky change `ticks` microtasks after the first. True when it landed mid-build: the build for the first
|
// A second sky change `ticks` microtasks after the first. True when it landed mid-build: the build for the first
|
||||||
// change finished, was found stale and dropped (never shown), and only the newest sky was announced.
|
// change finished loading, was found stale and was never made (so it never showed or spoke), and only the newest sky was announced.
|
||||||
const changeAfter = async (ticks: number) => {
|
const changeAfter = async (ticks: number) => {
|
||||||
createRidgeScene.mockReset();
|
createRidgeScene.mockReset();
|
||||||
setSkyState('auto');
|
setSkyState('auto');
|
||||||
|
|
@ -229,7 +280,7 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
const at = `at ${ticks} microtasks`;
|
const at = `at ${ticks} microtasks`;
|
||||||
const built = createRidgeScene.mock.calls.length;
|
const built = createRidgeScene.mock.calls.length;
|
||||||
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe(
|
expect(hex(createRidgeScene.mock.calls[built - 1][0].sky.top), at).toBe(
|
||||||
hex(ridgeSkyFor('dusk').top)
|
hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)
|
||||||
);
|
);
|
||||||
// The newest build is live, every earlier one disposed exactly once, and only the live one is shown.
|
// The newest build is live, every earlier one disposed exactly once, and only the live one is shown.
|
||||||
const live = [a, b, c][built - 1];
|
const live = [a, b, c][built - 1];
|
||||||
|
|
@ -241,7 +292,7 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
});
|
});
|
||||||
scene?.dispose();
|
scene?.dispose();
|
||||||
expect(live.dispose, at).toHaveBeenCalledOnce();
|
expect(live.dispose, at).toHaveBeenCalledOnce();
|
||||||
return built === 3 && onActive.mock.calls.length === 1;
|
return built === 2 && onActive.mock.calls.length === 1;
|
||||||
};
|
};
|
||||||
|
|
||||||
it('a sky change at any point of a build leaves only the newer build live; the stale one is disposed', async () => {
|
it('a sky change at any point of a build leaves only the newer build live; the stale one is disposed', async () => {
|
||||||
|
|
@ -255,7 +306,7 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
// This can fail after a correct refactor that changes the await count in create/skyKey and moves every offset
|
// This can fail after a correct refactor that changes the await count in create/skyKey and moves every offset
|
||||||
// off the build. Then widen the range of offsets until some land again; do not weaken the assertion.
|
// off the build. Then widen the range of offsets until some land again; do not weaken the assertion.
|
||||||
expect(landed.length, 'at least one offset must land mid-build').toBeGreaterThan(0);
|
expect(landed.length, 'at least one offset must land mid-build').toBeGreaterThan(0);
|
||||||
});
|
}, 30000);
|
||||||
|
|
||||||
it('leaves the ray-march scene alone: it has one fixed dusk', async () => {
|
it('leaves the ray-march scene alone: it has one fixed dusk', async () => {
|
||||||
const inner = fakeScene() as unknown as Scene;
|
const inner = fakeScene() as unknown as Scene;
|
||||||
|
|
@ -282,3 +333,409 @@ describe('startBackgroundScene follows the sky state', () => {
|
||||||
expect(onCompileFail).toHaveBeenCalledWith(boom);
|
expect(onCompileFail).toHaveBeenCalledWith(boom);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('the ridge planes', () => {
|
||||||
|
const served = (over: Record<string, unknown> = {}) => {
|
||||||
|
const files: Record<string, unknown> = {
|
||||||
|
'/public/ridge/index.json': wireIndex,
|
||||||
|
'/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(),
|
||||||
|
'/public/ridge/graz-def456def456/manifest.json': wireManifest({
|
||||||
|
place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' },
|
||||||
|
}),
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(async (url: string) =>
|
||||||
|
url in files
|
||||||
|
? { ok: true, status: 200, json: async () => files[url] }
|
||||||
|
: { ok: false, status: 404, json: async () => ({}) }
|
||||||
|
)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
beforeEach(() => forgetManifests());
|
||||||
|
|
||||||
|
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 { 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);
|
||||||
|
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();
|
||||||
|
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');
|
||||||
|
forgetManifests();
|
||||||
|
(await startBackgroundScene({ ...config, place: 'nowhere' }, caps, { canvas }))?.dispose();
|
||||||
|
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna');
|
||||||
|
});
|
||||||
|
|
||||||
|
const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => {
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail });
|
||||||
|
const opts = createRidgeScene.mock.calls[0][0];
|
||||||
|
expect(scene).not.toBeNull();
|
||||||
|
expect(opts.backdrop).toBeUndefined();
|
||||||
|
expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
|
||||||
|
expect(onPlanesFail).toHaveBeenCalledOnce();
|
||||||
|
expect(onCompileFail).not.toHaveBeenCalled();
|
||||||
|
scene?.dispose();
|
||||||
|
};
|
||||||
|
|
||||||
|
it('a 404 manifest gives the sky-only scene with the fallback view, one onPlanesFail and no onCompileFail', async () => {
|
||||||
|
served({ '/public/ridge/index.json': undefined });
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }))
|
||||||
|
);
|
||||||
|
loader();
|
||||||
|
await skyOnly();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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) => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => (url.endsWith('index.json') ? wireIndex : wireManifest()),
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
loader().ctl.fail = true;
|
||||||
|
forgetManifests();
|
||||||
|
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();
|
||||||
|
setSkyState('day');
|
||||||
|
await flush();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
|
expect(onPlanesFail).toHaveBeenCalledOnce();
|
||||||
|
expect(onCompileFail).not.toHaveBeenCalled();
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the ridge cards and the live scene', () => {
|
||||||
|
const serve = (manifest: Record<string, unknown> = wireManifest()) =>
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(async (url: string) => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => (url.endsWith('index.json') ? wireIndex : manifest),
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
beforeEach(() => forgetManifests());
|
||||||
|
|
||||||
|
it('says nothing about cards when they load', async () => {
|
||||||
|
serve();
|
||||||
|
loader();
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const onPlanesFail = vi.fn();
|
||||||
|
const onPlanesOk = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
|
||||||
|
setSkyState('day');
|
||||||
|
await flush();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
|
expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true);
|
||||||
|
expect(onPlanesFail).not.toHaveBeenCalled();
|
||||||
|
expect(onPlanesOk).not.toHaveBeenCalled();
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lights the cards again for the new sky on a sky-change rebuild, never otherwise', async () => {
|
||||||
|
serve();
|
||||||
|
const { ctl } = loader();
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas });
|
||||||
|
expect(ctl.calls.map((s) => s.state)).toEqual(['night']);
|
||||||
|
setSkyState('night'); // the sky already drawn: no rebuild, no lighting
|
||||||
|
await flush();
|
||||||
|
expect(ctl.calls).toHaveLength(1);
|
||||||
|
setSkyState('day');
|
||||||
|
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();
|
||||||
|
loader();
|
||||||
|
const [a, b] = [fakeScene(), fakeScene()];
|
||||||
|
createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b);
|
||||||
|
const w = wireManifest() as any;
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas });
|
||||||
|
// 'auto' at midnight and 'night' are one sky: no rebuild, while the place is the one drawn.
|
||||||
|
setSkyState('night');
|
||||||
|
await flush();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledOnce();
|
||||||
|
forgetManifests();
|
||||||
|
serve({ ...w, place: { ...w.place, id: 'graz' } });
|
||||||
|
setSkyState('auto');
|
||||||
|
await flush();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
|
expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz');
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reads the weather against the manifest place's sun, not the fallback place's", async () => {
|
||||||
|
const w = wireManifest() as any;
|
||||||
|
const place = { ...w.place, id: 'weather-place', lat: -33, lon: -163.65, tz_h: -11 };
|
||||||
|
const now = new Date('2026-11-11T10:50:00Z');
|
||||||
|
const wx = {
|
||||||
|
fetched_at: '2026-11-11T10:45:00Z',
|
||||||
|
observed_at: '2026-11-11T10:40:00Z',
|
||||||
|
station: 11035,
|
||||||
|
precip_mm_10min: 0,
|
||||||
|
humidity_pct: 60,
|
||||||
|
sunshine_s_10min: null,
|
||||||
|
glow_wm2: 100,
|
||||||
|
attribution: WEATHER_ATTRIBUTION,
|
||||||
|
};
|
||||||
|
vi.stubGlobal(
|
||||||
|
'fetch',
|
||||||
|
vi.fn(async (url: string) => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () =>
|
||||||
|
url.endsWith('weather.json')
|
||||||
|
? wx
|
||||||
|
: url.endsWith('index.json')
|
||||||
|
? wireIndex
|
||||||
|
: { ...w, place },
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
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
|
||||||
|
);
|
||||||
|
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 } = loader();
|
||||||
|
ctl.fail = true;
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas });
|
||||||
|
const opts = createRidgeScene.mock.calls[0][0];
|
||||||
|
expect(opts.backdrop).toBeUndefined();
|
||||||
|
expect(opts.sky.physical.view).toBe(FALLBACK_VIEW);
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a rebuild keeps the old scene until the new planes have loaded, then swaps', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
const first = fakeScene();
|
||||||
|
const second = fakeScene();
|
||||||
|
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second);
|
||||||
|
const onActive = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
|
||||||
|
d.ctl.hold = true;
|
||||||
|
setSkyState('day');
|
||||||
|
await flush();
|
||||||
|
expect(d.ctl.pending.length).toBeGreaterThan(0);
|
||||||
|
expect(first.dispose).not.toHaveBeenCalled();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledOnce();
|
||||||
|
scene?.login();
|
||||||
|
expect(first.login).toHaveBeenCalledOnce();
|
||||||
|
await d.release();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
|
expect(first.dispose).toHaveBeenCalledOnce();
|
||||||
|
expect(second.dispose).not.toHaveBeenCalled();
|
||||||
|
expect(onActive).toHaveBeenCalledOnce();
|
||||||
|
expect(second.login).toHaveBeenCalledOnce(); // replayed onto the swapped-in scene
|
||||||
|
scene?.dispose();
|
||||||
|
expect(second.dispose).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a build that fails after the scene is disposed makes nothing and says nothing', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const onPlanesFail = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
|
||||||
|
d.ctl.hold = true;
|
||||||
|
d.ctl.fail = true;
|
||||||
|
setSkyState('day');
|
||||||
|
await flush();
|
||||||
|
scene?.dispose();
|
||||||
|
await d.release();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledOnce();
|
||||||
|
expect(onPlanesFail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a superseded build that fails does not speak for the live scene, which has planes', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const onPlanesFail = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail });
|
||||||
|
d.ctl.hold = true;
|
||||||
|
d.ctl.fail = true;
|
||||||
|
setSkyState('day'); // stale: its decodes will reject
|
||||||
|
await flush();
|
||||||
|
d.ctl.fail = false;
|
||||||
|
setSkyState('dusk'); // the live one: its decodes will succeed
|
||||||
|
await flush();
|
||||||
|
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
|
||||||
|
await flush();
|
||||||
|
expect(onPlanesFail).not.toHaveBeenCalled();
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a superseded build that finishes after the newer one touches nothing of the live scene', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
const [first, second, third] = [fakeScene(), fakeScene(), fakeScene()];
|
||||||
|
createRidgeScene
|
||||||
|
.mockReturnValueOnce(first)
|
||||||
|
.mockReturnValueOnce(second)
|
||||||
|
.mockReturnValueOnce(third);
|
||||||
|
const onActive = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
|
||||||
|
d.ctl.hold = true;
|
||||||
|
setSkyState('day'); // stale: its decodes are held until after the newer build is live
|
||||||
|
await flush();
|
||||||
|
const dayDecodes = d.ctl.pending.splice(0);
|
||||||
|
setSkyState('dusk');
|
||||||
|
await flush();
|
||||||
|
const duskDecodes = d.ctl.pending.splice(0);
|
||||||
|
expect(dayDecodes.length).toBeGreaterThan(0);
|
||||||
|
expect(duskDecodes.length).toBeGreaterThan(0);
|
||||||
|
duskDecodes.forEach((s) => s());
|
||||||
|
await flush();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
|
expect(first.dispose).toHaveBeenCalledOnce();
|
||||||
|
expect(onActive).toHaveBeenCalledOnce();
|
||||||
|
dayDecodes.forEach((s) => s()); // the stale build finishes last
|
||||||
|
await flush();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledTimes(2);
|
||||||
|
expect(second.dispose).not.toHaveBeenCalled(); // the live scene is not disposed by a build that lost
|
||||||
|
expect(onActive).toHaveBeenCalledOnce();
|
||||||
|
scene?.login();
|
||||||
|
expect(second.login).toHaveBeenCalledOnce();
|
||||||
|
scene?.dispose();
|
||||||
|
expect(second.dispose).toHaveBeenCalledOnce();
|
||||||
|
expect(third.dispose).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a build that finishes after dispose makes nothing, shows nothing and disposes nothing twice', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
const first = fakeScene();
|
||||||
|
createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(fakeScene());
|
||||||
|
const onActive = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onActive });
|
||||||
|
d.ctl.hold = true;
|
||||||
|
setSkyState('day');
|
||||||
|
await flush();
|
||||||
|
scene?.dispose();
|
||||||
|
await d.release();
|
||||||
|
expect(createRidgeScene).toHaveBeenCalledOnce();
|
||||||
|
expect(first.dispose).toHaveBeenCalledOnce();
|
||||||
|
expect(onActive).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null);
|
||||||
|
const onPlanesFail = vi.fn();
|
||||||
|
const onInactive = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive });
|
||||||
|
d.ctl.fail = true;
|
||||||
|
setSkyState('day');
|
||||||
|
await flush();
|
||||||
|
expect(onInactive).toHaveBeenCalledOnce();
|
||||||
|
expect(onPlanesFail).not.toHaveBeenCalled();
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tells the host when the live scene loses its planes and when it gets them back', async () => {
|
||||||
|
serve();
|
||||||
|
const d = loader();
|
||||||
|
d.ctl.fail = true;
|
||||||
|
createRidgeScene.mockReturnValue(fakeScene());
|
||||||
|
const onPlanesFail = vi.fn();
|
||||||
|
const onPlanesOk = vi.fn();
|
||||||
|
const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk });
|
||||||
|
expect(onPlanesFail).toHaveBeenCalledOnce();
|
||||||
|
setSkyState('day'); // still failing: the host is not told twice
|
||||||
|
await flush();
|
||||||
|
expect(onPlanesFail).toHaveBeenCalledOnce();
|
||||||
|
expect(onPlanesOk).not.toHaveBeenCalled();
|
||||||
|
d.ctl.fail = false;
|
||||||
|
setSkyState('dusk');
|
||||||
|
await flush();
|
||||||
|
expect(onPlanesOk).toHaveBeenCalledOnce();
|
||||||
|
expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined();
|
||||||
|
d.ctl.fail = true;
|
||||||
|
setSkyState('night');
|
||||||
|
await flush();
|
||||||
|
expect(onPlanesFail).toHaveBeenCalledTimes(2);
|
||||||
|
scene?.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,13 @@
|
||||||
import type { Scene, SceneOptions } from './Scene';
|
import type { Scene, SceneOptions } from './Scene';
|
||||||
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
|
import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './tier';
|
||||||
import { debugOverlaysAllowed } from './debugOverlays';
|
import { debugOverlaysAllowed } from './debugOverlays';
|
||||||
import { getSkyState, subscribe } from './skyState';
|
import { getConstellationLines, getSkyState, subscribe } from './skyState';
|
||||||
import type { SkyState } 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';
|
||||||
|
|
||||||
export type { Scene, SceneStats } from './Scene';
|
export type { Scene, SceneStats } from './Scene';
|
||||||
export type { SceneStyle, SceneTier } from './tier';
|
export type { SceneStyle, SceneTier } from './tier';
|
||||||
|
|
@ -14,52 +19,112 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
|
||||||
onInactive?: () => void;
|
onInactive?: () => void;
|
||||||
/** A rebuild made a scene again: the host lets it show. */
|
/** A rebuild made a scene again: the host lets it show. */
|
||||||
onActive?: () => void;
|
onActive?: () => void;
|
||||||
|
/** 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;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */
|
/** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */
|
||||||
const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`;
|
const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`;
|
||||||
|
|
||||||
async function create(
|
/**
|
||||||
|
* The baked place's manifest, or why there is none. Its View is the one owner of the sun's place and the camera for the weather, the sky,
|
||||||
|
* the rebuild key and the planes; a scene with no manifest has FALLBACK_VIEW.
|
||||||
|
*/
|
||||||
|
async function manifestOf(
|
||||||
|
config: BackgroundSceneConfig | undefined
|
||||||
|
): Promise<{ manifest: RidgeManifest | null; fail: Error | null }> {
|
||||||
|
try {
|
||||||
|
return { manifest: await loadManifest(import.meta.env.BASE_URL, config?.place), fail: null };
|
||||||
|
} catch (e) {
|
||||||
|
return { manifest: null, fail: e instanceof Error ? e : new Error(String(e)) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */
|
||||||
|
interface Prepared {
|
||||||
|
make: () => Scene | null;
|
||||||
|
/** Why this scene is the sky alone, when the baked planes did not load; null when it has planes or none are asked for. */
|
||||||
|
planesFail: Error | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function prepare(
|
||||||
config: BackgroundSceneConfig | undefined,
|
config: BackgroundSceneConfig | undefined,
|
||||||
options: StartOptions & { tier: SceneTier; debug?: boolean },
|
options: StartOptions & { tier: SceneTier; debug?: boolean },
|
||||||
state: SkyState
|
state: SkyState
|
||||||
): Promise<Scene | null> {
|
): Promise<Prepared> {
|
||||||
|
// Whatever throws in making the scene is a compile failure, as whatever throws in loading it.
|
||||||
|
const guarded = (make: () => Scene | null): Prepared => ({
|
||||||
|
planesFail: null,
|
||||||
|
make: () => {
|
||||||
|
try {
|
||||||
|
return make();
|
||||||
|
} catch (e) {
|
||||||
|
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
try {
|
try {
|
||||||
// Loaded here, with the scenes, so the main chunk does not carry the terrain sky or the baked tables.
|
// Loaded here, with the scenes, so the main chunk does not carry the ridge sky or the baked tables.
|
||||||
const { loadWeather, ridgeSkyFor, terrainSkyFor } = await import('./skyForState');
|
const { loadWeather, ridgeSkyFor } = await import('./skyForState');
|
||||||
if (config?.style === 'raymarch') return (await import('./Scene')).createScene(options);
|
if (config?.style === 'raymarch') {
|
||||||
if (config?.style === 'terrain') {
|
const { createScene } = await import('./Scene');
|
||||||
const { createTerrainScene } = await import('./terrain/Terrain');
|
return guarded(() => createScene(options));
|
||||||
const sky = terrainSkyFor(state);
|
|
||||||
const scene = createTerrainScene({ ...options, ...sky });
|
|
||||||
// No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground.
|
|
||||||
if (scene) return scene;
|
|
||||||
const { createTerrainSkyScene } = await import('./terrain/TerrainSky2D');
|
|
||||||
return createTerrainSkyScene({ ...options, ...sky });
|
|
||||||
}
|
}
|
||||||
const { createRidgeScene } = await import('./ridge/Ridge');
|
const { createRidgeScene } = await import('./ridge/Ridge');
|
||||||
await loadWeather(weatherUrl());
|
const { manifest, fail } = await manifestOf(config);
|
||||||
return createRidgeScene({ ...options, sky: ridgeSkyFor(state) });
|
await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place);
|
||||||
|
// The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per
|
||||||
|
// frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone.
|
||||||
|
let backdrop: Backdrop | null = null;
|
||||||
|
let sky: SkyColours | undefined;
|
||||||
|
let planesFail: Error | null = fail;
|
||||||
|
if (manifest) {
|
||||||
|
try {
|
||||||
|
const manifestSky = ridgeSkyFor(state, manifest.view);
|
||||||
|
sky = manifestSky;
|
||||||
|
const { loadBackdrop } = await import('./ridge/Backdrop');
|
||||||
|
backdrop = await loadBackdrop(
|
||||||
|
manifest,
|
||||||
|
manifestSky.physical as NonNullable<typeof manifestSky.physical>
|
||||||
|
);
|
||||||
|
if (!backdrop) throw new Error('ridge cards did not load');
|
||||||
|
} catch (e) {
|
||||||
|
backdrop = null;
|
||||||
|
sky = undefined;
|
||||||
|
planesFail = e instanceof Error ? e : new Error(String(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const made = guarded(() =>
|
||||||
|
createRidgeScene({
|
||||||
|
...options,
|
||||||
|
sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW),
|
||||||
|
backdrop: backdrop ?? undefined,
|
||||||
|
lines: getConstellationLines(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return { ...made, planesFail };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
|
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
|
||||||
return null;
|
return { make: () => null, planesFail: null };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky
|
* What a rebuild is for: the sky options the scene would be built from. A change of choice that draws the same sky
|
||||||
* (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild; the page URL steers
|
* (Day picked while the clock says day, 'auto' to the fixed state it resolves to) is not a rebuild.
|
||||||
* only 'auto' (`terrainSkyFor`), so there the two differ and the key says so.
|
|
||||||
*/
|
*/
|
||||||
async function skyKey(
|
async function skyKey(
|
||||||
config: BackgroundSceneConfig | undefined,
|
config: BackgroundSceneConfig | undefined,
|
||||||
state: SkyState
|
state: SkyState
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
try {
|
try {
|
||||||
const { loadWeather, ridgeSkyKey, terrainSkyFor } = await import('./skyForState');
|
const { loadWeather, ridgeSkyKey } = await import('./skyForState');
|
||||||
if (config?.style === 'terrain') return JSON.stringify(terrainSkyFor(state));
|
const view = (await manifestOf(config)).manifest?.view ?? FALLBACK_VIEW;
|
||||||
await loadWeather(weatherUrl());
|
await loadWeather(weatherUrl(), view.place);
|
||||||
return ridgeSkyKey(state);
|
return ridgeSkyKey(state, view);
|
||||||
} catch {
|
} catch {
|
||||||
// The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure).
|
// The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure).
|
||||||
return null;
|
return null;
|
||||||
|
|
@ -69,12 +134,11 @@ async function skyKey(
|
||||||
/**
|
/**
|
||||||
* The client's one door to the scene. When the tier resolves to 'off' nothing is imported and no
|
* The client's one door to the scene. When the tier resolves to 'off' nothing is imported and no
|
||||||
* canvas context is requested; otherwise the scene code loads on demand, so it stays out of the
|
* canvas context is requested; otherwise the scene code loads on demand, so it stays out of the
|
||||||
* main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' or 'terrain' (which falls back to its
|
* main chunk. `config.style` picks the scene: the ridges unless it says 'raymarch' (any other value, an old 'terrain' included, is the ridges). Null means
|
||||||
* sky alone, `terrain/TerrainSky2D.ts`, where WebGL2 is missing). Null means
|
|
||||||
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
|
* "keep the CSS ground", including when that chunk fails to load (offline, stale deploy): the
|
||||||
* failure goes to onCompileFail and nothing throws.
|
* failure goes to onCompileFail and nothing throws.
|
||||||
*
|
*
|
||||||
* The ridge and terrain scenes bake their sky once, so they follow the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by
|
* The ridge scene bakes its sky once, so it follows the sky (`skyState.ts`: the choice, resolved, so 'auto' follows the clock) by
|
||||||
* being rebuilt on the same canvas when it changes: the door subscribes on start and the returned
|
* being rebuilt on the same canvas when it changes: the door subscribes on start and the returned
|
||||||
* scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is
|
* scene's `dispose` unsubscribes. The pull-back restarts from the tree; a later `login()` is
|
||||||
* replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state.
|
* replayed on the new scene. The ray-march scene has one fixed dusk and ignores the state.
|
||||||
|
|
@ -87,11 +151,20 @@ export async function startBackgroundScene(
|
||||||
const tier = resolveTier(config, capabilities);
|
const tier = resolveTier(config, capabilities);
|
||||||
if (tier === 'off') return null;
|
if (tier === 'off') return null;
|
||||||
const debug = debugOverlaysAllowed(config);
|
const debug = debugOverlaysAllowed(config);
|
||||||
const build = (state: SkyState) => create(config, { ...options, tier, debug }, state);
|
// What the host was last told of the planes: only the live scene speaks, and only when its state changes.
|
||||||
|
let planesFailed = false;
|
||||||
|
const announce = (planesFail: Error | null) => {
|
||||||
|
if (planesFail && !planesFailed) options.onPlanesFail?.(planesFail);
|
||||||
|
if (!planesFail && planesFailed) options.onPlanesOk?.();
|
||||||
|
planesFailed = planesFail !== null;
|
||||||
|
};
|
||||||
|
const prepared = (state: SkyState) => prepare(config, { ...options, tier, debug }, state);
|
||||||
const state = getSkyState();
|
const state = getSkyState();
|
||||||
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state);
|
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state);
|
||||||
const first = await build(state);
|
const firstReady = await prepared(state);
|
||||||
|
const first = firstReady.make();
|
||||||
if (!first || config?.style === 'raymarch') return first;
|
if (!first || config?.style === 'raymarch') return first;
|
||||||
|
announce(firstReady.planesFail);
|
||||||
|
|
||||||
let inner: Scene | null = first;
|
let inner: Scene | null = first;
|
||||||
let built = key0;
|
let built = key0;
|
||||||
|
|
@ -108,14 +181,14 @@ export async function startBackgroundScene(
|
||||||
generation += 1;
|
generation += 1;
|
||||||
const mine = generation;
|
const mine = generation;
|
||||||
built = key;
|
built = key;
|
||||||
|
// The old scene stays up while the next one loads; a build that is stale or after dispose is never made, so it never speaks.
|
||||||
|
const ready = await prepared(next);
|
||||||
|
if (disposed || mine !== generation) return;
|
||||||
inner?.dispose();
|
inner?.dispose();
|
||||||
inner = null;
|
inner = null;
|
||||||
const scene = await build(next);
|
const scene = ready.make();
|
||||||
if (disposed || mine !== generation) {
|
|
||||||
scene?.dispose();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
inner = scene;
|
inner = scene;
|
||||||
|
if (scene) announce(ready.planesFail);
|
||||||
if (!scene) options.onInactive?.();
|
if (!scene) options.onInactive?.();
|
||||||
else {
|
else {
|
||||||
options.onActive?.();
|
options.onActive?.();
|
||||||
|
|
|
||||||
90
src/app/features/scene/ridge/Backdrop.test.ts
Normal file
90
src/app/features/scene/ridge/Backdrop.test.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { loadBackdrop } from './Backdrop';
|
||||||
|
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 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('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()
|
||||||
|
);
|
||||||
|
made.forEach((b) =>
|
||||||
|
expect(b.opts).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' })
|
||||||
|
);
|
||||||
|
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('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);
|
||||||
|
});
|
||||||
|
});
|
||||||
55
src/app/features/scene/ridge/Backdrop.ts
Normal file
55
src/app/features/scene/ridge/Backdrop.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
// 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;
|
||||||
|
/** Nearest first, as the manifest lists them. */
|
||||||
|
cards: LitCard[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackdropDeps {
|
||||||
|
fetchBlob: (url: string) => Promise<Blob>;
|
||||||
|
light: (manifest: RidgeManifest, bitmaps: CardBitmaps[], sky: PhysicalSky) => LitCard[];
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
sky: PhysicalSky,
|
||||||
|
deps: Partial<BackdropDeps> = {}
|
||||||
|
): Promise<Backdrop | null> {
|
||||||
|
const get = deps.fetchBlob ?? fetchBlob;
|
||||||
|
const light = deps.light ?? lightCards;
|
||||||
|
const open: ImageBitmap[] = [];
|
||||||
|
try {
|
||||||
|
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?.());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,24 +1,16 @@
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { createRidgeScene } from './Ridge';
|
import { createRidgeScene } from './Ridge';
|
||||||
import { bakeSlice, BakeParams, layerPaint } from './ridgeBake';
|
|
||||||
import { valueNoise, hash2 } from './noise';
|
import { valueNoise, hash2 } from './noise';
|
||||||
import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe';
|
import { FrameSampler, frameStats, SLOW_P95_MS, WARMUP_FRAMES, WINDOW_MS } from './probe';
|
||||||
import {
|
import type { SkyColours } from './skyColour';
|
||||||
AERIAL,
|
import { nightBodies } from './nightBodies';
|
||||||
LAYERS,
|
import { sunAt } from './sunAt';
|
||||||
edgeBlur,
|
import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky';
|
||||||
hazeColour,
|
|
||||||
layerColour,
|
|
||||||
layerSize,
|
|
||||||
profile,
|
|
||||||
ridgeY,
|
|
||||||
scatterAlpha,
|
|
||||||
transmittance,
|
|
||||||
} from './ridgeWorld';
|
|
||||||
import { skyColours, SkyColours } from './skyColour';
|
|
||||||
import { makeStars } from './stars';
|
|
||||||
import { makePhysicalSky } from './physicalSky';
|
|
||||||
import { startBackgroundScene } from '../index';
|
import { startBackgroundScene } from '../index';
|
||||||
|
import { parseManifest } from './manifest';
|
||||||
|
import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture';
|
||||||
|
import type { Backdrop } from './Backdrop';
|
||||||
|
import { cardMotion, FALLBACK_VIEW, windowFor } from './view';
|
||||||
|
|
||||||
describe('noise', () => {
|
describe('noise', () => {
|
||||||
it('is deterministic and in [0, 1)', () => {
|
it('is deterministic and in [0, 1)', () => {
|
||||||
|
|
@ -36,111 +28,6 @@ describe('noise', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('ridge profile', () => {
|
|
||||||
it('stays in [0, 1] for any world-x, negative and far included, and layers differ', () => {
|
|
||||||
for (const spec of LAYERS) {
|
|
||||||
for (let i = -300; i < 300; i += 7) {
|
|
||||||
for (const off of [0, 1234.5, 98765.25]) {
|
|
||||||
const p = profile(spec, i / 50 + off);
|
|
||||||
expect(p).toBeGreaterThanOrEqual(0);
|
|
||||||
expect(p).toBeLessThanOrEqual(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(profile(LAYERS[0], 0.3)).not.toBeCloseTo(profile(LAYERS[1], 0.3), 3);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('ridge tops lie inside the layer band', () => {
|
|
||||||
const size = layerSize(400, 800, 1);
|
|
||||||
for (const spec of LAYERS) {
|
|
||||||
for (let x = -500; x < 5 * size.period; x += 17) {
|
|
||||||
const y = ridgeY(spec, x / size.period, size.height, 800);
|
|
||||||
expect(y).toBeGreaterThanOrEqual(0);
|
|
||||||
expect(y).toBeLessThanOrEqual(size.height);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('layers get darker and slower toward the viewer, and their sizes are integers', () => {
|
|
||||||
const sky = skyColours();
|
|
||||||
const lum = (c: readonly number[]) => c[0] + c[1] + c[2];
|
|
||||||
for (let i = 1; i < LAYERS.length; i += 1) {
|
|
||||||
expect(lum(layerColour(LAYERS[i], sky))).toBeLessThan(lum(layerColour(LAYERS[i - 1], sky)));
|
|
||||||
expect(LAYERS[i].seconds).toBeLessThan(LAYERS[i - 1].seconds);
|
|
||||||
}
|
|
||||||
for (const [w, h, s] of [
|
|
||||||
[393, 851, 2],
|
|
||||||
[1280, 720, 1],
|
|
||||||
[412.5, 915.3, 2],
|
|
||||||
] as const) {
|
|
||||||
const z = layerSize(w, h, s);
|
|
||||||
expect(
|
|
||||||
Number.isInteger(z.period) && Number.isInteger(z.chunk) && Number.isInteger(z.height)
|
|
||||||
).toBe(true);
|
|
||||||
expect(z.chunk).toBeGreaterThan(z.period);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('aerial perspective', () => {
|
|
||||||
const sky = skyColours();
|
|
||||||
const lum = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
|
|
||||||
const chroma = (c: readonly number[]) => Math.max(...c) - Math.min(...c);
|
|
||||||
const far = LAYERS[0];
|
|
||||||
const near = LAYERS[LAYERS.length - 1];
|
|
||||||
|
|
||||||
it('transmittance is Beer-Lambert in distance: 1 at the viewer, exp(-k d) behind, strictly falling', () => {
|
|
||||||
expect(transmittance(near)).toBe(1);
|
|
||||||
for (const l of LAYERS)
|
|
||||||
expect(transmittance(l)).toBeCloseTo(Math.exp(-AERIAL.extinction * (1 - l.depth)), 12);
|
|
||||||
for (let i = 1; i < LAYERS.length; i += 1)
|
|
||||||
expect(transmittance(LAYERS[i])).toBeGreaterThan(transmittance(LAYERS[i - 1]));
|
|
||||||
// two layers' optical depths add: T(a)*T(b) = T(a+b)
|
|
||||||
const t = (d: number) => Math.exp(-AERIAL.extinction * d);
|
|
||||||
expect(t(0.3) * t(0.4)).toBeCloseTo(t(0.7), 12);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the nearest layer is exactly the ground colour; the farthest tends to the haze', () => {
|
|
||||||
expect(layerColour(near, sky)).toEqual([...sky.ground]);
|
|
||||||
const h = hazeColour(sky);
|
|
||||||
const f = layerColour(far, sky);
|
|
||||||
const dist = (a: readonly number[], b: readonly number[]) =>
|
|
||||||
Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
|
|
||||||
expect(dist(f, h)).toBeLessThan(dist(sky.ground, h) * (transmittance(far) + 0.2));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('colour moves toward the haze and loses chroma with distance, beyond what the mix alone does', () => {
|
|
||||||
const h = hazeColour(sky);
|
|
||||||
for (const l of LAYERS.slice(0, -1)) {
|
|
||||||
const t = transmittance(l);
|
|
||||||
const c = layerColour(l, sky);
|
|
||||||
const mixed = [0, 1, 2].map((i) => sky.ground[i] * t + h[i] * (1 - t));
|
|
||||||
expect(chroma(c)).toBeLessThan(chroma(mixed));
|
|
||||||
expect(Math.abs(lum(c) - lum(mixed))).toBeLessThan(1.5); // desaturation keeps luma
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('edge softening grows with distance and is zero at the viewer', () => {
|
|
||||||
expect(edgeBlur(near)).toBe(0);
|
|
||||||
for (let i = 1; i < LAYERS.length; i += 1)
|
|
||||||
expect(edgeBlur(LAYERS[i])).toBeLessThan(edgeBlur(LAYERS[i - 1]));
|
|
||||||
expect(edgeBlur(far)).toBeLessThanOrEqual(AERIAL.blurPx);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('in-scatter is faint, grows with distance, is off without a sun, and never repeats', () => {
|
|
||||||
const az = 0.3;
|
|
||||||
const s = { ...sky, sunAzimuth: az };
|
|
||||||
const lobe = (t: number) => scatterAlpha(far, s, t);
|
|
||||||
expect(lobe(az * 1.9)).toBeGreaterThan(lobe(az * 1.9 + 0.95));
|
|
||||||
for (const period of [1, 1.9, 3.8, 5.7, 19])
|
|
||||||
expect(Math.abs(lobe(0.7 + period) - lobe(0.7))).toBeGreaterThan(1e-4);
|
|
||||||
expect(lobe(az * 1.9)).toBeLessThanOrEqual(AERIAL.scatter);
|
|
||||||
expect(scatterAlpha(near, s, az)).toBe(0);
|
|
||||||
expect(scatterAlpha(LAYERS[1], s, az * 1.9)).toBeLessThan(scatterAlpha(far, s, az * 1.9));
|
|
||||||
expect(scatterAlpha(far, { ...sky, sunAzimuth: undefined }, az)).toBe(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('frame sampler', () => {
|
describe('frame sampler', () => {
|
||||||
const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => {
|
const feed = (s: FrameSampler, dt: number, frames: number, from = 0) => {
|
||||||
let t = from;
|
let t = from;
|
||||||
|
|
@ -242,40 +129,51 @@ function fakeEl(tag = 'div') {
|
||||||
};
|
};
|
||||||
return el;
|
return el;
|
||||||
}
|
}
|
||||||
// A day sky has no stars, so the scene tests below see only the ridge loop; the dusk default
|
// A day sky has no stars, so the scene tests above see only the sky; the dusk default
|
||||||
// carries stars and a twinkle overlay, tested in 'the starfield in the scene'.
|
// carries stars and a twinkle overlay, tested in 'the starfield in the scene'.
|
||||||
const DAY: SkyColours = {
|
const DAY: SkyColours = {
|
||||||
top: [96, 150, 220],
|
top: [96, 150, 220],
|
||||||
mid: [150, 190, 235],
|
mid: [150, 190, 235],
|
||||||
horizon: [240, 215, 190],
|
horizon: [240, 215, 190],
|
||||||
ground: [7, 17, 26],
|
|
||||||
sunAzimuth: 0.3,
|
|
||||||
};
|
};
|
||||||
const draws: string[] = [];
|
const draws: string[] = [];
|
||||||
/** Every ImageData put on any canvas, in order. */
|
const images: unknown[][] = [];
|
||||||
const puts: any[] = [];
|
/** Every RGBA grid the host canvas was painted from (the small canvas's putImageData). */
|
||||||
/** For every drawImage: the source canvas's width as it was at the moment of the draw. */
|
const painted: Uint8ClampedArray[] = [];
|
||||||
const drawnWidths: number[] = [];
|
function ctx() {
|
||||||
function ctx(withFilter = false) {
|
|
||||||
const c: any = {
|
const c: any = {
|
||||||
globalCompositeOperation: 'source-over',
|
|
||||||
createLinearGradient: () => ({ addColorStop: vi.fn() }),
|
createLinearGradient: () => ({ addColorStop: vi.fn() }),
|
||||||
fillRect() {
|
fillRect() {
|
||||||
draws.push(c.globalCompositeOperation === 'source-atop' ? 'scatter' : 'sky');
|
draws.push('sky');
|
||||||
},
|
},
|
||||||
save() {},
|
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() {},
|
rect() {},
|
||||||
clip() {},
|
clip() {},
|
||||||
|
rotate() {},
|
||||||
|
ellipse() {},
|
||||||
createImageData: (w: number, h: number) => ({
|
createImageData: (w: number, h: number) => ({
|
||||||
data: new Uint8ClampedArray(w * h * 4),
|
data: new Uint8ClampedArray(w * h * 4),
|
||||||
width: w,
|
width: w,
|
||||||
height: h,
|
height: h,
|
||||||
}),
|
}),
|
||||||
putImageData: (img: any) => puts.push(img),
|
putImageData(img: { data: Uint8ClampedArray }) {
|
||||||
|
painted.push(img.data);
|
||||||
|
},
|
||||||
beginPath() {},
|
beginPath() {},
|
||||||
moveTo() {},
|
moveTo() {},
|
||||||
stroke() {},
|
stroke() {
|
||||||
|
draws.push('line');
|
||||||
|
},
|
||||||
createRadialGradient: () => ({ addColorStop: vi.fn() }),
|
createRadialGradient: () => ({ addColorStop: vi.fn() }),
|
||||||
lineTo() {},
|
lineTo() {},
|
||||||
closePath() {},
|
closePath() {},
|
||||||
|
|
@ -292,13 +190,16 @@ function ctx(withFilter = false) {
|
||||||
if (c.arcing) c.arcing = false;
|
if (c.arcing) c.arcing = false;
|
||||||
else draws.push('fill');
|
else draws.push('fill');
|
||||||
},
|
},
|
||||||
drawImage: (src: any) => {
|
drawImage(...a: unknown[]) {
|
||||||
drawnWidths.push(src.width);
|
draws.push('image');
|
||||||
draws.push('flatten');
|
images.push(
|
||||||
|
Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation, t: c.t, k: c.k })
|
||||||
|
);
|
||||||
},
|
},
|
||||||
|
globalAlpha: 1,
|
||||||
|
globalCompositeOperation: 'source-over',
|
||||||
set fillStyle(_v: unknown) {},
|
set fillStyle(_v: unknown) {},
|
||||||
};
|
};
|
||||||
if (withFilter) c.filter = 'none';
|
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -310,8 +211,8 @@ let search: string;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
rafQueue = [];
|
rafQueue = [];
|
||||||
draws.length = 0;
|
draws.length = 0;
|
||||||
puts.length = 0;
|
images.length = 0;
|
||||||
drawnWidths.length = 0;
|
painted.length = 0;
|
||||||
search = '';
|
search = '';
|
||||||
motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() };
|
motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() };
|
||||||
doc = Object.assign(new EventTarget(), {
|
doc = Object.assign(new EventTarget(), {
|
||||||
|
|
@ -347,11 +248,6 @@ function host() {
|
||||||
parent.appendChild(canvas);
|
parent.appendChild(canvas);
|
||||||
return { parent, canvas };
|
return { parent, canvas };
|
||||||
}
|
}
|
||||||
/** The rig holds one track per layer, farthest first; each track holds three chunk canvases. */
|
|
||||||
const rigOf = (parent: any) => parent.children.find((c: any) => c.tag === 'div');
|
|
||||||
const tracksOf = (parent: any): any[] => rigOf(parent).children;
|
|
||||||
const animsOf = (parent: any): any[] =>
|
|
||||||
[rigOf(parent), ...tracksOf(parent)].flatMap((e: any) => e.anims);
|
|
||||||
const runFrames = (dt: number, n: number, from = 0) => {
|
const runFrames = (dt: number, n: number, from = 0) => {
|
||||||
let t = from;
|
let t = from;
|
||||||
for (let i = 0; i < n && rafQueue.length; i += 1) {
|
for (let i = 0; i < n && rafQueue.length; i += 1) {
|
||||||
|
|
@ -375,29 +271,27 @@ describe('createRidgeScene', () => {
|
||||||
expect(createRidgeScene({ canvas, tier: 'full', sky: DAY })).toBeNull();
|
expect(createRidgeScene({ canvas, tier: 'full', sky: DAY })).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bakes the sky once, and per layer only the first chunk before the first frame, at integer sizes, farthest first', () => {
|
it('paints the sky once at the viewport in canvas pixels and adds nothing to the page in a clear day', () => {
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
const baked: any[] = [];
|
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, onBake: (b) => baked.push(b) })!;
|
|
||||||
expect(s).not.toBeNull();
|
expect(s).not.toBeNull();
|
||||||
const tracks = tracksOf(parent);
|
expect([canvas.width, canvas.height]).toEqual([800, 1600]);
|
||||||
expect(tracks).toHaveLength(LAYERS.length);
|
|
||||||
tracks.forEach((t: any, i: number) => {
|
|
||||||
expect(t.children).toHaveLength(3);
|
|
||||||
expect(t.animate).toHaveBeenCalledTimes(Number.isFinite(LAYERS[i].seconds) ? 1 : 0);
|
|
||||||
t.children.forEach((c: any) => {
|
|
||||||
expect(Number.isInteger(c.width) && Number.isInteger(c.height)).toBe(true);
|
|
||||||
expect(c.width).toBe(layerSize(400, 800, 2).chunk);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
expect(baked.map((b) => [b.layer, b.chunk, b.first])).toEqual(
|
|
||||||
LAYERS.map((l) => [l.index, 0, true])
|
|
||||||
);
|
|
||||||
expect(draws.filter((d) => d === 'sky')).toHaveLength(1);
|
expect(draws.filter((d) => d === 'sky')).toHaveLength(1);
|
||||||
|
expect(parent.children).toEqual([canvas]);
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('after the layers are painted, a smooth run draws nothing more and ends its rAF loop', () => {
|
it("paints the sky through the camera of the physical sky's own View, not a default one", () => {
|
||||||
|
const { canvas } = host();
|
||||||
|
const physical = makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), 0, ELSEWHERE_VIEW);
|
||||||
|
const s = createRidgeScene({ canvas, tier: 'full', sky: { ...DAY, physical } })!;
|
||||||
|
const want = paintPhysicalSky(physical, 400, 800, windowFor(ELSEWHERE_VIEW, 400, 800).camera);
|
||||||
|
expect(painted).toHaveLength(1);
|
||||||
|
expect(Array.from(painted[0])).toEqual(Array.from(want.data));
|
||||||
|
s.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a smooth run draws nothing more and ends its rAF loop', () => {
|
||||||
const { canvas } = host();
|
const { canvas } = host();
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
||||||
const before = draws.length;
|
const before = draws.length;
|
||||||
|
|
@ -407,53 +301,23 @@ describe('createRidgeScene', () => {
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('p95 over 33 ms across 2 s flattens to a still image and removes the layers', () => {
|
it('p95 over 33 ms across 2 s settles to a still and reports it', () => {
|
||||||
const { parent, canvas } = host();
|
const { canvas } = host();
|
||||||
const onProbe = vi.fn();
|
const onProbe = vi.fn();
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', onProbe, sky: DAY })!;
|
const s = createRidgeScene({ canvas, tier: 'full', onProbe, sky: DAY })!;
|
||||||
runFrames(100, 100);
|
runFrames(100, 100);
|
||||||
expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length);
|
|
||||||
expect(parent.children).toEqual([canvas]);
|
|
||||||
expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true }));
|
expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true }));
|
||||||
expect(rafQueue).toHaveLength(0);
|
expect(rafQueue).toHaveLength(0);
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("'still' tier flattens immediately and never starts a loop", () => {
|
it("'still' tier never starts a loop", () => {
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
createRidgeScene({ canvas, tier: 'still' });
|
createRidgeScene({ canvas, tier: 'still' });
|
||||||
expect(parent.children).toEqual([canvas]);
|
expect(parent.children).toEqual([canvas]);
|
||||||
expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length);
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
expect(rafQueue).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('prefers-reduced-motion: layers are built but never played, and nothing is sampled', () => {
|
|
||||||
motion.matches = true;
|
|
||||||
const { canvas } = host();
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
|
||||||
const anims = animsOf(canvas.parentElement);
|
|
||||||
expect(anims.length).toBe(LAYERS.filter((l) => Number.isFinite(l.seconds)).length + 1); // one drift per drifting layer (the horizon does not) and the sway
|
|
||||||
expect(anims.every((a: any) => a.pause.mock.calls.length > 0)).toBe(true);
|
|
||||||
anims.forEach((a: any) => expect(a.play).not.toHaveBeenCalled());
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('pauses the drift when the tab is hidden and resumes when it is visible', () => {
|
|
||||||
const { parent, canvas } = host();
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
|
||||||
const anims = animsOf(parent);
|
|
||||||
anims.forEach((a: any) => a.pause.mockClear());
|
|
||||||
doc.visibilityState = 'hidden';
|
|
||||||
doc.dispatchEvent(new Event('visibilitychange'));
|
|
||||||
anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
|
|
||||||
anims.forEach((a: any) => a.play.mockClear());
|
|
||||||
doc.visibilityState = 'visible';
|
|
||||||
doc.dispatchEvent(new Event('visibilitychange'));
|
|
||||||
anims.forEach((a: any) => expect(a.play).toHaveBeenCalled());
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('?probe=1 keeps the rAF loop alive and shows median and p95', () => {
|
it('?probe=1 keeps the rAF loop alive and shows median and p95', () => {
|
||||||
search = '?probe=1';
|
search = '?probe=1';
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
|
|
@ -469,9 +333,8 @@ describe('createRidgeScene', () => {
|
||||||
it('?probe=1 does nothing where the overlays are not allowed: no readout, the loop ends', () => {
|
it('?probe=1 does nothing where the overlays are not allowed: no readout, the loop ends', () => {
|
||||||
search = '?probe=1';
|
search = '?probe=1';
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
const before = parent.children.length;
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
||||||
expect(parent.children.length).toBe(before + 1); // the rig
|
expect(parent.children).toEqual([canvas]);
|
||||||
runFrames(16.7, 300);
|
runFrames(16.7, 300);
|
||||||
expect(rafQueue.length).toBe(0);
|
expect(rafQueue.length).toBe(0);
|
||||||
s.dispose();
|
s.dispose();
|
||||||
|
|
@ -485,31 +348,19 @@ describe('createRidgeScene', () => {
|
||||||
(window as any).innerHeight = 0;
|
(window as any).innerHeight = 0;
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY });
|
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY });
|
||||||
expect(s).not.toBeNull();
|
expect(s).not.toBeNull();
|
||||||
expect(parent.children).toEqual([canvas]);
|
|
||||||
expect(draws).toHaveLength(0);
|
expect(draws).toHaveLength(0);
|
||||||
// Still zero: a resize does not paint either.
|
// Still zero: a resize does not paint either.
|
||||||
window.dispatchEvent(new Event('resize'));
|
window.dispatchEvent(new Event('resize'));
|
||||||
await new Promise((r) => setTimeout(r, 300));
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
expect(parent.children).toEqual([canvas]);
|
expect(draws).toHaveLength(0);
|
||||||
(window as any).innerWidth = 400;
|
(window as any).innerWidth = 400;
|
||||||
(window as any).innerHeight = 800;
|
(window as any).innerHeight = 800;
|
||||||
window.dispatchEvent(new Event('resize'));
|
window.dispatchEvent(new Event('resize'));
|
||||||
await new Promise((r) => setTimeout(r, 300));
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
expect(tracksOf(parent)).toHaveLength(LAYERS.length);
|
|
||||||
expect(draws.filter((d) => d === 'sky')).toHaveLength(1);
|
expect(draws.filter((d) => d === 'sky')).toHaveLength(1);
|
||||||
s!.dispose();
|
s!.dispose();
|
||||||
expect(parent.children).toEqual([canvas]);
|
expect(parent.children).toEqual([canvas]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('dispose cancels the loop, the animations and the layers', () => {
|
|
||||||
const { parent, canvas } = host();
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
|
||||||
const anims = animsOf(parent);
|
|
||||||
s.dispose();
|
|
||||||
anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
|
|
||||||
expect(parent.children).toEqual([canvas]);
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('the door', () => {
|
describe('the door', () => {
|
||||||
|
|
@ -530,95 +381,38 @@ describe('the door', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('aerial perspective in the scene', () => {
|
|
||||||
it('is baked once: one scatter fill per hazy layer, none per frame, the nearest layer has none', () => {
|
|
||||||
const { canvas } = host();
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
|
||||||
expect(draws.filter((d) => d === 'scatter')).toHaveLength(LAYERS.length - 1);
|
|
||||||
const before = draws.length;
|
|
||||||
runFrames(16.7, 400);
|
|
||||||
expect(draws.length).toBe(before);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a sky without a sun bakes no scatter', () => {
|
|
||||||
const { canvas } = host();
|
|
||||||
const s = createRidgeScene({
|
|
||||||
canvas,
|
|
||||||
tier: 'full',
|
|
||||||
sky: { ...DAY, sunAzimuth: undefined },
|
|
||||||
})!;
|
|
||||||
expect(draws.filter((d) => d === 'scatter')).toHaveLength(0);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('softens with the canvas filter where it exists, blur scaled by DPR, from pixels baked past the chunk edges', () => {
|
|
||||||
const { parent, canvas } = host();
|
|
||||||
const filters: string[] = [];
|
|
||||||
const orig = (document as any).createElement;
|
|
||||||
(document as any).createElement = (t: string) => {
|
|
||||||
const el = orig(t);
|
|
||||||
el.getContext = vi.fn(() => {
|
|
||||||
const c = ctx(true);
|
|
||||||
let f = 'none';
|
|
||||||
Object.defineProperty(c, 'filter', {
|
|
||||||
get: () => f,
|
|
||||||
set: (v: string) => {
|
|
||||||
f = v;
|
|
||||||
filters.push(v);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return c;
|
|
||||||
});
|
|
||||||
return el;
|
|
||||||
};
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
|
||||||
const blurs = filters.filter((f) => f !== 'none');
|
|
||||||
expect(blurs).toHaveLength(LAYERS.length - 1); // nearest is sharp
|
|
||||||
expect(blurs[0]).toBe(`blur(${edgeBlur(LAYERS[0]) * 2}px)`); // DPR 2
|
|
||||||
expect(parent.children).toHaveLength(2); // sky canvas and the rig
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("'still' tier keeps the sky and flattens the aerial layers without extra elements", () => {
|
|
||||||
const { parent, canvas } = host();
|
|
||||||
createRidgeScene({ canvas, tier: 'still' });
|
|
||||||
expect(parent.children).toEqual([canvas]);
|
|
||||||
expect(draws.filter((d) => d === 'sky')).toHaveLength(1);
|
|
||||||
expect(draws.filter((d) => d === 'flatten')).toHaveLength(LAYERS.length);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the starfield in the scene', () => {
|
describe('the starfield in the scene', () => {
|
||||||
const count = (kind: string) => draws.filter((d) => d === kind).length;
|
const count = (kind: string) => draws.filter((d) => d === kind).length;
|
||||||
const night = {
|
// 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.
|
||||||
...DAY,
|
const t = new Date('2026-12-04T00:00:00Z');
|
||||||
top: [10, 14, 40],
|
const physical = makePhysicalSky('night', t, 0, FALLBACK_VIEW, sunAt(FALLBACK_VIEW.place, t));
|
||||||
mid: [30, 34, 80],
|
const night: SkyColours = { ...DAY, physical };
|
||||||
horizon: [60, 50, 90],
|
const N = nightBodies(
|
||||||
} as SkyColours;
|
physical,
|
||||||
const N = makeStars(night, 400, 800).length;
|
paintPhysicalSky(physical, 400, 800, windowFor(FALLBACK_VIEW, 400, 800).camera),
|
||||||
|
false
|
||||||
|
).stars.length;
|
||||||
const hear = (name: string) => {
|
const hear = (name: string) => {
|
||||||
const calls = motion.addEventListener.mock.calls.filter((c: any[]) => c[0] === name);
|
const calls = motion.addEventListener.mock.calls.filter((c: any[]) => c[0] === name);
|
||||||
return calls[calls.length - 1][1] as () => void;
|
return calls[calls.length - 1][1] as () => void;
|
||||||
};
|
};
|
||||||
// Everything but the overlay's own marks: the bake and the ridges.
|
// Everything but the overlay's own marks: the sky and its stars.
|
||||||
const baked = () => draws.filter((d) => d !== 'twinkle' && d !== 'clear').length;
|
const baked = () => draws.filter((d) => d !== 'twinkle' && d !== 'clear').length;
|
||||||
|
|
||||||
it('bakes every star once into the sky; per frame only the overlay is touched', () => {
|
it('bakes every star once into the sky; per frame only the overlay is touched', () => {
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
|
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
|
||||||
expect(count('star')).toBe(N);
|
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, under the ridges
|
expect(parent.children[1].anims).toHaveLength(0); // the overlay, above the sky
|
||||||
expect(parent.children).toHaveLength(3);
|
expect(parent.children).toHaveLength(2);
|
||||||
const before = baked();
|
const before = baked();
|
||||||
runFrames(16.7, 300); // 5 s at 60 fps; the overlay repaints at 20 fps
|
runFrames(16.7, 300); // 5 s at 60 fps; the overlay repaints at 20 fps
|
||||||
expect(baked()).toBe(before);
|
expect(baked()).toBe(before);
|
||||||
expect(count('clear')).toBeGreaterThan(60);
|
expect(count('clear')).toBeGreaterThan(60);
|
||||||
expect(count('clear')).toBeLessThanOrEqual(101);
|
expect(count('clear')).toBeLessThanOrEqual(101);
|
||||||
// each pass paints at most SLOTS stars
|
// each pass paints at most SLOTS stars, each as its cover and the star again
|
||||||
expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 32);
|
expect(count('twinkle')).toBeLessThanOrEqual(count('clear') * 64);
|
||||||
expect(count('twinkle')).toBeGreaterThan(0);
|
expect(count('twinkle')).toBeGreaterThan(0);
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
|
|
@ -627,7 +421,7 @@ describe('the starfield in the scene', () => {
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
||||||
expect(count('star')).toBe(0);
|
expect(count('star')).toBe(0);
|
||||||
expect(parent.children).toHaveLength(2);
|
expect(parent.children).toHaveLength(1);
|
||||||
runFrames(16.7, 60);
|
runFrames(16.7, 60);
|
||||||
expect(count('clear')).toBe(0);
|
expect(count('clear')).toBe(0);
|
||||||
s.dispose();
|
s.dispose();
|
||||||
|
|
@ -687,13 +481,12 @@ describe('the starfield in the scene', () => {
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('flattening to a still (slow frames) drops the overlay and leaves every star baked under the ridges', () => {
|
it('flattening to a still (slow frames) drops the overlay and leaves every star baked into the sky', () => {
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
|
const s = createRidgeScene({ canvas, tier: 'full', sky: night })!;
|
||||||
runFrames(100, 100);
|
runFrames(100, 100);
|
||||||
expect(parent.children).toEqual([canvas]);
|
expect(parent.children).toEqual([canvas]);
|
||||||
expect(count('star')).toBe(N);
|
expect(count('star')).toBe(N);
|
||||||
expect(draws.indexOf('flatten')).toBeGreaterThan(draws.lastIndexOf('star'));
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
expect(rafQueue).toHaveLength(0);
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
|
|
@ -707,125 +500,14 @@ describe('the starfield in the scene', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('endless drift: chunks baked on demand and recycled', () => {
|
|
||||||
const size = layerSize(400, 800, 2); // the fake host: 400 x 800 CSS px at DPR 2
|
|
||||||
const until = async (cond: () => boolean) => {
|
|
||||||
const t0 = Date.now();
|
|
||||||
while (!cond()) {
|
|
||||||
if (Date.now() - t0 > 10000) throw new Error('timed out waiting for the background bakes');
|
|
||||||
await new Promise((r) => setTimeout(r, 5));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
/** The pixels chunk `m` of layer `li` must hold: the pure bake of its world columns, no blur. */
|
|
||||||
const expected = (li: number, m: number) => {
|
|
||||||
const p: BakeParams = {
|
|
||||||
spec: LAYERS[li],
|
|
||||||
sky: DAY,
|
|
||||||
period: size.period,
|
|
||||||
scale: 2,
|
|
||||||
viewH: 1600,
|
|
||||||
rows: size.height,
|
|
||||||
bandH: size.height,
|
|
||||||
px0: m * size.chunk,
|
|
||||||
cols: size.chunk,
|
|
||||||
};
|
|
||||||
const out = new Uint8ClampedArray(p.cols * p.rows * 4);
|
|
||||||
bakeSlice(out, p, layerPaint(p.spec, DAY), 0, p.cols);
|
|
||||||
return Buffer.from(out.buffer);
|
|
||||||
};
|
|
||||||
/** Each distinct ImageData put, in order of first appearance: one per baked chunk. */
|
|
||||||
const baked = () => [...new Set(puts)].map((img) => Buffer.from(img.data.buffer));
|
|
||||||
const start = () => {
|
|
||||||
const { parent, canvas } = host();
|
|
||||||
const records: any[] = [];
|
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, onBake: (b) => records.push(b) })!;
|
|
||||||
return { parent, s, records };
|
|
||||||
};
|
|
||||||
|
|
||||||
it('bakes every chunk from its own world columns: no offset, the next chunk continues the last', async () => {
|
|
||||||
const { s, records } = start();
|
|
||||||
await until(() => records.length === 3 * LAYERS.length);
|
|
||||||
// First view: chunk 0 of each layer; then, per layer in queue order, chunks 1 and 2.
|
|
||||||
const order = [
|
|
||||||
...LAYERS.map((l) => [l.index, 0]),
|
|
||||||
...LAYERS.flatMap((l) => [
|
|
||||||
[l.index, 1],
|
|
||||||
[l.index, 2],
|
|
||||||
]),
|
|
||||||
];
|
|
||||||
expect(records.map((r) => [r.layer, r.chunk])).toEqual(order);
|
|
||||||
const imgs = baked();
|
|
||||||
expect(imgs).toHaveLength(order.length);
|
|
||||||
order.forEach(([li, m], i) => expect(imgs[i].equals(expected(li, m))).toBe(true));
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('when the drift animation ends, the chunks move one slot left and the track restarts', async () => {
|
|
||||||
const { parent, s, records } = start();
|
|
||||||
await until(() => records.length === 3 * LAYERS.length);
|
|
||||||
const track = tracksOf(parent)[1]; // the first layer that drifts: the horizon, [0], stands still
|
|
||||||
const [e0, e1, e2] = track.children;
|
|
||||||
const first = track.anims[0];
|
|
||||||
// One chunk of drift, not one viewport: the track slides by the width of a chunk.
|
|
||||||
expect(first.keyframes[1].transform).toContain(`${-size.chunk / 2}px`);
|
|
||||||
expect(track.animate).toHaveBeenCalledTimes(1);
|
|
||||||
first.finish();
|
|
||||||
expect(first.cancel).toHaveBeenCalled();
|
|
||||||
expect(track.animate).toHaveBeenCalledTimes(2);
|
|
||||||
const w = size.chunk / 2;
|
|
||||||
expect([e1.style.left, e2.style.left, e0.style.left]).toEqual(['0px', `${w}px`, `${2 * w}px`]);
|
|
||||||
expect(track.anims[1].keyframes[1].transform).toContain(`${-w}px`);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the canvas that left is baked with the next stretch of world, and each rotation after it, without end', async () => {
|
|
||||||
const { parent, s, records } = start();
|
|
||||||
await until(() => records.length === 3 * LAYERS.length);
|
|
||||||
const track = tracksOf(parent)[1];
|
|
||||||
const done = () => records.filter((r) => r.layer === 1).map((r) => r.chunk);
|
|
||||||
for (let m = 3; m <= 5; m += 1) {
|
|
||||||
track.anims[track.anims.length - 1].finish();
|
|
||||||
await until(() => done().includes(m));
|
|
||||||
}
|
|
||||||
expect(done()).toEqual([0, 1, 2, 3, 4, 5]);
|
|
||||||
// The pixels of chunks 3 to 5 are the world's, not a repeat of an earlier one.
|
|
||||||
const imgs = baked();
|
|
||||||
const layer1 = imgs.filter((_, i) => records[i].layer === 1);
|
|
||||||
[3, 4, 5].forEach((m, k) => expect(layer1[3 + k].equals(expected(1, m))).toBe(true));
|
|
||||||
expect(layer1[3].equals(layer1[0])).toBe(false);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('with the blur, each chunk is blurred from a scratch canvas of its own width: seams stay opaque and exact', async () => {
|
|
||||||
const orig = (document as any).createElement;
|
|
||||||
(document as any).createElement = (tag: string) => {
|
|
||||||
const el = orig(tag);
|
|
||||||
el.getContext = vi.fn(() => ctx(true));
|
|
||||||
return el;
|
|
||||||
};
|
|
||||||
const { s, records } = start();
|
|
||||||
await until(() => records.length === 3 * LAYERS.length);
|
|
||||||
const want = new Set(
|
|
||||||
LAYERS.filter((l) => edgeBlur(l) > 0).map(
|
|
||||||
(l) => size.chunk + 2 * Math.ceil(3 * edgeBlur(l) * 2)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
expect(want.size).toBeGreaterThan(1); // the layers' pads differ, which is what a shared canvas gets wrong
|
|
||||||
// Every blur reads a source exactly as wide as that chunk's padded bake, at the moment of the draw.
|
|
||||||
expect(new Set(drawnWidths)).toEqual(want);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('rain in the scene', () => {
|
describe('rain in the scene', () => {
|
||||||
const rainy = (w: number): SkyColours => ({
|
const rainy = (w: number): SkyColours => ({
|
||||||
...DAY,
|
...DAY,
|
||||||
physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w),
|
physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w, FALLBACK_VIEW),
|
||||||
});
|
});
|
||||||
const rainEls = (parent: any) =>
|
const rainEls = (parent: any) => parent.children.filter((c: any) => c.tag === 'div');
|
||||||
parent.children.filter((c: any) => c.tag === 'div' && c !== rigOf(parent));
|
|
||||||
|
|
||||||
it('lays one falling tile per rain layer over the ridges when it rains, each slid by its own height on the compositor', () => {
|
it('lays one falling tile per rain layer over the sky when it rains, each slid by its own height on the compositor', () => {
|
||||||
const { parent, canvas } = host();
|
const { parent, canvas } = host();
|
||||||
const s = createRidgeScene({ canvas, tier: 'full', sky: rainy(1) })!;
|
const s = createRidgeScene({ canvas, tier: 'full', sky: rainy(1) })!;
|
||||||
const els = rainEls(parent);
|
const els = rainEls(parent);
|
||||||
|
|
@ -860,3 +542,232 @@ describe('rain in the scene', () => {
|
||||||
s.dispose();
|
s.dispose();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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 night: SkyColours = {
|
||||||
|
...DAY,
|
||||||
|
top: [10, 14, 40],
|
||||||
|
mid: [30, 34, 80],
|
||||||
|
horizon: [60, 50, 90],
|
||||||
|
physical: makePhysicalSky('night', new Date('2026-06-21T22:40:00Z'), 1, FALLBACK_VIEW),
|
||||||
|
};
|
||||||
|
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: 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);
|
||||||
|
parent.children.forEach((c: any) => {
|
||||||
|
expect(c.style.zIndex).toBeUndefined();
|
||||||
|
expect(c.style.position).not.toBe('fixed');
|
||||||
|
});
|
||||||
|
s.dispose();
|
||||||
|
expect(parent.children).toEqual([canvas]);
|
||||||
|
});
|
||||||
|
|
||||||
|
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: litCards() })!;
|
||||||
|
const rig = rigOf(parent);
|
||||||
|
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(${-reachPx}px,0,0) scale(${scale})` },
|
||||||
|
{ transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
|
||||||
|
]);
|
||||||
|
expect(options).toMatchObject({
|
||||||
|
duration: 75000,
|
||||||
|
iterations: Infinity,
|
||||||
|
direction: 'alternate',
|
||||||
|
easing: 'ease-in-out',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// 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: litCards() })!;
|
||||||
|
expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards
|
||||||
|
s.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: 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());
|
||||||
|
motion.matches = true;
|
||||||
|
motion.addEventListener.mock.calls
|
||||||
|
.filter((c: any[]) => c[0] === 'change')
|
||||||
|
.forEach((c: any[]) => c[1]());
|
||||||
|
anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
|
||||||
|
motion.matches = false;
|
||||||
|
anims.forEach((a: any) => a.pause.mockClear());
|
||||||
|
doc.visibilityState = 'hidden';
|
||||||
|
doc.dispatchEvent(new Event('visibilitychange'));
|
||||||
|
anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled());
|
||||||
|
s.dispose();
|
||||||
|
anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled());
|
||||||
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
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([
|
||||||
|
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(parent.children).toEqual([canvas]);
|
||||||
|
});
|
||||||
|
|
||||||
|
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: litCards() });
|
||||||
|
runFrames(100, 400);
|
||||||
|
expect(images.filter((a) => (a[0] as any).id)).toHaveLength(3);
|
||||||
|
expect(parent.children).toEqual([canvas]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('with no backdrop it is the sky alone', () => {
|
||||||
|
const { parent, canvas } = host();
|
||||||
|
createRidgeScene({ canvas, tier: 'full', sky: DAY });
|
||||||
|
expect(parent.children).toEqual([canvas]);
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the scene wiring', () => {
|
||||||
|
it('sizes from the window when the canvas has no client size', () => {
|
||||||
|
const { canvas } = host();
|
||||||
|
canvas.clientWidth = 0;
|
||||||
|
canvas.clientHeight = 0;
|
||||||
|
(window as any).innerWidth = 300;
|
||||||
|
(window as any).innerHeight = 500;
|
||||||
|
createRidgeScene({ canvas, tier: 'full', sky: DAY })!.dispose();
|
||||||
|
expect([canvas.width, canvas.height]).toEqual([600, 1000]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a burst of resizes rebuilds once, after 250 ms, and not after dispose', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
(window as any).setTimeout = setTimeout;
|
||||||
|
const { canvas } = host();
|
||||||
|
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
||||||
|
const skies = () => draws.filter((d) => d === 'sky').length;
|
||||||
|
window.dispatchEvent(new Event('resize'));
|
||||||
|
vi.advanceTimersByTime(200);
|
||||||
|
window.dispatchEvent(new Event('resize'));
|
||||||
|
vi.advanceTimersByTime(200);
|
||||||
|
expect(skies()).toBe(1);
|
||||||
|
vi.advanceTimersByTime(60);
|
||||||
|
expect(skies()).toBe(2);
|
||||||
|
s.dispose();
|
||||||
|
window.dispatchEvent(new Event('resize'));
|
||||||
|
vi.advanceTimersByTime(1000);
|
||||||
|
expect(skies()).toBe(2);
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,32 +1,14 @@
|
||||||
/* eslint-disable no-param-reassign -- the bake writes into the canvases and layer records it is handed */
|
|
||||||
import type { Scene, SceneOptions } from '../Scene';
|
import type { Scene, SceneOptions } from '../Scene';
|
||||||
import { overlayRequested } from '../debugOverlays';
|
import { overlayRequested } from '../debugOverlays';
|
||||||
import { FrameSampler, FrameStats } from './probe';
|
import { FrameSampler, FrameStats } from './probe';
|
||||||
import { skyColours, SkyColours, Srgb } from './skyColour';
|
import { skyColours, SkyColours, Srgb } from './skyColour';
|
||||||
import { paintSky as paintPhysicalSky } from './physicalSky';
|
import { paintSky as paintPhysicalSky } from './physicalSky';
|
||||||
import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars';
|
import { cardMotion, windowFor } from './view';
|
||||||
import { bakeSlice, BakeParams, layerPaint } from './ridgeBake';
|
import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars';
|
||||||
import {
|
import { nightBodies, paintNightBodies } from './nightBodies';
|
||||||
LAYERS,
|
import type { NightBodies } from './nightBodies';
|
||||||
LayerSpec,
|
|
||||||
edgeBlur,
|
|
||||||
HORIZON_TRACK_SHIFT,
|
|
||||||
layerSize,
|
|
||||||
scatterAlpha,
|
|
||||||
transmittance,
|
|
||||||
} from './ridgeWorld';
|
|
||||||
import { hfovDeg } from './horizon';
|
|
||||||
import { viewFor, VFOV_DEG } from './skyDome';
|
|
||||||
import { drawRainTile, RAIN_TILES } from './rain';
|
import { drawRainTile, RAIN_TILES } from './rain';
|
||||||
|
import type { Backdrop } from './Backdrop';
|
||||||
/** One chunk's bake: `ms` is the summed task time, `maxTaskMs` the longest single task; `first` marks the bake of the first view. */
|
|
||||||
export interface BakeRecord {
|
|
||||||
layer: number;
|
|
||||||
chunk: number;
|
|
||||||
ms: number;
|
|
||||||
maxTaskMs: number;
|
|
||||||
first: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
|
export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
|
||||||
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */
|
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */
|
||||||
|
|
@ -37,8 +19,10 @@ export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
|
||||||
onProbe?: (s: FrameStats & { still: boolean }) => void;
|
onProbe?: (s: FrameStats & { still: boolean }) => void;
|
||||||
/** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */
|
/** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */
|
||||||
sky?: SkyColours;
|
sky?: SkyColours;
|
||||||
/** Called after each chunk is baked (a chunk is one layer's stretch of world-x): the cost record. */
|
/** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */
|
||||||
onBake?: (b: BakeRecord) => void;
|
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]})`;
|
const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`;
|
||||||
|
|
@ -75,11 +59,16 @@ function paintSky(
|
||||||
cssW: number,
|
cssW: number,
|
||||||
cssH: number,
|
cssH: number,
|
||||||
makeCanvas: () => HTMLCanvasElement
|
makeCanvas: () => HTMLCanvasElement
|
||||||
): boolean {
|
): { ok: boolean; px?: ReturnType<typeof paintPhysicalSky> } {
|
||||||
const ctx = context2d(canvas);
|
const ctx = context2d(canvas);
|
||||||
if (!ctx) return false;
|
if (!ctx) return { ok: false };
|
||||||
if (sky.physical) {
|
if (sky.physical) {
|
||||||
const px = paintPhysicalSky(sky.physical, cssW, cssH);
|
const px = paintPhysicalSky(
|
||||||
|
sky.physical,
|
||||||
|
cssW,
|
||||||
|
cssH,
|
||||||
|
windowFor(sky.physical.view, cssW, cssH).camera
|
||||||
|
);
|
||||||
const small = makeCanvas();
|
const small = makeCanvas();
|
||||||
small.width = px.w;
|
small.width = px.w;
|
||||||
small.height = px.h;
|
small.height = px.h;
|
||||||
|
|
@ -92,7 +81,7 @@ function paintSky(
|
||||||
ctx.imageSmoothingQuality = 'high';
|
ctx.imageSmoothingQuality = 'high';
|
||||||
ctx.drawImage(small, 0, 0, canvas.width, canvas.height);
|
ctx.drawImage(small, 0, 0, canvas.width, canvas.height);
|
||||||
if (px.sunDisc) drawSun(ctx, px.sunDisc, 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);
|
const g = ctx.createLinearGradient(0, 0, 0, canvas.height);
|
||||||
|
|
@ -102,222 +91,31 @@ function paintSky(
|
||||||
g.addColorStop(1, css(sky.horizon));
|
g.addColorStop(1, css(sky.horizon));
|
||||||
ctx.fillStyle = g;
|
ctx.fillStyle = g;
|
||||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
return true;
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
|
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
|
||||||
|
|
||||||
type Size = ReturnType<typeof layerSize>;
|
|
||||||
|
|
||||||
const SCATTER_STOPS = 16;
|
|
||||||
|
|
||||||
/** Warm in-scatter over the silhouette only (source-atop): a horizontal gradient over the chunk's world-x. */
|
|
||||||
function scatter(
|
|
||||||
ctx: CanvasRenderingContext2D,
|
|
||||||
spec: LayerSpec,
|
|
||||||
sky: SkyColours,
|
|
||||||
widthPx: number,
|
|
||||||
heightPx: number,
|
|
||||||
t0: number,
|
|
||||||
tPerPx: number,
|
|
||||||
bandX = 0,
|
|
||||||
bandW = widthPx
|
|
||||||
) {
|
|
||||||
if (sky.sunAzimuth === undefined || transmittance(spec) >= 1) return; // the nearest layer takes none
|
|
||||||
const g = ctx.createLinearGradient(0, 0, widthPx, 0);
|
|
||||||
const [r, gr, b] = sky.horizon;
|
|
||||||
for (let k = 0; k <= SCATTER_STOPS; k += 1) {
|
|
||||||
const a = scatterAlpha(spec, sky, t0 + (tPerPx * widthPx * k) / SCATTER_STOPS);
|
|
||||||
g.addColorStop(k / SCATTER_STOPS, `rgba(${r},${gr},${b},${a})`);
|
|
||||||
}
|
|
||||||
ctx.globalCompositeOperation = 'source-atop';
|
|
||||||
ctx.fillStyle = g;
|
|
||||||
ctx.fillRect(bandX, 0, bandW, heightPx);
|
|
||||||
ctx.globalCompositeOperation = 'source-over';
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A chunk's bake in slices: `step(budgetMs)` returns true once the chunk is on its canvas. */
|
|
||||||
interface Job {
|
|
||||||
step(budgetMs: number): boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One layer's stretch of world-x `[m * chunk, (m + 1) * chunk)` painted onto `el`, in three phases of
|
|
||||||
* column bands, each band sized to the task budget by measuring the last one: bake the pixels
|
|
||||||
* (`bakeSlice`), put them on a canvas with the in-scatter, and (where the 2D `filter` exists) blur them
|
|
||||||
* into `el`. The blur needs neighbours, so the pixels are baked `pad` columns past both ends and
|
|
||||||
* the bottom into a scratch canvas this job owns, and each blurred band reads `pad` columns either side of
|
|
||||||
* itself: seams show no fade. The scratch is made when the job first runs and dropped when it ends.
|
|
||||||
*/
|
|
||||||
function chunkJob(
|
|
||||||
el: HTMLCanvasElement,
|
|
||||||
makeCanvas: () => HTMLCanvasElement,
|
|
||||||
spec: LayerSpec,
|
|
||||||
sky: SkyColours,
|
|
||||||
size: Size,
|
|
||||||
viewH: number,
|
|
||||||
scale: number,
|
|
||||||
m: number,
|
|
||||||
record: (ms: number, maxTaskMs: number) => void
|
|
||||||
): Job | null {
|
|
||||||
const ctx = context2d(el);
|
|
||||||
if (!ctx) return null;
|
|
||||||
const blur = edgeBlur(spec) * scale;
|
|
||||||
const pad = blur > 0 && 'filter' in ctx ? Math.ceil(3 * blur) : 0;
|
|
||||||
const cols = size.chunk + 2 * pad;
|
|
||||||
const rows = size.height + pad;
|
|
||||||
const params: BakeParams = {
|
|
||||||
spec,
|
|
||||||
sky,
|
|
||||||
horizonView:
|
|
||||||
spec.horizon && sky.physical
|
|
||||||
? {
|
|
||||||
azimuthDeg: viewFor(sky.physical.sun, size.period / viewH).azimuthDeg,
|
|
||||||
hfovDeg: hfovDeg(size.period / viewH, VFOV_DEG),
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
period: size.period,
|
|
||||||
scale,
|
|
||||||
viewH,
|
|
||||||
rows,
|
|
||||||
bandH: size.height,
|
|
||||||
px0: m * size.chunk - pad,
|
|
||||||
cols,
|
|
||||||
};
|
|
||||||
const paint = layerPaint(spec, sky);
|
|
||||||
const t0World = params.px0 / size.period;
|
|
||||||
let scratch: HTMLCanvasElement | undefined;
|
|
||||||
let sctx: CanvasRenderingContext2D | null = ctx;
|
|
||||||
let img: ImageData | undefined;
|
|
||||||
/** 0 bake, 1 put and in-scatter, 2 blur into el; a chunk with no blur ends after 1. */
|
|
||||||
let phase = 0;
|
|
||||||
let pos = 0;
|
|
||||||
let sliceCols = 32;
|
|
||||||
let total = 0;
|
|
||||||
let longest = 0;
|
|
||||||
const last = pad > 0 ? 2 : 1;
|
|
||||||
const start = (): boolean => {
|
|
||||||
if (pad > 0) {
|
|
||||||
scratch = makeCanvas();
|
|
||||||
scratch.width = cols;
|
|
||||||
scratch.height = rows;
|
|
||||||
sctx = context2d(scratch);
|
|
||||||
} else {
|
|
||||||
el.width = size.chunk;
|
|
||||||
el.height = size.height;
|
|
||||||
}
|
|
||||||
if (!sctx) return false;
|
|
||||||
img = sctx.createImageData(cols, rows);
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
const work = (x: number, n: number) => {
|
|
||||||
if (!img || !sctx) return;
|
|
||||||
if (phase === 0) bakeSlice(img.data, params, paint, x, x + n);
|
|
||||||
else if (phase === 1) {
|
|
||||||
sctx.putImageData(img, 0, 0, x, 0, n, rows);
|
|
||||||
scatter(sctx, spec, sky, cols, rows, t0World, 1 / size.period, x, n);
|
|
||||||
} else {
|
|
||||||
// One draw: a blurred draw cut into bands costs more in the margins than it saves in task length.
|
|
||||||
ctx.drawImage(scratch as HTMLCanvasElement, -pad, 0);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
step(budgetMs) {
|
|
||||||
const t0 = clock();
|
|
||||||
// Allocating the canvases and the pixel buffer is a task of its own.
|
|
||||||
if (!img) {
|
|
||||||
if (!start()) return true;
|
|
||||||
if (Number.isFinite(budgetMs)) {
|
|
||||||
total += clock() - t0;
|
|
||||||
longest = Math.max(longest, clock() - t0);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
while (phase <= last && clock() - t0 < budgetMs) {
|
|
||||||
const end = phase === 2 ? size.chunk : cols;
|
|
||||||
if (pos === 0 && phase === 2) {
|
|
||||||
el.width = size.chunk;
|
|
||||||
el.height = size.height;
|
|
||||||
ctx.filter = `blur(${blur}px)`;
|
|
||||||
}
|
|
||||||
const n = phase === 2 ? end : Math.min(end - pos, sliceCols);
|
|
||||||
const s0 = clock();
|
|
||||||
work(pos, n);
|
|
||||||
pos += n;
|
|
||||||
const dt = Math.max(clock() - s0, 0.02);
|
|
||||||
sliceCols = Number.isFinite(budgetMs)
|
|
||||||
? Math.max(8, Math.min(512, Math.round((n * budgetMs * 0.4) / dt)))
|
|
||||||
: cols;
|
|
||||||
if (pos >= end) {
|
|
||||||
if (phase === 2) ctx.filter = 'none';
|
|
||||||
phase += 1;
|
|
||||||
pos = 0;
|
|
||||||
if (phase === 1 || phase === 2) sliceCols = Number.isFinite(budgetMs) ? 64 : cols;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const dt = clock() - t0;
|
|
||||||
total += dt;
|
|
||||||
longest = Math.max(longest, dt);
|
|
||||||
const done = phase > last;
|
|
||||||
if (done) {
|
|
||||||
img = undefined;
|
|
||||||
if (scratch) {
|
|
||||||
scratch.width = 0;
|
|
||||||
scratch.height = 0;
|
|
||||||
}
|
|
||||||
scratch = undefined;
|
|
||||||
record(total, longest);
|
|
||||||
}
|
|
||||||
return done;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Chunk {
|
|
||||||
el: HTMLCanvasElement;
|
|
||||||
/** World chunk index it holds or is being baked to hold. */
|
|
||||||
id: number;
|
|
||||||
job?: Job;
|
|
||||||
ready: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One layer: a track that drifts by one chunk per animation, holding three chunk canvases. */
|
|
||||||
interface LayerState {
|
|
||||||
spec: LayerSpec;
|
|
||||||
track: HTMLElement;
|
|
||||||
/** Slot 0 and 1 are what the window can see; slot 2 is the one ahead, baked in the background. */
|
|
||||||
slots: Chunk[];
|
|
||||||
anim?: Animation;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Built {
|
interface Built {
|
||||||
rig: HTMLElement;
|
/** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */
|
||||||
layers: LayerState[];
|
|
||||||
sway?: Animation;
|
|
||||||
size: Size;
|
|
||||||
/** CSS px to canvas px, and the viewport's height in canvas px, as baked. */
|
|
||||||
scale: number;
|
|
||||||
viewH: number;
|
|
||||||
/** Makes a canvas, bound to the document the scene was built in. */
|
|
||||||
makeCanvas: () => HTMLCanvasElement;
|
|
||||||
/** The twinkling stars' own canvas, between the sky and the ridges; absent in a day sky and in 'still'. */
|
|
||||||
twinkle?: HTMLCanvasElement;
|
twinkle?: HTMLCanvasElement;
|
||||||
|
/** The ridge cards' rig, over the twinkle canvas and under the rain; absent in 'still' (the cards are drawn into the host canvas). */
|
||||||
|
rig?: { el: HTMLElement; anims: (Animation | undefined)[] };
|
||||||
/** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */
|
/** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */
|
||||||
rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] };
|
rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Yaw and pitch: the camera's slow sway, a loop of this many seconds over the whole rig. */
|
|
||||||
const SWAY_SECONDS = 150;
|
|
||||||
const SLICE_BUDGET_MS = 6;
|
|
||||||
|
|
||||||
/** The twinkle overlay redraws at most this often: the swings are 2 to 7 s, no need for 60 fps. */
|
/** 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;
|
const TWINKLE_FRAME_MS = 50;
|
||||||
|
|
||||||
|
/** 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
|
* The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS
|
||||||
* ground"), no WebGL. The layers are painted once on the CPU; per frame the only work is the
|
* 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
|
||||||
* browser compositor sliding each layer with a CSS transform (a Web Animation, no script). The host
|
* 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
|
||||||
* canvas holds the baked sky; it and the layers' parent must be positioned, and the canvas should fill it.
|
* its parent must be positioned, and the canvas should fill the parent.
|
||||||
*/
|
*/
|
||||||
export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
const tier = opts.tier ?? 'full';
|
const tier = opts.tier ?? 'full';
|
||||||
|
|
@ -334,9 +132,6 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
let twRaf = 0;
|
let twRaf = 0;
|
||||||
let twLast = 0;
|
let twLast = 0;
|
||||||
let still = tier === 'still';
|
let still = tier === 'still';
|
||||||
let jobTimer: ReturnType<typeof setTimeout> | undefined;
|
|
||||||
let queue: Chunk[] = [];
|
|
||||||
let generation = 0;
|
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
let raf = 0;
|
let raf = 0;
|
||||||
let readout: HTMLElement | undefined;
|
let readout: HTMLElement | undefined;
|
||||||
|
|
@ -349,15 +144,10 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
return { w, h, scale: (window.devicePixelRatio || 1) >= 2 ? 2 : 1 };
|
return { w, h, scale: (window.devicePixelRatio || 1) >= 2 ? 2 : 1 };
|
||||||
};
|
};
|
||||||
|
|
||||||
const teardownLayers = () => {
|
const teardown = () => {
|
||||||
generation += 1;
|
|
||||||
clearTimeout(jobTimer);
|
|
||||||
jobTimer = undefined;
|
|
||||||
queue = [];
|
|
||||||
built?.sway?.cancel();
|
|
||||||
built?.layers.forEach((l) => l.anim?.cancel());
|
|
||||||
built?.rig.remove();
|
|
||||||
built?.twinkle?.remove();
|
built?.twinkle?.remove();
|
||||||
|
built?.rig?.anims.forEach((a) => a?.cancel());
|
||||||
|
built?.rig?.el.remove();
|
||||||
built?.rain?.anims.forEach((a) => a?.cancel());
|
built?.rain?.anims.forEach((a) => a?.cancel());
|
||||||
built?.rain?.els.forEach((e) => e.remove());
|
built?.rain?.els.forEach((e) => e.remove());
|
||||||
cancelAnimationFrame(twRaf);
|
cancelAnimationFrame(twRaf);
|
||||||
|
|
@ -368,111 +158,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
/** True while there is nothing to paint on: the canvas has no client size and the window itself is 0 x 0 (`viewSize` falls back to the window). */
|
/** True while there is nothing to paint on: the canvas has no client size and the window itself is 0 x 0 (`viewSize` falls back to the window). */
|
||||||
const hasNoArea = () => {
|
const hasNoArea = () => {
|
||||||
const { w, h, scale } = viewSize();
|
const { w, h, scale } = viewSize();
|
||||||
const size = layerSize(w, h, scale);
|
return Math.round(w * scale) < 1 || Math.round(h * scale) < 1;
|
||||||
return size.period < 1 || size.height < 1 || Math.round(h * scale) < 1;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Start baking chunk `c` of layer `l`. `first` runs it to the end in this task (the first view);
|
|
||||||
* otherwise it joins the queue, which `pump` works through in short tasks. False when the canvas has no 2D context.
|
|
||||||
*/
|
|
||||||
const bake = (l: LayerState, c: Chunk, first: boolean): boolean => {
|
|
||||||
if (!built) return false;
|
|
||||||
const { scale, viewH, makeCanvas } = built;
|
|
||||||
const job = chunkJob(
|
|
||||||
c.el,
|
|
||||||
makeCanvas,
|
|
||||||
l.spec,
|
|
||||||
sky,
|
|
||||||
built.size,
|
|
||||||
viewH,
|
|
||||||
scale,
|
|
||||||
c.id,
|
|
||||||
(ms, maxTaskMs) => {
|
|
||||||
c.ready = true;
|
|
||||||
c.job = undefined;
|
|
||||||
opts.onBake?.({ layer: l.spec.index, chunk: c.id, ms, maxTaskMs, first });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
if (!job) return false;
|
|
||||||
c.ready = false;
|
|
||||||
c.job = job;
|
|
||||||
if (first) job.step(Infinity);
|
|
||||||
else queue.push(c);
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
const pump = () => {
|
|
||||||
if (jobTimer !== undefined || !queue.length) return;
|
|
||||||
const gen = generation;
|
|
||||||
jobTimer = setTimeout(() => {
|
|
||||||
jobTimer = undefined;
|
|
||||||
if (gen !== generation) return;
|
|
||||||
const c = queue[0];
|
|
||||||
if (!c.job || c.job.step(SLICE_BUDGET_MS)) queue.shift();
|
|
||||||
pump();
|
|
||||||
}, 0);
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Bake a still-queued chunk to the end now: only when the drift has caught up with the background work. */
|
|
||||||
const flush = (c: Chunk) => {
|
|
||||||
while (c.job && !c.job.step(Infinity));
|
|
||||||
queue = queue.filter((q) => q !== c);
|
|
||||||
};
|
|
||||||
|
|
||||||
const chunkSeconds = (spec: LayerSpec, size: Size) => (spec.seconds * size.chunk) / size.period;
|
|
||||||
|
|
||||||
/** One chunk of drift as one animation, holding its end until `rotate` hands the track the next chunk. */
|
|
||||||
const startDrift = (l: LayerState, onEnd: (l: LayerState) => void) => {
|
|
||||||
if (!built || !Number.isFinite(l.spec.seconds)) return; // the horizon layer does not drift
|
|
||||||
const { size, scale } = built;
|
|
||||||
l.anim = l.track.animate?.(
|
|
||||||
[
|
|
||||||
{ transform: 'translate3d(0,0,0)' },
|
|
||||||
{ transform: `translate3d(${-size.chunk / scale}px,0,0)` },
|
|
||||||
],
|
|
||||||
{ duration: chunkSeconds(l.spec, size) * 1000, easing: 'linear', fill: 'forwards' }
|
|
||||||
);
|
|
||||||
if (l.anim) l.anim.onfinish = () => onEnd(l);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The window has drifted one chunk. Slot 1 is now slot 0 and slot 2 slot 1, at the same screen place
|
|
||||||
* (the track restarts at 0 and the chunks move one slot left in the same task, so nothing jumps); the
|
|
||||||
* canvas that left becomes slot 2 and is baked with the world one chunk further on, off the critical path.
|
|
||||||
*/
|
|
||||||
const rotate = (l: LayerState) => {
|
|
||||||
if (!built || !built.layers.includes(l)) return;
|
|
||||||
const [s0, s1, s2] = l.slots;
|
|
||||||
flush(s1);
|
|
||||||
flush(s2);
|
|
||||||
l.slots = [s1, s2, s0];
|
|
||||||
s0.id = s2.id + 1;
|
|
||||||
const { size, scale } = built;
|
|
||||||
l.slots.forEach((c, i) => {
|
|
||||||
c.el.style.left = `${(i * size.chunk) / scale}px`;
|
|
||||||
});
|
|
||||||
l.anim?.cancel();
|
|
||||||
startDrift(l, rotate);
|
|
||||||
bake(l, s0, false);
|
|
||||||
pump();
|
|
||||||
syncPlayState();
|
|
||||||
};
|
|
||||||
|
|
||||||
/** The camera's slow yaw and pitch: the rig eases sideways (up to 5% of the width) and down (up to 3% of the height) and back, in a loop. */
|
|
||||||
const startSway = (rig: HTMLElement, w: number, h: number) => {
|
|
||||||
const x = 0.05 * w;
|
|
||||||
const y = 0.03 * h;
|
|
||||||
const at = (fx: number, fy: number) => `translate3d(${-x * fx}px,${y * fy}px,0)`;
|
|
||||||
return rig.animate?.(
|
|
||||||
[
|
|
||||||
{ transform: at(0, 0), offset: 0 },
|
|
||||||
{ transform: at(0.55, 1), offset: 0.35 },
|
|
||||||
{ transform: at(1, 0.3), offset: 0.7 },
|
|
||||||
{ transform: at(0, 0), offset: 1 },
|
|
||||||
],
|
|
||||||
{ duration: SWAY_SECONDS * 1000, iterations: Infinity, easing: 'ease-in-out' }
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -525,21 +211,103 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
return { els, anims };
|
return { els, anims };
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Bake the sky, then the layers. Returns false when a 2D context is missing or there is no area yet. */
|
/**
|
||||||
|
* 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 { 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, {
|
||||||
|
position: 'absolute',
|
||||||
|
left: '0',
|
||||||
|
top: '0',
|
||||||
|
width: '100%',
|
||||||
|
height: '100%',
|
||||||
|
overflow: 'hidden',
|
||||||
|
pointerEvents: 'none',
|
||||||
|
});
|
||||||
|
const anims: (Animation | undefined)[] = [];
|
||||||
|
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`,
|
||||||
|
top: `${planeTop + card.top * win.plane.scale}px`,
|
||||||
|
width: `${win.plane.w}px`,
|
||||||
|
height: `${card.h * win.plane.scale}px`,
|
||||||
|
transformOrigin: `${win.plane.w / 2}px ${(view.horizonRow - card.top) * win.plane.scale}px`,
|
||||||
|
willChange: 'transform',
|
||||||
|
});
|
||||||
|
el.appendChild(node);
|
||||||
|
anims.push(
|
||||||
|
node.animate?.(
|
||||||
|
[
|
||||||
|
{ transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` },
|
||||||
|
{ transform: `translate3d(${reachPx}px,0,0) scale(${scale})` },
|
||||||
|
],
|
||||||
|
{
|
||||||
|
duration: DRIFT_LEG_S * 1000,
|
||||||
|
iterations: Infinity,
|
||||||
|
direction: 'alternate',
|
||||||
|
easing: 'ease-in-out',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
parent.appendChild(el);
|
||||||
|
return { el, anims };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 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(view, w, h);
|
||||||
|
const s = win.plane.scale * scale;
|
||||||
|
const dw = win.plane.w * scale;
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */
|
||||||
const build = (): boolean => {
|
const build = (): boolean => {
|
||||||
teardownLayers();
|
teardown();
|
||||||
// A zero-size canvas throws on drawImage; wait for the first resize that gives the host an area.
|
// A zero-size canvas throws on drawImage; wait for the first resize that gives the host an area.
|
||||||
if (hasNoArea()) return false;
|
if (hasNoArea()) return false;
|
||||||
const { w, h, scale } = viewSize();
|
const { w, h, scale } = viewSize();
|
||||||
const size = layerSize(w, h, scale);
|
canvas.width = Math.round(w * scale);
|
||||||
canvas.width = size.period;
|
|
||||||
canvas.height = Math.round(h * scale);
|
canvas.height = Math.round(h * scale);
|
||||||
if (!paintSky(canvas, sky, w, h, () => document.createElement('canvas'))) return false;
|
const painted = paintSky(canvas, sky, w, h, () => document.createElement('canvas'));
|
||||||
// Every star is baked into the sky; the twinkling ones get their own canvas, which a per-frame
|
if (!painted.ok) return false;
|
||||||
// pass clears and paints over. 'still' has no overlay.
|
// The real stars, the moon and (when asked) the constellation lines are baked into the sky; the twinkling stars get their own
|
||||||
const stars = makeStars(sky, w, h);
|
// 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);
|
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;
|
let twinkle: HTMLCanvasElement | undefined;
|
||||||
if (stars.length && tier !== 'still') {
|
if (stars.length && tier !== 'still') {
|
||||||
twinkle = document.createElement('canvas');
|
twinkle = document.createElement('canvas');
|
||||||
|
|
@ -557,75 +325,10 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
parent.appendChild(twinkle);
|
parent.appendChild(twinkle);
|
||||||
}
|
}
|
||||||
field = stars;
|
field = stars;
|
||||||
// The rig carries the camera's sway; each layer's track carries its drift; chunks sit on the track.
|
built = { twinkle };
|
||||||
const rig = document.createElement('div');
|
if (opts.backdrop && !still) built.rig = startRig(opts.backdrop, w, h);
|
||||||
rig.setAttribute('aria-hidden', 'true');
|
|
||||||
Object.assign(rig.style, {
|
|
||||||
position: 'absolute',
|
|
||||||
left: '0',
|
|
||||||
bottom: '0',
|
|
||||||
width: '100%',
|
|
||||||
height: '100%',
|
|
||||||
pointerEvents: 'none',
|
|
||||||
willChange: 'transform',
|
|
||||||
});
|
|
||||||
const layers: LayerState[] = LAYERS.map((spec) => {
|
|
||||||
const track = document.createElement('div');
|
|
||||||
Object.assign(track.style, {
|
|
||||||
position: 'absolute',
|
|
||||||
left: spec.horizon ? `${(-HORIZON_TRACK_SHIFT * size.period) / scale}px` : '0',
|
|
||||||
bottom: '0',
|
|
||||||
width: `${size.period / scale}px`,
|
|
||||||
height: `${size.height / scale}px`,
|
|
||||||
willChange: 'transform',
|
|
||||||
});
|
|
||||||
const slots: Chunk[] = [0, 1, 2].map((i) => {
|
|
||||||
const el = document.createElement('canvas');
|
|
||||||
el.width = size.chunk;
|
|
||||||
el.height = size.height;
|
|
||||||
Object.assign(el.style, {
|
|
||||||
position: 'absolute',
|
|
||||||
bottom: '0',
|
|
||||||
width: `${size.chunk / scale}px`,
|
|
||||||
height: `${size.height / scale}px`,
|
|
||||||
});
|
|
||||||
return { el, id: i, ready: false };
|
|
||||||
});
|
|
||||||
return { spec, track, slots };
|
|
||||||
});
|
|
||||||
const doc = document;
|
|
||||||
built = {
|
|
||||||
rig,
|
|
||||||
layers,
|
|
||||||
size,
|
|
||||||
scale,
|
|
||||||
viewH: canvas.height,
|
|
||||||
makeCanvas: () => doc.createElement('canvas'),
|
|
||||||
twinkle,
|
|
||||||
};
|
|
||||||
// First view: only slot 0 of each layer, in this task. The window sees nothing else for the first
|
|
||||||
// fifth of a chunk's drift; slots 1 and 2 are baked in short tasks behind it.
|
|
||||||
if (!layers.every((l) => bake(l, l.slots[0], true))) {
|
|
||||||
teardownLayers();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
layers.forEach((l) => {
|
|
||||||
l.slots.forEach((c, i) => {
|
|
||||||
c.el.setAttribute('aria-hidden', 'true');
|
|
||||||
c.el.style.left = `${(i * size.chunk) / scale}px`;
|
|
||||||
l.track.appendChild(c.el);
|
|
||||||
});
|
|
||||||
rig.appendChild(l.track);
|
|
||||||
bake(l, l.slots[1], false);
|
|
||||||
bake(l, l.slots[2], false);
|
|
||||||
});
|
|
||||||
// DOM order is paint order: farthest first, so the nearest ridge ends up on top.
|
|
||||||
parent.appendChild(rig);
|
|
||||||
layers.forEach((l) => startDrift(l, rotate));
|
|
||||||
built.sway = startSway(rig, w, h);
|
|
||||||
if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0)
|
if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0)
|
||||||
built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale);
|
built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale);
|
||||||
pump();
|
|
||||||
syncPlayState();
|
syncPlayState();
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
@ -658,9 +361,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
};
|
};
|
||||||
|
|
||||||
function syncPlayState() {
|
function syncPlayState() {
|
||||||
const anims = built
|
const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? [])];
|
||||||
? [built.sway, ...built.layers.map((l) => l.anim), ...(built.rain?.anims ?? [])]
|
|
||||||
: [];
|
|
||||||
anims.forEach((a) => (moving() ? a?.play() : a?.pause()));
|
anims.forEach((a) => (moving() ? a?.play() : a?.pause()));
|
||||||
if (!built?.twinkle) return;
|
if (!built?.twinkle) return;
|
||||||
if (moving()) {
|
if (moving()) {
|
||||||
|
|
@ -672,26 +373,14 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Flatten the sky and layers into the host canvas and drop the layers: a still image, no compositor layers left. */
|
/** Drop the twinkle and the rain, leaving the painted sky as a still image. */
|
||||||
const settleToStill = () => {
|
const settleToStill = () => {
|
||||||
if (still && !built) return;
|
if (still && !built) return;
|
||||||
still = true;
|
still = true;
|
||||||
const ctx = context2d(canvas);
|
teardown();
|
||||||
if (ctx && built) {
|
|
||||||
const { size } = built;
|
|
||||||
built.layers.forEach((l) => {
|
|
||||||
// Freeze where the drift is, so the swap to a still does not jump; whatever is baked and in view.
|
|
||||||
const dur = chunkSeconds(l.spec, size) * 1000;
|
|
||||||
const p = Math.min(1, Math.max(0, Number(l.anim?.currentTime ?? 0) / dur));
|
|
||||||
const x = -Math.round(p * size.chunk);
|
|
||||||
l.slots.slice(0, 2).forEach((c, i) => {
|
|
||||||
if (c.ready) ctx.drawImage(c.el, x + i * size.chunk, canvas.height - size.height);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
teardownLayers();
|
|
||||||
cancelAnimationFrame(raf);
|
cancelAnimationFrame(raf);
|
||||||
raf = 0;
|
raf = 0;
|
||||||
|
if (opts.backdrop) paintCards(opts.backdrop);
|
||||||
report(true);
|
report(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -773,7 +462,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
login() {
|
login() {
|
||||||
// No camera to pull back; the ridges are the same before and after.
|
// No camera to pull back; the sky is the same before and after.
|
||||||
},
|
},
|
||||||
dispose() {
|
dispose() {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
|
|
@ -783,7 +472,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
||||||
document.removeEventListener('visibilitychange', onVisibility);
|
document.removeEventListener('visibilitychange', onVisibility);
|
||||||
window.removeEventListener('resize', onResize);
|
window.removeEventListener('resize', onResize);
|
||||||
reducedMotion?.removeEventListener?.('change', syncPlayState);
|
reducedMotion?.removeEventListener?.('change', syncPlayState);
|
||||||
teardownLayers();
|
teardown();
|
||||||
readout?.remove();
|
readout?.remove();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,22 @@
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { HORIZON_CREDIT, WEATHER_CREDIT, WEATHER_CREDIT_URL, WEATHER_DATASET } from './credits';
|
import {
|
||||||
import { HORIZON_ATTRIBUTION } from './horizon';
|
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';
|
import { WEATHER_ATTRIBUTION } from './weatherFeed';
|
||||||
|
|
||||||
describe('the credits the Sky menu shows', () => {
|
describe('the credits the Sky menu shows', () => {
|
||||||
it("are the sources' own", () => {
|
it("are the sources' own", () => {
|
||||||
expect(HORIZON_CREDIT).toBe(HORIZON_ATTRIBUTION);
|
|
||||||
expect(WEATHER_CREDIT).toBe(WEATHER_ATTRIBUTION);
|
expect(WEATHER_CREDIT).toBe(WEATHER_ATTRIBUTION);
|
||||||
});
|
});
|
||||||
it('credit GeoSphere with its requested line, and state a licence only with the dataset named', () => {
|
it('credit GeoSphere with its requested line, and state a licence only with the dataset named', () => {
|
||||||
|
|
@ -14,3 +25,37 @@ describe('the credits the Sky menu shows', () => {
|
||||||
expect(WEATHER_DATASET).toMatch(/TAWES.*10-minute.*CC BY 4\.0/);
|
expect(WEATHER_DATASET).toMatch(/TAWES.*10-minute.*CC BY 4\.0/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('the terrain credit', () => {
|
||||||
|
const shipped = (): { attribution: { credit_line: string; licence: string } } | undefined => {
|
||||||
|
const root = join(process.cwd(), 'public', 'ridge');
|
||||||
|
const index = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8')));
|
||||||
|
return JSON.parse(
|
||||||
|
readFileSync(join(root, index.places[index.default], 'manifest.json'), 'utf8')
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
it("is the shipped manifest's attribution, credit line then licence", () => {
|
||||||
|
const wire = shipped();
|
||||||
|
const manifest = parseManifest(wireManifest({ attribution: wire?.attribution }), '/d/');
|
||||||
|
expect(terrainCredit(manifest)).toBe(
|
||||||
|
`${wire?.attribution.credit_line} ${wire?.attribution.licence}`
|
||||||
|
);
|
||||||
|
expect(terrainCredit(manifest)).toMatch(/Copernicus/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is absent without a manifest', () => {
|
||||||
|
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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,26 @@
|
||||||
// What the Ridge background owes its data sources, shown in the Sky menu (SkyStateControl). Plain strings in their own module so the
|
// What the Ridge background owes its data sources, shown in the Sky menu (SkyStateControl). Plain strings in their own module so the
|
||||||
// main chunk carries these and not the baked horizon table or the weather parser; credits.test.ts holds them equal to the sources'.
|
// main chunk carries these and not the weather parser; credits.test.ts holds them equal to the sources'. The terrain credit is the loaded
|
||||||
|
// manifest's own `attribution` (terrainCredit): the baker writes it, so no constant here can drift from the bake.
|
||||||
|
import type { RidgeManifest } from './manifest';
|
||||||
|
|
||||||
/** GeoSphere's own requested credit line. It names no licence: that is the dataset's (below). */
|
/** GeoSphere's own requested credit line. It names no licence: that is the dataset's (below). */
|
||||||
export const WEATHER_CREDIT = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at';
|
export const WEATHER_CREDIT = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at';
|
||||||
export const WEATHER_CREDIT_URL = 'https://data.hub.geosphere.at';
|
export const WEATHER_CREDIT_URL = 'https://data.hub.geosphere.at';
|
||||||
/** The dataset the weather is read from, and its licence as the dataset page names it (data.hub.geosphere.at, tawes-v1-10min). */
|
/** The dataset the weather is read from, and its licence as the dataset page names it (data.hub.geosphere.at, tawes-v1-10min). */
|
||||||
export const WEATHER_DATASET = 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0';
|
export const WEATHER_DATASET = 'TAWES weather stations, 10-minute data (station 11035), CC BY 4.0';
|
||||||
/** The terrain silhouette's credit, as the Copernicus DEM licence asks (equal to `HORIZON_ATTRIBUTION`). */
|
|
||||||
export const HORIZON_CREDIT =
|
/** The terrain's credit line and licence as the loaded bake states them; undefined until a manifest has loaded (no manifest, no 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.';
|
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';
|
||||||
|
|
|
||||||
|
|
@ -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. */
|
/** Nearest positive hit of a unit-direction ray with a sphere at the origin: its distance, or -1. */
|
||||||
function raySphere(
|
function raySphere(
|
||||||
ox: number,
|
ox: number,
|
||||||
|
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import bake from './viennaHorizon.json';
|
|
||||||
import { VIENNA } from './vienna';
|
|
||||||
import { horizonDistanceKm, horizonElevation, horizonNormal } from './horizon';
|
|
||||||
|
|
||||||
describe('the baked horizon', () => {
|
|
||||||
it('was baked from the viewpoint the sun is computed for', () => {
|
|
||||||
expect(bake.viewpoint.lat).toBe(VIENNA.lat);
|
|
||||||
expect(bake.viewpoint.lon).toBe(VIENNA.lon);
|
|
||||||
expect(bake.viewpoint.groundM / 1000).toBeCloseTo(VIENNA.altitudeKm, 2);
|
|
||||||
});
|
|
||||||
it('carries its source and licence beside the data', () => {
|
|
||||||
expect(bake.source.licence).toMatch(/attribution required/);
|
|
||||||
expect(bake.source.attribution).toMatch(/COPERNICUS/);
|
|
||||||
});
|
|
||||||
it('is a closed ring of plausible angles: the Wienerwald NW, open Marchfeld E', () => {
|
|
||||||
expect(bake.elevationDeg).toHaveLength(720);
|
|
||||||
expect(horizonElevation(0)).toBeCloseTo(horizonElevation(360), 6);
|
|
||||||
expect(horizonElevation(305)).toBeGreaterThan(horizonElevation(70));
|
|
||||||
expect(Math.max(...bake.elevationDeg)).toBeLessThan(5);
|
|
||||||
expect(horizonDistanceKm(305)).toBeGreaterThan(1);
|
|
||||||
});
|
|
||||||
it('interpolates between samples and returns unit normals', () => {
|
|
||||||
expect(horizonElevation(100.25)).toBeCloseTo(
|
|
||||||
(bake.elevationDeg[200] + bake.elevationDeg[201]) / 2,
|
|
||||||
6
|
|
||||||
);
|
|
||||||
expect(Math.hypot(...horizonNormal(250))).toBeCloseTo(1, 6);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,54 +0,0 @@
|
||||||
// The terrain horizon seen from the viewpoint, baked from open DEM by `scripts/bake-horizon.py` (source, licence and attribution are
|
|
||||||
// in the file's `source` block and in `HORIZON_ATTRIBUTION`).
|
|
||||||
import bake from './viennaHorizon.json';
|
|
||||||
|
|
||||||
export const HORIZON_ATTRIBUTION = bake.source.attribution;
|
|
||||||
|
|
||||||
const N = bake.elevationDeg.length;
|
|
||||||
|
|
||||||
/** Index pair and weight of an azimuth (degrees clockwise from north) on the baked ring. */
|
|
||||||
function at(azimuth: number): [number, number, number] {
|
|
||||||
const f = (((azimuth / bake.stepDeg) % N) + N) % N;
|
|
||||||
const i = Math.floor(f);
|
|
||||||
return [i, (i + 1) % N, f - i];
|
|
||||||
}
|
|
||||||
|
|
||||||
const lerp = (arr: readonly number[], az: number): number => {
|
|
||||||
const [a, b, t] = at(az);
|
|
||||||
return arr[a] * (1 - t) + arr[b] * t;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Elevation of the horizon, degrees above the astronomical horizon, at an azimuth. */
|
|
||||||
export const horizonElevation = (azimuth: number): number => lerp(bake.elevationDeg, azimuth);
|
|
||||||
|
|
||||||
/** Distance of the terrain that sets the horizon, km. */
|
|
||||||
export const horizonDistanceKm = (azimuth: number): number => lerp(bake.distanceKm, azimuth);
|
|
||||||
|
|
||||||
/** Unit surface normal of the terrain at the horizon point: x east, y up, z north. */
|
|
||||||
export function horizonNormal(azimuth: number): [number, number, number] {
|
|
||||||
const e = lerp(bake.slopeEast, azimuth);
|
|
||||||
const n = lerp(bake.slopeNorth, azimuth);
|
|
||||||
const l = Math.hypot(e, 1, n);
|
|
||||||
return [-e / l, 1 / l, -n / l];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The elevations blurred over +-SMOOTH_DEG (a box, around the ring): at 30 m a city's roofs are the horizon's teeth, and a silhouette of them reads as a fence. */
|
|
||||||
const SMOOTH_DEG = 1.5;
|
|
||||||
const SMOOTH = Array.from({ length: N }, (_, i) => {
|
|
||||||
const k = Math.round(SMOOTH_DEG / bake.stepDeg);
|
|
||||||
let sum = 0;
|
|
||||||
for (let d = -k; d <= k; d += 1) sum += bake.elevationDeg[(i + d + N) % N];
|
|
||||||
return sum / (2 * k + 1);
|
|
||||||
});
|
|
||||||
const MIN_E = Math.min(...SMOOTH);
|
|
||||||
const RANGE_E = Math.max(...SMOOTH) - MIN_E;
|
|
||||||
|
|
||||||
/** The horizon at an azimuth as 0..1 of the ring's own range (the lowest point of the horizon 0, the highest 1): the silhouette's shape, not its scale. */
|
|
||||||
export const horizonShape = (azimuth: number): number => (lerp(SMOOTH, azimuth) - MIN_E) / RANGE_E;
|
|
||||||
|
|
||||||
/** Real range of the smoothed horizon, degrees: what `horizonShape` stretches to the layer's relief. */
|
|
||||||
export const HORIZON_RANGE_DEG = RANGE_E;
|
|
||||||
|
|
||||||
/** Horizontal field of view, degrees, of a camera with the sky's vertical field (`skyDome.ts` VFOV_DEG) at an aspect ratio. */
|
|
||||||
export const hfovDeg = (aspect: number, vfovDeg: number): number =>
|
|
||||||
(2 * Math.atan(aspect * Math.tan((vfovDeg * Math.PI) / 360)) * 180) / Math.PI;
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { hfovDeg, horizonShape } from './horizon';
|
|
||||||
import { HORIZON_TRACK_SHIFT, LAYERS, layerProfile, profile } from './ridgeWorld';
|
|
||||||
import { layerPaint } from './ridgeBake';
|
|
||||||
import { weatherOf } from './weather';
|
|
||||||
import { skyColours } from './skyColour';
|
|
||||||
import { makePhysicalSky } from './physicalSky';
|
|
||||||
import { VFOV_DEG } from './skyDome';
|
|
||||||
|
|
||||||
describe('the horizon layer', () => {
|
|
||||||
const far = LAYERS[0];
|
|
||||||
const view = { azimuthDeg: 200, hfovDeg: hfovDeg(16 / 9, VFOV_DEG) };
|
|
||||||
|
|
||||||
it('is the farthest layer, real and standing still', () => {
|
|
||||||
expect(far.horizon).toBe(true);
|
|
||||||
expect(Number.isFinite(far.seconds)).toBe(false);
|
|
||||||
expect(LAYERS.slice(1).every((l) => !l.horizon && Number.isFinite(l.seconds))).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reads world-x as azimuth across the viewport: the left edge is half the field to the left of the view, the right edge half to the right', () => {
|
|
||||||
const left = layerProfile(far, HORIZON_TRACK_SHIFT, view);
|
|
||||||
const right = layerProfile(far, HORIZON_TRACK_SHIFT + 1, view);
|
|
||||||
expect(left).toBeCloseTo(horizonShape(200 - view.hfovDeg / 2), 9);
|
|
||||||
expect(right).toBeCloseTo(horizonShape(200 + view.hfovDeg / 2), 9);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('stays in 0..1 and covers a real range of shape, not a line', () => {
|
|
||||||
const v = Array.from({ length: 200 }, (_, i) =>
|
|
||||||
layerProfile(far, -0.06 + (i / 200) * 1.2, { azimuthDeg: 305, hfovDeg: view.hfovDeg })
|
|
||||||
);
|
|
||||||
expect(Math.min(...v)).toBeGreaterThanOrEqual(0);
|
|
||||||
expect(Math.max(...v)).toBeLessThanOrEqual(1);
|
|
||||||
expect(Math.max(...v) - Math.min(...v)).toBeGreaterThan(0.2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is the noise profile for the other layers, and for the horizon layer when no view is known', () => {
|
|
||||||
expect(layerProfile(LAYERS[2], 0.4, view)).toBe(profile(LAYERS[2], 0.4));
|
|
||||||
expect(layerProfile(far, 0.4)).toBe(profile(far, 0.4));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the horizontal field of a 1:1 view is the vertical one, and grows with the aspect', () => {
|
|
||||||
expect(hfovDeg(1, VFOV_DEG)).toBeCloseTo(VFOV_DEG, 9);
|
|
||||||
expect(hfovDeg(16 / 9, VFOV_DEG)).toBeGreaterThan(VFOV_DEG);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('weather in the layers', () => {
|
|
||||||
it("mist multiplies the layers' own, and clear air leaves it alone", () => {
|
|
||||||
const base = skyColours();
|
|
||||||
const day = new Date('2026-06-21T10:40:00Z');
|
|
||||||
const clear = layerPaint(LAYERS[1], { ...base, physical: makePhysicalSky('day', day, 0) });
|
|
||||||
const misty = layerPaint(LAYERS[1], { ...base, physical: makePhysicalSky('day', day, 0.8) });
|
|
||||||
expect(clear.mistK).toBe(1);
|
|
||||||
expect(misty.mistK).toBeGreaterThan(2);
|
|
||||||
expect(layerPaint(LAYERS[1], base).mistK).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the weather number', () => {
|
|
||||||
it('a number that is not finite is a clear sky, not an error', () => {
|
|
||||||
expect(weatherOf(Number.NaN).value).toBe(0);
|
|
||||||
expect(weatherOf(Infinity).value).toBe(0);
|
|
||||||
expect(weatherOf(0.5).value).toBe(0.5);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
358
src/app/features/scene/ridge/lightCards.test.ts
Normal file
358
src/app/features/scene/ridge/lightCards.test.ts
Normal 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]');
|
||||||
|
});
|
||||||
|
});
|
||||||
647
src/app/features/scene/ridge/lightCards.ts
Normal file
647
src/app/features/scene/ridge/lightCards.ts
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
77
src/app/features/scene/ridge/manifest.fixture.ts
Normal file
77
src/app/features/scene/ridge/manifest.fixture.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
// 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';
|
||||||
|
|
||||||
|
/** 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;
|
||||||
|
|
||||||
|
/** 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',
|
||||||
|
name: 'Vienna',
|
||||||
|
lat: 48.19,
|
||||||
|
lon: 16.35,
|
||||||
|
altitude_km: 0.183,
|
||||||
|
eye_m: 1.7,
|
||||||
|
},
|
||||||
|
view: {
|
||||||
|
look_az_deg: 214,
|
||||||
|
window_deg: 72,
|
||||||
|
plane_w: 1280,
|
||||||
|
plane_h: 600,
|
||||||
|
px_per_deg_h: 1280 / 72,
|
||||||
|
px_per_deg_v: 177.8,
|
||||||
|
exaggeration: 10,
|
||||||
|
horizon_row: 314.5,
|
||||||
|
sky_row: 24,
|
||||||
|
near_row: 396,
|
||||||
|
},
|
||||||
|
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',
|
||||||
|
dem_source: 'dem',
|
||||||
|
url: 'https://example.test',
|
||||||
|
},
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const wireIndex = {
|
||||||
|
schema: 1,
|
||||||
|
default: 'vienna',
|
||||||
|
places: { vienna: 'vienna-abc123abc123', graz: 'graz-def456def456' },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, window, horizon row), so a test can tell the two apart. */
|
||||||
|
export const ELSEWHERE_VIEW: View = {
|
||||||
|
place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5 },
|
||||||
|
lookAzDeg: 20,
|
||||||
|
windowDeg: 90,
|
||||||
|
planeW: 1600,
|
||||||
|
planeH: 700,
|
||||||
|
pxPerDegH: 1600 / 90,
|
||||||
|
pxPerDegV: 100,
|
||||||
|
horizonRow: 250,
|
||||||
|
};
|
||||||
157
src/app/features/scene/ridge/manifest.test.ts
Normal file
157
src/app/features/scene/ridge/manifest.test.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { forgetManifests, loadManifest, parseManifest } from './manifest';
|
||||||
|
import { wireIndex, wireManifest } from './manifest.fixture';
|
||||||
|
|
||||||
|
describe('parseManifest', () => {
|
||||||
|
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({
|
||||||
|
lookAzDeg: 214,
|
||||||
|
windowDeg: 72,
|
||||||
|
planeW: 1280,
|
||||||
|
planeH: 600,
|
||||||
|
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.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.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, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/);
|
||||||
|
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>) => {
|
||||||
|
const f = vi.fn(async (url: string) =>
|
||||||
|
url in files
|
||||||
|
? { ok: true, status: 200, json: async () => files[url] }
|
||||||
|
: { ok: false, status: 404, json: async () => ({}) }
|
||||||
|
);
|
||||||
|
vi.stubGlobal('fetch', f);
|
||||||
|
return f;
|
||||||
|
};
|
||||||
|
const files = () => ({
|
||||||
|
'/b/public/ridge/index.json': wireIndex,
|
||||||
|
'/b/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(),
|
||||||
|
'/b/public/ridge/graz-def456def456/manifest.json': wireManifest({
|
||||||
|
place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('loadManifest', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
forgetManifests();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reads the index then the default place, with its directory', async () => {
|
||||||
|
const f = serve(files());
|
||||||
|
const m = await loadManifest('/b/');
|
||||||
|
expect(m.view.place.id).toBe('vienna');
|
||||||
|
expect(m.dir).toBe('/b/public/ridge/vienna-abc123abc123/');
|
||||||
|
expect(f.mock.calls.map((c) => c[0])).toEqual([
|
||||||
|
'/b/public/ridge/index.json',
|
||||||
|
'/b/public/ridge/vienna-abc123abc123/manifest.json',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('revalidates the index, the one mutable pointer, and leaves the content-addressed manifest to the cache', async () => {
|
||||||
|
const f = serve(files());
|
||||||
|
await loadManifest('/b/');
|
||||||
|
expect(f.mock.calls).toEqual([
|
||||||
|
['/b/public/ridge/index.json', { cache: 'no-cache' }],
|
||||||
|
['/b/public/ridge/vienna-abc123abc123/manifest.json', undefined],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('place picks the index entry; an unknown id falls back to the default', async () => {
|
||||||
|
serve(files());
|
||||||
|
expect((await loadManifest('/b/', 'graz')).view.place.id).toBe('graz');
|
||||||
|
expect((await loadManifest('/b/', 'nowhere')).view.place.id).toBe('vienna');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is memoised per URL and place', async () => {
|
||||||
|
const f = serve(files());
|
||||||
|
await loadManifest('/b/');
|
||||||
|
await loadManifest('/b/');
|
||||||
|
expect(f).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects on a 404 and does not remember the failure', async () => {
|
||||||
|
serve({});
|
||||||
|
await expect(loadManifest('/b/')).rejects.toThrow(/404/);
|
||||||
|
serve(files());
|
||||||
|
await expect(loadManifest('/b/')).resolves.toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
166
src/app/features/scene/ridge/manifest.ts
Normal file
166
src/app/features/scene/ridge/manifest.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
||||||
|
// 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 cards share. Schema 2: K G-buffer cards, nearest first.
|
||||||
|
import type { View } from './view';
|
||||||
|
|
||||||
|
export const PLANE_W_MAX = 4096;
|
||||||
|
/** As export.py MAX_CARDS: the decode budget holds this many. */
|
||||||
|
export const MAX_CARDS = 6;
|
||||||
|
|
||||||
|
/** 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 {
|
||||||
|
bakeId: string;
|
||||||
|
/** Absolute-or-rooted URL of the bake's directory, with a trailing slash. */
|
||||||
|
dir: string;
|
||||||
|
/** Display name of the place. */
|
||||||
|
name: string;
|
||||||
|
view: View;
|
||||||
|
/** 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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RidgeIndex {
|
||||||
|
default: string;
|
||||||
|
places: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rec = Record<string, unknown>;
|
||||||
|
const fail = (path: string, why: string): never => {
|
||||||
|
throw new Error(`ridge manifest ${path}: ${why}`);
|
||||||
|
};
|
||||||
|
const rec = (x: unknown, path: string): Rec =>
|
||||||
|
typeof x === 'object' && x !== null && !Array.isArray(x)
|
||||||
|
? (x as Rec)
|
||||||
|
: fail(path, 'not an object');
|
||||||
|
const num = (x: unknown, path: string): number =>
|
||||||
|
typeof x === 'number' && Number.isFinite(x) ? x : fail(path, 'not a number');
|
||||||
|
const str = (x: unknown, path: string): string =>
|
||||||
|
typeof x === 'string' ? x : fail(path, 'not a string');
|
||||||
|
|
||||||
|
export function parseIndex(raw: unknown): RidgeIndex {
|
||||||
|
const r = rec(raw, 'index');
|
||||||
|
if (r.schema !== 1) fail('index.schema', 'must be 1');
|
||||||
|
const places = rec(r.places, 'index.places');
|
||||||
|
const out = Object.fromEntries(
|
||||||
|
Object.entries(places).map(([k, v]) => [k, str(v, `index.places.${k}`)])
|
||||||
|
);
|
||||||
|
return { default: str(r.default, 'index.default'), places: out };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `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 !== 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}`);
|
||||||
|
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 {
|
||||||
|
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 {
|
||||||
|
bakeId: str(r.bake_id, 'bake_id'),
|
||||||
|
dir,
|
||||||
|
name: str(p.name, 'place.name'),
|
||||||
|
view: {
|
||||||
|
place: {
|
||||||
|
id,
|
||||||
|
lat: num(p.lat, 'place.lat'),
|
||||||
|
lon: num(p.lon, 'place.lon'),
|
||||||
|
altitudeKm: num(p.altitude_km, 'place.altitude_km'),
|
||||||
|
},
|
||||||
|
lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'),
|
||||||
|
windowDeg: num(v.window_deg, 'view.window_deg'),
|
||||||
|
planeW,
|
||||||
|
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'),
|
||||||
|
},
|
||||||
|
encoding: { logDMin, logDMax },
|
||||||
|
camera: { headingMaxDeg },
|
||||||
|
cards,
|
||||||
|
attribution: {
|
||||||
|
creditLine: str(a.credit_line, 'attribution.credit_line'),
|
||||||
|
licence: str(a.licence, 'attribution.licence'),
|
||||||
|
demSource: str(a.dem_source, 'attribution.dem_source'),
|
||||||
|
url: str(a.url, 'attribution.url'),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getJson(url: string, init?: RequestInit): Promise<unknown> {
|
||||||
|
const res = await fetch(url, init);
|
||||||
|
if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
const memo = new Map<string, Promise<RidgeManifest>>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The manifest of a baked place: `${baseUrl}public/ridge/index.json` names each place's directory, then `<dir>/manifest.json` is read.
|
||||||
|
* `placeId` picks the entry (unknown or absent: the index's default). Memoised per index URL and place; a failure is not remembered.
|
||||||
|
* Rejects on any failure: the caller degrades to the sky-only scene.
|
||||||
|
*/
|
||||||
|
export function loadManifest(baseUrl: string, placeId?: string): Promise<RidgeManifest> {
|
||||||
|
const root = `${baseUrl}public/ridge/`;
|
||||||
|
const key = `${root}|${placeId ?? ''}`;
|
||||||
|
const hit = memo.get(key);
|
||||||
|
if (hit) return hit;
|
||||||
|
const p = (async () => {
|
||||||
|
const index = parseIndex(
|
||||||
|
// The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and planes are content-addressed.
|
||||||
|
await getJson(`${root}index.json`, { cache: 'no-cache' })
|
||||||
|
);
|
||||||
|
const id = placeId !== undefined && placeId in index.places ? placeId : index.default;
|
||||||
|
const name = index.places[id];
|
||||||
|
if (name === undefined) throw new Error(`ridge: index has no place ${id}`);
|
||||||
|
const dir = `${root}${name}/`;
|
||||||
|
return parseManifest(await getJson(`${dir}manifest.json`), dir);
|
||||||
|
})();
|
||||||
|
memo.set(key, p);
|
||||||
|
p.catch(() => memo.delete(key));
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For tests: forget every memoised manifest. */
|
||||||
|
export const forgetManifests = (): void => memo.clear();
|
||||||
155
src/app/features/scene/ridge/nightBodies.test.ts
Normal file
155
src/app/features/scene/ridge/nightBodies.test.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
268
src/app/features/scene/ridge/nightBodies.ts
Normal file
268
src/app/features/scene/ridge/nightBodies.ts
Normal 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();
|
||||||
|
}
|
||||||
190
src/app/features/scene/ridge/nightSky.ts
Normal file
190
src/app/features/scene/ridge/nightSky.ts
Normal 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;
|
||||||
|
};
|
||||||
271
src/app/features/scene/ridge/nightSkyData.ts
Normal file
271
src/app/features/scene/ridge/nightSkyData.ts
Normal 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 = `
|
||||||
|
B0g5aAsZQkQONRogHphImydWX5x6KSg8kcYotykZTThrwSpB6zdVdCoYp1FuhzAuXxGZLjERJD+IijJ2A5YjKjQOstOcjDckDTF6lzlm5a9oWj
|
||||||
|
t0JY8gcDwOuVLbpz9L6vTfVT8efIgcK0EOs9xlwEEeu4RCJkMNYJx6KUNFKGwFkUMUbErLVkYPioXFLkloT7s7S0kOzTkHiUkOAjqvqEkSWWLZ
|
||||||
|
HEoZxTtKfkoQu4RCJksMIew2PUsSm4mWz0sYB1etPEwOUyTpxkwx/3XS10xOKUx2Wk07TMQZT00YVlldK01ZHpMixk0Q+LvZQk0t6z/sv04aUb
|
||||||
|
PUHU5htEZSl08Z5dlPL08PSF0xMk8bCUR2ZlAO0VBarVAa52Svc1BhnBZeoVBSlKrdpFAe/Rrz/lA308mZWlAOwAdrZlFMlDw8fVEPfgFfqVEU
|
||||||
|
ZgyoslFo0z0/clEQhZZGTFFMWZ526VJii7vckVIgQfJSPVJpdCE/ulIWDn65lFMeYYdeOlMYSdlAuVQ7bGE6QlRsNAdo0FVUBjuTf1UOK6b+pV
|
||||||
|
UYZr86yVVl+FUbR1UMCmOyK1UiBxYzvFVeogEf1FUq7I4dzlUalrM6T1ZSwpH1M1YOypyaPFYPpZsLRFYQuqrTX1YTqXUv0FcYrATVQ1hQ2+cL
|
||||||
|
jlhm47x9SFgOAfbwp1hsLreiaVkc535dzFkZTuMC2Vkk805TVlkVjN1QsFlMFQpZ1lkSLvaflVoX7mPDMVoQaCDQhVtripS/PFsO13cwnVsfRr
|
||||||
|
H4cFsaJzunZlwkz4INZ1wUfIHcN1wTIsuBVVwdOG44nFxSBqOnclwU8z/stFwVoqvVY1wWYRSXnV0gYjyKT10THYa5Xl1G36cjiV1UQg+q1V4g
|
||||||
|
Y5Qqml42vZ+nQl4OzDQrr15m+3K3OV5GnIasHV4Pzbr1Sl4Ot009S15qVZ2Bpl5KvMOUVV5e5NIYj15lOK2+el9o7658119GVI7JS18bYZ4vaV
|
||||||
|
8gTnJrJF8OojuYd18NCrCQnl9IEL1+hl9TP6ZzRWAPuzbEeGAgvrpiymBKlAQhEmA4sYJyLGAOrVZvXWAuArLyrGA5+cTYW2BNDLHeV2AMWgKY
|
||||||
|
lWEODouWj2FIWzp5YmFCoClYrWEfzqnJJWEo1bkGMWFiHRVvKGEn9e1MKmFecShIomEUqtIvwGEYXegQaWEoFUQEoGJr0VBarWIbSSrnuGIQXa
|
||||||
|
NSHmIZdqrcWmIQb66aW2IgZ8wZYmIqfk/Ki2IU9ol/tmITnOUTeGJC2iAYzGM84UgEOGNVUPL7qmNEUSrJbGNoT4WCaGMW/roQOWMQsuuLf2NK
|
||||||
|
z0e9o2RfJ2jPoWRBrzVTvmQ0CMG7VGRLocu3k2QaCBfCsWQgBzwRnmQQzYHUX2RcCI4LX2RHoif2w2QSYGh0I2QnDXdJv2RSluncSmQTnEM+VW
|
||||||
|
QQNEsaXmQVCZt7tmUiy73uRmUyxhjDe2VgfZOXQ2UQo24Fu2VoOogiH2UQr6Mp5mUc5sw64GVL47PjSWYPIdDDp2ZSEtn6amZALl90iGZLfXP4
|
||||||
|
aGZYIsO3S2ZnA9y9PGZLZT4hTWZTvmPpsGdmjWXiLmdmsntfJmcX2p8eRGcPF7VeMGdp3F9TxGciAbhTo2cdArhZtGdhfjakumcQt0aRQmcU12
|
||||||
|
V+yWcw5bZ13WcTHsidWWcUhzPmiWgwTjYvYGhi5JyXI2gl67RVjWhSTeL9qmhKMr5RS2hUVPxo7mhMzaMwRmgOWNfUfmkWGOVa5GkOsR+tRmkg
|
||||||
|
ZihqFmlq7a1TeWlJe8p9rmkW3U9qQmlkysPge2lI/gbjq2lZtjC3MWkUkUjoJ2kkd5YNWmlRP7lyXGkOYvR/aWkcpUICoGppuaALXGpub6Tc02
|
||||||
|
pTwAuOPWpGojfzaGoUvoIc0WodHG1kHGoVXHBFKGoU58ulWGpUfreBQmstblOkXGtX3XfxlWsY2bnRL2sS1L8ZcmtKOy0mJ2tGmezG0mtorzmX
|
||||||
|
fGsQDUhXkmsut1pa1mtDM89uhGsp1pAnf2seCKRxQGsQVhSN2mwSpl0hiWw744nUhGxo7CA9t2xswy+SlmwitG3FKGxmCvJnj2wUtg9kQmxoGh
|
||||||
|
QRqmwyeJO2RGwOL6LnNWxHsKpkSWwOmL1sp2w+U93YIWwhY93y121Huwg50m0182EjLG0Qom1NoW0ox8sOeW0UMgyEcW1TtW0IvW0a58hyr20Z
|
||||||
|
CB2ahG0eyirDkW0T+UpFWG1ww1SmNG0QwqJhr21IHdW4m21onngRr25f8Ld3lG5hjvP9om5ITPMEN24dgBJVaW49WaBxuW5KzMSfPm4QQ8r7YW
|
||||||
|
5URVgQjW5jUWcRjm4y+GvXl24YgPMm3m5OwS9Hm29MP05Dn28q0qgfe28XS7Jat29He+zQiG8dsCcdcm9HlTsgjm8QHGpkMm8VM3uxUm9IBLwZ
|
||||||
|
am8mrj3ram8eyJh/Pm8QdANzc29WRRi9Nm8T2S3uT28Txnj7am9R4KNtTG9m4tbgIW8/bBEoxW9ZkVKyom9I+LPuSW8PvsNw528yi9gobm9I4k
|
||||||
|
2Gl3Ae/poxq3Balab8V3BezIMYKnBg8A5cdHBOaSTXjHBGdzhEdnAUPT0SYHAwYklMsHAepWAQw3AZdWVyRnArtlIASnBwjWxubnBMWX6CgnA0
|
||||||
|
RBDTlXBKf1y8NHAQEos+GnBUX7TAQ3Be3bqyKXAUd73zI3BUrfUyvHAUOB7FpnEUvSg1onEUAtzBlHEvcX0ZIXEhLy45lnFKaIfwfXErHZaO23
|
||||||
|
EWFN/dLHFYkwamzHEP36amVXEQLsHCOHEVA/fjYXFWm2Wv2XEqNqjulXEcFV3NUHIQaIfwfXI58qRkqXInIedNaHIpeCMOYXJqxTP4h3IQC2gZ
|
||||||
|
J3JWY/irhHJHnRSaNnJE+idLonIUmr+YqXJIXD/Za3IqhX3zw3JUCalehnIggNQciXJEUDR4g3IQ6j80zXJLjp2xgnIY4OB5vnJsoeIbtnIs0R
|
||||||
|
NNcXNS2yWMcnNF81NLRnNNT8GajXMf1STXjXMUvuQgYHNLBfQ4dXNrxjVrunNWvWAEPXNVkK49m3Mm2b3Zg3Mb2b7i0HNU2u8U03M3WR5+z3Nt
|
||||||
|
vi7ymHNKUDsgJ3NChLMILHNoYOfvEXNL6usLpHMvCSiOvHMu6VnwIXNSgMsUYXNMtc3my3NJYdyhlnMWz91+cnMZO/CDx3MaOUy8G3RNLXRMLH
|
||||||
|
RIZktBnXRAPk+Ip3RM88+RyXQgwtd5wnRZsCHLv3RKEWn203QoOG43nHQ5MKb8jnQmMKb9jnQmWbxuwXQQOTxNfHQNdT5OYnRKTm8OaHRj/TCI
|
||||||
|
VHRKWmNXtHQcn291LHQoKrDSgnQaF9NbmnRgA/wSwnRM4SfrrXUcJXSpsHVNB5UfRHUP152VD3VgV8HnqHUYO9Pv43VGvy+zlnVIjlynPXU8H1
|
||||||
|
/AKXUUTHFpO3Uo63qa4nVqmadlpXUZN8T1nnVUhO4GfnUW3CfUI3VSvT1fN3Ui7kNyUHVFTU3sWXUQSW0YRHUcgHA8jXUSCapGlnUxaa1tJXVQ
|
||||||
|
QsZGdHVcKC3ZQ3VQtIb2OnUcVb/6tHVccsIMYnUkFwrBtnUgJSLGVnUzJiinonUWdDGoa3VQ4jqNTXVSoEmbXXVwxoVpGXUS9IVA43USGZVHQH
|
||||||
|
UPH6KvOnUWrAHwPnZMjmJKg3YWYWn8pHZWMJD0R3ZU/Zzzd3YsHapzVnYPXR9Yc3ZQEXmAMnYSioMNf3YaLa7dwXYSnbDKD3ZGrdTlsXZM5Vlx
|
||||||
|
enYY/9NugXZGLfemP3ZMOiuEiHYahF2EPnYZFmdffnZb3HYgLHZW/ISPOHYQUab3anZMKAxtMXYVY7X7q3YY0OJ2h3Y0IDE7e3cPAFJqcndMhc
|
||||||
|
6eZnckqQTgQXciR13RmXdPlnn5jnctf9+MuncaORA1OndK+x4Jy3c+hUadZHdOGlK9GHdN7I4czncgD6ksUHcX8PKDoXdO8S6eT3dk2T8bQ3dS
|
||||||
|
3EjEUXcOdFLSVnciEoKFNXcS4KuaYncXcNVOGHcYfT6tt3dSdlzITXdIHWBsu3cvAWJfJ3cQHcArhHca6s48RncU3+8jQndMa/lpY3dQ8hX/5n
|
||||||
|
gYpEITd3hbqU1ZH3hAFdjcw3hlb/gtLXgtVhUFYnho6h4LOXiCb2CSIXggAW+2Fngqy5w/SngQaRgjsHgaUV6XWHhYJ480znghAatK03gzzaxS
|
||||||
|
ZHgbp8dqGnhSsc7FQHgUj9owq3gtfPOrbHho4f/CiXguwTJfe3gSo13nqHhMf4HUXHgpMq6rOHhPmspulXhP98rWd3hQC+bXwHhG9PDVf3gU8T
|
||||||
|
X21XlHfH1JiXlktYmuLnkQ+MCOg3lEPdsTkHkSfCrmsnkaNSzbw3kYxyxGdnkqR4P5JHkQ1smAvnlonSGPxnk2F3mTiHkW/ZgeSnkY0Jm+yXky
|
||||||
|
Epy0OXkSGJ35TXlckqGaP3kQagiDonlRDlFApnlmQrVlNHlibhIWyHkXWhx3gHkOsDQ4k3lSokngbnlgoViaEnksOl1YQ3lEdpN3lnllHaNfLH
|
||||||
|
keD+F9Z3kYIGbDK3oaS3X5ZXpQwnnZZnokLph3d3oz7eMqnHpQvOeY03qONRHjuno0MxlaHnoabSBmXnoh5Ts2jXpIqqjNmXpqkBxRR3pMXxzp
|
||||||
|
HnoWfSVmknpRbFMMPnoQ+XA0EHpomn39KHpGIINYH3poh6avIXpUWswXSnobc8wMSHpVjN63WXpr9e/HQXpoMR0DxnoybEC4jXohVkvEaXoTJ2
|
||||||
|
nianpH7YBrjHpKffX5NHpKIMU2OntMftR0RHtP8Od4pHsuge2vtXticPwAiHsyUS3ZxHtIlznldHtJB1zcQnse26WZrHsSh90PXHsuhPwNv3sV
|
||||||
|
JkW+nHsSx0xMf3sYOYEbJHsqkqk1aHtMPao5pntW2/JCDHsj3gWA2XsgvEAVoXtCB1wciHsZIrHcTXtoqe3udHtKyyiETHtIBbqeXXsn5fGJWX
|
||||||
|
sUPCgPonwW2E80rXwpP5iLwXwddZMBT3xkoJdjcXxcHsg4nXwwV+0g0Xwn+PJPkXwyzjp1iHwSxlR1X3w9u7BavHwYKyU/1XwtlDw8fXw5oG80
|
||||||
|
tHxGnfS4UXxKKfgTc3xQLS+0n3wgscN05XwUY8g/eXxQSMmOJ3wSmNqX2Xwjc92wq3xOs+QJI3wy4fdld3xnkQO8I302VB5/tn0qfSaKxH0WVC
|
||||||
|
jvXn0uypIBUX0s16uoS30QP7CkTn0R17Ks9H1GqNPPrn10GeMGuH0fUuggxn0TJVSWO30SU7LBEX1Oedg1bn1OOQys+n1WWwwww30WIRonPH0S
|
||||||
|
LR1KbH0ShC3GNn0oMDGvun1WATFzjn0iZVlsvX1mu1/dkH0gfm/QU31iOpqn631hvRIGjX1J/T9UwX1vQ4MzD30TAIbRun02x4ylp301oJUygn
|
||||||
|
0eOqzov30WsrywbX0dUx1ijn0oiyO/Qn08AiY7YX0UczHKkX0f9jaMc30QBVeqPH0OgInbRn0k5YsGOX0QS6PpO30Vod3uln1N0OtGbH0WMQs4
|
||||||
|
i35JVxoIjH4WjiaSgH42WC9yoH4mLTKmoH4SXlIUqX5RqHHrMH5NvX7GT34UNLBfaH5H9OMOaH5GjvYaQn4uTvoSiX5O1iucx34abi2ljH4WMy
|
||||||
|
9/mX4cRzRa3n4a0DhCbX4MmGap835jMrqFVX4t1bsNSX5Qy85JQH4qFOjt1n4zV+vp234qcewvr34wRPD/UX4aHfyJvX4UCSjMon4UBV3VhH4P
|
||||||
|
53vUfn5Lscl6tH5tt9dz0H4eawo/Vn4RpGWqoH5mtIX3aH4sW6QotX4o2zEFZH5qrE+xjH5glF27bH5GK35HJX4SHpoBCX5ahJ4GQn4S1aej7n
|
||||||
|
4b/KtSYn5DJtxtfn5IpAxvzn8ishXug38aqkWxXn8NjlwBK38UioD0JX8mcYlkOn9e8pjOL38fxKZ1Q39gCbm6bX8aiMNKs39U3FbBe39K4WIq
|
||||||
|
Ln9qpJUkP383LKMfVX9QDLrjhX9k/ucHUX8W6uesmH9UsR+tRn8dESIOnH9MSz2CIn8kvELzqX9ML0oW039EvlZpHn8UAVnNEX9TjGbOOX8i/Z
|
||||||
|
l2P38uhsFzJX8kjwb0r38StQdGLn8ZcCVCxH9cgCtnn39OqjOojH8asDeYbX8UkD/RTX8Q8l1NiH8XyoQ0qH9SaZZvRX8Qj8GanX8RD7sk+38a
|
||||||
|
IcSLKH9j9sd7tX8iXMjbmX8glM07tn9YMtErfn8V6+/Zw39tnAV2Jn8W2wavqX9EpReUjH9G8UIFTn9L+0m+Z38WEmw3jn9izNGemX9A99HamH
|
||||||
|
9OSdXUTX8SMvs2Sn8UDztxmoCAcIwfeIAYRbR1joAVEjQ+eIAmOEaoNIAYvFVRg4BYXHXyQ4AeEbn5YYAsHc2st4AS6taF7oAWiOP7M4AihPjw
|
||||||
|
coAS9/mkYoBi3Ui9M4BH/k2CXIAS8FahZIAShKD5goBNTOrKMYAn2PlJoYA3NBQmPoBohjt+jYARAD/WnIA2pkwDq4BYBVX2OYAQkXjXrIA2Rp
|
||||||
|
48WIBfzLoipYBhvL/vqoAsvfY364BBrvi7UYBSWQByd4BqLApNoYBINCjJboBqWUEAlYAQv3WznIAcbpnOR4AQIps9OIAQea/AZYAn0t3ZeIBs
|
||||||
|
y+/4f4AsqAjJioFkYi0ddYFCvEYQZoFSppyGk4EcQqh1ioE3k9nHrYFcD91wlYEpL+OhsYEU2+5HyoFMmgISZYFsCBLNh4FdmS2pK4FPOkSIho
|
||||||
|
Ei1VedRoFUOVzAhIFWIMphIIE8xc8Uo4Fk4TF2RIEqhTceb4EUuFBKYIEyWlenR4FqoljcS4EkBGBURYE5/nAkLoFqznJ0DYEQYbB4YYEgUMDb
|
||||||
|
gYEabs1T6IFYutB+ioFUDx7pUYFKsjcRhIFUYmQ8pYFWbX7BP4FagJtNqoErwevCR4Fe3/H4voFcAfQ+UYEXWh2WZYExniNQqYFmzigw3YF32j
|
||||||
|
RyzIEYEzVwgoFfgkhug4FQTHjOeoEkcIHzN4ESgK9ePIEWhfY7XoFGH0I1lIIQfUPs04IaAkWqUYIQlGFkyYIm6mC+GII3/WsgsoIiaHeJX4Ia
|
||||||
|
JdFsx4Ish++aI4IYWi82loIm0kfQkoJT5kx/PYIpB1S6SIIQo11DL4IQFGx4f4IXgJ/ReYIpk+I7joIyIu17uIJe7vxQa4IX2UVtioIZkVHhWY
|
||||||
|
IQN1McW4IWMWYHyoIaYm5LMIITjnQyo4IaEpPTmIIx9K6AY4JMROFvXIJqKOwVUYIcz/yIgoIj/P+8IoIVvQzLqoJQ2h2YqYJQ0yqYJ4JsoDCq
|
||||||
|
VYJKMT4eMIJQM2XeTIJhKKSiK4Ii1tWH4IJbKt0oNoImZd3j0YI0teHTb4JIG+X8YIJGFvBUvYIUQgNQtIIcgBrc34IfEz65t4JI/2bHKIIWu5
|
||||||
|
j7bIIgY6f5m4Ibi7nUtIIYytRbWYJiI9iOp4JYlPZhjYJokPdExoIo2whsuoMSfh7csYNnA0Cge4NWT1FEToMU3X3BnIM0sY5DKYMS7443JINE
|
||||||
|
/8GkPoNMw93ls4MUBvZuhYMTnAVzJoMg8werxIMWrhXY5IMhUSW804M1kTh2r4NYO0ZWX4MW908TkYNZu5enyYMjyqBTpoNXLKLaY4MVHqSUS4
|
||||||
|
MSYaYPQIMQEbrEeIMsyr1rWINBAP/G0YNWHjaJTYNVrkp67YNdFmbDs4NHeJ4qm4M/Vq6gXYNDLOHDw4NohPolkoNIqgBYZ4MWciqtKINqKWGv
|
||||||
|
toNNIWZQ44NA4ZMTUYMS+5mvP4MSdOdr5YNQTTzchYMUsGVQfoMeJ268MYNqaHLcKYNuL6/1k4MZcMGHV4NIU+WeoYNqaO4vwoMUBu9dxoMeCP
|
||||||
|
7+V4MamCa4RoRN0D5Fp4QYbmE5W4RoMGnMPYRVyryc5oQuLNQ/ooQWztWXWIRsWQd1PoRKnSfuSoRVGzpnhIQPoDseeYQQaFKXV4RqQ2njzIQa
|
||||||
|
iKn6W4QW26xIWIQRrLvcPYQYvMk0oIRAJ8xnRoRQV8513YQamt6JpoRCy+/4f4Q5H0X/dYQUe1x824RUL2UPfIQwlGtrbYQUwHQuS4RMk3c3Ko
|
||||||
|
Q02ozHKoQVYJ0gmIRKkp/E3YRogaTpSIQZMdGcXIQWAfnDoYQi8wDhd4RNCgMDt4Qc6S2Hx4QbT1XVZYQdf3Y4J4RMh85PaYQeXNsisoRpMBSI
|
||||||
|
hIRIAzuddYQMklHhWYQ5GV22dYRDzWLKSoQwg3vTMoQVt4nhK4QSE6avcYRMXalfvIQ1ELx0dIQeFsDAeoQs/8n6hYQiEwoq1IVJ3B9ZnoUb3B
|
||||||
|
9ZnoUbAiJVuIVQ9Chy5YUaskCknIUnGlRwOYUOOnZuioUqCXjYoIVs0agTpYVBS6vULYUlnK8YdIUiUPFOyYUl4jW0noUhnU1YWIVpak/9xYUY
|
||||||
|
9VCnV4UUF4chR4UVU6d7QIUtEKlgW4UWDMA2hoUYTcFrjIVJlMVtJ4UU9cXSQ4VMh9V4p4UiHA32ooVNjCn+XIUSrzAclYUmbTRvjoUe9D5FJo
|
||||||
|
VOt0m9koUoIFD3U4VIP4ipL4UR9pLaNoVJz5MM3IVoPav8OYVHh7OqcIUwergJtYUcNsOKWYVsFPYvx4VOtAzqnYVMDx1np4USpyrYXYUSSUcS
|
||||||
|
joUMM02FWoUQ7E3BS4UUB12InoUaim8GLoUyjnHUK4VjKIBoiYUg+oagdIVWkoeTOoVQ6ZHEzYVrGsl21IVUYs97gIU3Ke/1gYUYmv/Bo4Voex
|
||||||
|
PNcIUqOSVpxoUUGEHCaoUc8WFU2oUqEqcPT4VKA8DSl4VYO+AfUoVGfOfNyIUTJTbolYYW40lcY4YsjVUFfoZk1machoZbSa4UEIZuNcRLc4ZI
|
||||||
|
a9AS44ZAnNvelIYemOZQZIYQbxTKH4ZIIhZVVoYQZi/slIZKpjGjloYgWV8ENYYTIGT+VoZH22Q4YIZSHYhFKYZOWZAad4Zq5cDuVYZAq9Hiqo
|
||||||
|
ZK1+FojoYmtubUdIYiROs9L4ZOQuvvfIYWavI4ZYZeGfcPYIY5yB9ouIYc8x+rjIYTelHtW4YUtGpwi4Zp23sPcoYVe3yWToYWy5C1xYYfMcVI
|
||||||
|
a4YcmNSYWoY+sxA91IZL4xmBx4ZmUC2TuYZMvDgHuYY4+DjLYYYWnzpyfoZoQ1MLPYZOAWGtG4YSjXF5rYZCQ3RsvYYWyIsTO4YS6pRsJYZQUN
|
||||||
|
QIjIZOMOM+UoYcV/T194ZgQPtBYoYakvtkQ4YdOSV9JoYtUDZDLoYzVledbYZI0mMSW4Zq6X35IIZmxYAqJoYV6aAVPYYS0qvBP4YkhMcgc4Yq
|
||||||
|
pgWKzYcUcSXIeIcUpCh+SocYNDl0f4cQS33mZYdKyY2zuYcoIJSXUocSRLTAQ4cySbhdf4dSst45c4cpvuZL2IcolecrZYdF2efgqIcxRw/k4I
|
||||||
|
dOAjRElId1aD4OtYdqRm8QsIcmD3CcGYcbqXV3fIdqr4NOmYdM8I31ZYc84JP8sIdsdacDZIdoUdD/sIcS+N+Vw4cWHPNC9odYEPxMP4cdLxRw
|
||||||
|
m4cXChtRaocwaRz/QoccaB4gYodGTx49FYdcXlfdQocik3B+uYckGZf/M4dINZgNyYcjl6eiTocSOMshRIcYpfje4IdD2wfpcIdMIQ7Gpoca/C
|
||||||
|
Cl0IdMJzvIrYcqRU1ZO4cU71bQKIcudGAu4IdmjI9IaYdQrKDGw4c5HanVnYdmKqt5wYcUQ6zls4dM978gXocXAtnabYcWqdvXKYcnmfY4pIdc
|
||||||
|
lgWXOocabAlffodoakhui4dfqVy0PIcfV2dyXocTuXq6e4dmBJm8P4cocJmHWIdacavTb4cwhLy4OYcty8Uh0Yc3jc1rnocW99UKSodgGjAHl4
|
||||||
|
giBjQytIhgkDt2d4gMqD6jgoheu1fxTIgUvHhOtogfeorCmIhn661OV4gaPrmdH4hWDNhlpIgQd9qqZogszd4gv4gSSQBlEohY9xSOoYgnpynM
|
||||||
|
e4hIUjUrbogm/kZtvIhWn03XXohu61TbVIgghGP4bohI3GeBWIgyLW6xm4gwqolvcohpCbBIXIgUFMi9I4gjaezi5ohHce0yRYhBn++thohOF/
|
||||||
|
KuqYgYmQK8nIhoegfWx4gU0SJ0c4gkLygW2ohB8y7PmIggPzy9dYggWkOW4oga2WF634gypGNocohIRYRUyYhE8YtJp4hjYY1wH4gVzI3Hh4hs
|
||||||
|
57vJ4YguuP8VyYh09wQOUYhrlzXMdYgQ1UHSMYgOuWM/J4hIPGZZuIhKAITCpIgyMoYuoIgZiJiAsohOWZrUfIg8Dp26pYhsYKCRo4hk67rrXY
|
||||||
|
gZQb77RogmgsTJYohaf9gXtogude5KqIgZifDZJ4hqbwnu1og02BbXtYgfVCOrsIhkDzculogppT/ppIgW/Ebha4hkZVWYJYgQV1kJO4gSWHH2
|
||||||
|
bIifLXJQJIgSgnIIJYgSt4TTNogSVJGes4gk6JZJ7ohd6aAVPYg5SKK2QIgQHKm2sohLl652gYgqa7NlwYgehrX+eYhjargTr4gQn8Q+3YhUrM
|
||||||
|
lm5YhSLtwmnogYseP1RYgaHfDQcIgWwvypZohCxwnf04lWlQ+TwIkuLxRxm4k51BSbPIlFrxfovoljcSPLhIk7cThfTolLxzdyIIlZhUk8Y4kP
|
||||||
|
PkyZR4kQI1n9UIli4WLUzIkio27DRIlRtXmOcIlnL5evo4k0ppyGk4k5E6tuoIkd8bHb24lWE77pUokXMcjrpYlVocmmX4lgJcqvd4lPJtW+Wo
|
||||||
|
lGs9eUwokeCBC8iIleBxYzvIkaXhwdb4kwbh3VH4kcjiNe3YkSJS0sjYlBrlGESYkQ1lZAyYkcHXCdz4kz6HCt64lJb3UlhYlTd7BWkIlkCd6V
|
||||||
|
wYktyODDY4kiresxh4lhvhT2X4lggC4hwokY+U9BX4kk/3JvJIkSYn2+i4kiTIuPOYkaz4w8Sok8mK7vq4lKuLLB0Iksbs0UXIk1ZvIZRYlMx/
|
||||||
|
LpM4lUgvaB1IkYffi1xYlseA0LHokwthv0h4lEuDe7tokirTyDl4kSDD7woolMnVt/LYlL4Fx2NIkQQWxQNokTt4Q6JokT2Jgxl4lWvZybi4lL
|
||||||
|
I6OIJYlYbr/vQIlWtsPNhIlG6dLlY4lIxP/xeolIXRissIk3HyLN6YkaOi1pcYlUxz7tT4kSOEiJ1IkdkXjXrIk5uo0FIYlkMbZ4T4kmErt3zo
|
||||||
|
knDr0pYYkw4cdPTYkQZcq1NIkWcco5S4kts/1q04lQow7AwIpPRCP7X4pGijNQtYphPzoyn4oS3lJTmopiwFxTaYpOo2keW4pWcoeOjooeWKqx
|
||||||
|
a4oUDrt7zoomnL+rRIpsBNx9KIoupvGJt4oP0/9Lz4oWAQIAaooyrwh8yIoU8hmFbooYpiLtnYoYBE29P4oYZVz1VYpGNF+hWIoePnCbM4oySX
|
||||||
|
EDWYpqRqsZSYoSobSi3IoxitIgtYpI3dtffIppId5BPoplOQ88a4pWWhvZV4oWjkPPe4ppPkoiwIoavUzrt4pioVEvsYotjX5DI4oUeok2nopG
|
||||||
|
t4rIq4pUjrGVxYpmvcc7dIpR7dCXO4pQN971T4pLL+bNtopPfPSJjIoZ2BwpuYo2VTDwf4pbljV7Y4oW4jwYgopUJD7+kYoWbUQYxop7h3H/Z4
|
||||||
|
pHmn1mRoo673/AEIoWA4mlT4oXgZM9nopgQ5fQaIpvk5jKDIommaIsU4osuq9THIo0SrYekoofm9rle4pSUN3wo4pUEup92opyrPpE04oTfEz5
|
||||||
|
eYpMdl/DK4oQM43xK4oxG40auYpOW5nbLIpEVZ3zTYoaLKDic4oZoqvWY4oYdskeyIpGjtSUyoofud3jsIpbeOy1UYox1R8JsotWmCxGRIsqTC
|
||||||
|
4psYtI40COaIsl3kZrO4tEXEt7OYsgSVXEeotWMF6QP4scL3DdF4ttdYcdK4sXzIoq0IsrTKFeo4suq8q3rYtiz8tJS4szAtdktIsSJ/3CqYtI
|
||||||
|
ugfgwosi4hG1uYsUiBcYq4tAvC1EnYsmNDXjtYsbwzhsn4tIAlFJNYtf2VFKaotn9VWHp4tRx2IlSYtQgmf8XYs0wWn2ZItoSHYuWYsrmnyyJ4
|
||||||
|
tSLYaV44taMYkrp4s6vJA0hYsak5xZl4sYg53QW4sqZ566fItKTaRRcYsvEK1NMotNzayvcYseurBbQYscmdS8tosVptbKNItq6/OZvYtnH/rJ
|
||||||
|
gYsazQANcYtqGBKavIs40COfvYsbSS7lpotSvDmggosPmDxkfosPVEDtcIsTJULwlosSAUq1OotuTXoPhItL6IIOootKsoTHposmWoVq4otqR4
|
||||||
|
wfX4tORqrdzYsmx62964ssnMM7n4toOtEBdosZv9MnoIsS39edlYsdrdqexYsUs/S7xotyhP0EwotQXg0+P4s2MVA09Ytsnk70ZIsXnoO2hItT
|
||||||
|
KacgXotclqUB7otoD7LEZotQRcC2nosfpcWzPosUzc0LZYtMnNSw04toiSdOsIsY5ioiKYtguS9El4tSMz80S4tQrVBYa4tgLVQQposeEGE9h4
|
||||||
|
tWrmUSkItO9W4/3YsWNn4fHItf84/jXotpiJM1ZotOWJoOVosWHsKqrIts9c4gqosU69dYtIsgPQ7R0ow7qhEgv4xGAhfkpIwq/STGxYwUL0N8
|
||||||
|
14x0/E0SXYwSc1xBboxguY+Yk4w82pDhtIwt5LUKlIxpFsJKXoxOQMSg04wdAMr5hYwjtPhUcowYwPmU2IxtX/uNrIxeQxLAeoxenxSv4YwUyR
|
||||||
|
/gJIwgtzkrtYxgrTm4mIw0FT85z4wcC0kfT4xeL0v4eYwPOk8xjYxMUFJ/04wdtFeLaYxOklpkQIwRwG7aIIwSd3WtiIwhZHnXvYxKBoigwIyY
|
||||||
|
lKqhRIxL7Kp0qowWsa3KOIxBzMnBX4xcz8tJS4wzJM0R0oxT7NL3r4wwGtZoUoxWKuyVT4xjgyeTUowRKCro1oxihTZhyYwqqDaEmow5ZTkKhY
|
||||||
|
wS+kkGbIxUC037loxs+GEwQIwknma4iYxOU3I94oxednmRTIxi74IFr4xSYIOTMYxozIQmpowd8KPWO4wyQ6s2W4xWGqw+mIxIpK/N4YwW8riu
|
||||||
|
mYxqVMHPvYxG0dAfnIwUYNM5m4weSON/vowYWfX80IxgaPzGa4wlkv+OJIwcZhlCF4xQlTHCbowdzUJ9bIwVAEK3Ioxq90+zp4xQ9VOkTowvgl
|
||||||
|
v4OIxc52X4YYxMEmYaN4wQF5JnMowWEZKfc4xquZQZp4xgg5dtg4wT7MrAwowiUs5MeIxHCN/np4xjkuZ5uYwifegOVIwbfu5bkYwSagC7VYwS
|
||||||
|
uDWhWoxOEzh9rowkV0EES4wUqUdSv4xjBklru4xYhnAmPYxNmIR+t4xJP4YimoxSCqMl5oxegKUSuoxopqUquowdN6+nXowlD744yIwa+Mfugo
|
||||||
|
wW+NT3aYwcX+JEHIxo1gGGwY0tFwx+vo0egBY1oI0etBi8qI0b4SJxyI1SZiM+x40WNSqz2Y0Uyy+Oko0klzPvaI1KNzZ9OY1k5DhLsI0m1j9n
|
||||||
|
co0iqE31S40Q106go41Gk3Snr41QEn0gJ41Bu548So0Re6lRY40Yq7VJUo0Upbhzj41meMKV240sKc8kXY0kHtAIfI1wq9Ncy41ZieoT6I0vYf
|
||||||
|
H8eY1S3RLhM40bvhV9zY0VlECeWo1c7EJ0kY0u1lJJa40qL3vJU41o2YAsE41kz4z2aI0wwq+Qu41l3rMQo41YIL507Y0yQMF3q40zlMf8zo0U
|
||||||
|
L9xMoo0SPd6pvo0j3ejpqo0Yt+x/1I0mlf31hI2b2v1v4I0YwzF9y41OJTIsS40sWDmu8I0wQUGaJ41YHEKvdo0P9k1Zxo0d4k/9p40er1EjmY
|
||||||
|
1nhVafP41kSlzFX40+Vml5dI0bPXV/uY03Io9+FY1QBLvm4I1P1cPcxY1su86ZMo0ak9VCx41QStxYjo09fd6aNo1S8/inh41V/QRymY1sRSJM
|
||||||
|
fo01dSsh1I0yNDnEXI06jkEXHo0V+EQ6eY0QY0p8T40RTlLBP41AKmeda40S5o87N40dUJkRDo0Ub6OCgo00E8GZn41o4sdruI0hOtIRaY0q7d
|
||||||
|
G+wI0tVPgCdY1pC/2xjo1ttQgXmI0yowhxFY1elSjZj40SJjARQI0QoTF4lo0gZTV5841ZEjiuWY0UQDoIsY1fd0gzc41z3lHC+41ql1ivIo1S
|
||||||
|
r2XRjY1e/pfPLo0VAKcatI0TcavTb405ELgqWo1EssXsPo0Sj9aVoY0QbQYJzY4UbTbe044VsDm7fo5JoDtMeI4UGVM6SY4U0VdXTI4Q4Wj1Po
|
||||||
|
4UxGuhPI5Ft3A6Xo5p2nDjiY5IIHFJK45UY3L6oI4bfHXEt44lanpPQ44Ympc6WY5TG7FEy44XPbehQI5ECLf+uY5ZMsqfYo4geum6bI4sb+ne
|
||||||
|
pI4QB/G86I4sgfJ5u45Ju/jbbI5BcPmDkY5aqv4xm45p0gVbJo4bDCR/nY5XVSXdzo4cvyhToo4V0kGvFY4921REQY4QPlp/NI4mo2hzwY44DX
|
||||||
|
AYf44SfXlKZY4uUI91R45VA6NOKY4W3qluHo5S6Mu+j44WAOgVc45Q3RRXmY5Hfyfo2Y5qdCzF8o41zTPLmo4k+0VDfo4SE02DQI5nkU4TnY5l
|
||||||
|
W09xN45OUl7TPY4PMXShzY5d2IIwlY4cq40xU45JoplGiI4flMGCnI4g98MFSY5kusnPaY4i982LgY5SQNZunI5OdNw0Zo5sCOcwg45NOu6ZDY
|
||||||
|
5il+3MRI5HzPXPvI4eUwCxe44TVRSPQ44WhR9qrY4YpCAKK44qzygQr44diimaTo4SvzBLdI5uND7aII4S+02+S44RLFXZXo5RrWQVNI4UBmbi
|
||||||
|
DI4SfXmeI44VAH70WY5pa5+2Jo4ZRKZ6t45rHamae44fELgqWo5EItDFp44UvdPQjo40XduwQI5M9N1wQY4qJeeLvY5pleuT2I4d9PWUTo4omf
|
||||||
|
5aC45HkgLvdI5q3wN5Y4507g89YY4a6S50jY4diTZheY4W4japeY4vjEn54Y4SPFaoko4a6mILQY5sAGZOOo4TIHJ23Y5VS4iTl45cfZkDjI4Y
|
||||||
|
VZ2Bpo45HaqxT44f46pXmY5KDbnXoo4Yo7kxQY4WA75wpI5TvMMPqY4jT8QvuI4avszd0I5M6dD7cI5SqNMSt45udNzjKY40B/dXjI5iigZFv4
|
||||||
|
9pOg27dI8wmztVeI8aUEuTj49elk5HtI9PS1Eneo8vwFcrPY8S8VnCio9IjWJb148223bmJ48k+3p2K49PW4aoRY8kmqLH3480oawpVo9R97KO
|
||||||
|
II8Vycd/SY8eTMzi7I8opdWOK49mge5IYY9Oz//8NI9SoxVoQI9kURrpT48eaCUfkI8YAzo2LI9LnUABnI8UJUMVaI9aD0kZ4I8Q30i0PY8w0k
|
||||||
|
rlNo9qlkxoOo9XHVOGr49p3FODgo8T51i1po8wfmEb349kqmFan49KQWpjuo8wK4Ji7o8quIO1bI9Oz5jHfI9MYa2gPI8Sl8XTZY8ZO8ZjcI9H
|
||||||
|
5MdWuI8ia8phKo9eJNTP0Y8SoN3ulo8yvesFwI9oChtos49iUCNtx48WlEVgbo9YkV4wvo9KoXZbQ48a/XpbK48y6nvXKI9RHHwSKI8Yp4CmQ4
|
||||||
|
8t74P4H48i6Y2oxo8WA5NxTI8YZJTcfY9PEpV8XI8UWJ4/aY8t8qCYRY9MKKYcWI9a0bI0jI9mLr1INo88G81Dg48WUc+ms48TF9hvoY9Ny9wN
|
||||||
|
IY8W1+B0Eo8ypAyxrI8k1Q0jhY8dGByP549FDFiFJo8eGV0kOY8P5V/4K48uEm2aIY8k63Au0Y8qJYovN48W26L9RI82z77muI9U1r/5VI9ywc
|
||||||
|
WIR48dy8uPNY80G8/8kI9AMs8onI9KV9yxgI9O7uAqMo9WEuSviY8c/PP8jY8xa/dmjI8gBQUjv48aIwwbzo88Txlsz48sZh+4eo8d4C6seo8d
|
||||||
|
gz0NUo8LYT7kNY9Ko0poH49fb0tKL48Xb1LIRY9Q31M7bI839FQtP49YRFXVKY9w31luNo8Ro2fB5o9N6HkEJY8yW3z9Io9BtomxLo8T26DvJI
|
||||||
|
9IlqTxlY9sF6Wego8kIKbwco8UXcnkNY9ILtGQv49IotGth48aptjAsY85ON+Dk49RqOfa5o9OwQP/tZAu0wPIVpBLTRJw5JAXVB2zkZAlajfR
|
||||||
|
lpBkZjzUpJASGUtwopBI9lJbtZBogFN/Z5BZzV/SPJAmaXK2wZAqaHjcgpBlS3+bZ5AYZIHQFJBaUoQepZAdRMC2npBIu85ZpZAT3dfPqJAiJO
|
||||||
|
EAUpBQcuNC3JAXY+cFbJA5vP2ROJAQd/4bZZASZwUrXpAf6QjccJAyrBkex5BKpC0/zJAcaDRAkJAfADttE5BSdUf2cpBm9U7YuZBWcFyLNJAS
|
||||||
|
Eoy5cJBSTKgH2ZAbUtWutJAQivFu2pAcRAbjepA1VxkgXpA31ytAp5ASrjbVJZBsGz8s1ZAapEI+m5Av10RsgJBU50a/uJAW6EfPU5ATA0vcd5
|
||||||
|
BtY0vJQ5Ajf03R1JBOIVkcTJAQgFy8RpAYSFzlG5Aag1/KlZAg618brpBIRmg/0ZBqvnuX4pBMN5+BKpBTLqHhaJBoA6mFlZA5pK4RsJBpJbBY
|
||||||
|
KJBWibh1XZBQccjid5Bi79qZ6pAd1vCMYpAvXPmcapAjDgz/RJAhkBxrMpAtwEB1dpAWxEQU05BmikcYmZAcClc/QZAQMl5hUZBE6G8afJAWYI
|
||||||
|
A4vZAmqINnYJAUh5CLcZBJsZ2ANZBK1sRHgJAyOuEat5BUifHG0JBoAwl8N5ArURZA7JBIGR7WmJAWQy08jpAUyz/JgJAaTESab5BXPUUkL5BQ
|
||||||
|
eUhjxZBRmU9/npAsO1+3p5BL3Xm2TJBKwXzHUZBjHIjpipAqcYzumJAwcYzumJA5go2jY5BMpo1njZA2Ia0qb5Bg1bNcRZAdI8rKrpA2RMyjiJ
|
||||||
|
AqsdV3o5ArUdy7apAT5frNt5BMWwVQqpElbA7fqJFeshXug5E5xR8KfJEZYyTa25GBdCYoZ5ES6is+qZEqWjF7fJEnNjl0u5ESp0VrkJEgHlO2
|
||||||
|
PZESEFfSO5EPylxqP5EkT2DHNZETd2r0TJEo73KaJJEWBHNHL5EVmne8JJEW3ZjbKJEo8agfg5FMmK8xdZFv9bn9N5FOjrv/15E3gcpfk5E0/c
|
||||||
|
s5rpEq1t8bhpEw9AezYJEqHA3GipEpORLTnJFDPSMaJ5E3eSgLXpEdjy7aJZFJwUVjSpFLPVUcSJEsYWEsj5EU+GL2dpFUzW2GdJEo0nKiq5EW
|
||||||
|
LXRbY5Ew3YkR3ZEne5e/4pFo0p3lWpFIOqWJPZFwuqZjuZFFlafGSpFKKbN2h5EYjMBddJEsfciIRpFA1MgYY5FgV9houZFsx+KhYpFUPOUwwp
|
||||||
|
FKeOfqXpFIxOzW0JEy9/WV35FYMf0BZpEVFgIITpEvKgJ8ZpFjKRIGUpFO7xo5g5FY6idYfpEUgzkxbJEPT0j5vZE19008SJEap0/fiZEkX1C5
|
||||||
|
gpEkpFCClpEckGKFQpES0mY6uZEkAXSXLpEhuHs+PJEmsIvpspEVsYxSQpFOa4/tbZFl7ZPkNJEUz5ZWxpFsHqGXzZFJi65J4pFRGbAgnZFaX7
|
||||||
|
Q/d5FPnrW9r5EaeLl9PJEUG7x9MpEjUsREQZEQDsRamZFY3shLrpEdMdoZZpEWCvI1uZESRRXn25EaDR6tJpEewiAwdZEj8ihhpJEkVC53lZEk
|
||||||
|
vzA+c5FirDsYeZEla0gOSpEVmlsxLZESOGNlN5EWWmqykZEXMXBq9ZEslnxenpFKJ4AKZJEPk6J6qZEafaY8jpFI0tQ6LJEYUuLtR5EvH/MbZJ
|
||||||
|
FIBRDawpFLnBcqnpEuKiFXd5FpVy6k3JFCjTIMK5Ej3j0tiZEkgUPfdJEQTUWMOJEtQkbap5EYuEYBUpFUKknynpEYgFK6x5EZEVyoWpEX0WKy
|
||||||
|
0JFni2L3MJFK6GnaxpEdrX0dz5FYvpZevpFoTa4eEJFgo6/lJJEracPEopFmI8hd6ZFHoMpOpZFXPNLRkJE1mNUw3JFnj+tL2ZFgAu12+pEYyQ
|
||||||
|
EPC5JOhBHg55JJoRdNVJIYKxhxr5IYPBmQgJJs9xp9D5JKKCB0ypIWxiMTnpIWECoZyJIt8CrLfZISLy+Sn5ImTy+2rJJKgTnW0ZIYBU4wWpJJ
|
||||||
|
ylnNXZJjN2xlIpJKDG0iN5ImwIih9pIYvcloA5JZbcChnZIUCsYLUZIU98tXs5IU1s19kJIjqtQ/kJIYyNjPZJJfzeJsapJr4vwHapJekAzR4Z
|
||||||
|
IYVxoyqpI5IST9xZIWEy35ipIrSzKsvZIZ2DyyTpIW0T3Ek5IQFT8kNZIof0attpKcVEh7a5IXClUpg5JHQlmcF5IavF1NfZIbGWN8FZIazW+7
|
||||||
|
JJJ2d30FP5IThoOqxZJsJIXapJIW+ZddjpJLbLGqz5JP5bVJNJIxHLrNPpIWteVvRZJQDelbCpI+MeijoJJg6uiVmJIsW+vE2ZJoC+88GZI5hP
|
||||||
|
1vZZInwxhiw5IY6xu6sJJmkRx8ppIeMzO40JImuTYJnZIe4zh8bpITvkL1lpIS60lfX5IQG0+YkJIe5FJQj5Iat1axnpI4D3oUKZIV4nzs3pJZ
|
||||||
|
D39uW5JF/p70XJJbT9WnTpIih+AOSZIthuHbYZIag+cTiJJrheu1fpIkS/zHx5IWsP6Rj5Ii9gn5b5JlyBJeXJIswRegyJJI/BtFNZImxCWAwZ
|
||||||
|
ItSTFrgZITRTI0OJJK0TWTGpJLCzwyV5IwmD26PZJNXkG+ZJJt2UxnRpIcglKrpJJmGFaHUZJ4HF4ae5IUdmzFbZIrgHrxt5Iaf4L4PpJgnodR
|
||||||
|
JpImJ49JJJItGp7ga5Idvbp9fpI9q9XKIJJWdNmZh5JKsd/An5Jf3eTJtJISxuR0xZIdj/xiUpJKeyARdZJISUJ23ZJcLUj0apIdnFdi4ZJNdG
|
||||||
|
J2vZISPWeJLZIjOWmxopIkJ3jtkpJV2n26i5IaMoSiTZIV8okqL5Iap4q23pJavpm4XJJJPp/ZT5IbFbQWrZIoU9eoTJJEUdgWo5JINe0HYpJB
|
||||||
|
Gu/MLZI6O/k+rZIUSfv/n5JpTwceuJNG4h6GtpMtVSu6h5MVKDSRg5NraTQQi5NWzULZkZMYcEmM1JM5DU/1aJMW6lAIrJNMYlORXJM/gVrVO5
|
||||||
|
MSJlsSnZNY6F5qPJMmBGP2R5NU2G7xSZMmonyksJM9MI2nY5NEvI1zk5Nas6IGh5NQbqdFkpMbqa5/OZMXTbCHRJMqjbcNj5NoC8NSMJMWbMyv
|
||||||
|
HpNG4tNKR5MW8ew3sZNSsvb4wZNgrQuKnpMY2BLYd5NlGC4KQZNPvDYWjJMqvzixg5MtSztbfpMQMzunJJNNtWI/lZNb5G3EVpMl5XI/JJMUbH
|
||||||
|
P/jpMad4G/OpMYoJ/4EpNigsB3XZMzEsTZS5MShsUVUZMh7My1dJMgHOUmHZNmp+3AbZNSufxcZpNojhVUVZNFwhk5KpMsDRuHfpNMshtVsZNs
|
||||||
|
HyiaiJMTHy4RnpMVxjEMzJMpJTu8fZMQdz5OdZMPyUJU1ZNcU0hO0ZNJN01shJNUEE/CUpNOkFRHnJMXy1QiQpMQ81q7mZNnU14BIZMuv2UwRp
|
||||||
|
NGxmfxk5Nqjm2vqZMa04DSHpMYU4UQ05MjvaMEgZNU8687PpM1g7Q3mpNgfLn5V5NmPshI65Mc1dBRvJMcNNPXL5Mj4N5hR5Nbzuxp1pNUoPMM
|
||||||
|
DpMSGQd9npNTKwsDPpNGaCsFhJMybTtbhZMcLEG6tpMmxkHR05NQ30MFzJMuWkOlcpNXZU1bVJMQ/U+kxpMwY1fydJNGS2QaDZMw2WpmrZM6kX
|
||||||
|
crOpMiLHyRi5NoUpIIhZNQYp2TJpMoCcZ1ypNQAcpBQ5NLoNSol5M6d9Yos5NEqQOli5Nc9wskKJNF8ykVxJMVUiyyaJMSri5zpJMW2TKlkJMi
|
||||||
|
xVJmT5M321hKGpMWoFwvwZNKm2XssZNm/n8yhZMZwo7GZpNKu5qSOZMc4aPWrpMWZqSGR5MUtqlavZNsa6wRe5Ni2LsZxZNSCceUQpNtPcgnYJ
|
||||||
|
Nr5MdWuJM5WNXpmJNsNuCkwZMPb+yfT5Ml6u27M5M3Qu7gdJMWTu47iJMYKfZAM5NiywXcnJRPRwgClpRsVg9Em5QsPxbo7ZQoRCOtfpRNIiue
|
||||||
|
f5QyJy73npQSVi6lYpQYTjVncZRB1TUYOpQuozswopQULkEJepQSh0TiHJRK105qWJRmolbEYpQe8GRdd5Q57XC7R5SpQXLIK5QmWYPk6pQYI5
|
||||||
|
JkLJQYV5/kNJQg66aMZJREHayOWpRs67hRpJQatMKFYpQdE8rjSpQSW8qwmJRBtcrex5QQi8vwy5QY3dDnqZQ0XtuGkpQdjQfkIpQyBQlf25Qy
|
||||||
|
NB5CWJQaiy5g1pRknjExi5QmC0MjjpQetEh2apQU20vvb5QcVk7sNZQW2k4zUpQQ+l59q5ROE2NPHpQum3kAgpRIT3tGRpQfD4T5LZQUCZpYm5
|
||||||
|
QkPZwmv5QZlakbXZQYqq7ur5Rmv6/ygJRiw7Ybs5Qo8Ld3lJQ5ArksrpQ4aMNTipROlcN7aZRiR8UtfZRJe8b5jJQsstOxcJQsUtYr2JRU1tyX
|
||||||
|
x5QUyt2P8pRRHvf4jZQVaATv15QZJBTtuZRboyh+SpQaHDCEk5QmNDG2J5RokTLaj5QmNDxdq5QwQj+xnJRKIEX+dZQWVkgWN5RcJkkTG5QUuo
|
||||||
|
9B1ZQYMqhvfZQYvK371JRq8K5CSJQ4k81WP5RcrtHlvJQVp+xHyJQg4PYGg5RGDwJ2WJRcfghy6pQVng1xfJRGSxViYpRs5hzAN5Q1mCyppZQq
|
||||||
|
tjj/r5QQXlUg6ZRgR1+IkJRiGWXawJRKD2XhjJQ3V2btspRAom2Gk5Rqv33xLZRswph+kpQs+JtjPpRM1qe1aZQk2qpdr5Q3brTOnZRKQ7lFHJ
|
||||||
|
QX8MMdoZRpdNPiGJQkGd4vHpRRTORYYpRT6+RDp5QbqgEyWJQuDQiJzpQbSAo7qZRPDg/9RJRNEBEZapRWSBm9fpQosjqx2ZRuKjqLmZQUA0Z4
|
||||||
|
TJRhUlBMmJRSAVIySZQSL1YJ8ZQW8FooZJQWaV8rBpQoAHNmZ5QeyHfmf5QY+4VIr5RLb5ovdpRklqnlXZQXB6+SSpQUg8aZr5QUL8u9epQZjM
|
||||||
|
tEepRRsNPQK5QdXeK4WJRg0eqIV5QUvfNPSJRgDgU7R5Vn9gYxxpVrNQsfeZVQ5xUugJUgPBw7n5UhLB3/vpVGei/y8pVUiDcq6ZUT/jb6jZUl
|
||||||
|
qUVldJVewk6ZUpUS10/NSJURGVRITJVTbGEsqpVGNHYUTZUadYj93pVnGZOZZpVqEpgdZpUYcKbbQJVkaqqvXJUU0qzXc5Uf/seOR5VE0c2/oJ
|
||||||
|
UaM8/rXZVgDtwukJUcMeNrZpUTNu2CWJURhPOBz5VU0PQ9xZUUPfVegZVKQPYOdZUoBP572JU6wSjK5JUegywndpVI7TNR2pVo9UczqZViJ0yo
|
||||||
|
lpVM43YQWJUdA3wYPJVXsX/nL5UVC4V5SJUViKCTUZUT56aDNZUZtKninJVoy6tw4JUYpK14M5Vwdbp4gJUkicIeYZVlwckqu5VM5toAxpVm8O
|
||||||
|
QE35UUzfgnxZVMxwkeHZVQiR8QXpUknSON7pUimChPoZUWFS4tx5UkTS2MJ5VQqTGUa5VOxzgHOJUyajyYUZVHOEgo8ZUyrEllfpUiD0oMD5Uc
|
||||||
|
sUySf5Uou06fzpU5ZU6Ta5VKZVSlw5VidV/OrpUffWDGopUXWWW7NpUUnWasM5UgPWjPEpVGU3F4LJUyOHT4fJVJtIZnWZUpI5NuOJVd26S1S5
|
||||||
|
US66n3tZUqGa5PQ5UeRrSKRJUiJb9n5pUohMZ9iZUs19RpuZUU0N5BwJVQtuZ5m5UoXQnbXZVXQBmrcJUq9yeLopUXXiuoi5UsADCG9pVEyjFZ
|
||||||
|
kZUT4zquhJUQEDtCmJUXsjoLPZU4PEr4XJUrgEzmWJVLjk3VaZUdml2zPpUmtWGAc5VMZHAblJVt+IFuXpUcg4XwopUc9Ib0nZVJxonwBpVMsZ
|
||||||
|
FDy5Ueh5bBcpUqep5T1JVdbZ/Fb5VkWKP2KZUUrKTVsJVfNa55uJUtML8MpZUq08IhQZVJyMSRO5VDYtFjeZUuW9rM85VMBuoES5UdjuyNb5UT
|
||||||
|
e++h3JUsxgmaoZVLvxkXj5UUWB5CTZVY+B8ow5VGKiOcvpUWtyVMxJUUcStIopVEejRsFZVlijrEo5UXfj3cxpUaRj4hD5UVKUEhX5UdDE0kyZ
|
||||||
|
Vs7lkMRJUSfFum3JUi+FucJpVMrlyyD5UU+GKQc5UU3WOj0JVq0mQqGpVPnmUQGJVnt3KODZVIYHW/wJVi1on3QpVtuqp8aJUzIrELQ5Uti7nU
|
||||||
|
tJU5br8xepVTWcI2RZUQMsRFFZUaj+F8AZUmWdGpa5UysNeQfpVggdxzUJVR6t6Or5Vlw+9YSJVIS++m5JVVpAZYspZFXilgeJYUHjBRlpYm3j
|
||||||
|
RlmJZalTjbvJZsLTs6SZZWMVOobpYxVlz/M5YRKV6nRpYcUWUvWpZdpGrM0JZi63IwlJZGFXvf1pYyNXw5bZYzlYFcRZYWPIVJopYuoYV8K5Y4
|
||||||
|
AYaOcpYY04e3V5ZcVo77NJYSwpX9WJZcT54CtZZMBq0kh5Zil6zp65YU/LL/R5ZK1bSyUJZouLitPZZBbsHFs5ZU1sV0q5YUS8l4npYWzMooz5
|
||||||
|
ZEud9qj5ZI/u9NhpYs3RK6N5ZpfR5zlZYUFyHy8JZoCirksZYYxD02mZYoJz5ma5ZF2lJedpZeTVT5TJYQ63LempZRmqWgF5YTJK4LVJYwnbNO
|
||||||
|
ipYe28HSJ5Y2BsbSXZZyr8jgQZYgVM67fpYXadL/aZYwcNKnpJZIF9UQrJYWbtcgppZgTeSvbZYof+TxepZiqueHupZo4vSJnZY6UvqVA5ZY2/
|
||||||
|
0SfJZINgj4X5ZKXAgHkZZKKws7rZYWGgsgU5Ydag9dm5ZQ3BVWr5YaUiQpo5ZUTCzjm5ZOxjaCopYc9DdVh5ZeejjFbJZIRTqTlpYaWj9eU5Y5
|
||||||
|
mEEaYJYYZ0EMRJYZP0vWK5YUFlr/kZZpw2aSQpZL8m/S95Y59W70r5ZU6XXsb5ZIjHseOpZN44QaLJZieIaa1JY5R5FS5ZZVBpPQtpZMSJbHEp
|
||||||
|
ZmsZqLP5YV6qIkYJZeBqRKuJZo2qUIaJYScq0YdJY5xbAKG5ZWSr6zqZZO0cXbapZ7dMvYU5Yakt1ASJYUi+pkSZZLj+y+45Ys++8a8JYc
|
||||||
|
`;
|
||||||
|
|
||||||
|
export const LINE_CHAINS = 150;
|
||||||
|
export const LINES_B64 = `
|
||||||
|
BAcWM7xmDKiy/gbjq34BX6kHLApNoWoIg6LbBq+p/gbjq44G9K8d/Im9rfUyvAMd/Im9hPwNvwP8EsIFZgyoshcKwLbbCGy6Wwwvw2wRKMUChP
|
||||||
|
wNv4T9BMIDM2XeTH5v0FPAdC5LBNidlQ9JrhQQU7LBEZ2wyg8Kz91+crLeOXOc5RN4suuLf4TuBn7L7/h/9PDVfwX0OHWE+PByA/fjYQKc5RN4
|
||||||
|
0OtGbAKy64t/qe3udALL7/h/Ke/1gQNr+WljhPjwcsL8qWYK5NIYj7LTnIyA1ByJWNfUfv/TboEzz26Eocu3k7LTnIwzz26Ex8sOeQfZudEv3b
|
||||||
|
qyKYSzCCwXtV4wQrVlNP66EDnVuQYxBDgexaacFl6hYRSXnS8UcJsL6z/sv004a8F+NqS6zTQrrwI6r6jzP+y06z/sv+o/NM1NOGvBrzVTvsY1
|
||||||
|
a7oKEpPTmGOUKpoemEeb/poxqwmbe7ZZoHG5wqJhr1WdgaYemEebppyGkwUJm3u2P5iLwbqXp8nQmb3JP5iLwQQmMBFA4TF2RCUyLEseNolNBt
|
||||||
|
o0cszxNfXVRzRa3vQocuXOKDDdKyU/1QNHNFreWkOW4q5Keu0Eu1/dkEdd0ZkHXYieoV3oqAJHXdGZRVgQjQL1iX22AIbRugcJRHZmB0g5aDRL
|
||||||
|
Gl4pTHZa+UpFWGxKy1acQz5VAvNOU1YpTHZaBQdIOWj7Sb5nVkvEaaJJ4G77Sb5nAqdRbod+T8mLC3nYNW4S2fpqd9qqZofdD1yM3rdZvuQgYF
|
||||||
|
3oEGkh501o9OMOaA/hfWd52DVuDbdGkUJCRA41WWLZHBxtZBxOcmskXHBFKLRtxSgKY7IrVlldK8NUpTQHV608SF0xMgpjsisHTnJrJH92OCfb
|
||||||
|
duYnk3c3Ktx2ICwtdEwsXHBFKAVWFI3aQg+q1RUKWdY0B2jQogEf1AsReYAyfIHcN/yEjzhhh146wpH1M4qUvzx9k5hDeJO2RIWWRkylmwtE2p
|
||||||
|
8eRAJ4k7ZEVI7JSwNfnHopwpH1MwOWIyoD/ISPOBKChTX7enYrC5jal9lj3fLXTuMC2bznmNNX7SDRmezG0trvFNOA8ybeVPxo7hjlWeRO4wLZ
|
||||||
|
AhjlWeSA8ybeEAgdmoS2G/SHVxoIjFMdYo7zH6uMaCDQhQgdmoRaHHeAxhjDe9ETTXGAElVpwAdrZnQDc3MyDIRx8A5cdNETTXEGoFiaEvlwNB
|
||||||
|
C3co4NQ4MzD+9/wBD5cDQQAx2jXyzknJcjKKSiKwTuQ3JQZT4hTWI8ik/iOo1NAmU+IU3ZPxtDA3GM7pjHjKWnyoQ0qAhxyjlLz8tJS1rMF0pz
|
||||||
|
zAxIJ8xnRjjLIUTRyDpC9cXSQwfbpZms86RkqSum/qWZp2Wl0agTpT2qOabsqnSqBn+B1FzNgdRfz4INZ0+Fg2gdhrlezYHUXwnbew9ytXmOcM
|
||||||
|
Z4+2pLdfllaHeJX315SmXCedlmS33mZUt/m2cCxnj7asJ52WYCfIgcK7GCciwCu4RCJoqFxi4GTeL9qozdULBJ2UC5qtIvwPPPkcm1zebLBLPc
|
||||||
|
ZcBJ2UC5rdTlsSHQw6cGPdsTkALcwZRh3KGWoN3ulg/dcJUC3MGUCIQtxja2MLcxUDsgJ0s9giL0PkYmUDsgJ1A2Qy62MLcxDtm+4tBmvzrJvr
|
||||||
|
piyhK7d87ZvuLQ5sw64LHDdOXltnXd76581wGrStNvpNzTHZaO2/SFQOPrepriArHDdOW+w3DnAubMOuA70+/jA9DidoeT4juO1+Fojhu7NsR4
|
||||||
|
wjJfeyAxO3vHLEZ2USrJbDQoym6wJx1y2yWMcl0fWHMtHUpsWh2WZW0gZl54Iw5hAiY7YVQo7179MIhU8S6fT9kt7k/LKIRMmCa4Rosjv0KxH6
|
||||||
|
1GkBxRRyEaJzxFGL02nRSaNl8RmS4DJiLGVg8e6VEiFlVWC6VCAqAVRASgz0e9o6ZMA6vRUFmtuVLbpw5RQKY+TkOfZktBnbRGUpcNSFeSAj5O
|
||||||
|
Q5/iTYaXBn31+TRM8wQ3QfJSPfXvx0Eh7DY9QfJSPQTf7yNCce0yRcHrwkeW6dxKCJCuPZsKsJCeArLyrEuyWre7sFq8La7dwTqs6L9dqV+8Ag
|
||||||
|
Ky8qxjtfurAkuyWrcCuFm0CFW/+rSLudS0ArhZtGO1+6sBuFOjmL1sp5q/mKlXweeoAvC3d5QKsJCeBigt2UPmHMA3/BtFNZAcazKkIAoryR/g
|
||||||
|
JBOmXSCJ8l1NiAVd1YQ5XMCEB1wciKZdIIkuX3SIjmJKgxZnX37oZK9zJ2niao1sbm5Obw5ofXP4aDN7sVK9fsZPCI4LX3eWDVpGnjxYBpQEIR
|
||||||
|
JmKGoWXxzpHjMZWh5vFMofHRVvKAYD3L08Kt0oNhTf3SxM6soxiOP7MwPcvTwJ2+5Hyjvwg8fr79nDaO4vwhbwVL3f8fi+6+/ZwwbvXcbb7kfK
|
||||||
|
AxbwVL0i7Xu4ge2vtQcobAWR+GvXlzhuN5zXdzCdDn65lN138ZUobAWRBDhuN5yibU2hYWn8pCdoz6EG/WsgskZvELAldKmwoG80tP1rILIWZs
|
||||||
|
OzCRhBwmpcP9lrrj3raic7p2aiN/NoTjYvYFs6eWI9PRJgdT5OYgOvN5htojfzaNA4Qm0GuaALXGGeL2kGo6dyUab3apWm/FffpqZVAmGeL2lR
|
||||||
|
pvdqDA+pLFASpw9P4KNtTM2jMEa9n6dCypyaPC+i5zVLo+k7CKRxQD+mc0WwqmRJ16uoSwLNozBGP6ZzRQd9Q+zTL0oW02pP/cVlWWy9HWBsu1
|
||||||
|
pjV7S+Y+mwCPbHe7Xkx1a4kcYot/bHe7WxyXq0e8p9rufIcq/2x3u1BNJBrxUAO20TejRsFdE1kxoGN971T/TdcEGx4/VFMOM+UjvgH1I33vVP
|
||||||
|
BQBSanLcVsF7x0xMfyBF/3WkQhN3BcdMTH+CSG6DOkSIhtlFbYpJRxKOB3F9GSEgg1gfnIasHTqIIh8Siz4axoVpGZyGrB0F0qvBP4CvXjwyrq
|
||||||
|
s4Pav8OdKrwT8EH5oBCdvyQgxg5+8RH5oBCQrUvxly2b3ZgxC9foaLu9yR67RVjSqw0oI4rb567a1TeUax+HAut6JpBuu0VY1GsfhwNLBfaHmv
|
||||||
|
wGX0roBjN6+nXgQQvX6GLreiaT+5clwyuoVVCFlBAJUAP9acskCknB9CNZRsQLiNJD+Iis05B4ltNG+OCRM1cIJQNHiDxTP4h4cz5omqM6iMbT
|
||||||
|
RvjrA0OJMlNuiVDzculgjrN1V0rzmXfAY7k3/NOQeJlTsgjiQ/iIqUPDx90z0/cgOUPDx9xTtKfgY7k38L5dlPL1Pd2CHi1uAhSMmOJyHEiyiH
|
||||||
|
wXMld73zI6fHahpw1U4YU93YIbPkCSMKcewvr1Dy+6oB9vCnfgFfqVoCmJUu9p+V+PJPkQryZ4977NCI2+cLjgYu9p+VAfbwp47z/aLw8oOh6u
|
||||||
|
sLpPDneKQT4SfrraApWK18KuaySSrnuAkojryiJ/bDfSaKxFMk6cbaIBjMWR5+z/seCcudIY/GsCHLv3QhP7oCIlW47CA9t8gfaLjxH1u6dCE/
|
||||||
|
ugTWK5zHUS3ZxDUs28OiJ/bDA50hj8YxHQPGbhIWyAisBNVDwAuOPbYPZEI5EDU6KAxtMcALjj2sAfA+rATVQwORSOgnMT4eML09XzcXHA32or
|
||||||
|
0My6ohDsamHA32orQM6p1EENOVvRIGjbMV7oMwFIiECBLNhwgQvIgcDcaKMQs4i6gIyYrh/8KJcPwAiE76Eonz+KeHY/irhB/6yYHP/IiClf31
|
||||||
|
hHD8AIgCY/irhAb2boUK5fGJWer031Wd9LhRAfQ+UUXw/1Eo7BVR/ucHUX3oDlQo7BVR5fGJWQm3RpFCt009S/VQp1eSUeFZblOkXMZUdV+tVm
|
||||||
|
9d+FUbRwdXrTwEblOkXDdTHFt0UtJW9VCnVwT4VRtHdlzITRVdzVBRXpdYBTstJieZLakrciqtKNwn1CM7LSYnA8vRnpkX01yaHdW4mwL30dqY
|
||||||
|
F9NcmgUiw7dLTMQZT7vDlFX5xNhbcsIMYgWxzsVA6s48RiLLgVUeyJ1Z+cTYWxN+1HRESdXUTZjUmFox0ZxcKc8kXW7NFFzTyZlaHsidWbvDlF
|
||||||
|
UIwbtUTMQZTyLLgVXny6VY08mZWoDLFGFnzBlizc0LZYXOnmaHzk9pBIDLFGFDyvthocmmX9PJmVoDdqrcWrqq01+iq9VjDLqq019vrppb5a9o
|
||||||
|
Wgyx31eWszpP47PjSV+0wEN+t4FC+LvZQsu97kbjvH1IT7s7SwRrCj9WCP7+V674u1Ey+zZKBULGRnRjyD95hMcgczHFSGtCxkZ0CTao7pVjp/
|
||||||
|
mbqqjNmQmqRpY2qO6VMKb9jt+nI4kJqV6GOK2+egYut6JpBLwZatS/GXKMwF10ysPge//J+oUEFGx4f1ZpeXTobxp8DXAYfwcHPBGeDTF6l8Mv
|
||||||
|
kpYvLjmWvi7ymMEvR5sCOq+oBC8uOZbKKsOR1STXjTorhIgD1STXjWkk14yOJpKAA//BpD7MxJ8+IMU2OgQaFBGqCBfCsWkYI7AaFBGqBFGz1B
|
||||||
|
3OqcklXaNSHlGz1B0H9e1MKm/4LS2cBXUmkQO8I/z/vCKH75oj9e1MKgi+ghzR/3XS16l1L9Dnfl3MvoIc0ZuJls/sjh3OHpMixgTnfl3MhX3z
|
||||||
|
w554Ea+ReNesA4V988MNd0m/o24FuwINd0m/tW0IvQX/ddLXm2Wv2bdaWtYRaffTqXUv0ASpdS/QQ2njzNdlfsncX1PEAqVgEMPXZX7JCNWno+
|
||||||
|
7Hrb3rr6Mp5lmedunVp6Pu17Ks9BC7JPv9GvP+CEhdMTLuY8MxHGpkMvtytjlJbRhEdWVyRmxhOkIHV608CHx9SYlZfoKCioMNf2iH8H1wjB94
|
||||||
|
JY8gcC6Yd3f9nPN3Aw6Llo/jidSEaIfwfQRwjB941pAnf6CVMoKOnbGCB29gkiHpWfAhvlZpHqlNWR85TLwbvlZpHm9gkiEFjc1rnsXPFKMs1D
|
||||||
|
6ih9V4pyPYjqc=
|
||||||
|
`;
|
||||||
|
|
@ -1,10 +1,15 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { FALLBACK_VIEW } from './view';
|
||||||
|
import { ELSEWHERE_VIEW } from './manifest.fixture';
|
||||||
|
import { sunForState } from './sunAt';
|
||||||
import { makePhysicalSky, paintSky } from './physicalSky';
|
import { makePhysicalSky, paintSky } from './physicalSky';
|
||||||
import { skyBackdrop } from '../skyState';
|
import { ridgeDrawn } from '../skyForState';
|
||||||
import type { FixedSkyState } from '../skyBand';
|
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
|
// 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).
|
// viewports of different shape (the fit is made on one 16:9 grid and the paint on another).
|
||||||
const lin = (v: number): number => {
|
const lin = (v: number): number => {
|
||||||
const c = v / 255;
|
const c = v / 255;
|
||||||
|
|
@ -13,6 +18,13 @@ const lin = (v: number): number => {
|
||||||
const luma = (d: Uint8ClampedArray, i: number): number =>
|
const luma = (d: Uint8ClampedArray, i: number): number =>
|
||||||
0.2126 * lin(d[i]) + 0.7152 * lin(d[i + 1]) + 0.0722 * lin(d[i + 2]);
|
0.2126 * lin(d[i]) + 0.7152 * lin(d[i + 1]) + 0.0722 * lin(d[i + 2]);
|
||||||
|
|
||||||
|
const camera = (sky: PhysicalSky, w: number, h: number) => windowFor(sky.view, w, h).camera;
|
||||||
|
/** The camera of the viewport turned to face the sun, so the disc's colour and floor are measured wherever the sun is. */
|
||||||
|
const facingSun = (sky: PhysicalSky, w: number, h: number) => ({
|
||||||
|
...camera(sky, w, h),
|
||||||
|
azimuthDeg: sky.sun.azimuth,
|
||||||
|
});
|
||||||
|
|
||||||
const DAYS = ['2026-03-20', '2026-06-21', '2026-09-23', '2026-12-21'];
|
const DAYS = ['2026-03-20', '2026-06-21', '2026-09-23', '2026-12-21'];
|
||||||
const WEATHER = [0, 0.3, 0.55, 0.75, 1];
|
const WEATHER = [0, 0.3, 0.55, 0.75, 1];
|
||||||
const VIEWPORTS: [number, number][] = [
|
const VIEWPORTS: [number, number][] = [
|
||||||
|
|
@ -23,17 +35,17 @@ const VIEWPORTS: [number, number][] = [
|
||||||
];
|
];
|
||||||
|
|
||||||
describe.each(['day', 'dusk', 'night'] as FixedSkyState[])(
|
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) => {
|
(state) => {
|
||||||
it('over weather, season and viewport shape', () => {
|
it('over weather, season and viewport shape', () => {
|
||||||
const b = skyBackdrop(state);
|
const b = ridgeDrawn(state);
|
||||||
let lo = 2;
|
let lo = 2;
|
||||||
let hi = -1;
|
let hi = -1;
|
||||||
for (const day of DAYS) {
|
for (const day of DAYS) {
|
||||||
for (const w of WEATHER) {
|
for (const w of WEATHER) {
|
||||||
const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w);
|
const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w, FALLBACK_VIEW);
|
||||||
for (const [vw, vh] of VIEWPORTS) {
|
for (const [vw, vh] of VIEWPORTS) {
|
||||||
const px = paintSky(sky, vw, vh);
|
const px = paintSky(sky, vw, vh, camera(sky, vw, vh));
|
||||||
for (let i = 0; i < px.w * px.h * 4; i += 4) {
|
for (let i = 0; i < px.w * px.h * 4; i += 4) {
|
||||||
const l = luma(px.data, i);
|
const l = luma(px.data, i);
|
||||||
lo = Math.min(lo, l);
|
lo = Math.min(lo, l);
|
||||||
|
|
@ -51,8 +63,12 @@ describe.each(['day', 'dusk', 'night'] as FixedSkyState[])(
|
||||||
describe('weather in the sky', () => {
|
describe('weather in the sky', () => {
|
||||||
it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => {
|
it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => {
|
||||||
const at = new Date('2026-06-21T10:40:00Z');
|
const at = new Date('2026-06-21T10:40:00Z');
|
||||||
const clear = paintSky(makePhysicalSky('day', at, 0), 640, 360);
|
const paint = (w: number) => {
|
||||||
const grey = paintSky(makePhysicalSky('day', at, 0.7), 640, 360);
|
const sky = makePhysicalSky('day', at, w, FALLBACK_VIEW);
|
||||||
|
return paintSky(sky, 640, 360, camera(sky, 640, 360));
|
||||||
|
};
|
||||||
|
const clear = paint(0);
|
||||||
|
const grey = paint(0.7);
|
||||||
const spread = (p: typeof clear) => {
|
const spread = (p: typeof clear) => {
|
||||||
let lo = 2;
|
let lo = 2;
|
||||||
let hi = -1;
|
let hi = -1;
|
||||||
|
|
@ -73,44 +89,46 @@ describe('weather in the sky', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('the sun disc', () => {
|
describe('the sun disc', () => {
|
||||||
it('keeps the display floor the dark link was fitted to, at every hour it is drawn', () => {
|
const disc = (sky: PhysicalSky) => paintSky(sky, 1280, 720, facingSun(sky, 1280, 720));
|
||||||
const lin = (c: number) =>
|
const noon = new Date('2026-12-21T11:00:00Z'); // about 18 degrees: higher suns are above the top of the window
|
||||||
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 d = paintSky(
|
|
||||||
makePhysicalSky(state, new Date(Date.UTC(2026, 10, 11, 0, m)), 0),
|
|
||||||
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 noon = new Date('2026-11-11T10:40:00Z'); // 21 degrees: in June the noon sun is above the top of the image
|
|
||||||
it('is drawn by the host, in a clear sky by day, white with the sun high', () => {
|
it('is drawn by the host, in a clear sky by day, white with the sun high', () => {
|
||||||
const d = paintSky(makePhysicalSky('day', noon, 0), 1280, 720).sunDisc;
|
const sky = makePhysicalSky('day', noon, 0, FALLBACK_VIEW);
|
||||||
|
const d = disc(sky).sunDisc;
|
||||||
expect(d).toBeDefined();
|
expect(d).toBeDefined();
|
||||||
expect(d!.x).toBeGreaterThan(0);
|
expect(d!.x).toBeGreaterThan(0);
|
||||||
expect(d!.x).toBeLessThan(1);
|
expect(d!.x).toBeLessThan(1);
|
||||||
expect(d!.y).toBeGreaterThan(0);
|
expect(d!.y).toBeGreaterThan(0);
|
||||||
expect(d!.y).toBeLessThan(0.78); // above the horizon line
|
expect(d!.y).toBeLessThan(camera(sky, 1280, 720).horizonAt); // above the horizon line
|
||||||
expect(d!.alpha).toBe(1);
|
expect(d!.alpha).toBe(1);
|
||||||
expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees
|
expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees
|
||||||
});
|
});
|
||||||
it('is hidden by overcast and absent at night', () => {
|
it('is hidden by overcast and absent at night', () => {
|
||||||
expect(paintSky(makePhysicalSky('day', noon, 0.7), 1280, 720).sunDisc).toBeUndefined();
|
expect(disc(makePhysicalSky('day', noon, 0.7, FALLBACK_VIEW)).sunDisc).toBeUndefined();
|
||||||
expect(paintSky(makePhysicalSky('night', noon, 0), 1280, 720).sunDisc).toBeUndefined();
|
expect(disc(makePhysicalSky('night', noon, 0, FALLBACK_VIEW)).sunDisc).toBeUndefined();
|
||||||
});
|
});
|
||||||
it('is orange-tinted low in the sky', () => {
|
it('is orange-tinted low in the sky', () => {
|
||||||
const d = paintSky(makePhysicalSky('dusk', noon, 0), 1280, 720).sunDisc;
|
const d = disc(makePhysicalSky('dusk', noon, 0, FALLBACK_VIEW)).sunDisc;
|
||||||
expect(d).toBeDefined();
|
expect(d).toBeDefined();
|
||||||
expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]);
|
expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('the sky is made from the View it is given', () => {
|
||||||
|
const NOW = new Date('2026-06-21T10:40:00Z');
|
||||||
|
const sameSpotOtherCamera = { ...FALLBACK_VIEW, lookAzDeg: 30, windowDeg: 100, horizonRow: 200 };
|
||||||
|
|
||||||
|
it("lights the sky from the sun over the View's place, at its altitude", () => {
|
||||||
|
const sky = makePhysicalSky('day', NOW, 0, ELSEWHERE_VIEW);
|
||||||
|
expect(sky.view).toBe(ELSEWHERE_VIEW);
|
||||||
|
expect(sky.sun).toEqual(sunForState(ELSEWHERE_VIEW.place, 'day', NOW));
|
||||||
|
expect(sky.sun).not.toEqual(sunForState(FALLBACK_VIEW.place, 'day', NOW));
|
||||||
|
expect(sky.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("fits and samples the stops through the View's camera: the same place and sun with another look is another gradient", () => {
|
||||||
|
const a = makePhysicalSky('day', NOW, 0, FALLBACK_VIEW);
|
||||||
|
const b = makePhysicalSky('day', NOW, 0, sameSpotOtherCamera);
|
||||||
|
expect(b.sun).toEqual(a.sun);
|
||||||
|
expect(b.stops).not.toEqual(a.stops);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,30 +1,32 @@
|
||||||
// The ridge scene's sky: Vienna's sun on the real clock, the atmosphere baked from it, a camera, and the display that makes it
|
// The ridge scene's sky: the View's place's sun on the real clock, the atmosphere baked from it, a camera, and the display that makes it
|
||||||
// pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9
|
// pixels. `makePhysicalSky` does the one expensive thing (the LUT bake, tens of ms) and fits the display from a fixed 16:9
|
||||||
// grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only.
|
// grid, so resizing the window repaints the same sky. `paintSky` is per-texel lookups only.
|
||||||
import type { FixedSkyState } from '../skyBand';
|
import type { FixedSkyState } from '../skyState';
|
||||||
import { bakeAtmosphere } from './earthAtmosphere';
|
import { bakeAtmosphere } from './earthAtmosphere';
|
||||||
import type { Atmosphere } from './earthAtmosphere';
|
import type { Atmosphere } from './earthAtmosphere';
|
||||||
import {
|
import { domeSize, renderDome, SUN_RADIUS, sunOnScreen } from './skyDome';
|
||||||
domeSize,
|
import type { Dome } from './skyDome';
|
||||||
HORIZON_AT,
|
|
||||||
renderDome,
|
|
||||||
SUN_RADIUS,
|
|
||||||
sunOnScreen,
|
|
||||||
viewFor,
|
|
||||||
VFOV_DEG,
|
|
||||||
} from './skyDome';
|
|
||||||
import type { Dome, DomeView } from './skyDome';
|
|
||||||
import type { Srgb } from './skyColour';
|
import type { Srgb } from './skyColour';
|
||||||
import { display8, fitDisplay, holdBudget, MARGIN } from './toneMap';
|
import { display8, fitDisplay } from './toneMap';
|
||||||
import type { Display, Fit } from './toneMap';
|
import type { Display, Fit } from './toneMap';
|
||||||
import { sunForState, VIENNA } from './vienna';
|
import { moonAt } from './nightSky';
|
||||||
import type { SunSample } from './vienna';
|
import type { MoonSample, NightLight } from './nightSky';
|
||||||
|
import { sunForState } from './sunAt';
|
||||||
|
import type { SunSample } from './sunAt';
|
||||||
|
import { windowFor } from './view';
|
||||||
|
import type { Camera, View } from './view';
|
||||||
import { weatherOf } from './weather';
|
import { weatherOf } from './weather';
|
||||||
import type { Weather } from './weather';
|
import type { Weather } from './weather';
|
||||||
|
|
||||||
export interface PhysicalSky {
|
export interface PhysicalSky {
|
||||||
state: FixedSkyState;
|
state: FixedSkyState;
|
||||||
|
/** Where the observer stands and where the planes look: the camera of any viewport is `windowFor(view, w, h).camera`. */
|
||||||
|
view: View;
|
||||||
sun: SunSample;
|
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;
|
weather: Weather;
|
||||||
atm: Atmosphere;
|
atm: Atmosphere;
|
||||||
/** The display fitted to this sky's budget. */
|
/** The display fitted to this sky's budget. */
|
||||||
|
|
@ -35,7 +37,7 @@ export interface PhysicalSky {
|
||||||
bakeMs: number;
|
bakeMs: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const CANON = { w: 64, h: 36, aspect: 16 / 9 };
|
const CANON = { w: 64, h: 36 };
|
||||||
|
|
||||||
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
|
const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());
|
||||||
|
|
||||||
|
|
@ -56,26 +58,52 @@ export function rowMean(dome: Dome, display: Display, row: number): Srgb {
|
||||||
export function makePhysicalSky(
|
export function makePhysicalSky(
|
||||||
state: FixedSkyState,
|
state: FixedSkyState,
|
||||||
now: Date,
|
now: Date,
|
||||||
weatherValue: number
|
weatherValue: number,
|
||||||
|
view: View,
|
||||||
|
/** A sun to draw instead of the state's own (the look sheet's grid of elevations); `state` still picks the display budget. */
|
||||||
|
sunOverride?: SunSample
|
||||||
): PhysicalSky {
|
): PhysicalSky {
|
||||||
const t0 = clock();
|
const t0 = clock();
|
||||||
const sun = sunForState(state, now);
|
const sun = sunOverride ?? sunForState(view.place, state, now);
|
||||||
const weather = weatherOf(weatherValue);
|
const weather = weatherOf(weatherValue);
|
||||||
const atm = bakeAtmosphere({
|
const atm = bakeAtmosphere({
|
||||||
sunElevationDeg: sun.elevation,
|
sunElevationDeg: sun.elevation,
|
||||||
mieScale: weather.mieScale,
|
mieScale: weather.mieScale,
|
||||||
observerKm: VIENNA.altitudeKm,
|
observerKm: view.place.altitudeKm,
|
||||||
});
|
});
|
||||||
const dome = renderDome(atm, sun, viewFor(sun, CANON.aspect), CANON.w, CANON.h, weather.cover);
|
// 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);
|
||||||
|
// 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 fit = fitDisplay(state, dome.hdr, dome.meanLuma);
|
||||||
const at = (f: number) => rowMean(dome, fit.display, Math.round(f * CANON.h));
|
const at = (f: number) => rowMean(dome, fit.display, Math.round(f * CANON.h));
|
||||||
return {
|
return {
|
||||||
state,
|
state,
|
||||||
|
view,
|
||||||
sun,
|
sun,
|
||||||
|
moon,
|
||||||
|
night,
|
||||||
weather,
|
weather,
|
||||||
atm,
|
atm,
|
||||||
fit,
|
fit,
|
||||||
stops: { top: at(0.02), mid: at(0.5), horizon: at(HORIZON_AT) },
|
stops: { top: at(0.02), mid: at(0.5), horizon: at(camera.horizonAt) },
|
||||||
bakeMs: clock() - t0,
|
bakeMs: clock() - t0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
@ -86,19 +114,18 @@ export interface SkyPixels {
|
||||||
/** RGBA, 8 bit. */
|
/** RGBA, 8 bit. */
|
||||||
data: Uint8ClampedArray;
|
data: Uint8ClampedArray;
|
||||||
dome: Dome;
|
dome: Dome;
|
||||||
view: DomeView;
|
camera: Camera;
|
||||||
/** The sun's disc for the host to draw on the upscaled canvas (it is smaller than a texel): place as fractions of the image, colour, radius in fractions of the height, opacity after the cloud. */
|
/** The sun's disc for the host to draw on the upscaled canvas (it is smaller than a texel): place as fractions of the image, colour, radius in fractions of the height, opacity after the cloud. */
|
||||||
sunDisc?: { x: number; y: number; rgb: Srgb; radius: number; alpha: number };
|
sunDisc?: { x: number; y: number; rgb: Srgb; radius: number; alpha: number };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The sky for a viewport, as a small RGBA grid the host canvas upscales smoothly. */
|
/** 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): SkyPixels {
|
export function paintSky(p: PhysicalSky, cssW: number, cssH: number, camera: Camera): SkyPixels {
|
||||||
const { w, h } = domeSize(cssW, cssH);
|
const { w, h } = domeSize(cssW, cssH);
|
||||||
const view = viewFor(p.sun, cssW / cssH);
|
const dome = renderDome(p.atm, p.sun, camera, w, h, p.weather.cover, p.night);
|
||||||
const dome = renderDome(p.atm, p.sun, view, w, h, p.weather.cover);
|
|
||||||
const data = new Uint8ClampedArray(w * h * 4);
|
const data = new Uint8ClampedArray(w * h * 4);
|
||||||
const out = [0, 0, 0];
|
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) {
|
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);
|
display8(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], display, out);
|
||||||
data[i * 4] = out[0];
|
data[i * 4] = out[0];
|
||||||
|
|
@ -106,11 +133,9 @@ export function paintSky(p: PhysicalSky, cssW: number, cssH: number): SkyPixels
|
||||||
data[i * 4 + 2] = out[2];
|
data[i * 4 + 2] = out[2];
|
||||||
data[i * 4 + 3] = 255;
|
data[i * 4 + 3] = 255;
|
||||||
}
|
}
|
||||||
return { w, h, data, dome, view, sunDisc: sunDisc(p, view) };
|
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 smooth01 = (a: number, b: number, v: number): number => {
|
||||||
const t = Math.min(1, Math.max(0, (v - a) / (b - a)));
|
const t = Math.min(1, Math.max(0, (v - a) / (b - a)));
|
||||||
return t * t * (3 - 2 * t);
|
return t * t * (3 - 2 * t);
|
||||||
|
|
@ -120,25 +145,18 @@ const smooth01 = (a: number, b: number, v: number): number => {
|
||||||
* The sun's disc: always brighter than the display's white, so what is left of it is its colour, the air's transmittance to the sun
|
* The sun's disc: always brighter than the display's white, so what is left of it is its colour, the air's transmittance to the sun
|
||||||
* normalised to its strongest channel (white high up, orange near the horizon). Thick cloud hides it.
|
* normalised to its strongest channel (white high up, orange near the horizon). Thick cloud hides it.
|
||||||
*/
|
*/
|
||||||
function sunDisc(p: PhysicalSky, view: DomeView): SkyPixels['sunDisc'] {
|
function sunDisc(p: PhysicalSky, camera: Camera): SkyPixels['sunDisc'] {
|
||||||
const at = sunOnScreen(p.sun, view);
|
const at = sunOnScreen(p.sun, camera);
|
||||||
const alpha = 1 - smooth01(0.1, 0.6, p.weather.cover);
|
const alpha = 1 - smooth01(0.1, 0.6, p.weather.cover);
|
||||||
if (!at || alpha <= 0) return undefined;
|
if (!at || alpha <= 0) return undefined;
|
||||||
const trans = [0, 0, 0];
|
const trans = [0, 0, 0];
|
||||||
p.atm.transmittanceToSpace(Math.max(Math.sin((p.sun.elevation * Math.PI) / 180), 0), trans);
|
p.atm.transmittanceToSpace(Math.max(Math.sin((p.sun.elevation * Math.PI) / 180), 0), trans);
|
||||||
const top = Math.max(...trans, 1e-9);
|
const top = Math.max(...trans, 1e-9);
|
||||||
const rgb = trans.map((t) => Math.round(255 * (t / top) ** 0.6));
|
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 {
|
return {
|
||||||
...at,
|
...at,
|
||||||
rgb: rgb as unknown as Srgb,
|
rgb: rgb as unknown as Srgb,
|
||||||
radius: (SUN_RADIUS * 180) / Math.PI / VFOV_DEG,
|
radius: (SUN_RADIUS * 180) / Math.PI / camera.vfovDeg,
|
||||||
alpha,
|
alpha,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
242
src/app/features/scene/ridge/ridgeAssets.test.ts
Normal file
242
src/app/features/scene/ridge/ridgeAssets.test.ts
Normal file
|
|
@ -0,0 +1,242 @@
|
||||||
|
// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on
|
||||||
|
// (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, sep } from 'node:path';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { MAX_CARDS, parseIndex, parseManifest } from './manifest';
|
||||||
|
|
||||||
|
/** 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 WireFile {
|
||||||
|
file: string;
|
||||||
|
bytes: number;
|
||||||
|
}
|
||||||
|
interface WireCard {
|
||||||
|
top: number;
|
||||||
|
h: number;
|
||||||
|
scale: number;
|
||||||
|
colour: WireFile;
|
||||||
|
geometry: WireFile;
|
||||||
|
}
|
||||||
|
export interface WireManifest {
|
||||||
|
bake_id: string;
|
||||||
|
w: number;
|
||||||
|
cards: WireCard[];
|
||||||
|
camera?: { heading_max_deg?: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
const files = (c: WireCard): WireFile[] => [c.colour, c.geometry];
|
||||||
|
|
||||||
|
/** 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 {
|
||||||
|
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 `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);
|
||||||
|
const tag = (o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);
|
||||||
|
if (b.length < 20 || tag(0) !== 'RIFF' || tag(8) !== 'WEBP') return 'not a RIFF WEBP';
|
||||||
|
if (u32(4) + 8 !== b.length) return `RIFF size ${u32(4)} does not fit a ${b.length} byte file`;
|
||||||
|
const dims: string[] = [];
|
||||||
|
let seen = 0;
|
||||||
|
let o = 12;
|
||||||
|
while (o < b.length) {
|
||||||
|
if (o + 8 > b.length) return 'a chunk header runs past the file';
|
||||||
|
const id = tag(o);
|
||||||
|
const len = u32(o + 4);
|
||||||
|
const body = o + 8;
|
||||||
|
if (body + len > b.length) return `chunk ${id} runs past the file`;
|
||||||
|
if (id === 'VP8X') dims.push(`${u24(body + 4) + 1}x${u24(body + 7) + 1}`);
|
||||||
|
if (id === 'VP8 ') {
|
||||||
|
if (b[body + 3] !== 0x9d || b[body + 4] !== 0x01 || b[body + 5] !== 0x2a)
|
||||||
|
return 'VP8 start code missing';
|
||||||
|
dims.push(
|
||||||
|
`${(b[body + 6] | (b[body + 7] << 8)) & 0x3fff}x${
|
||||||
|
(b[body + 8] | (b[body + 9] << 8)) & 0x3fff
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
seen += 1;
|
||||||
|
}
|
||||||
|
if (id === 'VP8L') {
|
||||||
|
if (b[body] !== 0x2f) return 'VP8L signature missing';
|
||||||
|
const bits = u32(body + 1);
|
||||||
|
dims.push(`${(bits & 0x3fff) + 1}x${((bits >>> 14) & 0x3fff) + 1}`);
|
||||||
|
seen += 1;
|
||||||
|
}
|
||||||
|
o = body + len + (len & 1);
|
||||||
|
}
|
||||||
|
if (o !== b.length) return 'the chunks do not tile the file';
|
||||||
|
if (seen !== 1) return `${seen} bitstream chunks`;
|
||||||
|
const bad = dims.find((d) => d !== `${w}x${h}`);
|
||||||
|
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 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');
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROOT = join(process.cwd(), 'public', 'ridge');
|
||||||
|
const readJson = (p: string): unknown => JSON.parse(readFileSync(p, 'utf8'));
|
||||||
|
const index = parseIndex(readJson(join(ROOT, 'index.json')));
|
||||||
|
const dirs = Object.entries(index.places);
|
||||||
|
|
||||||
|
describe('the committed ridge assets', () => {
|
||||||
|
it('ship at least one place, and the index default is one of them', () => {
|
||||||
|
expect(dirs.length).toBeGreaterThan(0);
|
||||||
|
expect(index.places[index.default]).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
dirs.forEach(([id, dir]) => {
|
||||||
|
describe(`${id} (${dir})`, () => {
|
||||||
|
const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest & { schema: number };
|
||||||
|
const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file));
|
||||||
|
|
||||||
|
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 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 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 = (i: number, kind: 'colour' | 'geometry') => read(raw.cards[i][kind]);
|
||||||
|
expect(bakeIdOf(bytes, raw.cards.length)).toBe(raw.bake_id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the place inside the card, byte and decode budget', () => {
|
||||||
|
expect(sizeGate(raw)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
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).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)
|
||||||
|
.split(sep)
|
||||||
|
.join('/')
|
||||||
|
);
|
||||||
|
expect(onDisk.filter((f) => !named.has(f))).toEqual([]);
|
||||||
|
expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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 card at its size', () => {
|
||||||
|
expect(webpFault(real, w, h)).toBeUndefined();
|
||||||
|
});
|
||||||
|
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 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 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 card = (bytes: number, h: number): WireCard => ({
|
||||||
|
top: 0,
|
||||||
|
h,
|
||||||
|
scale: 1,
|
||||||
|
colour: { file: 'c.webp', bytes },
|
||||||
|
geometry: { file: 'g.webp', bytes },
|
||||||
|
});
|
||||||
|
const set = (n: number, bytes: number, h: number): WireManifest => ({
|
||||||
|
bake_id: 'x',
|
||||||
|
w: 1280,
|
||||||
|
cards: Array.from({ length: n }, () => card(bytes, h)),
|
||||||
|
});
|
||||||
|
|
||||||
|
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 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/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,404 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { BakeParams, bakeSlice, faceLight, layerPaint, sunDirection } from './ridgeBake';
|
|
||||||
import { SKY_BAND } from '../skyBand';
|
|
||||||
import { ridgeSkyFor } from '../skyForState';
|
|
||||||
import { LACUNARITY, LAYERS, profile } from './ridgeWorld';
|
|
||||||
import { skyColours, SkyColours } from './skyColour';
|
|
||||||
|
|
||||||
const SKY: SkyColours = { ...skyColours(), sunAzimuth: 0.3 }; // sun toward +x
|
|
||||||
const PERIOD = 400;
|
|
||||||
const VIEW_H = 800;
|
|
||||||
const BAND = 480;
|
|
||||||
|
|
||||||
const params = (
|
|
||||||
li: number,
|
|
||||||
px0: number,
|
|
||||||
cols: number,
|
|
||||||
over: Partial<BakeParams> = {}
|
|
||||||
): BakeParams => ({
|
|
||||||
spec: LAYERS[li],
|
|
||||||
sky: SKY,
|
|
||||||
period: PERIOD,
|
|
||||||
scale: 1,
|
|
||||||
viewH: VIEW_H,
|
|
||||||
rows: BAND,
|
|
||||||
bandH: BAND,
|
|
||||||
px0,
|
|
||||||
cols,
|
|
||||||
...over,
|
|
||||||
});
|
|
||||||
|
|
||||||
function bake(p: BakeParams, slices: number[] = [p.cols]): Uint8ClampedArray {
|
|
||||||
const out = new Uint8ClampedArray(p.cols * p.rows * 4);
|
|
||||||
const paint = layerPaint(p.spec, p.sky);
|
|
||||||
let c = 0;
|
|
||||||
for (const n of slices) {
|
|
||||||
bakeSlice(out, p, paint, c, Math.min(p.cols, c + n));
|
|
||||||
c += n;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lum = (d: Uint8ClampedArray, cols: number, x: number, y: number) => {
|
|
||||||
const o = (y * cols + x) * 4;
|
|
||||||
return 0.2126 * d[o] + 0.7152 * d[o + 1] + 0.0722 * d[o + 2];
|
|
||||||
};
|
|
||||||
/** First row of column x whose alpha is full. */
|
|
||||||
const solidRow = (d: Uint8ClampedArray, cols: number, x: number) => {
|
|
||||||
let y = 0;
|
|
||||||
while (y < BAND && d[(y * cols + x) * 4 + 3] < 255) y += 1;
|
|
||||||
return y;
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('the field is a function of world-x', () => {
|
|
||||||
it('is deterministic, and defined and bounded at any world-x', () => {
|
|
||||||
for (const spec of LAYERS) {
|
|
||||||
for (const t of [-40.3, 0, 0.5, 17.77, 5000.123]) {
|
|
||||||
expect(profile(spec, t)).toBe(profile(spec, t));
|
|
||||||
expect(profile(spec, t)).toBeGreaterThanOrEqual(0);
|
|
||||||
expect(profile(spec, t)).toBeLessThanOrEqual(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('has no repeat at the old period (1 viewport) or its multiples: the profile differs from itself shifted', () => {
|
|
||||||
for (const spec of LAYERS) {
|
|
||||||
for (const lag of [1, 2, 3, 0.5]) {
|
|
||||||
let diff = 0;
|
|
||||||
for (let i = 0; i < 400; i += 1)
|
|
||||||
diff += Math.abs(profile(spec, i / 100) - profile(spec, i / 100 + lag));
|
|
||||||
expect(diff / 400).toBeGreaterThan(0.04);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the same world column bakes to the same pixels whichever chunk or slice paints it', () => {
|
|
||||||
for (const li of [0, 3]) {
|
|
||||||
const whole = bake(params(li, 1000, 200));
|
|
||||||
const sliced = bake(params(li, 1000, 200), [37, 64, 1000]);
|
|
||||||
expect(Array.from(sliced)).toEqual(Array.from(whole));
|
|
||||||
// A chunk starting 120 columns later sees the same pixels for the columns it shares.
|
|
||||||
const shifted = bake(params(li, 1120, 80));
|
|
||||||
for (const x of [0, 17, 79]) {
|
|
||||||
for (const y of [0, 100, 300, BAND - 1]) {
|
|
||||||
const a = (y * 200 + 120 + x) * 4;
|
|
||||||
const b = (y * 80 + x) * 4;
|
|
||||||
expect(Array.from(shifted.slice(b, b + 4))).toEqual(Array.from(whole.slice(a, a + 4)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is continuous across a chunk seam: the crest steps no more at the seam than elsewhere', () => {
|
|
||||||
const chunk = Math.round(PERIOD * 1.2);
|
|
||||||
for (const li of [0, 1, 2, 3]) {
|
|
||||||
const p = params(li, chunk - 40, 80);
|
|
||||||
const d = bake(p);
|
|
||||||
let worst = 0;
|
|
||||||
for (let x = 1; x < 80; x += 1)
|
|
||||||
worst = Math.max(worst, Math.abs(solidRow(d, 80, x) - solidRow(d, 80, x - 1)));
|
|
||||||
const seam = Math.abs(solidRow(d, 80, 40) - solidRow(d, 80, 39));
|
|
||||||
expect(seam).toBeLessThanOrEqual(Math.max(worst, 1));
|
|
||||||
// and the seam columns equal a chunk baked from the other side
|
|
||||||
const other = bake(params(li, chunk - 40, 80, { cols: 80 }));
|
|
||||||
expect(Array.from(other)).toEqual(Array.from(d));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('shading from the slope normal', () => {
|
|
||||||
const sun = sunDirection(SKY);
|
|
||||||
|
|
||||||
it('the sun is toward +x for azimuth 0.3', () => {
|
|
||||||
expect(sun[0]).toBeGreaterThan(0.5);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a face looking at the sun is lit more than one looking away', () => {
|
|
||||||
// slope < 0: the crest falls toward +x, so the face looks at +x, at the sun.
|
|
||||||
for (const s of [0.2, 0.6, 1.5]) expect(faceLight(-s, sun)).toBeGreaterThan(faceLight(s, sun));
|
|
||||||
expect(faceLight(1.5, sun)).toBeLessThan(0.2);
|
|
||||||
expect(faceLight(-1.5, sun)).toBeGreaterThan(0.6);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('in the baked pixels the lit side is brighter than the shadow side', () => {
|
|
||||||
for (const li of [0, 1, 2]) {
|
|
||||||
const cols = 900;
|
|
||||||
const p = params(li, 0, cols);
|
|
||||||
const d = bake(p);
|
|
||||||
const slope = (x: number) => (solidRow(d, cols, x - 1) - solidRow(d, cols, x + 1)) / 2; // rows up per column
|
|
||||||
const litX: number[] = [];
|
|
||||||
const shadeX: number[] = [];
|
|
||||||
for (let x = 2; x < cols - 2; x += 1) {
|
|
||||||
if (slope(x) < -0.8) litX.push(x);
|
|
||||||
if (slope(x) > 0.8) shadeX.push(x);
|
|
||||||
}
|
|
||||||
expect(litX.length).toBeGreaterThan(5);
|
|
||||||
expect(shadeX.length).toBeGreaterThan(5);
|
|
||||||
const mean = (xs: number[]) =>
|
|
||||||
xs.reduce((a, x) => a + lum(d, cols, x, solidRow(d, cols, x) + 12), 0) / xs.length;
|
|
||||||
expect(mean(litX)).toBeGreaterThan(mean(shadeX));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a lit crest rim: the crest pixels are brighter than the face a little below, on both sides', () => {
|
|
||||||
for (const li of [0, 1, 2, 3]) {
|
|
||||||
const cols = 600;
|
|
||||||
const d = bake(params(li, 300, cols));
|
|
||||||
let rimmed = 0;
|
|
||||||
let n = 0;
|
|
||||||
for (let x = 3; x < cols - 3; x += 1) {
|
|
||||||
const y = solidRow(d, cols, x);
|
|
||||||
if (y + 40 >= BAND) continue;
|
|
||||||
n += 1;
|
|
||||||
if (lum(d, cols, x, y + 1) > lum(d, cols, x, y + 30)) rimmed += 1;
|
|
||||||
}
|
|
||||||
expect(n).toBeGreaterThan(100);
|
|
||||||
expect(rimmed / n).toBeGreaterThan(0.8);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the foot of the face is clearly darker than its top, on every layer: volume from the depth below the crest', () => {
|
|
||||||
// Without the depth shading the bottom row is 0.93 to 0.98 of the luminance 12 rows under the crest; with it, 0.73 to 0.82.
|
|
||||||
for (const li of [0, 1, 2, 3]) {
|
|
||||||
const cols = 900;
|
|
||||||
const d = bake(params(li, 0, cols, { spec: { ...LAYERS[li], mist: 0, gully: 0 } }));
|
|
||||||
let ratio = 0;
|
|
||||||
let n = 0;
|
|
||||||
for (let x = 0; x < cols; x += 1) {
|
|
||||||
const y = solidRow(d, cols, x);
|
|
||||||
if (y + 90 >= BAND) continue;
|
|
||||||
n += 1;
|
|
||||||
ratio += lum(d, cols, x, BAND - 1) / Math.max(1, lum(d, cols, x, y + 12));
|
|
||||||
}
|
|
||||||
expect(n).toBeGreaterThan(30);
|
|
||||||
expect(ratio / n).toBeLessThan(0.88);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the valley mist still pulls the foot toward the haze colour', () => {
|
|
||||||
const cols = 300;
|
|
||||||
const p = params(0, 0, cols);
|
|
||||||
const misty = bake(p);
|
|
||||||
const clear = bake(params(0, 0, cols, { spec: { ...LAYERS[0], mist: 0 } }));
|
|
||||||
const haze = layerPaint(p.spec, p.sky).haze;
|
|
||||||
const dist = (d: Uint8ClampedArray, x: number, y: number) => {
|
|
||||||
const o = (y * cols + x) * 4;
|
|
||||||
return Math.hypot(d[o] - haze[0], d[o + 1] - haze[1], d[o + 2] - haze[2]);
|
|
||||||
};
|
|
||||||
let nearer = 0;
|
|
||||||
let n = 0;
|
|
||||||
for (let x = 0; x < cols; x += 1) {
|
|
||||||
const y = solidRow(misty, cols, x);
|
|
||||||
if (y + 200 >= BAND) continue;
|
|
||||||
n += 1;
|
|
||||||
if (dist(misty, x, y + 200) < dist(clear, x, y + 200)) nearer += 1;
|
|
||||||
}
|
|
||||||
expect(n).toBeGreaterThan(50);
|
|
||||||
expect(nearer / n).toBeGreaterThan(0.9);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('erosion streaks run down the face: brightness varies across columns at one depth, and not without them', () => {
|
|
||||||
const cols = 500;
|
|
||||||
const spread = (gully: number) => {
|
|
||||||
const d = bake(params(2, 0, cols, { spec: { ...LAYERS[2], gully } }));
|
|
||||||
// The same depth below the crest in every column, in the lit-independent part (gullies darken, lit is column-wise).
|
|
||||||
const v: number[] = [];
|
|
||||||
for (let x = 0; x < cols; x += 1) {
|
|
||||||
const y = solidRow(d, cols, x);
|
|
||||||
if (y + 90 < BAND) v.push(lum(d, cols, x, y + 80) / Math.max(1, lum(d, cols, x, y + 8)));
|
|
||||||
}
|
|
||||||
const m = v.reduce((a, b) => a + b, 0) / v.length;
|
|
||||||
return v.reduce((a, b) => a + (b - m) ** 2, 0) / v.length;
|
|
||||||
};
|
|
||||||
expect(spread(LAYERS[2].gully)).toBeGreaterThan(spread(0) * 1.2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('bake cost', () => {
|
|
||||||
it('is recorded, not asserted: one chunk of every layer at 1280 x 720', () => {
|
|
||||||
const period = 1280;
|
|
||||||
const rows = Math.round(720 * 0.6);
|
|
||||||
const ms = LAYERS.map((spec) => {
|
|
||||||
const p: BakeParams = {
|
|
||||||
spec,
|
|
||||||
sky: SKY,
|
|
||||||
period,
|
|
||||||
scale: 1,
|
|
||||||
viewH: 720,
|
|
||||||
rows,
|
|
||||||
bandH: rows,
|
|
||||||
px0: 0,
|
|
||||||
cols: Math.round(period * 1.2),
|
|
||||||
};
|
|
||||||
const t0 = performance.now();
|
|
||||||
bake(p);
|
|
||||||
return performance.now() - t0;
|
|
||||||
});
|
|
||||||
expect(ms.every((v) => Number.isFinite(v) && v >= 0)).toBe(true);
|
|
||||||
console.info(
|
|
||||||
`ridge bake ms per layer (node, 1 chunk, 1280x720): ${ms.map((v) => v.toFixed(1)).join(' ')}`
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the ridged multifractal core, each rule on its own', () => {
|
|
||||||
const one = { ...LAYERS[0], octaves: 1, warp: 0, crag: 1 };
|
|
||||||
|
|
||||||
it('folds each octave at its crest: a creased, sharp ridge line, not a smooth swell', () => {
|
|
||||||
// Largest second difference over a fine scan. A smooth curve of this size stays in the hundreds;
|
|
||||||
// a fold leaves a crease where the noise crosses its midpoint.
|
|
||||||
const h = 1e-3;
|
|
||||||
let worst = 0;
|
|
||||||
for (let i = 1; i < 20000; i += 1) {
|
|
||||||
const t = i * h;
|
|
||||||
worst = Math.max(
|
|
||||||
worst,
|
|
||||||
Math.abs(profile(one, t + h) - 2 * profile(one, t) + profile(one, t - h)) / (h * h)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
expect(worst).toBeGreaterThan(2000);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('domain-warps: the same layer without its warp is a measurably different line', () => {
|
|
||||||
const spec = LAYERS[1];
|
|
||||||
let diff = 0;
|
|
||||||
for (let i = 0; i < 2000; i += 1)
|
|
||||||
diff += Math.abs(profile(spec, i / 100) - profile({ ...spec, warp: 0 }, i / 100));
|
|
||||||
expect(diff / 2000).toBeGreaterThan(0.02);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('weights each octave by the previous one: where the first octave is low, the later ones add almost nothing', () => {
|
|
||||||
const lo = { ...LAYERS[1], octaves: 1, warp: 0 };
|
|
||||||
const hi = { ...LAYERS[1], octaves: 5, warp: 0 };
|
|
||||||
let valley = 0;
|
|
||||||
let nv = 0;
|
|
||||||
let peak = 0;
|
|
||||||
let np = 0;
|
|
||||||
for (let i = 0; i < 10000; i += 1) {
|
|
||||||
const a = profile(lo, i / 500);
|
|
||||||
const d = Math.abs(profile(hi, i / 500) - a);
|
|
||||||
if (a < 0.12) {
|
|
||||||
valley += d;
|
|
||||||
nv += 1;
|
|
||||||
} else if (a > 0.35) {
|
|
||||||
peak += d;
|
|
||||||
np += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(nv).toBeGreaterThan(200);
|
|
||||||
expect(np).toBeGreaterThan(200);
|
|
||||||
expect(valley / nv).toBeLessThan(0.25 * (peak / np));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('octave lattices do not line up: the lacunarity is not a power of two', () => {
|
|
||||||
expect(Number.isInteger(Math.log2(LACUNARITY))).toBe(false);
|
|
||||||
expect(Number.isInteger(LACUNARITY)).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('distance flattens relief: contrast falls from the nearest layer to the farthest', () => {
|
|
||||||
const c = LAYERS.map((spec) => layerPaint(spec, SKY).contrast);
|
|
||||||
expect(c[LAYERS.length - 1]).toBe(1);
|
|
||||||
for (let i = 1; i < c.length; i += 1) expect(c[i]).toBeGreaterThan(c[i - 1]);
|
|
||||||
// and it shows in the pixels: the lit/shadow difference is smaller on the farthest layer than the nearest
|
|
||||||
const gap = (li: number) => {
|
|
||||||
const cols = 700;
|
|
||||||
const d = bake(params(li, 0, cols));
|
|
||||||
const slope = (x: number) => (solidRow(d, cols, x - 1) - solidRow(d, cols, x + 1)) / 2;
|
|
||||||
const avg = (pick: (s: number) => boolean) => {
|
|
||||||
const xs = Array.from({ length: cols - 4 }, (_, k) => k + 2).filter((x) => pick(slope(x)));
|
|
||||||
return (
|
|
||||||
xs.reduce((a, x) => a + lum(d, cols, x, solidRow(d, cols, x) + 12), 0) /
|
|
||||||
Math.max(1, xs.length)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
return (
|
|
||||||
Math.abs(avg((s) => s < -0.8) - avg((s) => s > 0.8)) /
|
|
||||||
Math.max(
|
|
||||||
1,
|
|
||||||
avg(() => true)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
expect(gap(0)).toBeLessThan(gap(3));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the state band: the theme ink clears 4.5:1 on a ridge as on bare sky', () => {
|
|
||||||
const linear = (v: number) => {
|
|
||||||
const c = v / 255;
|
|
||||||
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
||||||
};
|
|
||||||
const luma = (d: Uint8ClampedArray, o: number) =>
|
|
||||||
0.2126 * linear(d[o]) + 0.7152 * linear(d[o + 1]) + 0.0722 * linear(d[o + 2]);
|
|
||||||
/** Lowest and highest luminance over the solid pixels of every layer. */
|
|
||||||
const range = (band: typeof SKY_BAND[keyof typeof SKY_BAND] | undefined) => {
|
|
||||||
let lo = 1;
|
|
||||||
let hi = 0;
|
|
||||||
for (const li of [0, 1, 2, 3]) {
|
|
||||||
const p = params(li, 0, 700, { sky: { ...SKY, band } });
|
|
||||||
const d = bake(p);
|
|
||||||
for (let o = 0; o < d.length; o += 4) {
|
|
||||||
if (d[o + 3] < 255) continue;
|
|
||||||
const l = luma(d, o);
|
|
||||||
lo = Math.min(lo, l);
|
|
||||||
hi = Math.max(hi, l);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { lo, hi };
|
|
||||||
};
|
|
||||||
|
|
||||||
it("day and dusk: no ridge pixel is darker than the text floor (Day's), on every layer", () => {
|
|
||||||
for (const band of [SKY_BAND.day, SKY_BAND.dusk]) {
|
|
||||||
expect(range(band).lo).toBeGreaterThanOrEqual(SKY_BAND.day.floor);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('night: no ridge pixel is lighter than the ceiling', () => {
|
|
||||||
expect(range(SKY_BAND.night).hi).toBeLessThanOrEqual(SKY_BAND.night.ceiling);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is the identity with no band, so nothing else changes', () => {
|
|
||||||
expect(layerPaint(LAYERS[2], SKY).shift).toBeNull();
|
|
||||||
expect(range(undefined).lo).toBeLessThan(SKY_BAND.day.floor);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps the shading: the foot is still darker than the top inside the band', () => {
|
|
||||||
// Inside the band the face's range is compressed, not removed: dusk, no mist or gullies, bottom row over 12 rows under the crest.
|
|
||||||
const sky = { ...SKY, band: SKY_BAND.dusk };
|
|
||||||
for (const li of [0, 1, 2, 3]) {
|
|
||||||
const cols = 900;
|
|
||||||
const d = bake(params(li, 0, cols, { sky, spec: { ...LAYERS[li], mist: 0, gully: 0 } }));
|
|
||||||
let ratio = 0;
|
|
||||||
let n = 0;
|
|
||||||
for (let x = 0; x < cols; x += 1) {
|
|
||||||
const y = solidRow(d, cols, x);
|
|
||||||
if (y + 90 >= BAND) continue;
|
|
||||||
n += 1;
|
|
||||||
ratio += luma(d, ((BAND - 1) * cols + x) * 4) / luma(d, ((y + 12) * cols + x) * 4);
|
|
||||||
}
|
|
||||||
expect(n).toBeGreaterThan(30);
|
|
||||||
// Measured 0.84, 0.85, 0.91, 0.97 far to near: the nearest ground is near black, so its range is small in absolute terms.
|
|
||||||
expect(ratio / n).toBeLessThan(li < 3 ? 0.95 : 1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the real states, over a sweep of the sun: no pixel overflows the encoding (an overflow reads as a stray black or yellow channel)', () => {
|
|
||||||
for (const state of ['day', 'dusk', 'night'] as const) {
|
|
||||||
for (const sunAzimuth of [0, 0.1, 0.25, 0.3, 0.5, 0.75, 0.9]) {
|
|
||||||
const sky = { ...ridgeSkyFor(state), sunAzimuth };
|
|
||||||
for (const li of [0, 1, 2, 3]) {
|
|
||||||
const d = bake(params(li, 1000, 400, { sky }));
|
|
||||||
let stray = 0;
|
|
||||||
for (let o = 0; o < d.length; o += 4) {
|
|
||||||
if (d[o + 3] < 255) continue;
|
|
||||||
// A channel far below both others is the signature of a lookup that read past its table.
|
|
||||||
const lo = Math.min(d[o], d[o + 1], d[o + 2]);
|
|
||||||
const mid = d[o] + d[o + 1] + d[o + 2] - lo - Math.max(d[o], d[o + 1], d[o + 2]);
|
|
||||||
if (mid - lo > 120) stray += 1;
|
|
||||||
}
|
|
||||||
expect(stray).toBe(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,221 +0,0 @@
|
||||||
/* eslint-disable no-param-reassign -- `bakeSlice` fills the caller's pixel buffer */
|
|
||||||
// The pixels of a ridge chunk, as a pure function: no DOM, no canvas. Each column is lit from the
|
|
||||||
// slope of the heightfield's crest line against the sun; the face under it takes a light-to-haze
|
|
||||||
// gradient, erosion streaks and a lit rim on the crest. The depth treatment (colour, haze, contrast
|
|
||||||
// by distance) is ridgeWorld's `layerColour`, `hazeColour` and `transmittance`, used here and not redone.
|
|
||||||
import {
|
|
||||||
gullyAt,
|
|
||||||
HorizonView,
|
|
||||||
LayerSpec,
|
|
||||||
layerProfile,
|
|
||||||
hazeColour,
|
|
||||||
layerColour,
|
|
||||||
transmittance,
|
|
||||||
} from './ridgeWorld';
|
|
||||||
import type { SkyBand } from '../skyBand';
|
|
||||||
import { LUMA, SKY_BAND } from '../skyBand';
|
|
||||||
import type { SkyColours, Srgb } from './skyColour';
|
|
||||||
|
|
||||||
export type Vec3 = readonly [number, number, number];
|
|
||||||
|
|
||||||
/** Unit vector toward the sun: x across the screen (from the azimuth), y up, z toward the viewer. */
|
|
||||||
export function sunDirection(sky: SkyColours): Vec3 {
|
|
||||||
const az = sky.sunAzimuth ?? 0.3;
|
|
||||||
const x = 0.9 * Math.sin(2 * Math.PI * az);
|
|
||||||
const l = Math.hypot(x, 0.35, 0.45);
|
|
||||||
return [x / l, 0.35 / l, 0.45 / l];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** How steeply the crest's slope tilts the face's normal sideways. */
|
|
||||||
const TILT = 1.2;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sun light on the face under a crest whose silhouette has `slope` (rows per column, positive when the
|
|
||||||
* crest rises toward +x, so the face looks toward -x). 0 in full shadow .. 1 head-on to the sun.
|
|
||||||
*/
|
|
||||||
export function faceLight(slope: number, sun: Vec3): number {
|
|
||||||
const nx = -slope * TILT;
|
|
||||||
const inv = 1 / Math.hypot(nx, 0.55, 0.85);
|
|
||||||
const d = (nx * sun[0] + 0.55 * sun[1] + 0.85 * sun[2]) * inv;
|
|
||||||
return Math.min(1, Math.max(0, (d - 0.2) / 0.7));
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BakeParams {
|
|
||||||
spec: LayerSpec;
|
|
||||||
sky: SkyColours;
|
|
||||||
/** Pixels in one viewport width: the unit of world-x. */
|
|
||||||
period: number;
|
|
||||||
/** CSS px to canvas px. */
|
|
||||||
scale: number;
|
|
||||||
/** Viewport height in canvas px. */
|
|
||||||
viewH: number;
|
|
||||||
/** Rows of the pixel buffer (the band plus any padding below it). */
|
|
||||||
rows: number;
|
|
||||||
/** Row count of the visible band; the crest is measured from the top of it. */
|
|
||||||
bandH: number;
|
|
||||||
/** Where world-x is a compass azimuth, for the horizon layer (`LayerSpec.horizon`); absent: every layer is noise. */
|
|
||||||
horizonView?: HorizonView;
|
|
||||||
/** World pixel of the buffer's column 0 (may be fractional-free negative: a chunk's left minus its padding). */
|
|
||||||
px0: number;
|
|
||||||
/** Columns of the buffer. */
|
|
||||||
cols: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const clamp01 = (v: number): number => Math.min(1, Math.max(0, v));
|
|
||||||
const smoothstep = (a: number, b: number, v: number): number => {
|
|
||||||
const t = clamp01((v - a) / (b - a));
|
|
||||||
return t * t * (3 - 2 * t);
|
|
||||||
};
|
|
||||||
const SUN_WHITE: Srgb = [255, 238, 205];
|
|
||||||
|
|
||||||
/** Everything `bakeSlice` needs per layer, computed once. */
|
|
||||||
export interface LayerPaint {
|
|
||||||
/** The state's band as a shift of linear light (raises the floor, lowers the ceiling); null when the sky has none. */
|
|
||||||
shift: BandShift | null;
|
|
||||||
base: Srgb;
|
|
||||||
haze: Srgb;
|
|
||||||
warm: Srgb;
|
|
||||||
contrast: number;
|
|
||||||
sun: Vec3;
|
|
||||||
/** How much the weather's mist multiplies the layer's own (`weather.ts`): 1 in clear air. */
|
|
||||||
mistK: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
const decode = (v: number): number => {
|
|
||||||
const s = v / 255;
|
|
||||||
return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
||||||
};
|
|
||||||
const DECODE = Float32Array.from({ length: 256 }, (_, v) => decode(v));
|
|
||||||
const ENCODE_STEPS = 4095;
|
|
||||||
const ENCODE = Uint8ClampedArray.from({ length: ENCODE_STEPS + 1 }, (_, i) => {
|
|
||||||
const l = i / ENCODE_STEPS;
|
|
||||||
return 255 * (l <= 0.0031308 ? 12.92 * l : 1.055 * l ** (1 / 2.4) - 0.055);
|
|
||||||
});
|
|
||||||
/** What the band is held clear of at its edges: the 8-bit rounding and the blur and in-scatter the chunk takes after the bake. */
|
|
||||||
const BAND_MARGIN = 0.012;
|
|
||||||
|
|
||||||
/** Linear light out = in * `scale` + `add[channel]`. */
|
|
||||||
export interface BandShift {
|
|
||||||
add: readonly [number, number, number];
|
|
||||||
scale: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The state's band (skyBand.ts) as a shift of linear light, solved once per layer. Adding `add` (the zenith colour, so
|
|
||||||
* the ridge reads as shadowed by the sky above, a hue apart from the horizon behind it) raises every pixel's
|
|
||||||
* luminance by exactly the floor, so the face keeps its whole gradient and the darkest pixel is on the floor; scaling by
|
|
||||||
* `scale` puts the lightest pixel on the ceiling. Smooth in the pixel's own luminance: no cut and no region.
|
|
||||||
* The floor is the text bound (Day's), not Dusk's higher link bound: the link ink is not set on ridges, and Dusk's
|
|
||||||
* floor washes the faces to a flat pale slab.
|
|
||||||
*/
|
|
||||||
export function bandShift(band: SkyBand | undefined, lift: Srgb): BandShift | null {
|
|
||||||
if (!band) return null;
|
|
||||||
const floor = Math.min(band.floor, SKY_BAND.day.floor);
|
|
||||||
const scale = band.ceiling < 1 ? band.ceiling - BAND_MARGIN / 3 : 1;
|
|
||||||
if (floor <= 0 && scale === 1) return null;
|
|
||||||
const lin = lift.map(decode);
|
|
||||||
const k =
|
|
||||||
floor > 0
|
|
||||||
? (floor + BAND_MARGIN) / (LUMA[0] * lin[0] + LUMA[1] * lin[1] + LUMA[2] * lin[2])
|
|
||||||
: 0;
|
|
||||||
return { add: [lin[0] * k, lin[1] * k, lin[2] * k], scale };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function layerPaint(spec: LayerSpec, sky: SkyColours): LayerPaint {
|
|
||||||
const warm: Srgb = [
|
|
||||||
(sky.horizon[0] + SUN_WHITE[0]) / 2,
|
|
||||||
(sky.horizon[1] + SUN_WHITE[1]) / 2,
|
|
||||||
(sky.horizon[2] + SUN_WHITE[2]) / 2,
|
|
||||||
];
|
|
||||||
return {
|
|
||||||
shift: bandShift(sky.band, sky.top),
|
|
||||||
base: layerColour(spec, sky),
|
|
||||||
haze: hazeColour(sky),
|
|
||||||
warm,
|
|
||||||
// Distance flattens relief: the same transmittance that thins the colour.
|
|
||||||
contrast: 0.35 + 0.65 * transmittance(spec),
|
|
||||||
sun: sunDirection(sky),
|
|
||||||
mistK: 1 + 2.5 * (sky.physical?.weather.mist ?? 0),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Crest row (float, from the top of the band) of every buffer column from c0 - 1 to c1 (inclusive). */
|
|
||||||
function crestRows(p: BakeParams, c0: number, c1: number): Float64Array {
|
|
||||||
const out = new Float64Array(c1 - c0 + 2);
|
|
||||||
const amp = p.spec.relief * p.viewH;
|
|
||||||
const lift = p.spec.base * p.viewH;
|
|
||||||
for (let c = c0 - 1; c <= c1; c += 1) {
|
|
||||||
const top = Math.min(
|
|
||||||
p.bandH,
|
|
||||||
lift + amp * layerProfile(p.spec, (p.px0 + c) / p.period, p.horizonView)
|
|
||||||
);
|
|
||||||
out[c - c0 + 1] = p.bandH - top;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Paint columns [c0, c1) of the chunk into `out` (RGBA, `p.cols` wide, `p.rows` tall, zeroed). One
|
|
||||||
* call is a slice of a chunk, so a caller can keep each task short. Seams are exact: a column's pixels
|
|
||||||
* depend only on its world pixel, never on where the slice or chunk begins.
|
|
||||||
*/
|
|
||||||
export function bakeSlice(
|
|
||||||
out: Uint8ClampedArray,
|
|
||||||
p: BakeParams,
|
|
||||||
paint: LayerPaint,
|
|
||||||
c0: number,
|
|
||||||
c1: number
|
|
||||||
): void {
|
|
||||||
const { spec } = p;
|
|
||||||
const crest = crestRows(p, c0, c1);
|
|
||||||
const faceH = 0.45 * p.viewH;
|
|
||||||
const rim = 2.2 * p.scale;
|
|
||||||
const glow = 9 * p.scale;
|
|
||||||
const { base, haze, warm, contrast, sun, shift, mistK } = paint;
|
|
||||||
for (let c = c0; c < c1; c += 1) {
|
|
||||||
const cy = crest[c - c0 + 1];
|
|
||||||
const slope = (crest[c - c0 + 2] - crest[c - c0]) * -0.5; // rows up per column
|
|
||||||
const lit = faceLight(slope, sun);
|
|
||||||
const steep = 0.45 + 0.55 * clamp01(Math.abs(slope) * 0.8);
|
|
||||||
const gl = gullyAt(spec, (p.px0 + c) / p.scale) * steep;
|
|
||||||
const y0 = Math.max(0, Math.floor(cy));
|
|
||||||
for (let y = y0; y < p.rows; y += 1) {
|
|
||||||
const d = y + 0.5 - cy;
|
|
||||||
const dn = clamp01(d / faceH);
|
|
||||||
const cover = clamp01(y + 1 - cy);
|
|
||||||
const gully = spec.gully * gl * smoothstep(0, 0.2, dn);
|
|
||||||
// Shade the ground colour by the sun; the lit warm light fades down the face and in the gullies.
|
|
||||||
// Volume from the depth below the crest: the face darkens toward its foot (before the mist lifts it
|
|
||||||
// toward the haze), and the sun catches its top. A few multiplies per pixel, in the bake only.
|
|
||||||
const foot = 1 - 0.4 * contrast * smoothstep(0.05, 0.9, dn);
|
|
||||||
const top = 1 - smoothstep(0, 0.3, dn);
|
|
||||||
const shade = (0.7 + 0.3 * lit * contrast + 0.3 * (1 - contrast)) * (1 - 0.5 * gully) * foot;
|
|
||||||
const warmK =
|
|
||||||
0.22 * contrast * lit * lit * (1 - 0.7 * dn) * (1 - 0.6 * gully) +
|
|
||||||
0.04 * contrast * lit * top;
|
|
||||||
// A hard 2 px lip on the crest and a soft glow under it.
|
|
||||||
const rimK =
|
|
||||||
(clamp01(1 - d / rim) * 0.4 + (d < glow * 5 ? Math.exp(-d / glow) * 0.08 : 0)) *
|
|
||||||
contrast *
|
|
||||||
(0.3 + 0.7 * lit);
|
|
||||||
const mist = Math.min(0.9, spec.mist * mistK) * smoothstep(0, 1, dn);
|
|
||||||
const o = (y * p.cols + c) * 4;
|
|
||||||
for (let i = 0; i < 3; i += 1) {
|
|
||||||
let v = base[i] * shade + warm[i] * (warmK + rimK);
|
|
||||||
v += (haze[i] - v) * mist;
|
|
||||||
out[o + i] = shift
|
|
||||||
? ENCODE[
|
|
||||||
Math.min(
|
|
||||||
ENCODE_STEPS,
|
|
||||||
((DECODE[v >= 255 ? 255 : v <= 0 ? 0 : Math.round(v)] * shift.scale +
|
|
||||||
shift.add[i]) *
|
|
||||||
ENCODE_STEPS) |
|
|
||||||
0
|
|
||||||
)
|
|
||||||
]
|
|
||||||
: v;
|
|
||||||
}
|
|
||||||
out[o + 3] = cover * 255;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,236 +0,0 @@
|
||||||
// Every number of the ridge scene, and the pure functions that turn them into silhouettes. No DOM.
|
|
||||||
// A ridge is a function of world-x (t, in viewport widths): ridged multifractal noise, domain-warped,
|
|
||||||
// one function for every layer with the parameters below. Nothing in it repeats.
|
|
||||||
import { horizonShape } from './horizon';
|
|
||||||
import { valueNoise } from './noise';
|
|
||||||
import type { Srgb, SkyColours } from './skyColour';
|
|
||||||
|
|
||||||
export interface LayerSpec {
|
|
||||||
/** 0 farthest. Also the noise row, so layers never share a profile. */
|
|
||||||
index: number;
|
|
||||||
/** Lattice cells per viewport width for the first octave; each octave multiplies it by LACUNARITY. */
|
|
||||||
baseCells: number;
|
|
||||||
/** Peak-to-valley height of the silhouette, as a fraction of the viewport height. */
|
|
||||||
relief: number;
|
|
||||||
/** 0 rounded hills .. 1 sharp crags: how tightly each octave is folded at its crest. */
|
|
||||||
crag: number;
|
|
||||||
/** Ridge top at its lowest point, fraction of the viewport height up from the bottom. */
|
|
||||||
base: number;
|
|
||||||
/** 0 = the layer is the horizon haze, 1 = the nearest ground colour. */
|
|
||||||
depth: number;
|
|
||||||
/** Seconds for the layer to drift one viewport width. Farther layers are slower. */
|
|
||||||
seconds: number;
|
|
||||||
/** Octaves of the ridged multifractal; the bake cost is linear in it. */
|
|
||||||
octaves: number;
|
|
||||||
/** Domain warp, in cells of the first octave. */
|
|
||||||
warp: number;
|
|
||||||
/** 0..1 depth of the erosion streaks down the face. */
|
|
||||||
gully: number;
|
|
||||||
/** Width of one gully, CSS px. */
|
|
||||||
gullyPx: number;
|
|
||||||
/** 0..1 how far the foot of the face dissolves into the valley mist. */
|
|
||||||
mist: number;
|
|
||||||
/**
|
|
||||||
* The layer is the real horizon of the viewpoint (`horizon.ts`), not noise: world-x is compass azimuth across the viewport
|
|
||||||
* (`HorizonView`) and it does not drift, so it stays under the sun it is lit by. Its `relief` is the ring's own range.
|
|
||||||
*/
|
|
||||||
horizon?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Where the camera looks and how wide it sees, to read world-x as an azimuth: the sky's own view (`skyDome.ts viewFor`). */
|
|
||||||
export interface HorizonView {
|
|
||||||
/** Compass azimuth of the viewport's centre, degrees clockwise from north. */
|
|
||||||
azimuthDeg: number;
|
|
||||||
hfovDeg: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The static horizon layer's track sits this many viewport widths left of the screen, so the camera's sway never shows its edge. */
|
|
||||||
export const HORIZON_TRACK_SHIFT = 0.06;
|
|
||||||
|
|
||||||
/** Four layers: one function, four parameter rows. */
|
|
||||||
export const LAYERS: readonly LayerSpec[] = [
|
|
||||||
{
|
|
||||||
index: 0,
|
|
||||||
baseCells: 2.2,
|
|
||||||
relief: 0.16,
|
|
||||||
crag: 0.85,
|
|
||||||
base: 0.3,
|
|
||||||
depth: 0.12,
|
|
||||||
seconds: Infinity,
|
|
||||||
octaves: 5,
|
|
||||||
warp: 0.6,
|
|
||||||
gully: 0.3,
|
|
||||||
gullyPx: 16,
|
|
||||||
mist: 0.35,
|
|
||||||
horizon: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
index: 1,
|
|
||||||
baseCells: 3.0,
|
|
||||||
relief: 0.2,
|
|
||||||
crag: 0.7,
|
|
||||||
base: 0.26,
|
|
||||||
depth: 0.38,
|
|
||||||
seconds: 300,
|
|
||||||
octaves: 5,
|
|
||||||
warp: 0.55,
|
|
||||||
gully: 0.5,
|
|
||||||
gullyPx: 20,
|
|
||||||
mist: 0.3,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
index: 2,
|
|
||||||
baseCells: 3.8,
|
|
||||||
relief: 0.16,
|
|
||||||
crag: 0.5,
|
|
||||||
base: 0.17,
|
|
||||||
depth: 0.66,
|
|
||||||
seconds: 210,
|
|
||||||
octaves: 5,
|
|
||||||
warp: 0.5,
|
|
||||||
gully: 0.6,
|
|
||||||
gullyPx: 24,
|
|
||||||
mist: 0.22,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
index: 3,
|
|
||||||
baseCells: 4.6,
|
|
||||||
relief: 0.12,
|
|
||||||
crag: 0.3,
|
|
||||||
base: 0.08,
|
|
||||||
depth: 1,
|
|
||||||
seconds: 150,
|
|
||||||
octaves: 4,
|
|
||||||
warp: 0.45,
|
|
||||||
gully: 0.7,
|
|
||||||
gullyPx: 30,
|
|
||||||
mist: 0.16,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
/** Not an integer power of two, so no octave's lattice lines up with another's. */
|
|
||||||
export const LACUNARITY = 2.07;
|
|
||||||
/** Each octave is weighted by the previous octave's folded signal, times this, clamped to 1. */
|
|
||||||
export const WEIGHT_GAIN = 2;
|
|
||||||
const AMP_GAIN = 0.5;
|
|
||||||
/** Calibration: the weighted sum's typical top is about 1 / this. */
|
|
||||||
const PEAK_NORM = 1.25;
|
|
||||||
|
|
||||||
/** Silhouette height in [0, 1] at world-x `t` (viewport widths); defined for every real t. */
|
|
||||||
export function profile(spec: LayerSpec, t: number): number {
|
|
||||||
const row = spec.index * 101;
|
|
||||||
const wt =
|
|
||||||
t + (spec.warp * (2 * valueNoise(t * spec.baseCells * 0.7, row + 97) - 1)) / spec.baseCells;
|
|
||||||
const e = 0.03 + (1 - spec.crag) * 0.4;
|
|
||||||
const top = Math.sqrt(1 + e * e);
|
|
||||||
let sum = 0;
|
|
||||||
let norm = 0;
|
|
||||||
let amp = 1;
|
|
||||||
let f = spec.baseCells;
|
|
||||||
let w = 1;
|
|
||||||
for (let k = 0; k < spec.octaves; k += 1) {
|
|
||||||
const v = 2 * valueNoise(wt * f, row + k * 13) - 1;
|
|
||||||
// Fold: 1 at the zero crossing of the noise, 0 at its extremes; `e` rounds the crease.
|
|
||||||
let sig = 1 - Math.sqrt(v * v + e * e) / top;
|
|
||||||
sig *= sig;
|
|
||||||
sig *= w;
|
|
||||||
w = Math.min(1, sig * WEIGHT_GAIN);
|
|
||||||
sum += sig * amp;
|
|
||||||
norm += amp;
|
|
||||||
amp *= AMP_GAIN;
|
|
||||||
f *= LACUNARITY;
|
|
||||||
}
|
|
||||||
// A soft swell under the folds, so the valleys between sharp crests are not flat floors.
|
|
||||||
const swell = valueNoise(wt * spec.baseCells * 0.6, row + 211);
|
|
||||||
return Math.min(1, 0.85 * (sum / norm) * PEAK_NORM + 0.15 * swell);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Silhouette height in [0, 1] of a layer at world-x `t` (viewport widths). The horizon layer reads the baked horizon at the azimuth `t`
|
|
||||||
* is under `view`; every other layer, or a horizon layer with no view, is the noise `profile`.
|
|
||||||
*/
|
|
||||||
export function layerProfile(spec: LayerSpec, t: number, view?: HorizonView): number {
|
|
||||||
if (!spec.horizon || !view) return profile(spec, t);
|
|
||||||
return horizonShape(view.azimuthDeg + (t - HORIZON_TRACK_SHIFT - 0.5) * view.hfovDeg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Erosion streak strength in [0, 1] at world-x `wxCss` (CSS px): a folded noise at gully width. */
|
|
||||||
export function gullyAt(spec: LayerSpec, wxCss: number): number {
|
|
||||||
const g = 1 - Math.abs(2 * valueNoise(wxCss / spec.gullyPx, spec.index * 131 + 5) - 1);
|
|
||||||
return g * g;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The distance haze the far layers dissolve into: between the mid sky and the horizon, not the horizon glow itself. */
|
|
||||||
export function hazeColour(sky: SkyColours): Srgb {
|
|
||||||
const m = (a: number, b: number) => Math.round(a + (b - a) * 0.4);
|
|
||||||
return [
|
|
||||||
m(sky.mid[0], sky.horizon[0]),
|
|
||||||
m(sky.mid[1], sky.horizon[1]),
|
|
||||||
m(sky.mid[2], sky.horizon[2]),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Aerial perspective, applied once at bake time. A layer at distance d (0 nearest, 1 farthest) is seen
|
|
||||||
* through Beer-Lambert transmittance T = exp(-extinction * d): it shows T of its own colour and 1 - T of
|
|
||||||
* the haze, then loses `desaturate * (1 - T)` of its chroma, is softened by up to `blurPx` (canvas
|
|
||||||
* pixels at scale 1) and takes a faint warm in-scatter of at most `scatter` on the sun side.
|
|
||||||
*/
|
|
||||||
export const AERIAL = { extinction: 1.6, desaturate: 0.5, blurPx: 2, scatter: 0.16 };
|
|
||||||
|
|
||||||
/** Distance of a layer from the viewer, 0 (nearest) .. 1 (farthest). */
|
|
||||||
export const layerDistance = (spec: LayerSpec): number => 1 - spec.depth;
|
|
||||||
|
|
||||||
export const transmittance = (spec: LayerSpec): number =>
|
|
||||||
Math.exp(-AERIAL.extinction * layerDistance(spec));
|
|
||||||
|
|
||||||
/** Layer colour as seen: its own ground colour thinned by the haze between it and the eye. */
|
|
||||||
export function layerColour(spec: LayerSpec, sky: SkyColours): Srgb {
|
|
||||||
const h = hazeColour(sky);
|
|
||||||
const t = transmittance(spec);
|
|
||||||
const seen = (i: number) => sky.ground[i] * t + h[i] * (1 - t);
|
|
||||||
const luma = 0.2126 * seen(0) + 0.7152 * seen(1) + 0.0722 * seen(2);
|
|
||||||
const keep = 1 - AERIAL.desaturate * (1 - t);
|
|
||||||
const out = (i: number) => Math.round(luma + (seen(i) - luma) * keep);
|
|
||||||
return [out(0), out(1), out(2)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Edge softening for a layer, in canvas pixels at scale 1; 0 for the nearest. */
|
|
||||||
export const edgeBlur = (spec: LayerSpec): number => AERIAL.blurPx * (1 - transmittance(spec));
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Alpha of the warm sun-side in-scatter at world-x `t` (viewport widths). Zero when the sky has no
|
|
||||||
* sun; grows with distance. The lobe is the product of two cosines with incommensurate wavelengths
|
|
||||||
* (1.9 and 1.9 * golden ratio), so it is not periodic; its peaks are where the sun's azimuth puts them.
|
|
||||||
*/
|
|
||||||
export function scatterAlpha(spec: LayerSpec, sky: SkyColours, t: number): number {
|
|
||||||
if (sky.sunAzimuth === undefined) return 0;
|
|
||||||
const a = 0.5 + 0.5 * Math.cos(2 * Math.PI * (t / 1.9 - sky.sunAzimuth));
|
|
||||||
const b = 0.75 + 0.25 * Math.cos((2 * Math.PI * t) / (1.9 * 1.618034));
|
|
||||||
return AERIAL.scatter * (1 - transmittance(spec)) * a * a * b;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Chunk width as a multiple of the viewport width: room for the yaw sway on top of the viewport. */
|
|
||||||
export const CHUNK_OVER = 1.2;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Integer pixel sizes for a viewport. `period` is one viewport width, the unit of world-x; a chunk
|
|
||||||
* is `chunk` pixels of world, `height` the band a layer is painted in.
|
|
||||||
*/
|
|
||||||
export function layerSize(cssW: number, cssH: number, scale: number) {
|
|
||||||
const period = Math.round(cssW * scale);
|
|
||||||
const band = Math.round(cssH * scale * 0.6);
|
|
||||||
return { period, chunk: Math.round(period * CHUNK_OVER), height: band };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Ridge-top y (canvas pixels, from the top of the layer's band) at world-x `t` (viewport widths). */
|
|
||||||
export function ridgeY(
|
|
||||||
spec: LayerSpec,
|
|
||||||
t: number,
|
|
||||||
bandH: number,
|
|
||||||
viewH: number,
|
|
||||||
view?: HorizonView
|
|
||||||
): number {
|
|
||||||
const topFromBottom = spec.base * viewH + spec.relief * viewH * layerProfile(spec, t, view);
|
|
||||||
return bandH - Math.min(bandH, topFromBottom);
|
|
||||||
}
|
|
||||||
|
|
@ -1,10 +1,8 @@
|
||||||
// The one place the sky's colours come from. Void's `src/sky/sun.js` (`light({ time, lat, lon,
|
// The one place the sky's colours come from. Void's `src/sky/sun.js` (`light({ time, lat, lon,
|
||||||
// cloud_cover, precipitation })`, PR #20) is the intended source; until it lands this returns a
|
// cloud_cover, precipitation })`, PR #20) is the intended source; until it lands this returns a
|
||||||
// fixed twilight: lavender zenith, rose mid-sky, orange horizon. These are the raw stops: the scene draws them
|
// fixed twilight: lavender zenith, rose mid-sky, orange horizon. Replace the body, keep the signature: the scene calls it once, at startup,
|
||||||
// shaped into the dusk band of ../skyBand.ts (`ridgeSkyFor`, skyForState.ts), whose floor the link of Noonday Sky needs. Replace the body, keep the signature: the scene calls it once, at startup,
|
// and paints the result.
|
||||||
// and bakes the result.
|
|
||||||
|
|
||||||
import type { SkyBand } from '../skyBand';
|
|
||||||
import type { PhysicalSky } from './physicalSky';
|
import type { PhysicalSky } from './physicalSky';
|
||||||
|
|
||||||
export type Srgb = readonly [number, number, number];
|
export type Srgb = readonly [number, number, number];
|
||||||
|
|
@ -14,14 +12,8 @@ export interface SkyColours {
|
||||||
top: Srgb;
|
top: Srgb;
|
||||||
/** Mid-sky band. */
|
/** Mid-sky band. */
|
||||||
mid: Srgb;
|
mid: Srgb;
|
||||||
/** Colour at the horizon, which the far ridges fade into. */
|
/** Colour at the horizon. */
|
||||||
horizon: Srgb;
|
horizon: Srgb;
|
||||||
/** Nearest ridge: the ground colour the farther layers mix away from. */
|
|
||||||
ground: Srgb;
|
|
||||||
/** Where the sun sits across one drift period, 0..1; the layers pick up a faint warm in-scatter there. Omit for none. */
|
|
||||||
sunAzimuth?: number;
|
|
||||||
/** The state's luminance band (skyBand.ts): the layers are shaped into it as the sky is, so the theme ink clears 4.5:1 on a ridge as on bare sky. Omit for none. */
|
|
||||||
band?: SkyBand;
|
|
||||||
/** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */
|
/** The physical sky this palette was read from; when present the host canvas is painted from it, not from the three stops. */
|
||||||
physical?: PhysicalSky;
|
physical?: PhysicalSky;
|
||||||
}
|
}
|
||||||
|
|
@ -31,7 +23,5 @@ export function skyColours(_now: Date = new Date()): SkyColours {
|
||||||
top: [170, 145, 220],
|
top: [170, 145, 220],
|
||||||
mid: [225, 130, 165],
|
mid: [225, 130, 165],
|
||||||
horizon: [240, 150, 80],
|
horizon: [240, 150, 80],
|
||||||
ground: [7, 17, 26],
|
|
||||||
sunAzimuth: 0.3,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,29 +2,15 @@
|
||||||
// LUT (`earthAtmosphere.ts`), and nothing else; one lookup per texel, no march. The result is linear HDR
|
// LUT (`earthAtmosphere.ts`), and nothing else; one lookup per texel, no march. The result is linear HDR
|
||||||
// radiance per unit of sun irradiance (a `Float32Array`); `toneMap.ts` makes it pixels.
|
// radiance per unit of sun irradiance (a `Float32Array`); `toneMap.ts` makes it pixels.
|
||||||
import type { Atmosphere } from './earthAtmosphere';
|
import type { Atmosphere } from './earthAtmosphere';
|
||||||
import type { SunSample } from './vienna';
|
import type { SunSample } from './sunAt';
|
||||||
|
import type { Camera } from './view';
|
||||||
import { cloudAmount, cloudRadiance } from './clouds';
|
import { cloudAmount, cloudRadiance } from './clouds';
|
||||||
|
import { addNightRadiance } from './nightSky';
|
||||||
|
import type { NightLight } from './nightSky';
|
||||||
|
|
||||||
const RAD = Math.PI / 180;
|
const RAD = Math.PI / 180;
|
||||||
/** The sun's angular radius in radians (Hillaire's/Bruneton's `sun_angular_radius`). */
|
/** The sun's angular radius in radians (Hillaire's/Bruneton's `sun_angular_radius`). */
|
||||||
export const SUN_RADIUS = 0.004675;
|
export const SUN_RADIUS = 0.004675;
|
||||||
/** Vertical field of view of the camera, degrees, and where the horizon sits down the image: the ridge scene's sky stops. */
|
|
||||||
export const VFOV_DEG = 50;
|
|
||||||
export const HORIZON_AT = 0.78;
|
|
||||||
|
|
||||||
export interface DomeView {
|
|
||||||
/** Compass azimuth the camera faces, degrees clockwise from north. */
|
|
||||||
azimuthDeg: number;
|
|
||||||
/** Width over height of the viewport. */
|
|
||||||
aspect: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Where the camera looks: toward the sun's side while it is up, so the sun sits right of centre; south in the dark. */
|
|
||||||
export const viewFor = (sun: SunSample, aspect: number): DomeView => ({
|
|
||||||
azimuthDeg: sun.elevation > -6 ? sun.azimuth - 24 : 180,
|
|
||||||
aspect,
|
|
||||||
});
|
|
||||||
|
|
||||||
export interface Dome {
|
export interface Dome {
|
||||||
w: number;
|
w: number;
|
||||||
h: number;
|
h: number;
|
||||||
|
|
@ -41,23 +27,18 @@ 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(
|
export function renderDome(
|
||||||
atm: Atmosphere,
|
atm: Atmosphere,
|
||||||
sun: SunSample,
|
sun: SunSample,
|
||||||
view: DomeView,
|
camera: Camera,
|
||||||
w: number,
|
w: number,
|
||||||
h: number,
|
h: number,
|
||||||
cover = 0
|
cover = 0,
|
||||||
|
night?: NightLight
|
||||||
): Dome {
|
): Dome {
|
||||||
const hdr = new Float32Array(w * h * 3);
|
const hdr = new Float32Array(w * h * 3);
|
||||||
const tanHalf = Math.tan((VFOV_DEG * RAD) / 2);
|
|
||||||
const fa = view.azimuthDeg * RAD;
|
|
||||||
const fx = Math.sin(fa);
|
|
||||||
const fy = Math.cos(fa);
|
|
||||||
const rx = Math.cos(fa);
|
|
||||||
const ry = -Math.sin(fa);
|
|
||||||
const sunAz = sun.azimuth * RAD;
|
const sunAz = sun.azimuth * RAD;
|
||||||
const sunEl = sun.elevation * RAD;
|
const sunEl = sun.elevation * RAD;
|
||||||
const sz = Math.sin(sunEl);
|
const sz = Math.sin(sunEl);
|
||||||
|
|
@ -69,25 +50,36 @@ export function renderDome(
|
||||||
const zenith = [0, 0, 0];
|
const zenith = [0, 0, 0];
|
||||||
atm.radiance(1, 1, zenith);
|
atm.radiance(1, 1, zenith);
|
||||||
cloudRadiance(sz, trans, zenith, cover, cloud);
|
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;
|
let logSum = 0;
|
||||||
for (let j = 0; j < h; j += 1) {
|
for (let j = 0; j < h; j += 1) {
|
||||||
const v = (HORIZON_AT - (j + 0.5) / h) * 2 * tanHalf;
|
const el = (camera.horizonAt - (j + 0.5) / h) * camera.vfovDeg * RAD;
|
||||||
|
const vz = Math.sin(el);
|
||||||
|
const ground = Math.cos(el);
|
||||||
for (let i = 0; i < w; i += 1) {
|
for (let i = 0; i < w; i += 1) {
|
||||||
const u = ((i + 0.5) / w - 0.5) * view.aspect * 2 * tanHalf;
|
const az = (camera.azimuthDeg + ((i + 0.5) / w - 0.5) * camera.hfovDeg) * RAD;
|
||||||
const dx = fx + rx * u;
|
const cosFromSun = Math.cos(az - sunAz);
|
||||||
const dy = fy + ry * u;
|
|
||||||
const dz = v;
|
|
||||||
const n = Math.hypot(dx, dy, dz);
|
|
||||||
const vz = dz / n;
|
|
||||||
const cosFromSun = Math.cos(Math.atan2(dx, dy) - sunAz);
|
|
||||||
atm.radiance(vz, cosFromSun, rgb);
|
atm.radiance(vz, cosFromSun, rgb);
|
||||||
|
addNightRadiance(night, vz, az, rgb);
|
||||||
let r = rgb[0];
|
let r = rgb[0];
|
||||||
let g = rgb[1];
|
let g = rgb[1];
|
||||||
let b = rgb[2];
|
let b = rgb[2];
|
||||||
let lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
|
let lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
|
||||||
if (cover > 0) {
|
if (cover > 0) {
|
||||||
const c = cloudAmount(dx / n, dy / n, vz, cover);
|
const c = cloudAmount(ground * Math.sin(az), ground * Math.cos(az), vz, cover);
|
||||||
lum += (0.2126 * cloud[0] + 0.7152 * cloud[1] + 0.0722 * cloud[2] - lum) * c;
|
lum += (0.2126 * cloud[0] + 0.7152 * cloud[1] + 0.0722 * cloud[2] - lum) * c;
|
||||||
r += (cloud[0] - r) * c;
|
r += (cloud[0] - r) * c;
|
||||||
g += (cloud[1] - g) * c;
|
g += (cloud[1] - g) * c;
|
||||||
|
|
@ -103,20 +95,11 @@ export function renderDome(
|
||||||
return { w, h, hdr, meanLuma: Math.exp(logSum / (w * h)) };
|
return { w, h, hdr, meanLuma: Math.exp(logSum / (w * h)) };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Where the sun is on the image, as fractions of its width and height (y down), or null when it is behind the camera or below the horizon. */
|
/** Where the sun is on the image (the camera's angle-linear mapping, `view.ts`), as fractions of its width and height (y down), or null when it is behind the camera or below the horizon. */
|
||||||
export function sunOnScreen(sun: SunSample, view: DomeView): { x: number; y: number } | null {
|
export function sunOnScreen(sun: SunSample, camera: Camera): { x: number; y: number } | null {
|
||||||
if (sun.elevation < -0.3) return null;
|
if (sun.elevation < -0.3) return null;
|
||||||
const tanHalf = Math.tan((VFOV_DEG * RAD) / 2);
|
const dAz = ((sun.azimuth - camera.azimuthDeg + 540) % 360) - 180;
|
||||||
const fa = view.azimuthDeg * RAD;
|
const x = 0.5 + dAz / camera.hfovDeg;
|
||||||
const az = sun.azimuth * RAD;
|
const y = camera.horizonAt - sun.elevation / camera.vfovDeg;
|
||||||
const el = sun.elevation * RAD;
|
|
||||||
const sx = Math.cos(el) * Math.sin(az);
|
|
||||||
const sy = Math.cos(el) * Math.cos(az);
|
|
||||||
const along = sx * Math.sin(fa) + sy * Math.cos(fa);
|
|
||||||
if (along <= 0.05) return null;
|
|
||||||
const u = (sx * Math.cos(fa) - sy * Math.sin(fa)) / along;
|
|
||||||
const v = Math.sin(el) / along;
|
|
||||||
const x = u / (view.aspect * 2 * tanHalf) + 0.5;
|
|
||||||
const y = HORIZON_AT - v / (2 * tanHalf);
|
|
||||||
return x < -0.05 || x > 1.05 || y < -0.05 || y > 1.05 ? null : { x, y };
|
return x < -0.05 || x > 1.05 || y < -0.05 || y > 1.05 ? null : { x, y };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
117
src/app/features/scene/ridge/starCatalogue.test.ts
Normal file
117
src/app/features/scene/ridge/starCatalogue.test.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
120
src/app/features/scene/ridge/starCatalogue.ts
Normal file
120
src/app/features/scene/ridge/starCatalogue.ts
Normal 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;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -1,88 +1,23 @@
|
||||||
/* eslint-disable no-restricted-syntax, no-continue -- test loops over sample times */
|
/* eslint-disable no-restricted-syntax, no-continue -- test loops over sample times */
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { skyColours } from './skyColour';
|
|
||||||
import {
|
import {
|
||||||
MAX_STARS,
|
|
||||||
NIGHT_LUMA,
|
|
||||||
SLOTS,
|
SLOTS,
|
||||||
TWINKLE_GAIN,
|
TWINKLE_GAIN,
|
||||||
TWINKLE_PERIOD,
|
TWINKLE_PERIOD,
|
||||||
activeAt,
|
activeAt,
|
||||||
makeStars,
|
|
||||||
skyLuma,
|
|
||||||
slotCount,
|
slotCount,
|
||||||
slotOffset,
|
slotOffset,
|
||||||
slotPeriod,
|
slotPeriod,
|
||||||
starCount,
|
|
||||||
twinkleGain,
|
twinkleGain,
|
||||||
} from './stars';
|
} from './stars';
|
||||||
|
|
||||||
const DAY = {
|
/** A field the size of a night's visible stars. */
|
||||||
...skyColours(),
|
const N = 1200;
|
||||||
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;
|
|
||||||
|
|
||||||
function hash2(a: number, b: number) {
|
function hash2(a: number, b: number) {
|
||||||
return ((a * 7919 + b * 104729) % 1000) / 1000;
|
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', () => {
|
describe('twinkle schedule', () => {
|
||||||
const times = Array.from({ length: 400 }, (_, i) => i * 0.37);
|
const times = Array.from({ length: 400 }, (_, i) => i * 0.37);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,22 +1,11 @@
|
||||||
// The Midnight starfield: placed once from a seeded PRNG and baked once into the sky canvas. A
|
// The twinkle of the real stars (`nightBodies.ts` places them from the catalogue for the place and moment). A rolling window of them twinkles
|
||||||
// rolling window of them twinkles on an overlay canvas: SLOTS slots, each running back-to-back
|
// 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
|
||||||
// twinkles of one star at a time, so the active set is always SLOTS stars and every star gets its turn.
|
// 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
|
||||||
// The schedule is a pure function of (seed, time): no state accumulates and no Math.random runs
|
// straight to the active set and its gains. A gain multiplies the star's radiance before the display (scintillation is flux), so a star
|
||||||
// after the field is built, so any instant maps straight to the active set and its brightnesses.
|
// the twilight hides stays hidden whatever it does.
|
||||||
|
|
||||||
/* eslint-disable no-bitwise -- the seeded PRNG and hash are 32-bit integer arithmetic */
|
/* eslint-disable no-bitwise -- the seeded hash is 32-bit integer arithmetic */
|
||||||
import type { SkyColours, Srgb } from './skyColour';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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). */
|
/** Twinkling stars at any instant (fewer only if the field has fewer stars). */
|
||||||
export const SLOTS = 32;
|
export const SLOTS = 32;
|
||||||
export const TWINKLE_PERIOD = { min: 2, max: 7 } as const;
|
export const TWINKLE_PERIOD = { min: 2, max: 7 } as const;
|
||||||
|
|
@ -30,43 +19,12 @@ export interface Star {
|
||||||
y: number;
|
y: number;
|
||||||
/** Radius in CSS px. */
|
/** Radius in CSS px. */
|
||||||
r: number;
|
r: number;
|
||||||
/** Base alpha 0..0.9 (brightness times how dark the sky is there). */
|
/** 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. */
|
||||||
alpha: number;
|
|
||||||
/** CSS colour, white tinted blue or warm. */
|
|
||||||
fill: string;
|
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;
|
cover: string;
|
||||||
}
|
/** The star's centre colour with its radiance multiplied by `gain` (scintillation). */
|
||||||
|
shade: (gain: number) => 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;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stateless seeded hash of up to three integers to [0, 1). */
|
/** 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;
|
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 ---------------------------------------------------------------------------
|
// ---- The schedule ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const slotCount = (stars: number): number => Math.min(SLOTS, stars);
|
export const slotCount = (stars: number): number => Math.min(SLOTS, stars);
|
||||||
|
|
@ -199,28 +114,9 @@ export function activeAt(stars: number, t: number): Twinkling[] {
|
||||||
|
|
||||||
// ---- Drawing --------------------------------------------------------------------------------
|
// ---- 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
|
* 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
|
||||||
* star. Dimming covers it with the sky's own colour at (1 - gain), which leaves exactly
|
* at the gain. A star at base draws nothing.
|
||||||
* alpha * gain of the star; brightening adds a second star on top. A star at base draws nothing.
|
|
||||||
*/
|
*/
|
||||||
export function drawTwinkle(
|
export function drawTwinkle(
|
||||||
ctx: CanvasRenderingContext2D,
|
ctx: CanvasRenderingContext2D,
|
||||||
|
|
@ -234,16 +130,13 @@ export function drawTwinkle(
|
||||||
active.forEach((a) => {
|
active.forEach((a) => {
|
||||||
const s = stars[a.star];
|
const s = stars[a.star];
|
||||||
if (!s || Math.abs(a.gain - 1) < 0.01) return;
|
if (!s || Math.abs(a.gain - 1) < 0.01) return;
|
||||||
if (a.gain < 1) {
|
ctx.fillStyle = s.cover;
|
||||||
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.beginPath();
|
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.fill();
|
||||||
});
|
});
|
||||||
ctx.globalAlpha = 1;
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
74
src/app/features/scene/ridge/sunAt.test.ts
Normal file
74
src/app/features/scene/ridge/sunAt.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { solarNoon, STATE_ELEVATION, sunAt, sunForState } from './sunAt';
|
||||||
|
import { FALLBACK_VIEW } from './view';
|
||||||
|
|
||||||
|
const P = FALLBACK_VIEW.place;
|
||||||
|
|
||||||
|
const at = (iso: string) => new Date(iso);
|
||||||
|
|
||||||
|
describe('the sun over Vienna', () => {
|
||||||
|
it('the Vienna place reproduces the sun the old Vienna constant gave, exactly, at three dates', () => {
|
||||||
|
// Values taken from the old constant's sunPosition before it was replaced.
|
||||||
|
const pinned: [string, number, number][] = [
|
||||||
|
['2026-03-20T06:30:00Z', 14.339283830037077, 106.82531633377323],
|
||||||
|
['2026-06-21T10:40:00Z', 65.0288142821217, 171.0604046707017],
|
||||||
|
['2026-12-21T15:20:00Z', -3.19313392852625, 237.64629073006313],
|
||||||
|
];
|
||||||
|
for (const [iso, el, az] of pinned) {
|
||||||
|
const s = sunAt(P, at(iso));
|
||||||
|
expect(s.elevation).toBe(el);
|
||||||
|
expect(s.azimuth).toBe(az);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => {
|
||||||
|
const june = sunAt(P, solarNoon(P, at('2026-06-21T12:00:00Z')));
|
||||||
|
expect(june.elevation).toBeCloseTo(90 - P.lat + 23.44, 0);
|
||||||
|
const december = sunAt(P, solarNoon(P, at('2026-12-21T12:00:00Z')));
|
||||||
|
expect(december.elevation).toBeCloseTo(90 - P.lat - 23.44, 0);
|
||||||
|
const march = sunAt(P, solarNoon(P, at('2026-03-20T12:00:00Z')));
|
||||||
|
expect(march.elevation).toBeCloseTo(90 - P.lat, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is due south at solar noon, east in the morning and west in the afternoon', () => {
|
||||||
|
const noon = solarNoon(P, at('2026-09-23T12:00:00Z'));
|
||||||
|
expect(Math.abs(sunAt(P, noon).azimuth - 180)).toBeLessThan(2); // solarNoon is found to 5 minutes, which is 1.25 degrees of azimuth
|
||||||
|
expect(sunAt(P, new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150);
|
||||||
|
expect(sunAt(P, new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('solar noon at 16.35 E falls near 10:40 UTC in mid November', () => {
|
||||||
|
// 16.3534 E is 65.4 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC.
|
||||||
|
const n = solarNoon(P, at('2026-11-11T12:00:00Z'));
|
||||||
|
const minutes = n.getUTCHours() * 60 + n.getUTCMinutes();
|
||||||
|
expect(minutes).toBeGreaterThan(10 * 60 + 30);
|
||||||
|
expect(minutes).toBeLessThan(10 * 60 + 50);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has a short day in December and a long one in June: published 8 h 4 min and 16 h 0 min with refraction, which adds about 6 minutes each end the ephemeris leaves out', () => {
|
||||||
|
const daylight = (day: string) => {
|
||||||
|
let n = 0;
|
||||||
|
for (let m = 0; m < 24 * 60; m += 1)
|
||||||
|
if (sunAt(P, new Date(Date.parse(day) + m * 60_000)).elevation > 0) n += 1;
|
||||||
|
return n;
|
||||||
|
};
|
||||||
|
expect(Math.abs(daylight('2026-12-21T00:00:00Z') - (8 * 60 + 4))).toBeLessThan(15);
|
||||||
|
expect(Math.abs(daylight('2026-06-21T00:00:00Z') - (16 * 60 + 0))).toBeLessThan(15);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sunForState: the real sun when it is in the state, else a moment of today that is', () => {
|
||||||
|
const noon = solarNoon(P, at('2026-11-11T12:00:00Z'));
|
||||||
|
expect(sunForState(P, 'day', noon).time).toEqual(noon);
|
||||||
|
const midnight = new Date(noon.getTime() + 12 * 3600_000);
|
||||||
|
for (const state of ['day', 'dusk', 'night'] as const) {
|
||||||
|
for (const now of [noon, midnight, at('2026-11-11T15:30:00Z')]) {
|
||||||
|
const s = sunForState(P, state, now);
|
||||||
|
const [lo, hi] = STATE_ELEVATION[state];
|
||||||
|
expect(s.elevation).toBeGreaterThanOrEqual(lo - 0.01);
|
||||||
|
expect(s.elevation).toBeLessThanOrEqual(hi + 0.01);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(sunForState(P, 'dusk', noon).elevation).toBeCloseTo(0, 1);
|
||||||
|
expect(sunForState(P, 'dusk', noon).azimuth).toBeGreaterThan(180); // sets in the west half
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,11 +1,10 @@
|
||||||
// The sun over the server's viewpoint in Vienna (48.1929826 N, 16.3534237 E, 183 m: Meta's location, the Copernicus DSM height there) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the
|
// The sun over a Place (`view.ts`) at a real moment: one ephemeris, `sunPosition` of src/sky/sun.js (the
|
||||||
// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction), and the choice of a moment for each
|
// low-precision NOAA/Meeus series, a hundredth of a degree for 1900..2100; no refraction), and the choice of a moment for each
|
||||||
// fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
|
// fixed sky state. The ridge sky is the physical atmosphere (`earthAtmosphere.ts`) lit from this sun.
|
||||||
import { sunPosition } from '../../../../sky/sun.js';
|
import { sunPosition } from '../../../../sky/sun.js';
|
||||||
import { DAY_FROM } from '../skyState';
|
import { DAY_FROM } from '../skyState';
|
||||||
import type { FixedSkyState } from '../skyBand';
|
import type { FixedSkyState } from '../skyState';
|
||||||
|
import type { Place } from './view';
|
||||||
export const VIENNA = { lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183 } as const;
|
|
||||||
|
|
||||||
export interface SunSample {
|
export interface SunSample {
|
||||||
/** Degrees above the horizon, no refraction. */
|
/** Degrees above the horizon, no refraction. */
|
||||||
|
|
@ -16,8 +15,8 @@ export interface SunSample {
|
||||||
time: Date;
|
time: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function viennaSun(time: Date): SunSample {
|
export function sunAt(place: Place, time: Date): SunSample {
|
||||||
const { elevation, azimuth } = sunPosition(time, VIENNA.lat, VIENNA.lon) as {
|
const { elevation, azimuth } = sunPosition(time, place.lat, place.lon) as {
|
||||||
elevation: number;
|
elevation: number;
|
||||||
azimuth: number;
|
azimuth: number;
|
||||||
};
|
};
|
||||||
|
|
@ -36,13 +35,13 @@ export const STATE_ELEVATION: Record<FixedSkyState, readonly [number, number]> =
|
||||||
const startOfUtcDay = (t: Date): number =>
|
const startOfUtcDay = (t: Date): number =>
|
||||||
Math.floor(t.getTime() / (24 * 60 * MIN)) * 24 * 60 * MIN;
|
Math.floor(t.getTime() / (24 * 60 * MIN)) * 24 * 60 * MIN;
|
||||||
|
|
||||||
/** The moment of the day (UTC day of `t`, every 5 minutes) the sun is highest over Vienna: solar noon to the step. */
|
/** The moment of the day (UTC day of `t`, every 5 minutes) the sun is highest over the place: solar noon to the step. */
|
||||||
export function solarNoon(t: Date): Date {
|
export function solarNoon(place: Place, t: Date): Date {
|
||||||
const d0 = startOfUtcDay(t);
|
const d0 = startOfUtcDay(t);
|
||||||
let best = d0;
|
let best = d0;
|
||||||
let bestEl = -90;
|
let bestEl = -90;
|
||||||
for (let m = 0; m < 24 * 60; m += 5) {
|
for (let m = 0; m < 24 * 60; m += 5) {
|
||||||
const el = viennaSun(new Date(d0 + m * MIN)).elevation;
|
const el = sunAt(place, new Date(d0 + m * MIN)).elevation;
|
||||||
if (el > bestEl) {
|
if (el > bestEl) {
|
||||||
bestEl = el;
|
bestEl = el;
|
||||||
best = d0 + m * MIN;
|
best = d0 + m * MIN;
|
||||||
|
|
@ -52,24 +51,24 @@ export function solarNoon(t: Date): Date {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The sun a state draws. The real sun over Vienna now when it is in the state's range (so 'auto' is the real sky); otherwise the
|
* The sun a state draws. The real sun over the place now when it is in the state's range (so 'auto' is the real sky); otherwise the
|
||||||
* sun of today at a moment that is: noon for Day, the evening sunset for Dusk, the opposite of noon for Night. A picker that
|
* sun of today at a moment that is: noon for Day, the evening sunset for Dusk, the opposite of noon for Night. A picker that
|
||||||
* forces Day at night shows a noon sky, as a person looking at a noon photograph would.
|
* forces Day at night shows a noon sky, as a person looking at a noon photograph would.
|
||||||
*/
|
*/
|
||||||
export function sunForState(state: FixedSkyState, now: Date): SunSample {
|
export function sunForState(place: Place, state: FixedSkyState, now: Date): SunSample {
|
||||||
const real = viennaSun(now);
|
const real = sunAt(place, now);
|
||||||
const [lo, hi] = STATE_ELEVATION[state];
|
const [lo, hi] = STATE_ELEVATION[state];
|
||||||
if (real.elevation >= lo && real.elevation <= hi) return real;
|
if (real.elevation >= lo && real.elevation <= hi) return real;
|
||||||
const noon = solarNoon(now);
|
const noon = solarNoon(place, now);
|
||||||
if (state === 'day') return viennaSun(noon);
|
if (state === 'day') return sunAt(place, noon);
|
||||||
if (state === 'night') return viennaSun(new Date(noon.getTime() + 12 * 60 * MIN));
|
if (state === 'night') return sunAt(place, new Date(noon.getTime() + 12 * 60 * MIN));
|
||||||
// Dusk: bisect the evening crossing of the horizon between noon and the opposite moment.
|
// Dusk: bisect the evening crossing of the horizon between noon and the opposite moment.
|
||||||
let a = noon.getTime();
|
let a = noon.getTime();
|
||||||
let b = noon.getTime() + 12 * 60 * MIN;
|
let b = noon.getTime() + 12 * 60 * MIN;
|
||||||
for (let i = 0; i < 30; i += 1) {
|
for (let i = 0; i < 30; i += 1) {
|
||||||
const m = (a + b) / 2;
|
const m = (a + b) / 2;
|
||||||
if (viennaSun(new Date(m)).elevation > 0) a = m;
|
if (sunAt(place, new Date(m)).elevation > 0) a = m;
|
||||||
else b = m;
|
else b = m;
|
||||||
}
|
}
|
||||||
return viennaSun(new Date((a + b) / 2));
|
return sunAt(place, new Date((a + b) / 2));
|
||||||
}
|
}
|
||||||
116
src/app/features/scene/ridge/toneMap.test.ts
Normal file
116
src/app/features/scene/ridge/toneMap.test.ts
Normal 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));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -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
|
// 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).
|
// 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
|
// Exposure adapts to the sky's own luminance in every state (the sky is physical radiance, so brightness is the camera's); night
|
||||||
// shaping of the result. Day and dusk expose to the sky's own luminance (adaptation, as an eye or auto-exposure does) so the
|
// adapts only in part (`Budget.partial`), so a new-moon night reads darker than a full-moon one. Before exposure a scotopic grade
|
||||||
// darkest of the sky stays where the state's dark ink needs a backdrop; night is fixed, the physical dark.
|
// (`scotopic`: desaturation and a blue shift as the adapted luminance falls through the mesopic range) carries the night read. After
|
||||||
import type { FixedSkyState } from '../skyBand';
|
// 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];
|
type Rgb = readonly [number, number, number];
|
||||||
|
|
||||||
const IN: readonly Rgb[] = [
|
export const ACES_IN: readonly Rgb[] = [
|
||||||
[0.59719, 0.35458, 0.04823],
|
[0.59719, 0.35458, 0.04823],
|
||||||
[0.076, 0.90834, 0.01566],
|
[0.076, 0.90834, 0.01566],
|
||||||
[0.0284, 0.13383, 0.83777],
|
[0.0284, 0.13383, 0.83777],
|
||||||
];
|
];
|
||||||
const OUT: readonly Rgb[] = [
|
export const ACES_OUT: readonly Rgb[] = [
|
||||||
[1.60475, -0.53108, -0.07367],
|
[1.60475, -0.53108, -0.07367],
|
||||||
[-0.10208, 1.10813, -0.00605],
|
[-0.10208, 1.10813, -0.00605],
|
||||||
[-0.00327, -0.07276, 1.07602],
|
[-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 =>
|
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 encode = (l: number): number => {
|
||||||
const c = Math.min(1, Math.max(0, l));
|
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);
|
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 x = r * exposure;
|
||||||
const y = g * exposure;
|
const y = g * exposure;
|
||||||
const z = b * 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)
|
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. */
|
/** The 8-bit sRGB of linear radiance, exposed and tone-mapped. */
|
||||||
|
|
@ -49,43 +98,127 @@ export function toneMap8(r: number, g: number, b: number, exposure: number, out:
|
||||||
export const displayLuma = (c: ArrayLike<number>): number =>
|
export const displayLuma = (c: ArrayLike<number>): number =>
|
||||||
0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
|
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 (skyBand.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 {
|
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;
|
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;
|
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;
|
key?: number;
|
||||||
/** Exposure range, in multiples of scene radiance (per unit sun irradiance). */
|
/** Exposure range, in multiples of scene radiance (per unit sun irradiance). */
|
||||||
min: number;
|
min: number;
|
||||||
max: 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. */
|
/** 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 MARGIN = 0.004;
|
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
|
* The scotopic grade (Thompson, Shirley & Ferwerda 2002; Kirk & O'Brien 2011; Jensen et al. 2001): `strength` scales it (EYEBALLED, 0 off),
|
||||||
* dimmer foldout headers (L 0.386 on screen, rat-crest-a7c95ce-20261111) need a backdrop of at most 0.047.
|
* 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> = {
|
export const SCOTOPIC = {
|
||||||
day: { floor: 0.4744 + MARGIN, ceiling: 1, key: 0.45, min: 4, max: 60 },
|
strength: 1,
|
||||||
dusk: { floor: 0.4744 + MARGIN, ceiling: 1, key: 0.5, min: 4, max: 400 },
|
mesopic: [-2, 0.5] as const,
|
||||||
night: { floor: 0, ceiling: 0.047 - MARGIN, key: 0.03, min: 8, max: 3000 },
|
tint: [1.05, 0.97, 1.27] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The display transform of a sky: exposure, then ACES, then a black lift (veiling glare) in display-linear. */
|
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 },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 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 {
|
export interface Display {
|
||||||
exposure: number;
|
exposure: number;
|
||||||
/** Added to every channel after the curve, then rescaled so white stays white: out = lift + (1 - lift) * aces. */
|
curve: Curve;
|
||||||
lift: number;
|
/** 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. */
|
/** The 8-bit sRGB of linear radiance through a display. */
|
||||||
export function display8(r: number, g: number, b: number, d: Display, out: number[]): void {
|
export function display8(r: number, g: number, b: number, d: Display, out: number[]): void {
|
||||||
acesLinear(r, g, b, d.exposure, out);
|
if (d.grade) {
|
||||||
for (let i = 0; i < 3; i += 1) out[i] = Math.round(encode(d.lift + (1 - d.lift) * out[i]));
|
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 => {
|
const decode = (v: number): number => {
|
||||||
|
|
@ -109,15 +242,16 @@ export interface Fit {
|
||||||
/** Darkest and lightest display luminance of the grid under `display`. */
|
/** Darkest and lightest display luminance of the grid under `display`. */
|
||||||
lo: number;
|
lo: number;
|
||||||
hi: 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;
|
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
|
* 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
|
||||||
* `meanLuma` its log-mean luminance. Exposure starts at the state's key (adaptation); a ceiling lowers it until the
|
* 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
|
||||||
* lightest texel is inside the budget (bisection: luminance is monotone in exposure); a floor raises the black lift until 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),
|
||||||
* darkest is (luminance is monotone in lift, and linear: the lift needed is solved in one step).
|
* 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 {
|
export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: number): Fit {
|
||||||
const b = BUDGET[state];
|
const b = BUDGET[state];
|
||||||
|
|
@ -126,83 +260,47 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu
|
||||||
? b.min
|
? b.min
|
||||||
: Math.min(b.max, Math.max(b.min, (b.key * 1.6) / Math.max(meanLuma, 1e-9)));
|
: Math.min(b.max, Math.max(b.min, (b.key * 1.6) / Math.max(meanLuma, 1e-9)));
|
||||||
const n = hdr.length / 3;
|
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 stride = Math.max(1, Math.floor(n / 4000));
|
||||||
const tmp = [0, 0, 0];
|
for (let i = 0; i < n; i += stride) {
|
||||||
const range = (d: Display) => {
|
const l = displayLumaOf(hdr[i * 3], hdr[i * 3 + 1], hdr[i * 3 + 2], display, tmp);
|
||||||
let lo = 2;
|
if (l < lo) lo = l;
|
||||||
let hi = -1;
|
if (l > hi) hi = l;
|
||||||
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 });
|
|
||||||
}
|
}
|
||||||
let lift = 0;
|
return { display, lo, hi, keyExposure };
|
||||||
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 += (b.floor - probe.lo) * 1.05;
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { solarNoon, STATE_ELEVATION, sunForState, VIENNA, viennaSun } from './vienna';
|
|
||||||
|
|
||||||
const at = (iso: string) => new Date(iso);
|
|
||||||
|
|
||||||
describe('the sun over Vienna', () => {
|
|
||||||
it('stands at 90 - lat + declination at solar noon: the solstices and equinox', () => {
|
|
||||||
const june = viennaSun(solarNoon(at('2026-06-21T12:00:00Z')));
|
|
||||||
expect(june.elevation).toBeCloseTo(90 - VIENNA.lat + 23.44, 0);
|
|
||||||
const december = viennaSun(solarNoon(at('2026-12-21T12:00:00Z')));
|
|
||||||
expect(december.elevation).toBeCloseTo(90 - VIENNA.lat - 23.44, 0);
|
|
||||||
const march = viennaSun(solarNoon(at('2026-03-20T12:00:00Z')));
|
|
||||||
expect(march.elevation).toBeCloseTo(90 - VIENNA.lat, 0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is due south at solar noon, east in the morning and west in the afternoon', () => {
|
|
||||||
const noon = solarNoon(at('2026-09-23T12:00:00Z'));
|
|
||||||
expect(Math.abs(viennaSun(noon).azimuth - 180)).toBeLessThan(2); // solarNoon is found to 5 minutes, which is 1.25 degrees of azimuth
|
|
||||||
expect(viennaSun(new Date(noon.getTime() - 3 * 3600_000)).azimuth).toBeLessThan(150);
|
|
||||||
expect(viennaSun(new Date(noon.getTime() + 3 * 3600_000)).azimuth).toBeGreaterThan(210);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('solar noon at 16.35 E falls near 10:40 UTC in mid November', () => {
|
|
||||||
// 16.3534 E is 65.4 minutes ahead of Greenwich; the equation of time in mid November is +15 minutes (sun early): 12:00 - 65.5 - 15 = 10:40 UTC.
|
|
||||||
const n = solarNoon(at('2026-11-11T12:00:00Z'));
|
|
||||||
const minutes = n.getUTCHours() * 60 + n.getUTCMinutes();
|
|
||||||
expect(minutes).toBeGreaterThan(10 * 60 + 30);
|
|
||||||
expect(minutes).toBeLessThan(10 * 60 + 50);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('has a short day in December and a long one in June: published 8 h 4 min and 16 h 0 min with refraction, which adds about 6 minutes each end the ephemeris leaves out', () => {
|
|
||||||
const daylight = (day: string) => {
|
|
||||||
let n = 0;
|
|
||||||
for (let m = 0; m < 24 * 60; m += 1)
|
|
||||||
if (viennaSun(new Date(Date.parse(day) + m * 60_000)).elevation > 0) n += 1;
|
|
||||||
return n;
|
|
||||||
};
|
|
||||||
expect(Math.abs(daylight('2026-12-21T00:00:00Z') - (8 * 60 + 4))).toBeLessThan(15);
|
|
||||||
expect(Math.abs(daylight('2026-06-21T00:00:00Z') - (16 * 60 + 0))).toBeLessThan(15);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('sunForState: the real sun when it is in the state, else a moment of today that is', () => {
|
|
||||||
const noon = solarNoon(at('2026-11-11T12:00:00Z'));
|
|
||||||
expect(sunForState('day', noon).time).toEqual(noon);
|
|
||||||
const midnight = new Date(noon.getTime() + 12 * 3600_000);
|
|
||||||
for (const state of ['day', 'dusk', 'night'] as const) {
|
|
||||||
for (const now of [noon, midnight, at('2026-11-11T15:30:00Z')]) {
|
|
||||||
const s = sunForState(state, now);
|
|
||||||
const [lo, hi] = STATE_ELEVATION[state];
|
|
||||||
expect(s.elevation).toBeGreaterThanOrEqual(lo - 0.01);
|
|
||||||
expect(s.elevation).toBeLessThanOrEqual(hi + 0.01);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
expect(sunForState('dusk', noon).elevation).toBeCloseTo(0, 1);
|
|
||||||
expect(sunForState('dusk', noon).azimuth).toBeGreaterThan(180); // sets in the west half
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,306 +0,0 @@
|
||||||
{
|
|
||||||
"viewpoint": { "lat": 48.1929826, "lon": 16.3534237, "groundM": 183.3 },
|
|
||||||
"stepDeg": 0.5,
|
|
||||||
"radiusKm": 60.0,
|
|
||||||
"minKm": 1.0,
|
|
||||||
"curvature": "drop d^2/2R*(1-0.13), R=6371000 m",
|
|
||||||
"source": {
|
|
||||||
"dataset": "Copernicus DEM GLO-30 (COP-DEM_GLO-30-DGED), a DSM, EGM2008 heights, 1 arc-second grid",
|
|
||||||
"tiles": [
|
|
||||||
"N47_00_E015_00",
|
|
||||||
"N47_00_E016_00",
|
|
||||||
"N47_00_E017_00",
|
|
||||||
"N48_00_E015_00",
|
|
||||||
"N48_00_E016_00",
|
|
||||||
"N48_00_E017_00",
|
|
||||||
"N49_00_E015_00",
|
|
||||||
"N49_00_E016_00",
|
|
||||||
"N49_00_E017_00"
|
|
||||||
],
|
|
||||||
"tileBytesEach": "about 42-44 MB (Cloud Optimized GeoTIFF); nine tiles, about 380 MB, read once, not committed",
|
|
||||||
"url": "https://copernicus-dem-30m.s3.amazonaws.com/ (AWS Open Data, eu-central-1, no account)",
|
|
||||||
"licence": "Copernicus DEM licence: free of charge for any use incl. commercial, attribution required, no warranty (https://spacedata.copernicus.eu/collections/copernicus-digital-elevation-model, Licencing)",
|
|
||||||
"attribution": "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.",
|
|
||||||
"bakedBy": "scripts/bake-horizon.py"
|
|
||||||
},
|
|
||||||
"elevationDeg": [
|
|
||||||
1.608, 1.522, 1.467, 1.452, 1.433, 1.426, 1.497, 1.6, 1.597, 1.564, 1.532, 1.495, 1.467, 1.544,
|
|
||||||
1.62, 1.655, 1.707, 1.775, 1.803, 1.683, 1.532, 1.394, 1.263, 1.297, 1.358, 1.412, 1.433, 1.339,
|
|
||||||
1.264, 1.269, 1.195, 1.142, 1.13, 1.22, 1.401, 1.368, 1.326, 1.294, 1.378, 1.46, 1.488, 1.516,
|
|
||||||
1.549, 1.598, 1.647, 1.698, 1.769, 1.816, 1.801, 1.783, 1.695, 1.619, 1.586, 1.547, 1.442,
|
|
||||||
1.335, 1.282, 1.286, 1.335, 1.421, 1.449, 1.437, 1.313, 1.268, 1.164, 1.14, 1.098, 1.06, 0.984,
|
|
||||||
0.938, 0.91, 0.877, 0.884, 0.872, 0.943, 0.974, 0.919, 0.873, 0.861, 0.839, 0.731, 0.673, 0.56,
|
|
||||||
0.494, 0.527, 0.601, 0.566, 0.584, 0.579, 0.643, 0.666, 0.741, 0.851, 0.711, 0.703, 0.573, 0.54,
|
|
||||||
0.488, 0.433, 0.452, 0.467, 0.483, 0.475, 0.517, 0.419, 0.428, 0.457, 0.489, 0.522, 0.482, 0.5,
|
|
||||||
0.527, 0.528, 0.471, 0.458, 0.487, 0.521, 0.578, 0.553, 0.419, 0.301, 0.324, 0.425, 0.468,
|
|
||||||
0.512, 0.558, 0.575, 0.521, 0.477, 0.444, 0.372, 0.297, 0.365, 0.446, 0.486, 0.523, 0.532,
|
|
||||||
0.516, 0.516, 0.531, 0.52, 0.546, 0.565, 0.535, 0.527, 0.508, 0.516, 0.37, 0.359, 0.33, 0.375,
|
|
||||||
0.454, 0.546, 0.496, 0.449, 0.425, 0.447, 0.398, 0.388, 0.439, 0.476, 0.496, 0.517, 0.541,
|
|
||||||
0.494, 0.439, 0.383, 0.411, 0.502, 0.621, 0.578, 0.548, 0.568, 0.642, 0.713, 0.708, 0.654,
|
|
||||||
0.704, 0.741, 0.709, 0.677, 0.661, 0.66, 0.666, 0.662, 0.651, 0.699, 0.727, 0.746, 0.809, 0.788,
|
|
||||||
0.799, 0.793, 0.702, 0.734, 0.79, 0.754, 0.704, 0.616, 0.598, 0.708, 0.719, 0.706, 0.704, 0.726,
|
|
||||||
0.826, 0.849, 0.85, 0.813, 0.853, 0.926, 0.971, 0.918, 1.003, 1.0, 0.927, 0.985, 1.031, 1.043,
|
|
||||||
1.067, 1.13, 1.022, 1.02, 1.043, 1.101, 1.144, 1.099, 1.082, 1.064, 1.2, 1.238, 1.16, 1.084,
|
|
||||||
1.202, 1.326, 1.39, 1.429, 1.405, 1.332, 1.358, 1.361, 1.357, 1.354, 1.335, 1.319, 1.376, 1.309,
|
|
||||||
1.289, 1.257, 1.283, 1.237, 1.296, 1.353, 1.259, 1.314, 1.236, 1.307, 1.344, 1.36, 1.251, 1.292,
|
|
||||||
1.308, 1.26, 1.288, 1.365, 1.391, 1.414, 1.32, 1.299, 1.35, 1.288, 1.361, 1.303, 1.268, 1.29,
|
|
||||||
1.305, 1.326, 1.344, 1.328, 1.32, 1.358, 1.375, 1.443, 1.477, 1.492, 1.525, 1.513, 1.422, 1.314,
|
|
||||||
1.294, 1.337, 1.414, 1.343, 1.397, 1.431, 1.409, 1.378, 1.423, 1.438, 1.343, 1.257, 1.208,
|
|
||||||
1.209, 1.233, 1.251, 1.267, 1.274, 1.248, 1.254, 1.297, 1.34, 1.359, 1.34, 1.199, 1.162, 1.255,
|
|
||||||
1.292, 1.29, 1.24, 1.222, 1.24, 1.271, 1.264, 1.317, 1.256, 1.26, 1.321, 1.301, 1.266, 1.268,
|
|
||||||
1.308, 1.357, 1.474, 1.419, 1.438, 1.393, 1.354, 1.343, 1.354, 1.333, 1.321, 1.359, 1.437, 1.47,
|
|
||||||
1.395, 1.413, 1.446, 1.466, 1.434, 1.446, 1.458, 1.419, 1.522, 1.502, 1.506, 1.512, 1.528,
|
|
||||||
1.526, 1.485, 1.427, 1.508, 1.5, 1.48, 1.534, 1.514, 1.449, 1.449, 1.386, 1.368, 1.388, 1.404,
|
|
||||||
1.374, 1.374, 1.352, 1.3, 1.347, 1.332, 1.265, 1.235, 1.39, 1.285, 1.226, 1.233, 1.235, 1.211,
|
|
||||||
1.164, 1.183, 1.217, 1.143, 1.128, 1.117, 1.112, 1.086, 1.071, 1.118, 1.103, 1.002, 0.99, 0.995,
|
|
||||||
1.025, 0.998, 1.024, 0.971, 1.045, 1.09, 1.11, 1.108, 1.081, 1.171, 1.308, 1.446, 1.482, 1.484,
|
|
||||||
1.494, 1.469, 1.472, 1.479, 1.493, 1.467, 1.388, 1.293, 1.203, 1.104, 1.145, 1.12, 1.028, 1.004,
|
|
||||||
0.982, 0.968, 0.933, 0.97, 0.986, 1.035, 1.12, 1.227, 1.281, 1.316, 1.312, 1.273, 1.187, 1.205,
|
|
||||||
1.197, 1.199, 1.176, 1.177, 1.142, 1.19, 1.377, 1.369, 1.322, 1.295, 1.385, 1.493, 1.576, 1.679,
|
|
||||||
1.769, 1.622, 1.711, 1.641, 1.517, 1.582, 1.525, 1.39, 1.389, 1.343, 1.331, 1.369, 1.343, 1.257,
|
|
||||||
1.212, 1.134, 1.039, 1.03, 1.075, 1.027, 1.059, 1.112, 1.132, 1.14, 1.16, 1.167, 1.178, 1.179,
|
|
||||||
1.192, 1.214, 1.245, 1.289, 1.286, 1.279, 1.259, 1.256, 1.202, 1.138, 1.159, 1.116, 1.12, 1.102,
|
|
||||||
0.999, 1.042, 1.051, 1.09, 1.143, 1.244, 1.269, 1.296, 1.353, 1.412, 1.579, 1.686, 1.814, 1.857,
|
|
||||||
1.773, 1.731, 1.748, 1.742, 1.668, 1.594, 1.628, 1.692, 1.76, 1.822, 1.863, 1.904, 1.895, 1.849,
|
|
||||||
1.786, 1.778, 1.731, 1.666, 1.633, 1.561, 1.526, 1.662, 1.747, 1.75, 1.704, 1.631, 1.563, 1.473,
|
|
||||||
1.501, 1.488, 1.464, 1.441, 1.386, 1.31, 1.298, 1.293, 1.306, 1.371, 1.42, 1.416, 1.417, 1.418,
|
|
||||||
1.409, 1.399, 1.408, 1.431, 1.434, 1.437, 1.509, 1.544, 1.58, 1.674, 1.528, 1.534, 1.517, 1.497,
|
|
||||||
1.525, 1.546, 1.562, 1.58, 1.55, 1.634, 1.614, 1.66, 1.643, 1.663, 1.68, 1.829, 1.99, 2.058,
|
|
||||||
2.014, 1.911, 2.025, 2.023, 2.036, 2.031, 2.009, 2.012, 2.02, 2.109, 2.107, 2.12, 2.171, 2.179,
|
|
||||||
2.125, 2.084, 2.09, 2.129, 2.183, 2.16, 2.172, 2.239, 2.237, 2.218, 2.217, 2.137, 2.169, 2.203,
|
|
||||||
2.233, 2.262, 2.272, 2.21, 2.133, 1.955, 1.909, 1.97, 2.138, 2.187, 2.229, 2.278, 2.191, 2.167,
|
|
||||||
2.213, 2.327, 2.409, 2.31, 2.242, 2.205, 2.152, 2.154, 2.258, 2.217, 2.126, 2.054, 1.97, 1.942,
|
|
||||||
2.022, 1.894, 1.886, 1.921, 1.897, 1.936, 1.964, 1.978, 1.961, 1.927, 1.879, 1.904, 1.96, 1.9,
|
|
||||||
1.922, 2.023, 2.061, 2.115, 1.99, 1.805, 1.736, 1.776, 1.841, 1.863, 1.934, 1.942, 1.962, 2.043,
|
|
||||||
2.082, 2.082, 2.092, 2.062, 1.957, 1.794, 1.821, 1.913, 2.009, 2.066, 2.105, 2.036, 1.964,
|
|
||||||
1.984, 2.005, 2.036, 2.072, 2.094, 2.022, 2.153, 2.177, 2.146, 2.125, 2.061, 2.004, 1.955,
|
|
||||||
1.902, 1.84, 1.767, 1.7, 1.696, 1.718, 1.725, 1.709, 1.745, 1.805, 1.836, 1.939, 2.053, 2.14,
|
|
||||||
2.139, 2.142, 2.035, 1.902, 1.779, 1.667, 1.564, 1.57, 1.581, 1.628, 1.693, 1.739, 1.738, 1.738,
|
|
||||||
1.675
|
|
||||||
],
|
|
||||||
"distanceKm": [
|
|
||||||
1.0, 1.0, 1.06, 1.06, 1.06, 1.06, 1.06, 1.03, 1.0, 1.0, 1.0, 1.0, 1.09, 1.09, 1.0, 1.09, 1.09,
|
|
||||||
1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.12, 1.12, 1.12, 1.12, 1.12, 1.12, 1.09, 1.09, 1.09, 1.09,
|
|
||||||
1.0, 1.0, 1.0, 1.0, 1.03, 1.06, 1.06, 1.03, 1.03, 1.03, 1.03, 1.03, 1.03, 1.0, 1.0, 1.0, 1.0,
|
|
||||||
1.0, 1.03, 1.03, 1.03, 1.03, 1.03, 1.0, 1.0, 1.06, 1.06, 1.06, 1.06, 1.06, 1.12, 1.0, 1.0, 1.24,
|
|
||||||
1.24, 1.21, 1.21, 1.3, 1.3, 1.27, 1.3, 1.33, 1.33, 1.33, 1.33, 1.27, 1.24, 1.27, 1.27, 1.27,
|
|
||||||
1.03, 1.03, 1.42, 1.84, 1.84, 1.81, 1.03, 1.72, 1.63, 1.63, 1.63, 1.33, 1.33, 1.06, 1.06, 1.72,
|
|
||||||
1.72, 1.69, 1.69, 1.69, 1.69, 1.69, 1.81, 1.81, 1.75, 1.51, 1.75, 1.75, 1.75, 1.75, 1.75, 1.72,
|
|
||||||
1.72, 1.72, 1.72, 1.72, 1.72, 1.72, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.42,
|
|
||||||
1.42, 1.24, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.3, 1.27, 1.03, 1.36, 1.36, 1.36, 1.36, 1.36, 1.45,
|
|
||||||
1.45, 1.09, 1.12, 1.12, 1.54, 1.57, 1.48, 1.48, 1.48, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
|
|
||||||
1.0, 1.18, 1.18, 1.21, 1.21, 1.21, 1.12, 1.12, 1.12, 1.12, 1.12, 1.15, 1.15, 1.15, 1.15, 1.18,
|
|
||||||
1.15, 1.15, 1.24, 1.24, 1.27, 1.27, 1.24, 1.24, 1.24, 1.27, 1.27, 1.27, 1.9, 1.9, 1.93, 1.93,
|
|
||||||
1.93, 1.99, 1.99, 1.99, 1.99, 1.9, 2.02, 2.02, 2.02, 2.05, 2.02, 1.99, 1.99, 1.99, 1.48, 1.21,
|
|
||||||
1.21, 1.57, 1.69, 1.69, 1.66, 1.39, 1.39, 1.39, 1.54, 1.6, 1.54, 1.54, 1.54, 1.48, 1.45, 1.21,
|
|
||||||
1.21, 1.21, 1.27, 1.39, 1.39, 1.36, 1.39, 1.39, 1.39, 1.33, 1.33, 1.33, 1.33, 1.33, 1.48, 1.45,
|
|
||||||
1.39, 1.39, 1.18, 1.18, 1.18, 1.48, 1.48, 1.27, 1.24, 1.27, 1.36, 1.36, 1.39, 1.33, 1.3, 1.3,
|
|
||||||
1.3, 1.3, 1.3, 1.3, 1.33, 1.0, 1.42, 1.42, 1.27, 1.27, 1.27, 1.27, 1.03, 1.03, 1.03, 1.03, 1.03,
|
|
||||||
1.03, 1.03, 1.03, 1.06, 1.06, 1.03, 1.03, 1.03, 1.36, 1.06, 1.06, 1.06, 1.06, 1.09, 1.09, 1.18,
|
|
||||||
1.21, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.09, 1.15, 1.15, 1.36, 1.36, 1.36,
|
|
||||||
1.36, 1.33, 1.33, 3.13, 1.21, 1.21, 3.34, 3.31, 2.83, 2.65, 2.65, 1.3, 2.29, 1.3, 1.15, 1.15,
|
|
||||||
1.15, 2.29, 2.68, 2.41, 2.23, 2.23, 2.2, 1.12, 2.23, 2.17, 2.17, 2.17, 1.84, 2.74, 1.87, 1.87,
|
|
||||||
2.95, 2.2, 2.17, 2.17, 2.35, 2.35, 2.23, 2.23, 2.11, 2.14, 2.08, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2,
|
|
||||||
2.41, 2.41, 2.38, 2.41, 2.41, 2.44, 2.44, 2.44, 1.99, 2.08, 2.08, 2.08, 2.08, 2.05, 2.05, 2.5,
|
|
||||||
2.38, 2.47, 2.29, 2.23, 2.17, 1.69, 1.69, 2.38, 2.47, 2.38, 2.17, 2.71, 2.71, 2.2, 2.47, 2.41,
|
|
||||||
2.41, 2.32, 2.38, 2.38, 2.08, 2.5, 2.11, 2.11, 1.75, 1.75, 1.48, 1.81, 1.81, 1.78, 1.78, 1.87,
|
|
||||||
17.2, 17.2, 17.26, 17.32, 17.44, 18.1, 17.56, 17.5, 17.38, 17.5, 17.62, 17.68, 17.74, 17.8,
|
|
||||||
14.86, 14.92, 14.98, 2.98, 26.38, 26.38, 26.38, 26.62, 26.14, 26.02, 26.02, 26.38, 26.26, 26.38,
|
|
||||||
26.38, 26.26, 26.26, 26.26, 14.98, 14.98, 14.98, 14.44, 13.12, 13.18, 13.66, 13.72, 13.72,
|
|
||||||
13.84, 13.84, 13.84, 13.72, 12.52, 12.58, 12.58, 12.28, 12.22, 12.28, 16.54, 14.02, 15.04,
|
|
||||||
16.18, 16.24, 17.08, 17.26, 17.44, 17.5, 17.44, 17.32, 17.44, 17.02, 13.96, 14.14, 9.22, 9.16,
|
|
||||||
9.1, 9.22, 9.28, 9.28, 9.22, 9.16, 9.16, 9.34, 8.68, 8.68, 8.62, 8.74, 8.86, 8.92, 8.86, 8.92,
|
|
||||||
8.92, 11.74, 14.08, 11.98, 12.22, 12.04, 34.3, 10.36, 10.06, 9.64, 9.58, 9.58, 9.7, 9.7, 10.18,
|
|
||||||
10.18, 10.18, 10.24, 10.06, 10.48, 9.94, 9.82, 9.76, 9.7, 8.02, 8.14, 8.14, 8.14, 8.08, 8.56,
|
|
||||||
8.38, 8.38, 8.32, 8.38, 8.02, 8.02, 8.02, 8.14, 8.2, 7.9, 7.9, 7.84, 7.78, 7.66, 7.72, 7.72,
|
|
||||||
7.72, 1.0, 1.0, 1.0, 1.0, 1.0, 1.45, 1.21, 1.21, 1.3, 1.15, 1.15, 1.15, 1.15, 1.15, 1.15, 1.15,
|
|
||||||
1.33, 1.33, 1.33, 1.48, 1.3, 1.3, 1.3, 1.42, 1.09, 2.02, 1.81, 2.59, 2.59, 2.53, 1.21, 1.75,
|
|
||||||
1.69, 1.66, 2.38, 1.57, 1.57, 1.57, 7.18, 7.18, 7.24, 7.24, 7.18, 7.12, 1.0, 1.0, 1.0, 1.0, 1.0,
|
|
||||||
7.36, 7.3, 7.3, 7.18, 7.24, 7.06, 7.06, 7.06, 7.06, 7.0, 7.12, 7.12, 7.12, 7.0, 7.0, 7.0, 7.0,
|
|
||||||
7.24, 7.24, 7.06, 7.18, 7.0, 7.06, 7.0, 7.0, 6.94, 7.0, 7.24, 1.03, 1.03, 1.03, 1.0, 1.0, 1.0,
|
|
||||||
1.06, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.03, 1.03, 1.03, 1.03, 1.03, 1.03, 1.27, 1.27, 1.27,
|
|
||||||
1.24, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.09, 1.09, 1.06, 1.06, 1.06, 1.06, 1.06,
|
|
||||||
1.09, 1.09, 9.64, 9.58, 9.64, 9.64, 9.7, 9.7, 9.7, 9.7, 9.7, 9.64, 9.64, 9.64, 9.7, 1.03, 1.03,
|
|
||||||
1.03, 1.03, 1.03, 1.03, 9.52, 1.0, 1.0, 9.4, 8.68, 8.68, 8.68, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
|
|
||||||
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 9.52, 9.46, 9.46, 9.46, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
|
|
||||||
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
|
|
||||||
],
|
|
||||||
"peakHeightM": [
|
|
||||||
211.4, 209.9, 210.5, 210.2, 209.9, 209.7, 211.0, 212.1, 211.2, 210.6, 210.1, 209.4, 211.3,
|
|
||||||
212.7, 211.6, 214.8, 215.8, 217.1, 217.7, 215.4, 212.5, 209.9, 207.4, 208.7, 209.9, 211.0,
|
|
||||||
211.4, 209.5, 208.1, 207.5, 206.1, 205.1, 204.8, 204.6, 207.8, 207.2, 206.5, 206.6, 208.8,
|
|
||||||
210.4, 210.1, 210.6, 211.2, 212.1, 213.0, 213.9, 214.2, 215.0, 214.8, 214.5, 212.9, 212.5,
|
|
||||||
211.9, 211.2, 209.3, 207.3, 205.7, 205.8, 208.1, 209.6, 210.2, 209.9, 207.6, 208.2, 203.7,
|
|
||||||
203.2, 207.2, 206.3, 204.2, 203.2, 204.0, 203.3, 203.0, 203.2, 205.3, 206.0, 204.7, 203.7,
|
|
||||||
202.5, 201.5, 199.6, 198.3, 195.8, 192.2, 192.8, 198.3, 201.7, 202.3, 201.8, 194.9, 203.5,
|
|
||||||
204.5, 207.7, 203.7, 199.7, 196.7, 193.3, 192.4, 196.5, 197.1, 197.2, 197.7, 197.5, 198.7,
|
|
||||||
195.8, 197.0, 197.9, 198.4, 197.2, 198.2, 198.7, 199.6, 199.6, 197.9, 197.2, 198.1, 199.1,
|
|
||||||
200.8, 200.1, 196.0, 192.5, 189.0, 190.8, 191.5, 192.3, 193.1, 193.4, 192.4, 191.7, 191.1,
|
|
||||||
189.8, 190.8, 192.5, 193.0, 194.4, 195.2, 195.5, 195.1, 195.1, 195.4, 195.2, 195.5, 193.5,
|
|
||||||
196.1, 195.9, 195.5, 195.6, 192.2, 192.5, 191.8, 190.5, 192.2, 194.0, 196.8, 195.7, 194.4,
|
|
||||||
195.0, 193.7, 190.1, 191.0, 191.7, 192.0, 192.4, 192.8, 192.0, 191.0, 190.0, 191.8, 193.7,
|
|
||||||
196.5, 195.6, 194.9, 194.5, 195.9, 197.3, 197.2, 196.1, 197.5, 198.2, 197.6, 196.9, 197.0,
|
|
||||||
196.6, 196.7, 197.7, 197.5, 198.9, 199.5, 199.5, 200.9, 200.4, 201.1, 201.0, 198.9, 207.9,
|
|
||||||
209.7, 208.9, 207.2, 204.3, 204.3, 208.1, 208.5, 208.1, 206.9, 209.1, 212.7, 213.5, 214.0,
|
|
||||||
212.2, 213.2, 215.7, 217.3, 207.1, 204.6, 204.5, 208.8, 212.5, 213.9, 213.7, 209.3, 210.8,
|
|
||||||
208.2, 210.9, 212.6, 213.0, 214.2, 213.0, 211.4, 210.3, 208.7, 209.5, 207.9, 207.4, 212.6,
|
|
||||||
215.6, 216.4, 218.1, 217.5, 215.7, 214.9, 215.0, 214.9, 214.8, 214.4, 217.5, 218.3, 215.2,
|
|
||||||
214.7, 209.3, 209.8, 208.9, 216.9, 218.4, 211.3, 211.8, 210.8, 214.4, 215.3, 216.4, 212.4,
|
|
||||||
212.7, 213.1, 212.0, 212.6, 214.4, 215.0, 216.2, 206.4, 215.6, 216.9, 211.9, 213.6, 212.3,
|
|
||||||
211.5, 206.5, 206.8, 207.2, 207.5, 207.2, 207.1, 207.8, 208.1, 210.0, 210.7, 210.2, 210.8,
|
|
||||||
210.5, 217.2, 207.7, 207.3, 208.1, 209.5, 208.9, 209.9, 212.8, 213.1, 209.6, 210.4, 210.7,
|
|
||||||
208.9, 207.3, 206.3, 206.4, 206.8, 207.2, 207.5, 208.9, 208.4, 213.2, 214.2, 215.2, 215.7,
|
|
||||||
214.5, 211.2, 247.4, 209.9, 210.7, 259.2, 255.7, 244.2, 241.1, 242.6, 212.1, 236.3, 211.9,
|
|
||||||
208.7, 209.9, 209.5, 234.2, 243.1, 238.7, 236.5, 241.0, 238.1, 211.5, 237.8, 234.9, 234.5,
|
|
||||||
234.9, 226.3, 246.9, 227.9, 230.4, 259.6, 237.2, 237.1, 238.4, 243.8, 242.5, 239.9, 240.4,
|
|
||||||
235.8, 240.4, 238.1, 241.4, 241.7, 242.3, 242.2, 240.6, 238.4, 247.1, 246.8, 245.2, 248.2,
|
|
||||||
247.4, 245.4, 245.4, 242.7, 231.1, 234.0, 234.5, 233.4, 233.5, 231.9, 230.1, 242.5, 239.0,
|
|
||||||
238.2, 233.0, 237.7, 232.3, 219.6, 219.9, 235.0, 235.9, 232.0, 228.4, 241.4, 237.8, 226.9,
|
|
||||||
231.8, 230.5, 229.4, 227.0, 230.1, 229.5, 219.9, 226.9, 220.2, 221.3, 214.0, 214.8, 208.5,
|
|
||||||
216.5, 217.9, 218.0, 217.9, 218.8, 554.9, 596.3, 639.3, 651.8, 655.9, 677.7, 654.8, 653.7,
|
|
||||||
652.5, 660.3, 655.7, 632.9, 605.1, 578.6, 484.8, 496.7, 491.5, 237.4, 693.3, 682.9, 676.3,
|
|
||||||
665.1, 672.6, 677.4, 699.5, 746.5, 793.0, 820.8, 836.9, 831.7, 813.8, 774.3, 513.7, 511.5,
|
|
||||||
512.0, 493.9, 464.6, 457.9, 479.7, 526.0, 524.0, 515.7, 509.3, 531.0, 553.8, 538.4, 562.8,
|
|
||||||
582.7, 541.4, 558.5, 545.3, 640.0, 583.8, 599.0, 593.8, 595.2, 603.6, 604.7, 620.9, 614.5,
|
|
||||||
586.6, 570.3, 549.1, 511.8, 447.5, 462.2, 354.3, 358.3, 365.5, 371.3, 373.8, 377.0, 376.8,
|
|
||||||
377.3, 377.6, 383.6, 372.4, 377.1, 382.3, 384.6, 386.4, 384.8, 382.9, 375.9, 365.9, 430.3,
|
|
||||||
471.0, 427.2, 428.5, 403.2, 887.7, 380.7, 381.5, 382.0, 397.5, 401.8, 409.1, 418.8, 441.2,
|
|
||||||
470.9, 490.1, 514.8, 516.4, 515.3, 490.4, 489.5, 486.6, 472.2, 410.8, 419.1, 428.3, 437.9,
|
|
||||||
444.8, 466.6, 466.6, 465.3, 456.6, 449.4, 436.6, 430.0, 421.0, 419.8, 411.4, 398.0, 416.8,
|
|
||||||
426.6, 425.1, 415.1, 407.2, 398.0, 385.9, 209.6, 209.3, 208.9, 208.5, 207.5, 216.6, 210.8,
|
|
||||||
210.7, 213.0, 210.9, 211.9, 211.8, 211.8, 211.8, 211.6, 211.4, 216.1, 216.6, 216.7, 220.6,
|
|
||||||
217.6, 218.4, 219.2, 224.9, 212.4, 237.7, 231.4, 251.4, 252.7, 252.0, 216.4, 231.7, 229.2,
|
|
||||||
230.8, 250.7, 228.9, 228.5, 229.0, 397.4, 416.0, 438.4, 447.0, 439.3, 424.3, 218.7, 218.7,
|
|
||||||
218.9, 218.8, 218.4, 445.6, 444.4, 455.8, 451.0, 454.8, 454.3, 455.3, 448.6, 443.6, 442.1,
|
|
||||||
451.4, 458.2, 455.3, 452.1, 460.3, 460.0, 457.7, 467.1, 457.0, 454.1, 463.0, 459.5, 465.5,
|
|
||||||
464.3, 456.8, 445.0, 425.5, 428.2, 218.8, 221.8, 222.7, 222.3, 223.1, 221.6, 223.5, 222.0,
|
|
||||||
224.0, 225.4, 223.7, 222.5, 221.8, 220.9, 222.1, 224.0, 223.2, 221.6, 220.3, 218.8, 226.4,
|
|
||||||
228.2, 225.4, 224.2, 216.9, 216.5, 217.1, 217.6, 217.9, 217.6, 217.0, 216.1, 216.6, 220.6,
|
|
||||||
219.5, 218.9, 220.8, 221.5, 222.5, 220.2, 217.7, 216.4, 488.4, 497.5, 503.2, 515.2, 518.5,
|
|
||||||
522.0, 535.7, 542.3, 542.3, 541.8, 536.7, 518.9, 493.5, 216.1, 217.8, 219.5, 220.5, 221.2,
|
|
||||||
220.0, 516.0, 218.0, 218.4, 523.4, 502.5, 505.8, 494.9, 220.9, 221.3, 220.8, 220.4, 219.3,
|
|
||||||
218.3, 217.5, 216.5, 215.5, 214.2, 213.0, 212.9, 213.3, 213.5, 473.5, 477.6, 487.5, 492.6,
|
|
||||||
217.2, 219.2, 220.7, 220.7, 220.7, 218.9, 216.5, 214.4, 212.5, 210.6, 210.7, 210.9, 211.8,
|
|
||||||
212.9, 213.7, 213.7, 213.7, 212.6
|
|
||||||
],
|
|
||||||
"slopeEast": [
|
|
||||||
0.002, -0.001, 0.056, 0.043, 0.022, 0.002, 0.007, -0.005, 0.014, 0.012, 0.002, -0.013, 0.046,
|
|
||||||
0.027, -0.083, -0.005, -0.017, -0.01, -0.007, -0.03, -0.051, -0.056, -0.058, -0.088, -0.109,
|
|
||||||
-0.099, -0.085, -0.079, -0.077, 0.008, 0.005, 0.006, -0.01, 0.062, 0.068, 0.071, 0.074, 0.084,
|
|
||||||
0.019, -0.001, 0.023, 0.02, 0.021, 0.024, 0.025, 0.031, 0.054, 0.031, 0.003, -0.022, -0.034,
|
|
||||||
-0.054, -0.055, -0.049, -0.047, -0.045, -0.038, -0.041, -0.051, -0.054, -0.073, -0.086, -0.104,
|
|
||||||
-0.05, -0.085, -0.083, 0.125, 0.082, 0.049, 0.018, 0.064, 0.034, -0.013, -0.004, -0.06, -0.087,
|
|
||||||
-0.128, -0.166, -0.129, -0.038, -0.154, -0.158, -0.163, -0.116, -0.12, 0.088, 0.055, 0.048,
|
|
||||||
0.095, 0.036, 0.154, 0.016, -0.009, -0.018, -0.079, -0.121, -0.161, -0.174, 0.003, 0.037, 0.108,
|
|
||||||
0.103, 0.1, 0.106, 0.101, -0.064, -0.045, 0.013, 0.149, 0.083, 0.078, 0.071, 0.039, -0.062,
|
|
||||||
-0.065, -0.118, -0.105, -0.072, -0.045, -0.025, -0.001, -0.008, -0.007, -0.02, -0.037, -0.058,
|
|
||||||
-0.078, -0.075, -0.069, -0.063, -0.054, -0.008, 0.003, 0.123, 0.036, 0.015, -0.005, 0.017,
|
|
||||||
0.049, 0.086, 0.068, 0.013, 0.032, -0.024, -0.01, 0.005, 0.009, -0.005, -0.004, 0.021, 0.062,
|
|
||||||
-0.012, -0.014, -0.013, -0.031, 0.02, -0.004, -0.021, -0.005, -0.018, -0.026, -0.032, -0.038,
|
|
||||||
-0.046, -0.055, -0.063, -0.067, -0.007, 0.009, -0.048, -0.051, -0.051, -0.004, -0.015, -0.025,
|
|
||||||
-0.018, 0.002, -0.002, 0.005, 0.013, 0.02, 0.049, 0.013, 0.002, -0.023, -0.009, -0.075, -0.065,
|
|
||||||
0.018, 0.02, 0.024, -0.023, -0.022, -0.049, 0.01, 0.056, -0.003, -0.001, 0.008, -0.048, -0.05,
|
|
||||||
-0.03, -0.015, 0.002, -0.045, -0.077, -0.052, -0.113, -0.035, 0.052, 0.029, -0.006, -0.008,
|
|
||||||
0.119, 0.111, 0.049, 0.019, -0.001, -0.008, 0.003, 0.025, 0.028, 0.004, -0.059, 0.008, 0.005,
|
|
||||||
-0.0, 0.055, 0.03, -0.044, -0.024, -0.002, -0.029, -0.015, -0.028, -0.04, -0.079, -0.084,
|
|
||||||
-0.073, 0.118, 0.104, 0.095, 0.098, 0.122, -0.042, 0.014, 0.108, 0.117, -0.077, -0.066, -0.052,
|
|
||||||
0.006, 0.018, -0.026, -0.008, 0.016, -0.019, -0.02, 0.006, 0.033, 0.056, 0.035, 0.017, 0.002,
|
|
||||||
0.011, 0.009, -0.015, 0.039, -0.016, -0.019, 0.073, 0.06, 0.028, 0.012, -0.052, -0.037, -0.027,
|
|
||||||
-0.026, -0.025, -0.027, -0.034, -0.033, -0.112, -0.098, -0.018, -0.005, 0.014, -0.002, -0.012,
|
|
||||||
-0.021, -0.041, -0.06, -0.073, -0.068, -0.007, 0.023, -0.002, 0.014, 0.031, 0.042, 0.045, 0.05,
|
|
||||||
0.06, 0.075, 0.066, 0.054, 0.029, 0.03, -0.066, -0.045, -0.033, -0.035, 0.1, 0.072, 0.022,
|
|
||||||
-0.017, 0.002, 0.006, 0.105, 0.007, -0.015, 0.014, -0.019, -0.045, 0.021, -0.027, -0.032,
|
|
||||||
-0.043, 0.023, -0.048, 0.051, -0.072, -0.099, -0.013, 0.016, 0.062, 0.05, 0.066, 0.041, 0.022,
|
|
||||||
-0.031, -0.028, -0.003, 0.047, -0.019, -0.007, 0.014, -0.047, 0.019, -0.023, -0.023, 0.008,
|
|
||||||
-0.064, 0.049, -0.035, -0.026, 0.01, 0.043, 0.057, 0.094, -0.076, -0.07, 0.043, 0.029, 0.051,
|
|
||||||
0.001, 0.036, 0.056, -0.016, -0.042, -0.015, -0.0, 0.037, 0.052, 0.089, 0.032, 0.021, 0.06,
|
|
||||||
-0.018, 0.018, 0.002, 0.036, 0.058, -0.043, 0.005, -0.0, -0.004, -0.084, -0.088, 0.055, -0.004,
|
|
||||||
0.02, 0.027, 0.018, -0.003, -0.013, -0.01, -0.005, 0.032, 0.037, -0.085, -0.114, 0.016, -0.076,
|
|
||||||
-0.081, 0.043, 0.029, 0.014, -0.247, -0.334, -0.183, -0.03, -0.023, 0.027, 0.067, 0.018, -0.17,
|
|
||||||
0.04, 0.076, 0.16, 0.142, 0.214, -0.239, -0.036, 0.236, 0.006, -0.075, -0.015, -0.134, 0.191,
|
|
||||||
-0.098, -0.235, -0.094, -0.348, -0.156, -0.126, 0.06, -0.008, 0.039, 0.184, 0.048, 0.037, 0.035,
|
|
||||||
-0.057, -0.06, 0.062, -0.295, -0.071, -0.175, 0.046, -0.045, -0.173, -0.173, -0.161, -0.148,
|
|
||||||
0.042, -0.034, -0.145, 0.247, 0.002, -0.209, 0.028, -0.129, -0.037, 0.154, -0.069, -0.023,
|
|
||||||
0.149, 0.119, -0.146, 0.175, 0.112, -0.005, -0.029, -0.11, -0.064, -0.06, -0.018, -0.04, 0.03,
|
|
||||||
-0.087, -0.043, -0.015, -0.031, -0.13, -0.068, -0.06, 0.001, -0.021, -0.0, -0.013, 0.032, 0.012,
|
|
||||||
-0.025, 0.013, 0.081, 0.008, -0.101, 0.006, -0.063, -0.072, -0.034, -0.109, -0.03, -0.058,
|
|
||||||
-0.068, -0.174, -0.1, -0.092, -0.088, -0.053, 0.072, 0.007, -0.043, -0.029, -0.004, -0.033,
|
|
||||||
-0.07, -0.071, -0.07, -0.077, -0.07, -0.021, -0.02, -0.061, -0.004, -0.114, -0.02, -0.023,
|
|
||||||
0.032, 0.05, -0.037, -0.005, -0.02, -0.109, -0.063, 0.014, -0.015, -0.037, 0.007, 0.019, 0.035,
|
|
||||||
0.051, 0.064, -0.018, -0.034, -0.025, 0.038, -0.074, -0.071, -0.068, -0.065, -0.061, -0.056,
|
|
||||||
-0.05, -0.038, -0.032, -0.02, 0.035, -0.023, -0.034, -0.042, -0.009, -0.053, -0.061, -0.048,
|
|
||||||
0.032, 0.055, -0.052, 0.019, 0.04, -0.026, 0.007, -0.033, -0.04, -0.044, -0.047, 0.134, -0.002,
|
|
||||||
0.095, 0.061, -0.082, -0.127, 0.039, 0.057, 0.077, 0.092, 0.081, 0.007, -0.041, 0.057, -0.038,
|
|
||||||
0.02, 0.004, -0.126, -0.118, -0.042, -0.061, -0.009, -0.034, -0.028, -0.016, 0.066, -0.008,
|
|
||||||
-0.033, -0.062, -0.168, 0.054, 0.058, -0.007, 0.007, -0.054, -0.042, -0.257, -0.152, 0.009,
|
|
||||||
0.029, 0.032, 0.036, -0.033, -0.046, -0.05, 0.018, -0.059, -0.065, -0.078, -0.093, -0.109,
|
|
||||||
-0.126, -0.136, -0.072, -0.057, -0.05, -0.039, -0.032, -0.029, -0.024, -0.055, -0.05, -0.057,
|
|
||||||
0.019, 0.031, 0.057, 0.078, 0.091, 0.084, 0.071, 0.05, 0.033, 0.066, 0.024, -0.039, -0.043,
|
|
||||||
-0.062, -0.086, -0.078, -0.035, -0.041, 0.114, -0.004, 0.08, -0.043, 0.008, 0.035, 0.117, 0.075,
|
|
||||||
0.091, -0.088, -0.074, -0.157, -0.187, 0.023, 0.023, 0.021, 0.021, 0.017, 0.002, -0.01, 0.054,
|
|
||||||
0.037, 0.016, 0.058, -0.096, -0.292, 0.009, 0.007, -0.003, -0.011, -0.009, -0.005, -0.017,
|
|
||||||
-0.031, -0.04, -0.029, -0.019, 0.007, 0.036, 0.064, 0.06, 0.091, 0.084, 0.021, 0.044, 0.024,
|
|
||||||
0.007, 0.007, 0.006, -0.001, -0.004, -0.011, -0.026, -0.037, -0.048, -0.06, -0.057, -0.054,
|
|
||||||
-0.051, -0.031, -0.014, -0.007
|
|
||||||
],
|
|
||||||
"slopeNorth": [
|
|
||||||
-0.005, 0.005, -0.003, 0.002, -0.006, -0.016, -0.044, -0.027, -0.024, -0.026, -0.026, -0.026,
|
|
||||||
-0.05, -0.054, 0.02, -0.042, -0.033, -0.022, -0.009, 0.008, 0.025, 0.032, 0.037, 0.003, 0.01,
|
|
||||||
0.01, 0.013, 0.017, 0.026, 0.059, 0.018, -0.02, -0.039, 0.024, 0.024, 0.008, -0.005, -0.003,
|
|
||||||
-0.06, -0.088, -0.024, -0.033, -0.037, -0.039, -0.046, -0.052, -0.026, -0.019, -0.023, -0.025,
|
|
||||||
-0.027, -0.106, -0.113, -0.118, -0.111, -0.103, -0.016, -0.016, -0.129, -0.122, -0.096, -0.075,
|
|
||||||
-0.046, -0.071, 0.056, 0.061, -0.108, -0.077, 0.028, 0.067, -0.029, -0.009, 0.048, -0.009,
|
|
||||||
-0.029, -0.018, 0.006, 0.025, 0.144, 0.19, 0.17, 0.167, 0.149, -0.078, -0.083, -0.0, -0.081,
|
|
||||||
-0.04, -0.001, -0.033, -0.082, -0.031, 0.061, 0.14, 0.078, 0.132, 0.104, 0.127, -0.011, -0.01,
|
|
||||||
0.071, 0.129, 0.113, 0.103, 0.13, -0.038, -0.037, 0.044, 0.052, 0.016, 0.01, -0.01, -0.02,
|
|
||||||
-0.014, 0.06, 0.086, 0.082, 0.067, 0.049, 0.051, 0.058, -0.08, -0.095, -0.099, -0.098, -0.093,
|
|
||||||
-0.064, -0.024, 0.007, 0.03, 0.041, -0.085, -0.064, -0.021, -0.069, -0.063, -0.054, -0.027,
|
|
||||||
0.013, 0.058, 0.082, 0.091, 0.065, 0.04, 0.085, 0.117, 0.139, 0.134, 0.059, 0.047, 0.008, 0.002,
|
|
||||||
0.005, 0.01, 0.034, 0.039, 0.068, 0.077, -0.041, -0.017, -0.011, -0.017, -0.021, -0.021, -0.003,
|
|
||||||
0.016, 0.034, -0.057, -0.046, -0.067, -0.062, -0.059, -0.032, -0.028, -0.023, -0.01, -0.01,
|
|
||||||
-0.033, -0.028, -0.004, 0.019, -0.01, 0.056, 0.067, -0.061, -0.049, -0.108, -0.079, -0.0, 0.018,
|
|
||||||
0.024, 0.053, 0.08, 0.085, -0.008, 0.015, 0.016, 0.027, 0.048, -0.05, -0.038, -0.058, -0.086,
|
|
||||||
-0.001, -0.061, -0.038, -0.014, 0.027, 0.062, -0.036, -0.007, 0.046, -0.023, -0.001, 0.01,
|
|
||||||
-0.073, 0.053, 0.073, -0.02, 0.004, -0.001, -0.014, -0.069, -0.016, -0.041, 0.001, 0.021,
|
|
||||||
-0.017, -0.019, -0.115, -0.11, -0.083, -0.119, -0.097, -0.076, -0.101, -0.069, -0.054, -0.022,
|
|
||||||
-0.045, -0.028, -0.016, -0.008, 0.019, -0.037, 0.005, 0.007, 0.01, -0.092, -0.096, -0.079,
|
|
||||||
0.074, 0.07, -0.076, -0.025, -0.075, -0.039, 0.003, -0.006, 0.013, -0.03, -0.064, -0.079,
|
|
||||||
-0.076, -0.056, -0.026, 0.042, -0.084, 0.038, 0.055, 0.002, 0.033, 0.01, -0.003, 0.001, -0.02,
|
|
||||||
-0.041, -0.057, -0.056, -0.053, -0.045, -0.037, 0.043, 0.037, -0.023, -0.013, -0.012, 0.063,
|
|
||||||
0.029, 0.024, 0.012, -0.007, 0.01, 0.006, -0.057, 0.007, -0.017, 0.02, 0.061, 0.058, 0.039,
|
|
||||||
0.021, 0.001, -0.02, -0.025, -0.024, 0.039, 0.052, 0.03, 0.03, 0.028, 0.035, 0.003, 0.005,
|
|
||||||
0.027, -0.048, -0.059, 0.005, -0.037, -0.029, -0.058, -0.066, -0.009, -0.02, 0.014, -0.009,
|
|
||||||
-0.015, -0.01, -0.045, -0.036, -0.085, -0.017, 0.011, -0.052, 0.048, -0.025, -0.024, -0.035,
|
|
||||||
-0.031, -0.05, -0.058, -0.013, -0.05, -0.053, -0.058, -0.033, -0.017, 0.001, -0.025, -0.066,
|
|
||||||
-0.023, -0.014, -0.011, -0.059, -0.019, -0.009, 0.005, -0.007, -0.034, -0.051, 0.002, 0.036,
|
|
||||||
0.0, 0.007, -0.022, -0.028, -0.046, -0.051, -0.018, -0.021, -0.013, 0.012, -0.005, -0.035,
|
|
||||||
-0.036, 0.011, -0.065, 0.025, 0.006, 0.018, -0.103, 0.005, -0.007, -0.025, -0.061, -0.044,
|
|
||||||
-0.049, -0.008, 0.004, -0.043, 0.022, -0.062, -0.019, -0.055, 0.001, -0.01, -0.057, -0.005,
|
|
||||||
-0.051, -0.064, -0.023, 0.029, -0.044, 0.079, 0.066, -0.049, -0.043, 0.043, 0.037, 0.009, -0.04,
|
|
||||||
-0.175, -0.046, -0.025, -0.055, -0.045, 0.01, -0.078, -0.036, -0.127, -0.126, -0.145, 0.102,
|
|
||||||
0.094, -0.123, 0.055, -0.109, 0.133, -0.142, -0.009, -0.085, 0.067, 0.024, 0.056, -0.06, 0.156,
|
|
||||||
0.025, -0.068, 0.018, -0.106, 0.077, 0.019, -0.02, -0.043, 0.021, -0.021, 0.053, -0.023, -0.091,
|
|
||||||
-0.044, 0.016, 0.174, 0.024, 0.172, 0.213, -0.05, -0.021, -0.051, -0.255, 0.041, 0.076, -0.168,
|
|
||||||
0.031, -0.153, -0.058, -0.022, 0.063, -0.084, -0.122, -0.153, -0.157, -0.171, 0.014, 0.054,
|
|
||||||
0.036, 0.084, 0.009, 0.019, 0.018, -0.012, 0.013, 0.008, 0.011, 0.061, 0.061, 0.057, -0.013,
|
|
||||||
-0.036, -0.024, -0.045, -0.046, -0.101, -0.156, -0.066, -0.239, -0.1, -0.077, -0.243, -0.08,
|
|
||||||
0.073, 0.039, 0.179, 0.106, 0.005, 0.086, 0.044, 0.321, 0.232, 0.195, 0.145, -0.074, -0.069,
|
|
||||||
-0.057, 0.021, -0.1, -0.165, 0.063, 0.139, 0.12, 0.091, 0.134, 0.082, 0.064, -0.056, -0.118,
|
|
||||||
-0.146, -0.004, -0.123, -0.142, -0.092, -0.121, 0.172, 0.209, 0.083, -0.15, -0.088, -0.128,
|
|
||||||
-0.152, -0.196, 0.004, -0.017, -0.027, -0.037, -0.042, 0.021, 0.014, 0.009, 0.003, 0.082, 0.074,
|
|
||||||
0.061, 0.048, 0.031, 0.013, -0.006, 0.081, 0.074, 0.055, -0.036, 0.041, 0.024, 0.006, -0.068,
|
|
||||||
-0.022, 0.073, 0.021, 0.055, 0.009, 0.022, 0.079, -0.019, 0.052, 0.08, 0.02, 0.073, 0.04, 0.01,
|
|
||||||
0.224, 0.291, 0.218, -0.011, -0.137, -0.234, 0.091, 0.094, 0.095, 0.093, 0.062, 0.02, 0.061,
|
|
||||||
0.003, 0.044, -0.063, 0.145, -0.012, -0.046, -0.011, 0.075, 0.117, 0.046, -0.033, 0.108, 0.084,
|
|
||||||
-0.011, -0.094, -0.024, -0.13, 0.075, 0.1, 0.124, -0.018, -0.058, -0.136, -0.149, -0.227,
|
|
||||||
-0.022, 0.105, 0.119, 0.113, 0.09, 0.076, 0.045, -0.045, 0.032, 0.029, 0.034, 0.051, 0.055,
|
|
||||||
0.044, 0.028, -0.072, -0.095, -0.088, -0.06, -0.032, -0.005, 0.003, -0.016, -0.008, 0.039,
|
|
||||||
0.085, 0.076, 0.061, 0.046, 0.035, 0.031, 0.022, 0.018, 0.014, 0.006, 0.014, 0.009, -0.002,
|
|
||||||
-0.002, 0.003, -0.003, -0.024, -0.018, 0.068, 0.212, 0.049, 0.187, 0.06, 0.024, 0.003, -0.084,
|
|
||||||
-0.173, 0.03, -0.138, -0.17, -0.157, 0.006, -0.007, -0.026, -0.034, -0.038, -0.045, 0.001,
|
|
||||||
-0.075, -0.067, 0.237, 0.215, 0.109, 0.055, -0.068, -0.066, -0.059, -0.054, -0.059, -0.062,
|
|
||||||
-0.065, -0.07, -0.072, -0.064, -0.054, -0.045, -0.035, -0.022, 0.059, 0.161, 0.071, 0.021,
|
|
||||||
-0.021, -0.027, -0.033, -0.039, -0.044, -0.038, -0.029, -0.034, -0.057, -0.078, -0.075, -0.071,
|
|
||||||
-0.076, -0.085, -0.083, -0.057, -0.03, -0.018
|
|
||||||
]
|
|
||||||
}
|
|
||||||
155
src/app/features/scene/ridge/view.test.ts
Normal file
155
src/app/features/scene/ridge/view.test.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { sunOnScreen } from './skyDome';
|
||||||
|
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][] = [
|
||||||
|
[390, 844],
|
||||||
|
[1920, 1080],
|
||||||
|
[3440, 1440],
|
||||||
|
];
|
||||||
|
|
||||||
|
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'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('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(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', () => {
|
||||||
|
for (const [w, h] of VIEWPORTS) {
|
||||||
|
const v = FALLBACK_VIEW;
|
||||||
|
const win = windowFor(v, w, h);
|
||||||
|
const sun = { elevation: 12, azimuth: v.lookAzDeg + 10, time: new Date(0) };
|
||||||
|
const at = sunOnScreen(sun, win.camera)!;
|
||||||
|
const planeX = w / 2 + 10 * v.pxPerDegH * win.plane.scale; // plane centred on lookAz
|
||||||
|
expect(Math.abs(at.x * w - planeX)).toBeLessThan(0.5);
|
||||||
|
// and its height above the ridge's horizon is 12 degrees of plane pixels
|
||||||
|
const planeY = win.camera.horizonAt * h - 12 * v.pxPerDegH * win.plane.scale;
|
||||||
|
expect(Math.abs(at.y * h - planeY)).toBeLessThan(0.5);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the sun is seen across north: azimuths wrap', () => {
|
||||||
|
const v: View = { ...FALLBACK_VIEW, lookAzDeg: 355 };
|
||||||
|
const win = windowFor(v, 1920, 1080);
|
||||||
|
const at = sunOnScreen({ elevation: 10, azimuth: 5, time: new Date(0) }, win.camera)!;
|
||||||
|
expect(Math.abs(at.x * 1920 - (960 + 10 * v.pxPerDegH * win.plane.scale))).toBeLessThan(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the sun does not turn the camera: the same camera for any sun', () => {
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
132
src/app/features/scene/ridge/view.ts
Normal file
132
src/app/features/scene/ridge/view.ts
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
// 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.
|
||||||
|
|
||||||
|
/** Where the observer stands. `id` names the baked place (it keys a rebuild); `altitudeKm` is the ground height, eye height excluded. */
|
||||||
|
export interface Place {
|
||||||
|
id: string;
|
||||||
|
lat: number;
|
||||||
|
lon: number;
|
||||||
|
altitudeKm: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The manifest's `view`: the baked window of the sky the planes cover. Angles are degrees, planes are in plane pixels. */
|
||||||
|
export interface ManifestView {
|
||||||
|
/** Compass azimuth at the centre of the planes, degrees clockwise from north. */
|
||||||
|
lookAzDeg: number;
|
||||||
|
/** Horizontal angle the planes span. */
|
||||||
|
windowDeg: number;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface View extends ManifestView {
|
||||||
|
place: Place;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The camera of the sky. Angle-linear, as the planes are (`pxPerDegH` is constant across a plane): a pixel's azimuth is
|
||||||
|
* `azimuthDeg + (x - 0.5) * hfovDeg` and its elevation is `(horizonAt - y) * vfovDeg`, x and y as fractions of the viewport.
|
||||||
|
*/
|
||||||
|
export interface Camera {
|
||||||
|
/** Compass azimuth at the centre column. */
|
||||||
|
azimuthDeg: number;
|
||||||
|
hfovDeg: number;
|
||||||
|
vfovDeg: number;
|
||||||
|
/** Where the horizon sits down the viewport, as a fraction of its height (0 top). */
|
||||||
|
horizonAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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,
|
||||||
|
windowDeg: 72,
|
||||||
|
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, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function windowFor(view: View, viewportW: number, viewportH: number): Window {
|
||||||
|
const scale = Math.max(
|
||||||
|
(RIDGE_BAND_FRAC * viewportH) / view.planeH,
|
||||||
|
(viewportW * (1 + 2 * DRIFT_FRAC)) / view.planeW
|
||||||
|
);
|
||||||
|
const hfovDeg = viewportW / (scale * view.pxPerDegH);
|
||||||
|
return {
|
||||||
|
camera: {
|
||||||
|
azimuthDeg: view.lookAzDeg,
|
||||||
|
hfovDeg,
|
||||||
|
vfovDeg: (hfovDeg * viewportH) / viewportW,
|
||||||
|
horizonAt: HORIZON_AT,
|
||||||
|
},
|
||||||
|
plane: {
|
||||||
|
scale,
|
||||||
|
w: scale * view.planeW,
|
||||||
|
h: scale * view.planeH,
|
||||||
|
bottom: (1 - HORIZON_AT) * viewportH - scale * (view.planeH - view.horizonRow),
|
||||||
|
},
|
||||||
|
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,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { viennaSun } from './vienna';
|
import { sunAt } from './sunAt';
|
||||||
|
import { FALLBACK_VIEW } from './view';
|
||||||
|
import { ELSEWHERE_VIEW } from './manifest.fixture';
|
||||||
import {
|
import {
|
||||||
CLEAR_SKY,
|
CLEAR_SKY,
|
||||||
currentWeather,
|
currentWeather,
|
||||||
|
|
@ -85,8 +87,8 @@ describe('weather from the file', () => {
|
||||||
expect(weatherFromFile(file({ glow_wm2: 0, humidity_pct: 100 }), -20)).toBe(0.75);
|
expect(weatherFromFile(file({ glow_wm2: 0, humidity_pct: 100 }), -20)).toBe(0.75);
|
||||||
});
|
});
|
||||||
it('the 2026-11-10 midday fixture, GLOW 56-89 W/m2 under an overcast sky, is full cloud; the clear midday of 2026-10-15, 546-569, is none', () => {
|
it('the 2026-11-10 midday fixture, GLOW 56-89 W/m2 under an overcast sky, is full cloud; the clear midday of 2026-10-15, 546-569, is none', () => {
|
||||||
const nov = viennaSun(new Date('2026-11-10T10:40:00Z')).elevation;
|
const nov = sunAt(FALLBACK_VIEW.place, new Date('2026-11-10T10:40:00Z')).elevation;
|
||||||
const oct = viennaSun(new Date('2026-10-15T10:50:00Z')).elevation;
|
const oct = sunAt(FALLBACK_VIEW.place, new Date('2026-10-15T10:50:00Z')).elevation;
|
||||||
for (const g of [56, 72, 89]) expect(cloudFromGlow(g, nov)).toBeGreaterThan(0.95);
|
for (const g of [56, 72, 89]) expect(cloudFromGlow(g, nov)).toBeGreaterThan(0.95);
|
||||||
for (const g of [546, 569]) expect(cloudFromGlow(g, oct)).toBe(0);
|
for (const g of [546, 569]) expect(cloudFromGlow(g, oct)).toBe(0);
|
||||||
expect(weatherFromFile(file({ glow_wm2: 72, sunshine_s_10min: 0 }), nov)).toBeGreaterThan(0.65);
|
expect(weatherFromFile(file({ glow_wm2: 72, sunshine_s_10min: 0 }), nov)).toBeGreaterThan(0.65);
|
||||||
|
|
@ -120,17 +122,18 @@ describe('weather from the file', () => {
|
||||||
|
|
||||||
describe('the weather now', () => {
|
describe('the weather now', () => {
|
||||||
it('uses the file while it is fresh', () => {
|
it('uses the file while it is fresh', () => {
|
||||||
expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), NOW)).toBeCloseTo(0.7, 2);
|
expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), FALLBACK_VIEW.place, NOW)).toBeCloseTo(0.7, 2);
|
||||||
});
|
});
|
||||||
it('falls back to a clear sky when the file was fetched more than 30 minutes ago', () => {
|
it('falls back to a clear sky when the file was fetched more than 30 minutes ago', () => {
|
||||||
const f = file({ humidity_pct: 100, fetched_at: '2026-11-11T10:19:00Z' });
|
const f = file({ humidity_pct: 100, fetched_at: '2026-11-11T10:19:00Z' });
|
||||||
expect(NOW.getTime() - Date.parse(f.fetched_at)).toBeGreaterThan(STALE_MS);
|
expect(NOW.getTime() - Date.parse(f.fetched_at)).toBeGreaterThan(STALE_MS);
|
||||||
expect(currentWeather(f, NOW)).toBe(CLEAR_SKY);
|
expect(currentWeather(f, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY);
|
||||||
});
|
});
|
||||||
it('the 30 minute mark itself is still fresh', () => {
|
it('the 30 minute mark itself is still fresh', () => {
|
||||||
expect(
|
expect(
|
||||||
currentWeather(
|
currentWeather(
|
||||||
file({ glow_wm2: 0, humidity_pct: 100, fetched_at: '2026-11-11T10:20:00Z' }),
|
file({ glow_wm2: 0, humidity_pct: 100, fetched_at: '2026-11-11T10:20:00Z' }),
|
||||||
|
FALLBACK_VIEW.place,
|
||||||
NOW
|
NOW
|
||||||
)
|
)
|
||||||
).toBe(0.75);
|
).toBe(0.75);
|
||||||
|
|
@ -138,19 +141,34 @@ describe('the weather now', () => {
|
||||||
it('falls back to a clear sky when the observation is more than 40 minutes old, though the file is fresh', () => {
|
it('falls back to a clear sky when the observation is more than 40 minutes old, though the file is fresh', () => {
|
||||||
const f = file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:09:00Z' });
|
const f = file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:09:00Z' });
|
||||||
expect(NOW.getTime() - Date.parse(f.observed_at)).toBeGreaterThan(OBSERVATION_STALE_MS);
|
expect(NOW.getTime() - Date.parse(f.observed_at)).toBeGreaterThan(OBSERVATION_STALE_MS);
|
||||||
expect(currentWeather(f, NOW)).toBe(CLEAR_SKY);
|
expect(currentWeather(f, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY);
|
||||||
expect(
|
expect(
|
||||||
currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:11:00Z' }), NOW)
|
currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T10:11:00Z' }), FALLBACK_VIEW.place, NOW)
|
||||||
).toBeGreaterThan(0.8);
|
).toBeGreaterThan(0.8);
|
||||||
});
|
});
|
||||||
it('falls back to a clear sky with no file, and with a fetch time from the future', () => {
|
it('falls back to a clear sky with no file, and with a fetch time from the future', () => {
|
||||||
expect(currentWeather(null, NOW)).toBe(CLEAR_SKY);
|
expect(currentWeather(null, FALLBACK_VIEW.place, NOW)).toBe(CLEAR_SKY);
|
||||||
expect(
|
expect(
|
||||||
currentWeather(file({ precip_mm_10min: 2, fetched_at: '2026-11-12T10:40:00Z' }), NOW)
|
currentWeather(file({ precip_mm_10min: 2, fetched_at: '2026-11-12T10:40:00Z' }), FALLBACK_VIEW.place, NOW)
|
||||||
).toBe(CLEAR_SKY);
|
).toBe(CLEAR_SKY);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('the sun the weather is read against is the place it is given', () => {
|
||||||
|
it("sets radiation against the sun over that place: by day in Vienna it reads cloud, at the other side of the world, in the night, it reads the humidity", () => {
|
||||||
|
const f = file({ glow_wm2: 100, sunshine_s_10min: null, humidity_pct: 60 });
|
||||||
|
const sunEl = (place: typeof FALLBACK_VIEW.place) =>
|
||||||
|
sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation;
|
||||||
|
expect(sunEl(FALLBACK_VIEW.place)).toBeGreaterThan(20);
|
||||||
|
expect(sunEl(ELSEWHERE_VIEW.place)).toBeLessThan(0);
|
||||||
|
const vienna = currentWeather(f, FALLBACK_VIEW.place, NOW);
|
||||||
|
const elsewhere = currentWeather(f, ELSEWHERE_VIEW.place, NOW);
|
||||||
|
expect(vienna).toBe(weatherFromFile(f, sunEl(FALLBACK_VIEW.place)));
|
||||||
|
expect(elsewhere).toBe(weatherFromFile(f, sunEl(ELSEWHERE_VIEW.place)));
|
||||||
|
expect(vienna).not.toBe(elsewhere);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('bad instrument values', () => {
|
describe('bad instrument values', () => {
|
||||||
it('a negative sunshine is no reading, not full cloud', () => {
|
it('a negative sunshine is no reading, not full cloud', () => {
|
||||||
expect(cloudEstimate(file({ glow_wm2: null, sunshine_s_10min: -5 }), 21)).toBeNull();
|
expect(cloudEstimate(file({ glow_wm2: null, sunshine_s_10min: -5 }), 21)).toBeNull();
|
||||||
|
|
@ -164,7 +182,7 @@ describe('bad instrument values', () => {
|
||||||
sunshine_s_10min: null,
|
sunshine_s_10min: null,
|
||||||
humidity_pct: 50,
|
humidity_pct: 50,
|
||||||
});
|
});
|
||||||
const at = (m: number) => currentWeather(f, new Date(Date.parse(f.observed_at) + m * 60_000));
|
const at = (m: number) => currentWeather(f, FALLBACK_VIEW.place, new Date(Date.parse(f.observed_at) + m * 60_000));
|
||||||
expect(at(0)).toBe(at(29));
|
expect(at(0)).toBe(at(29));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
@ -193,7 +211,7 @@ describe('reading weather.json', () => {
|
||||||
sunshine_s_10min: null,
|
sunshine_s_10min: null,
|
||||||
glow_wm2: null,
|
glow_wm2: null,
|
||||||
});
|
});
|
||||||
expect(currentWeather(gap, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY);
|
expect(currentWeather(gap, FALLBACK_VIEW.place, new Date('2026-11-11T22:50:00Z'))).toBe(CLEAR_SKY);
|
||||||
});
|
});
|
||||||
it("is not another station's file", () => {
|
it("is not another station's file", () => {
|
||||||
expect(parseWeatherFile({ ...file(), station: 11036 })).toBeNull();
|
expect(parseWeatherFile({ ...file(), station: 11036 })).toBeNull();
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,8 @@
|
||||||
// 600 the direct beam was strong enough to burn the card); with the sun low or down it is a ramp of the humidity. A file that is
|
// 600 the direct beam was strong enough to burn the card); with the sun low or down it is a ramp of the humidity. A file that is
|
||||||
// missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky.
|
// missing, unreadable, malformed or stale (below) is no observation, and no observation is a clear sky.
|
||||||
import { WEATHER_CREDIT } from './credits';
|
import { WEATHER_CREDIT } from './credits';
|
||||||
import { viennaSun } from './vienna';
|
import { sunAt } from './sunAt';
|
||||||
|
import type { Place } from './view';
|
||||||
|
|
||||||
/** Reader rule of docs/weather-feed.md: the file is stale 30 minutes after it was fetched or 40 after the observation it holds (the station reports every 10). */
|
/** Reader rule of docs/weather-feed.md: the file is stale 30 minutes after it was fetched or 40 after the observation it holds (the station reports every 10). */
|
||||||
export const STALE_MS = 30 * 60_000;
|
export const STALE_MS = 30 * 60_000;
|
||||||
|
|
@ -104,8 +105,8 @@ export function weatherFromFile(f: WeatherFile, sunEl: number): number {
|
||||||
return Math.max(0.7 * cloud, mist);
|
return Math.max(0.7 * cloud, mist);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The weather number now: the file's, or a clear sky when there is none or it is stale (see STALE_MS) or from the future. */
|
/** The weather number now, its sun taken at `place` (the View's): the file's, or a clear sky when there is none or it is stale (see STALE_MS) or from the future. */
|
||||||
export function currentWeather(f: WeatherFile | null, now: Date = new Date()): number {
|
export function currentWeather(f: WeatherFile | null, place: Place, now: Date = new Date()): number {
|
||||||
if (!f) return CLEAR_SKY;
|
if (!f) return CLEAR_SKY;
|
||||||
const fetched = now.getTime() - Date.parse(f.fetched_at);
|
const fetched = now.getTime() - Date.parse(f.fetched_at);
|
||||||
const observed = now.getTime() - Date.parse(f.observed_at);
|
const observed = now.getTime() - Date.parse(f.observed_at);
|
||||||
|
|
@ -119,7 +120,7 @@ export function currentWeather(f: WeatherFile | null, now: Date = new Date()): n
|
||||||
)
|
)
|
||||||
return CLEAR_SKY;
|
return CLEAR_SKY;
|
||||||
// GLOW and SO are means of the ten minutes ending at observed_at: the sun of their midpoint is the one to set them against.
|
// GLOW and SO are means of the ten minutes ending at observed_at: the sun of their midpoint is the one to set them against.
|
||||||
return weatherFromFile(f, viennaSun(new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation);
|
return weatherFromFile(f, sunAt(place, new Date(Date.parse(f.observed_at) - 5 * 60_000)).elevation);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fetch and parse `weather.json`; null on any failure. */
|
/** Fetch and parse `weather.json`; null on any failure. */
|
||||||
|
|
|
||||||
37
src/app/features/scene/sceneDrawn.test.ts
Normal file
37
src/app/features/scene/sceneDrawn.test.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import {
|
||||||
|
SCENE_ACTIVE_ATTRIBUTE,
|
||||||
|
getSceneDrawn,
|
||||||
|
setSceneDrawn,
|
||||||
|
subscribeSceneDrawn,
|
||||||
|
} from './sceneDrawn';
|
||||||
|
|
||||||
|
const attrs = new Set<string>();
|
||||||
|
vi.stubGlobal('document', {
|
||||||
|
documentElement: {
|
||||||
|
setAttribute: (n: string) => attrs.add(n),
|
||||||
|
removeAttribute: (n: string) => attrs.delete(n),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => setSceneDrawn(false));
|
||||||
|
|
||||||
|
describe('sceneDrawn: one store owns the flag and html[data-scene]', () => {
|
||||||
|
it('starts off, and on/off move the flag, the attribute and the subscribers together', () => {
|
||||||
|
const cb = vi.fn();
|
||||||
|
const off = subscribeSceneDrawn(cb);
|
||||||
|
expect(getSceneDrawn()).toBe(false);
|
||||||
|
setSceneDrawn(true);
|
||||||
|
expect(getSceneDrawn()).toBe(true);
|
||||||
|
expect(attrs.has(SCENE_ACTIVE_ATTRIBUTE)).toBe(true);
|
||||||
|
setSceneDrawn(true);
|
||||||
|
expect(cb).toHaveBeenCalledTimes(1);
|
||||||
|
setSceneDrawn(false);
|
||||||
|
expect(getSceneDrawn()).toBe(false);
|
||||||
|
expect(attrs.has(SCENE_ACTIVE_ATTRIBUTE)).toBe(false);
|
||||||
|
expect(cb).toHaveBeenCalledTimes(2);
|
||||||
|
off();
|
||||||
|
setSceneDrawn(true);
|
||||||
|
expect(cb).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
29
src/app/features/scene/sceneDrawn.ts
Normal file
29
src/app/features/scene/sceneDrawn.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
// Whether a background scene is drawing a sky right now. BackgroundScene is the only writer: it sets this when the
|
||||||
|
// ridge scene starts, and clears it when the scene stops, fails to start, or loses its WebGL context (a restored
|
||||||
|
// context sets it again). This store also owns html[data-scene], so the attribute the CSS reads and the flag the theme
|
||||||
|
// hooks read cannot disagree. The configured tier only says a scene may run; this says one does.
|
||||||
|
|
||||||
|
/** Set on <html> while a scene is drawn, so signed-out screens can let it show through. */
|
||||||
|
export const SCENE_ACTIVE_ATTRIBUTE = 'data-scene';
|
||||||
|
|
||||||
|
let drawn = false;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
export const getSceneDrawn = (): boolean => drawn;
|
||||||
|
|
||||||
|
export const subscribeSceneDrawn = (cb: () => void): (() => void) => {
|
||||||
|
listeners.add(cb);
|
||||||
|
return () => {
|
||||||
|
listeners.delete(cb);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export function setSceneDrawn(on: boolean): void {
|
||||||
|
if (typeof document !== 'undefined') {
|
||||||
|
if (on) document.documentElement.setAttribute(SCENE_ACTIVE_ATTRIBUTE, '');
|
||||||
|
else document.documentElement.removeAttribute(SCENE_ACTIVE_ATTRIBUTE);
|
||||||
|
}
|
||||||
|
if (on === drawn) return;
|
||||||
|
drawn = on;
|
||||||
|
[...listeners].forEach((cb) => cb());
|
||||||
|
}
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
// Temporary: which background the viewer picked (terrain or ridges), kept in one localStorage key so the two scenes we
|
|
||||||
// serve can be compared on any device. Absent, the client config's backgroundScene.style decides.
|
|
||||||
import type { SceneStyle } from './tier';
|
|
||||||
|
|
||||||
export type ServedSceneStyle = Extract<SceneStyle, 'terrain' | 'ridge'>;
|
|
||||||
export const SERVED_SCENE_STYLES: readonly ServedSceneStyle[] = ['terrain', 'ridge'];
|
|
||||||
export const SCENE_STYLE_KEY = 'ratatoskr.sceneStyle';
|
|
||||||
|
|
||||||
export function getSceneStyleOverride(): ServedSceneStyle | undefined {
|
|
||||||
try {
|
|
||||||
const v = localStorage.getItem(SCENE_STYLE_KEY);
|
|
||||||
return SERVED_SCENE_STYLES.includes(v as ServedSceneStyle)
|
|
||||||
? (v as ServedSceneStyle)
|
|
||||||
: undefined;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Store the pick and reload, so the scene host mounts the other scene from a clean page. */
|
|
||||||
export function setSceneStyle(s: ServedSceneStyle): void {
|
|
||||||
try {
|
|
||||||
localStorage.setItem(SCENE_STYLE_KEY, s);
|
|
||||||
} catch {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
window.location.reload();
|
|
||||||
}
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
import { describe, expect, it } from 'vitest';
|
|
||||||
import { displayedLuminance, hexToLinear, luma, shapeToBand, SKY_BAND } from './skyBand';
|
|
||||||
import type { Linear } from './skyBand';
|
|
||||||
import { GRID_FRAG, SHAPE_SKY_GLSL, SKY_FRAG } from './terrain/terrainShaders';
|
|
||||||
|
|
||||||
const near = (a: number, b: number) => Math.abs(a - b) < 1e-9;
|
|
||||||
|
|
||||||
describe('shapeToBand', () => {
|
|
||||||
const dark: Linear = [0.02, 0.05, 0.2]; // a deep blue
|
|
||||||
const { day } = SKY_BAND;
|
|
||||||
|
|
||||||
it('lifts a sky below the floor onto the floor, mixing toward the tint so the hue is kept', () => {
|
|
||||||
const c = shapeToBand(dark, day);
|
|
||||||
expect(near(luma(c), day.floor)).toBe(true);
|
|
||||||
// Between the sky and the tint on every channel: a mix, not a grey clamp.
|
|
||||||
[0, 1, 2].forEach((i) => {
|
|
||||||
expect(c[i]).toBeGreaterThanOrEqual(Math.min(dark[i], day.lift[i]));
|
|
||||||
expect(c[i]).toBeLessThanOrEqual(Math.max(dark[i], day.lift[i]));
|
|
||||||
});
|
|
||||||
expect(c[2]).toBeGreaterThan(c[0]); // still blue
|
|
||||||
});
|
|
||||||
|
|
||||||
it('lifts black to the tint scaled in, not to grey', () => {
|
|
||||||
const c = shapeToBand([0, 0, 0], SKY_BAND.dusk);
|
|
||||||
expect(near(luma(c), SKY_BAND.dusk.floor)).toBe(true);
|
|
||||||
expect(c[2]).toBeGreaterThan(c[0]); // the dusk tint is Day's pale blue
|
|
||||||
});
|
|
||||||
|
|
||||||
it('leaves a sky already in the band as it is, and is continuous at the floor', () => {
|
|
||||||
const ok: Linear = [0.5, 0.6, 0.7];
|
|
||||||
expect(shapeToBand(ok, day)).toEqual(ok);
|
|
||||||
const lo = shapeToBand([0.31, 0.31, 0.31], day);
|
|
||||||
const below = shapeToBand([0.3099, 0.3099, 0.3099], day);
|
|
||||||
expect(Math.abs(lo[0] - below[0])).toBeLessThan(1e-3);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('scales a sky above the ceiling down to it, keeping its hue', () => {
|
|
||||||
const c = shapeToBand([0.9, 0.8, 1], SKY_BAND.night);
|
|
||||||
expect(near(luma(c), SKY_BAND.night.ceiling)).toBe(true);
|
|
||||||
expect(near(c[0] / c[2], 0.9)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('clamps to 0..1 as the screen does, and never leaves the band when shaped twice', () => {
|
|
||||||
expect(shapeToBand([4, 4, 4], day)).toEqual([1, 1, 1]);
|
|
||||||
const once = shapeToBand(dark, day);
|
|
||||||
shapeToBand(once, day).forEach((v, i) => expect(v).toBeCloseTo(once[i], 12));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the bands', () => {
|
|
||||||
it('have a tint above the floor to lift toward', () => {
|
|
||||||
Object.values(SKY_BAND).forEach((b) => expect(luma(b.lift)).toBeGreaterThan(b.floor));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keep the floor above the 0.2983 text bound by what gamma 2.2, 8-bit rounding and dither can take', () => {
|
|
||||||
const grey = shapeToBand([0, 0, 0], SKY_BAND.day);
|
|
||||||
const shown = displayedLuminance(grey, 'low');
|
|
||||||
expect(shown).toBeGreaterThanOrEqual(0.2983);
|
|
||||||
expect(shown).toBeLessThan(SKY_BAND.day.floor);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('decode hex as linear light', () => {
|
|
||||||
expect(hexToLinear('#ffffff')).toEqual([1, 1, 1]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the GLSL twin', () => {
|
|
||||||
it('shapes with the same arithmetic: clamp, luma weights, mix to the floor, scale to the ceiling', () => {
|
|
||||||
expect(SHAPE_SKY_GLSL).toContain('c = clamp(c, 0.0, 1.0);');
|
|
||||||
expect(SHAPE_SKY_GLSL).toContain('const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);');
|
|
||||||
expect(SHAPE_SKY_GLSL).toContain(
|
|
||||||
'if (l < uBand.x) return mix(c, uLift, (uBand.x - l) / (dot(uLift, LUMA) - l));'
|
|
||||||
);
|
|
||||||
expect(SHAPE_SKY_GLSL).toContain('if (l > uBand.y) return c * (uBand.y / l);');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('is applied to the sky colour in both shaders that draw it, the sky pass and the haze that fades into it', () => {
|
|
||||||
[SKY_FRAG, GRID_FRAG].forEach((src) => {
|
|
||||||
expect(src).toContain(SHAPE_SKY_GLSL);
|
|
||||||
expect(src).toMatch(/return shapeSky\(1\.0 - exp\(-45\.0 \* skyScatter\(d\)\)/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,90 +0,0 @@
|
||||||
// The luminance band each fixed sky state's drawn sky is shaped into, so the state's theme ink
|
|
||||||
// clears 4.5:1 on bare sky (WCAG relative luminance, the `luminance` of src/sky/skyTokens.js).
|
|
||||||
//
|
|
||||||
// day Noonday Sky's dark text ink #342d25 (L 0.0274) needs a backdrop of at least 0.2983.
|
|
||||||
// The floor is that text bound (0.30 as drawn); there is no ceiling, dark ink on light is fine.
|
|
||||||
// dusk The same ink, and its link #2a4f27 (L 0.0623), which needs a backdrop of at least 0.4554. The floor is
|
|
||||||
// the link bound (0.4744 as drawn), so text clears 4.5:1 with room (6.6) and the link clears too.
|
|
||||||
// night Midnight Sky's light text ink #aeccff (L 0.594) needs a backdrop of at most 0.0931.
|
|
||||||
// The baked night sky (0.058 to 0.077) is kept; the ceiling is the bound.
|
|
||||||
//
|
|
||||||
// Night's link ink is not part of the band: see skyTheme.ts.
|
|
||||||
//
|
|
||||||
// The terrain sky is a physical scatter function, so it is shaped downstream, on its final colour:
|
|
||||||
// `shapeToBand` here, and its GLSL twin (`SHAPE_SKY_GLSL`) in terrain/terrainShaders.ts, built from the
|
|
||||||
// same constants. The ridge sky is a three-stop gradient whose stops are chosen inside the band
|
|
||||||
// (ridge/skyColour.ts, skyForState.ts), and its test sweeps the blends.
|
|
||||||
export type FixedSkyState = 'day' | 'dusk' | 'night';
|
|
||||||
export type Linear = readonly [number, number, number];
|
|
||||||
|
|
||||||
/** WCAG luma weights, applied to linear RGB. */
|
|
||||||
export const LUMA: Linear = [0.2126, 0.7152, 0.0722];
|
|
||||||
export const luma = (c: Linear): number => LUMA[0] * c[0] + LUMA[1] * c[1] + LUMA[2] * c[2];
|
|
||||||
|
|
||||||
/** sRGB hex `#rrggbb` to linear RGB 0..1. */
|
|
||||||
export function hexToLinear(hex: string): Linear {
|
|
||||||
const ch = (at: number) => {
|
|
||||||
const s = parseInt(hex.slice(at, at + 2), 16) / 255;
|
|
||||||
return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
||||||
};
|
|
||||||
return [ch(1), ch(3), ch(5)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** How a displayed colour is read: as encoded, or moved one 8-bit step down or up in every channel ('low', 'high'). */
|
|
||||||
export type Reading = 'exact' | 'low' | 'high';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Relative luminance of what the terrain shaders put on screen for a linear colour: they encode with
|
|
||||||
* pow(1/2.2), not the sRGB curve, so the screen colour is read back through the sRGB curve. 'low' and 'high' move every
|
|
||||||
* encoded channel one 8-bit step down or up first: rounding to 8 bits (half a step) plus the sky pass's dither (half a
|
|
||||||
* step) cannot move a channel further, so they bound what the screen shows. A smooth bound, so a search can climb it.
|
|
||||||
*/
|
|
||||||
export function displayedLuminance(c: Linear, reading: Reading = 'exact'): number {
|
|
||||||
const shift = { exact: 0, low: -1 / 255, high: 1 / 255 }[reading];
|
|
||||||
const ch = (v: number) => {
|
|
||||||
const e = Math.min(1, Math.max(0, Math.min(1, Math.max(0, v)) ** (1 / 2.2) + shift));
|
|
||||||
return e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** 2.4;
|
|
||||||
};
|
|
||||||
return luma([ch(c[0]), ch(c[1]), ch(c[2])]);
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SkyBand {
|
|
||||||
/** Linear luma the shaped colour is at least (0: no floor). */
|
|
||||||
floor: number;
|
|
||||||
/** Linear luma the shaped colour is at most (1: no ceiling). */
|
|
||||||
ceiling: number;
|
|
||||||
/** The colour a too-dark sky is mixed toward: the state's own tint, so the hue survives the lift. Its luma is above `floor`. */
|
|
||||||
lift: Linear;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The shaping targets, in linear luma. Day's floor sits 0.019 above the text bound (0.2983), Dusk's 0.019 above the link
|
|
||||||
* bound (0.4554), which skyForState.test.ts derives from the ink and ties to these: the screen encoding is
|
|
||||||
* gamma 2.2, which reads about 0.006 darker through the sRGB curve at this level, and 8-bit rounding with the sky
|
|
||||||
* pass's dither at its worst (one step in every channel) takes about 0.007 more. The night ceiling is lower than the text bound
|
|
||||||
* (0.0931) by more than that: 0.077394 is the luma at which one step up reads 0.08164, the lightest the baked night sky shows
|
|
||||||
* (skyState.ts), so a sky the page URL steers at night, scaled down to the ceiling, cannot show lighter than the baked one.
|
|
||||||
*/
|
|
||||||
export const SKY_BAND: Record<FixedSkyState, SkyBand> = {
|
|
||||||
day: { floor: 0.317, ceiling: 1, lift: hexToLinear('#e2f4ff') },
|
|
||||||
// Dusk lifts toward Day's pale blue rather than a rose: mixing a third of the sky toward rose washed the twilight pink, and
|
|
||||||
// a rose lighter than the floor shifts hues by 47 to 72 degrees where Day's tint shifts them by 18 (measured, PR body).
|
|
||||||
dusk: { floor: 0.4744, ceiling: 1, lift: hexToLinear('#e2f4ff') },
|
|
||||||
night: { floor: 0, ceiling: 0.077394, lift: hexToLinear('#5a6a9a') },
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shape a linear sky colour into the band. Below the floor it mixes toward `lift` by exactly the amount
|
|
||||||
* that lands on the floor (continuous at the floor, hue kept); above the ceiling it scales down to the
|
|
||||||
* ceiling. The colour is clamped to 0..1 first, as the screen does.
|
|
||||||
*/
|
|
||||||
export function shapeToBand(c: Linear, band: SkyBand): Linear {
|
|
||||||
const k = [0, 1, 2].map((i) => Math.min(1, Math.max(0, c[i]))) as unknown as Linear;
|
|
||||||
const l = luma(k);
|
|
||||||
if (l < band.floor) {
|
|
||||||
const t = (band.floor - l) / (luma(band.lift) - l);
|
|
||||||
return [0, 1, 2].map((i) => k[i] + (band.lift[i] - k[i]) * t) as unknown as Linear;
|
|
||||||
}
|
|
||||||
if (l > band.ceiling) return [0, 1, 2].map((i) => (k[i] * band.ceiling) / l) as unknown as Linear;
|
|
||||||
return k;
|
|
||||||
}
|
|
||||||
|
|
@ -1,87 +1,22 @@
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
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 { atStandardTime } from './standardTime.testkit';
|
||||||
import { baked } from '../../../sky/baked';
|
import { ridgeDrawn, ridgeSkyFor, ridgeSkyKey, loadWeather } from './skyForState';
|
||||||
import { AA, luminance } from '../../../sky/skyTokens.js';
|
import { DAY_FROM, setSkyClock } from './skyState';
|
||||||
import { skyColours } from './ridge/skyColour';
|
import { BUDGET } from './ridge/toneMap';
|
||||||
import { chooseSky, skyColour } from './terrain/terrainSky';
|
|
||||||
import {
|
|
||||||
DUSK_SUN_ELEVATION,
|
|
||||||
TERRAIN_REACH_DEG,
|
|
||||||
ridgeDrawn,
|
|
||||||
ridgeSkyFor,
|
|
||||||
ridgeSkyKey,
|
|
||||||
terrainDrawn,
|
|
||||||
terrainSkyFor,
|
|
||||||
} from './skyForState';
|
|
||||||
import { displayedLuminance, luma, shapeToBand, SKY_BAND } from './skyBand';
|
|
||||||
import type { FixedSkyState } from './skyBand';
|
|
||||||
import { DAY_FROM, setSkyClock, skyBackdrop } from './skyState';
|
|
||||||
import { view } from './terrain/terrainWorld';
|
|
||||||
import { skyThemeId } from './skyTheme';
|
|
||||||
|
|
||||||
const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`;
|
|
||||||
const EPS = 1e-9;
|
|
||||||
const STATES = ['day', 'dusk', 'night'] as const;
|
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 };
|
|
||||||
};
|
|
||||||
|
|
||||||
let search = '';
|
|
||||||
beforeEach(() => {
|
|
||||||
search = '';
|
|
||||||
vi.stubGlobal('window', {
|
|
||||||
get location() {
|
|
||||||
return { search };
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
setSkyClock();
|
setSkyClock();
|
||||||
vi.unstubAllGlobals();
|
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);
|
|
||||||
});
|
|
||||||
|
|
||||||
// The drawn floor and the lift are tied to those bounds, not to themselves: nudge either constant and this fails.
|
|
||||||
it('give Dusk a floor 0.019 above the link bound (as Day has above the text bound) and a lift Day shares', () => {
|
|
||||||
expect(SKY_BAND.dusk.floor).toBeCloseTo(needs('dusk').floor + 0.019, 4);
|
|
||||||
expect(SKY_BAND.day.floor).toBeCloseTo(needs('day').floor + 0.019, 3);
|
|
||||||
expect(SKY_BAND.dusk.lift).toEqual(SKY_BAND.day.lift);
|
|
||||||
expect(luma(SKY_BAND.dusk.lift)).toBeGreaterThan(SKY_BAND.dusk.floor);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(['day', 'dusk'] as const)(
|
|
||||||
'%s: the darkest the shaping can show reads at the bound and under the floor',
|
|
||||||
(state) => {
|
|
||||||
const shown = displayedLuminance(shapeToBand([0, 0, 0], SKY_BAND[state]), 'low');
|
|
||||||
expect(shown).toBeGreaterThanOrEqual(needs(state).floor);
|
|
||||||
expect(shown).toBeLessThan(SKY_BAND[state].floor);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('ridgeSkyFor', () => {
|
describe('ridgeSkyFor', () => {
|
||||||
it('carries the state band, which the layers are shaped into, and the physical sky of that state', () => {
|
it('carries the physical sky of the state', () => {
|
||||||
for (const state of STATES) {
|
for (const state of STATES) {
|
||||||
const sky = ridgeSkyFor(state, 0.3);
|
const sky = ridgeSkyFor(state, FALLBACK_VIEW, 0.3);
|
||||||
expect(sky.band).toEqual(SKY_BAND[state]);
|
|
||||||
expect(sky.physical?.state).toBe(state);
|
expect(sky.physical?.state).toBe(state);
|
||||||
expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
|
expect(sky.physical?.stops).toEqual({ top: sky.top, mid: sky.mid, horizon: sky.horizon });
|
||||||
}
|
}
|
||||||
|
|
@ -92,282 +27,80 @@ describe('ridgeSkyFor', () => {
|
||||||
s.top,
|
s.top,
|
||||||
s.mid,
|
s.mid,
|
||||||
s.horizon,
|
s.horizon,
|
||||||
s.band,
|
|
||||||
s.physical?.sun,
|
s.physical?.sun,
|
||||||
];
|
];
|
||||||
setSkyClock(() => atStandardTime(12, 0));
|
setSkyClock(() => atStandardTime(12, 0));
|
||||||
expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('day', 0.3)));
|
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('day', FALLBACK_VIEW, 0.3)));
|
||||||
setSkyClock(() => atStandardTime(0, 0));
|
setSkyClock(() => atStandardTime(0, 0));
|
||||||
expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('night', 0.3)));
|
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('night', FALLBACK_VIEW, 0.3)));
|
||||||
setSkyClock(() => atStandardTime(18, 10));
|
setSkyClock(() => atStandardTime(18, 10));
|
||||||
expect(key(ridgeSkyFor('auto', 0.3))).toEqual(key(ridgeSkyFor('dusk', 0.3)));
|
expect(key(ridgeSkyFor('auto', FALLBACK_VIEW, 0.3))).toEqual(key(ridgeSkyFor('dusk', FALLBACK_VIEW, 0.3)));
|
||||||
});
|
});
|
||||||
|
|
||||||
it("is lit from the real sun over Vienna: a forced state's sun is inside the state, the clear noon sky is blue", () => {
|
it("is lit from the real sun over Vienna: a forced state's sun is inside the state, the clear noon sky is blue", () => {
|
||||||
const day = ridgeSkyFor('day', 0);
|
const day = ridgeSkyFor('day', FALLBACK_VIEW, 0);
|
||||||
expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM);
|
expect(day.physical?.sun.elevation).toBeGreaterThanOrEqual(DAY_FROM);
|
||||||
expect(day.top[2]).toBeGreaterThan(day.top[0]);
|
expect(day.top[2]).toBeGreaterThan(day.top[0]);
|
||||||
const dusk = ridgeSkyFor('dusk', 0);
|
const dusk = ridgeSkyFor('dusk', FALLBACK_VIEW, 0);
|
||||||
expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
|
expect(Math.abs(dusk.physical?.sun.elevation ?? 99)).toBeLessThanOrEqual(DAY_FROM);
|
||||||
expect(ridgeSkyFor('night', 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
|
expect(ridgeSkyFor('night', FALLBACK_VIEW, 0).physical?.sun.elevation).toBeLessThanOrEqual(-DAY_FROM);
|
||||||
expect(day.ground).toEqual(skyColours().ground);
|
});
|
||||||
|
|
||||||
|
it("is made over the View's place: the sun and the observer are the View's", () => {
|
||||||
|
const sky = ridgeSkyFor('day', ELSEWHERE_VIEW, 0);
|
||||||
|
expect(sky.physical?.view).toBe(ELSEWHERE_VIEW);
|
||||||
|
expect(sky.physical?.atm.observerKm).toBe(ELSEWHERE_VIEW.place.altitudeKm);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keys a rebuild by the View's place as well: another place is another key", () => {
|
||||||
|
const other = { ...FALLBACK_VIEW, place: { ...FALLBACK_VIEW.place, id: 'graz' } };
|
||||||
|
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', other, 0.3));
|
||||||
|
expect(ridgeSkyKey('day', other, 0.3)).toContain('graz');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keys a rebuild by state and weather, not by the moving sun', () => {
|
it('keys a rebuild by state and weather, not by the moving sun', () => {
|
||||||
setSkyClock(() => atStandardTime(12, 0));
|
setSkyClock(() => atStandardTime(12, 0));
|
||||||
expect(ridgeSkyKey('auto', 0.3)).toBe(ridgeSkyKey('day', 0.3));
|
expect(ridgeSkyKey('auto', FALLBACK_VIEW, 0.3)).toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.3));
|
||||||
expect(ridgeSkyKey('day', 0.3)).not.toBe(ridgeSkyKey('day', 0.8));
|
expect(ridgeSkyKey('day', FALLBACK_VIEW, 0.3)).not.toBe(ridgeSkyKey('day', FALLBACK_VIEW, 0.8));
|
||||||
expect(ridgeSkyKey('day', 0.3)).not.toBe(ridgeSkyKey('night', 0.3));
|
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) => {
|
// Each state's ceiling is its budget's (night's is a tunable, NIGHT_CEILING: the operator tunes it by eye).
|
||||||
const { floor, ceiling } = needs(state);
|
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);
|
const r = ridgeDrawn(state);
|
||||||
expect(r.darkest).toBeGreaterThanOrEqual(floor);
|
expect(r.darkest).toBe(BUDGET[state].floor);
|
||||||
expect(r.lightest).toBeLessThanOrEqual(ceiling);
|
expect(r.lightest).toBeLessThanOrEqual(BUDGET[state].ceiling);
|
||||||
const fit = ridgeSkyFor(state, 0.3).physical?.fit;
|
const fit = ridgeSkyFor(state, FALLBACK_VIEW, 0.3).physical?.fit;
|
||||||
expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9);
|
expect(fit?.lo).toBeGreaterThanOrEqual(r.darkest - 1e-9);
|
||||||
expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9);
|
expect(fit?.hi).toBeLessThanOrEqual(r.lightest + 1e-9);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Not the generator's grid: a golden-angle spiral over the upper sphere (no shared rows or columns)
|
describe('loadWeather', () => {
|
||||||
// plus a 0.05 degree grid across the sun, five times finer than the generator's.
|
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 dirAt = (el: number, az: number): [number, number, number] => {
|
const fetched = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
|
||||||
const rad = Math.PI / 180;
|
vi.stubGlobal('fetch', fetched);
|
||||||
return [
|
const t = new Date('2030-01-01T00:00:00Z');
|
||||||
Math.cos(el * rad) * Math.sin(az * rad),
|
await loadWeather('/w.json', FALLBACK_VIEW.place, t);
|
||||||
Math.sin(el * rad),
|
await loadWeather('/w.json', FALLBACK_VIEW.place, new Date(t.getTime() + 60_000));
|
||||||
-Math.cos(el * rad) * Math.cos(az * rad),
|
expect(fetched).toHaveBeenCalledTimes(1);
|
||||||
];
|
await loadWeather('/w.json', ELSEWHERE_VIEW.place, new Date(t.getTime() + 120_000));
|
||||||
};
|
expect(fetched).toHaveBeenCalledTimes(2);
|
||||||
/** Over the sweep: the darkest the 8-bit screen can show (dither at its worst), the lightest, and the darkest as encoded. */
|
vi.unstubAllGlobals();
|
||||||
const sweepOf = (sky: ReturnType<typeof chooseSky>, N = 4000, maxEl = TERRAIN_REACH_DEG) => {
|
|
||||||
const rad = Math.PI / 180;
|
|
||||||
const out = { low: Infinity, high: -Infinity, exactMin: Infinity };
|
|
||||||
const see = (el: number, az: number) => {
|
|
||||||
const c = skyColour(sky, dirAt(el, az));
|
|
||||||
out.low = Math.min(out.low, displayedLuminance(c, 'low'));
|
|
||||||
out.high = Math.max(out.high, displayedLuminance(c, 'high'));
|
|
||||||
out.exactMin = Math.min(out.exactMin, displayedLuminance(c));
|
|
||||||
};
|
|
||||||
for (let i = 0; i < N; i += 1) {
|
|
||||||
const y = ((i + 0.5) / N) * Math.sin(maxEl * rad); // sin(elevation): uniform from the horizon to maxEl
|
|
||||||
see(Math.asin(y) / rad, (i * 137.50776405) % 360);
|
|
||||||
}
|
|
||||||
for (let dEl = -3; dEl <= 3; dEl += 0.05) {
|
|
||||||
for (let dAz = -3; dAz <= 3; dAz += 0.05) {
|
|
||||||
see(Math.min(maxEl, Math.max(0, sky.elevation + dEl)), sky.azimuth + dAz);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('the terrain camera reach', () => {
|
|
||||||
it('covers the highest ray the frozen camera sees, at any aspect, with a small margin', () => {
|
|
||||||
const tanHalf = Math.tan((55 * Math.PI) / 360);
|
|
||||||
const tops = [0.4, 0.5, 1, 16 / 9, 2.4].flatMap((aspect) =>
|
|
||||||
[0, 0.125, 0.25, 0.5, 0.75].flatMap((turns) => {
|
|
||||||
const v = view(aspect, turns);
|
|
||||||
return [-1, 0, 1].map((nx) => {
|
|
||||||
const d = [0, 1, 2].map(
|
|
||||||
(i) => v.forward[i] + nx * tanHalf * aspect * v.right[i] + tanHalf * v.up[i]
|
|
||||||
);
|
|
||||||
return (Math.asin(d[1] / Math.hypot(d[0], d[1], d[2])) * 180) / Math.PI;
|
|
||||||
});
|
|
||||||
})
|
|
||||||
);
|
|
||||||
const top = Math.max(...tops);
|
|
||||||
expect(top).toBeCloseTo(14.5, 1);
|
|
||||||
expect(TERRAIN_REACH_DEG).toBeGreaterThanOrEqual(top);
|
|
||||||
expect(TERRAIN_REACH_DEG - top).toBeLessThan(2);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('terrainSkyFor', () => {
|
describe('the rebuild key and the constellation lines', () => {
|
||||||
it('draws the sky auto resolves to, with that state band', () => {
|
it('carries the lines at night only: toggling them is a different sky, a day sky is the same', async () => {
|
||||||
setSkyClock(() => atStandardTime(12, 0));
|
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => undefined });
|
||||||
expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('day'));
|
vi.resetModules();
|
||||||
setSkyClock(() => atStandardTime(0, 0));
|
const st = await import('./skyState');
|
||||||
expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('night'));
|
const f = await import('./skyForState');
|
||||||
});
|
const off = f.ridgeSkyKey('night', FALLBACK_VIEW, 0);
|
||||||
|
const dayOff = f.ridgeSkyKey('day', FALLBACK_VIEW, 0);
|
||||||
it('lets the page URL steer auto, shaped into the band of the state the clock resolves to', () => {
|
st.pickSkyState('night');
|
||||||
setSkyClock(() => atStandardTime(0, 0)); // night
|
st.pickSkyState('night');
|
||||||
search = '?sun=30&az=120';
|
expect(f.ridgeSkyKey('night', FALLBACK_VIEW, 0)).toBe(`${off}:lines`);
|
||||||
expect(terrainSkyFor('auto')).toEqual({
|
expect(f.ridgeSkyKey('day', FALLBACK_VIEW, 0)).toBe(dayOff);
|
||||||
sun: { elevation: 30, azimuth: 120 },
|
|
||||||
band: SKY_BAND.night,
|
|
||||||
});
|
|
||||||
search = '?sky=noonday';
|
|
||||||
expect(terrainSkyFor('auto')).toEqual({ sky: 'noonday', band: SKY_BAND.night });
|
|
||||||
search = '?sky=garbage';
|
|
||||||
expect(terrainSkyFor('auto')).toEqual(terrainSkyFor('night'));
|
|
||||||
setSkyClock(() => atStandardTime(18, 10)); // dusk, URL azimuth honoured
|
|
||||||
search = '?sun=2&az=250';
|
|
||||||
expect(terrainSkyFor('auto').sun).toEqual({ elevation: 2, azimuth: 250 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps a URL-chosen sun inside the band of the resolved state', () => {
|
|
||||||
setSkyClock(() => atStandardTime(12, 0)); // day: floor
|
|
||||||
search = '?sun=-30';
|
|
||||||
const day = sweepOf(chooseSky(terrainSkyFor('auto')));
|
|
||||||
expect(day.low).toBeGreaterThanOrEqual(needs('day').floor);
|
|
||||||
setSkyClock(() => atStandardTime(0, 0)); // night: ceiling
|
|
||||||
search = '?sun=60';
|
|
||||||
const night = sweepOf(chooseSky(terrainSkyFor('auto')));
|
|
||||||
expect(night.high).toBeLessThanOrEqual(needs('night').ceiling);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('keeps a URL-steered sky at night no lighter than the Night backdrop the text was checked against', () => {
|
|
||||||
setSkyClock(() => atStandardTime(0, 0));
|
|
||||||
['?sun=60', '?sun=10&az=40', '?sun=2&az=250', '?sky=noonday'].forEach((q) => {
|
|
||||||
search = q;
|
|
||||||
expect(terrainDrawn('auto').lightest).toBeLessThanOrEqual(skyBackdrop('night').lightest);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('lets an explicit state beat the URL, as before auto had one', () => {
|
|
||||||
search = '?sun=30&az=120&sky=midnight';
|
|
||||||
expect(terrainSkyFor('day')).toEqual({ sky: 'noonday', band: SKY_BAND.day });
|
|
||||||
expect(terrainSkyFor('dusk').sun).toEqual({ elevation: DUSK_SUN_ELEVATION });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('names the baked sky for day and night, and a low sun for dusk, each with its band', () => {
|
|
||||||
expect(terrainSkyFor('day')).toEqual({ sky: 'noonday', band: SKY_BAND.day });
|
|
||||||
expect(terrainSkyFor('night')).toEqual({ sky: 'midnight', band: SKY_BAND.night });
|
|
||||||
expect(terrainSkyFor('dusk')).toEqual({
|
|
||||||
sun: { elevation: DUSK_SUN_ELEVATION },
|
|
||||||
band: SKY_BAND.dusk,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the terrain sky lies in the band its text ink needs', () => {
|
|
||||||
const sweep = (state: FixedSkyState) => sweepOf(chooseSky(terrainSkyFor(state)));
|
|
||||||
|
|
||||||
it('dusk needs its lift: the scatter sky alone dips below the text bound within the reach', () => {
|
|
||||||
const { sun } = terrainSkyFor('dusk');
|
|
||||||
expect(sweepOf(chooseSky({ sun })).exactMin).toBeLessThan(needs('dusk').floor - 0.02);
|
|
||||||
expect(sweep('dusk').low).toBeGreaterThanOrEqual(needs('dusk').floor);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(STATES)('%s', (state) => {
|
|
||||||
const { floor, ceiling } = needs(state);
|
|
||||||
const l = sweep(state);
|
|
||||||
expect(l.low).toBeGreaterThanOrEqual(floor);
|
|
||||||
expect(l.high).toBeLessThanOrEqual(ceiling);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(STATES)('%s holds for a sun at any elevation, as ?sun= can put it', (state) => {
|
|
||||||
const { floor, ceiling } = needs(state);
|
|
||||||
for (let e = -90; e <= 90; e += 10) {
|
|
||||||
const l = sweepOf(chooseSky({ sun: { elevation: e }, band: SKY_BAND[state] }), 4000, 90);
|
|
||||||
expect(l.low).toBeGreaterThanOrEqual(floor);
|
|
||||||
expect(l.high).toBeLessThanOrEqual(ceiling);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it('and the terrain dusk still reaches the sun glow the ridge dusk does not', () => {
|
|
||||||
expect(skyBackdrop('dusk').lightest).toBeGreaterThan(0.9);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('skyBackdrop holds the union of what the scenes draw', () => {
|
|
||||||
// An independent extremum of the screen reading ('low' for the darkest, 'high' for the lightest: one 8-bit step each way) over the terrain camera's reach: not terrainDrawn's grid and compass search but alternating golden-section
|
|
||||||
// line searches in elevation and azimuth from 60 starts (a golden-angle spiral and scatter about the sun), the bracket
|
|
||||||
// shrinking to 1e-3 degrees. A plateau (the shader clamps) cannot stall it: each line search always
|
|
||||||
// moves to the better end of its bracket.
|
|
||||||
const extremes = (state: FixedSkyState) => {
|
|
||||||
const sky = chooseSky(terrainSkyFor(state));
|
|
||||||
const rad = Math.PI / 180;
|
|
||||||
const f = (el: number, az: number, reading: 'low' | 'high') => {
|
|
||||||
const e = Math.min(TERRAIN_REACH_DEG, Math.max(0, el)) * rad;
|
|
||||||
const a = az * rad;
|
|
||||||
return displayedLuminance(
|
|
||||||
skyColour(sky, [Math.cos(e) * Math.sin(a), Math.sin(e), -Math.cos(e) * Math.cos(a)]),
|
|
||||||
reading
|
|
||||||
);
|
|
||||||
};
|
|
||||||
const P = 0.6180339887;
|
|
||||||
const line = (g: (x: number) => number, mid: number, w: number) => {
|
|
||||||
let a = mid - w;
|
|
||||||
let b = mid + w;
|
|
||||||
for (let k = 0; k < 40; k += 1) {
|
|
||||||
const c = b - P * (b - a);
|
|
||||||
const d = a + P * (b - a);
|
|
||||||
if (g(c) > g(d)) b = d;
|
|
||||||
else a = c;
|
|
||||||
}
|
|
||||||
return (a + b) / 2;
|
|
||||||
};
|
|
||||||
const hunt = (sign: 1 | -1) => {
|
|
||||||
const reading = sign === 1 ? 'high' : 'low';
|
|
||||||
let best = -Infinity;
|
|
||||||
for (let i = 0; i < 60; i += 1) {
|
|
||||||
let el =
|
|
||||||
i % 2
|
|
||||||
? sky.elevation + (((i * 7919) % 1600) - 800) / 100
|
|
||||||
: Math.asin(((i + 0.5) / 60) * Math.sin(TERRAIN_REACH_DEG * rad)) / rad;
|
|
||||||
let az =
|
|
||||||
i % 2 ? sky.azimuth + (((i * 104729) % 1600) - 800) / 100 : (i * 137.50776405) % 360;
|
|
||||||
for (let w = 8; w > 1e-3; w /= 2) {
|
|
||||||
const [el0, az0] = [el, az];
|
|
||||||
el = line((x) => sign * f(Math.max(0, x), az0, reading), el0, w);
|
|
||||||
const el1 = el;
|
|
||||||
az = line((x) => sign * f(el1, x, reading), az0, w);
|
|
||||||
best = Math.max(best, sign * f(el, az, reading));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return sign * best;
|
|
||||||
};
|
|
||||||
return { darkest: hunt(-1), lightest: hunt(1) };
|
|
||||||
};
|
|
||||||
|
|
||||||
// At night a sky the page URL steers (?sun= ?sky=) is shaped to the band's ceiling, so the lightest it can show is one
|
|
||||||
// 8-bit step above the ceiling's own grey: the Night constant must cover it too, or text is checked against a sky
|
|
||||||
// lighter than the one it sits on.
|
|
||||||
const steeredNight = displayedLuminance(
|
|
||||||
[SKY_BAND.night.ceiling, SKY_BAND.night.ceiling, SKY_BAND.night.ceiling],
|
|
||||||
'high'
|
|
||||||
);
|
|
||||||
|
|
||||||
const computed = (state: FixedSkyState) => {
|
|
||||||
const r = [ridgeDrawn(state), terrainDrawn(state)];
|
|
||||||
const ind = extremes(state);
|
|
||||||
return {
|
|
||||||
darkest: Math.min(...r.map((x) => x.darkest), ind.darkest),
|
|
||||||
lightest: Math.max(
|
|
||||||
...r.map((x) => x.lightest),
|
|
||||||
ind.lightest,
|
|
||||||
...(state === 'night' ? [steeredNight] : [])
|
|
||||||
),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// The constants are the swept extremes rounded outward to six places, so each lies in [extreme, extreme + 1e-6):
|
|
||||||
// a constant 1e-6 low is under the extreme, one 2e-5 high is over the bound. SEARCH is the searches' own error.
|
|
||||||
const SEARCH = 1e-8;
|
|
||||||
it.each(STATES)(
|
|
||||||
'%s: the constant is the swept extreme rounded outward, within 1e-6 above it',
|
|
||||||
(state) => {
|
|
||||||
const c = computed(state);
|
|
||||||
const b = skyBackdrop(state);
|
|
||||||
expect(b.darkest).toBeLessThanOrEqual(c.darkest);
|
|
||||||
expect(b.lightest).toBeGreaterThanOrEqual(c.lightest);
|
|
||||||
expect(c.darkest - b.darkest).toBeLessThan(1e-6 + SEARCH);
|
|
||||||
expect(b.lightest - c.lightest).toBeLessThan(1e-6 + SEARCH);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
it.each(STATES)('%s: an independent sweep, no looser than 5e-4 from the constant', (state) => {
|
|
||||||
// The sweep is not the generator's grid (see above), so it cannot share its blind spots.
|
|
||||||
const l = sweepOf(chooseSky(terrainSkyFor(state)), 20000);
|
|
||||||
const b = skyBackdrop(state);
|
|
||||||
const r = ridgeDrawn(state);
|
|
||||||
expect(l.low).toBeGreaterThanOrEqual(b.darkest - EPS);
|
|
||||||
expect(l.high).toBeLessThanOrEqual(b.lightest + EPS);
|
|
||||||
expect(b.lightest - Math.max(l.high, r.lightest)).toBeLessThan(5e-4);
|
|
||||||
expect(Math.min(l.low, r.darkest) - b.darkest).toBeLessThan(5e-4);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,96 +1,62 @@
|
||||||
// What each scene is told for a sky state. 'auto' is a choice, not a sky: both functions draw the sky it
|
// 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 every scene paints one of day, dusk or night. Each is drawn
|
// resolves to (`resolveSkyState`, the clock), so the scene paints one of day, dusk or night, fitted to that
|
||||||
// inside that state's luminance band (skyBand.ts): the ridge sky from gradients whose stops and blends lie in
|
// state's luminance budget (ridge/toneMap.ts).
|
||||||
// it, the terrain sky shaped into it downstream of the scatter function. `skyBackdrop` bounds what comes out,
|
import type { SkyColours } from './ridge/skyColour';
|
||||||
// and the login text was checked against that bound.
|
|
||||||
import { baked } from '../../../sky/baked';
|
|
||||||
import { chooseSky, skyColour, urlSky } from './terrain/terrainSky';
|
|
||||||
import type { SkyName } from './terrain/terrainSky';
|
|
||||||
import type { SkyColours, Srgb } from './ridge/skyColour';
|
|
||||||
import { skyColours } from './ridge/skyColour';
|
|
||||||
import { makePhysicalSky } from './ridge/physicalSky';
|
import { makePhysicalSky } from './ridge/physicalSky';
|
||||||
|
import type { Place, View } from './ridge/view';
|
||||||
import { BUDGET } from './ridge/toneMap';
|
import { BUDGET } from './ridge/toneMap';
|
||||||
import { ridgeWeather, setFedWeather } from './ridge/weather';
|
import { ridgeWeather, setFedWeather } from './ridge/weather';
|
||||||
import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed';
|
import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed';
|
||||||
import { resolveSkyState, skyNow } from './skyState';
|
import { getConstellationLines, resolveSkyState, skyNow } from './skyState';
|
||||||
import type { SkyState } from './skyState';
|
import type { SkyState } from './skyState';
|
||||||
import { displayedLuminance, SKY_BAND } from './skyBand';
|
|
||||||
import type { SkyBand } from './skyBand';
|
|
||||||
import { luminance } from '../../../sky/skyTokens.js';
|
|
||||||
import { CAMERA } from './terrain/terrainWorld';
|
|
||||||
|
|
||||||
/** Sun elevation in degrees for the terrain's dusk: just above the horizon, between the two bakes (as `?sun=` puts it). */
|
|
||||||
export const DUSK_SUN_ELEVATION = 2;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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.
|
* 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 = (
|
export const ridgeSkyKey = (
|
||||||
state: SkyState,
|
state: SkyState,
|
||||||
|
view: View,
|
||||||
weather: number = ridgeWeather(),
|
weather: number = ridgeWeather(),
|
||||||
now: Date = skyNow()
|
now: Date = skyNow()
|
||||||
): string => `ridge:${resolveSkyState(state, now)}:${weather}`;
|
): string => {
|
||||||
|
const fixed = resolveSkyState(state, now);
|
||||||
|
return `ridge:${fixed}:${weather}:${view.place.id}${fixed === 'night' && getConstellationLines() ? ':lines' : ''}`;
|
||||||
|
};
|
||||||
|
|
||||||
const WEATHER_REFRESH_MS = 10 * 60_000;
|
const WEATHER_REFRESH_MS = 10 * 60_000;
|
||||||
let weatherAt = -Infinity;
|
let weatherAt = -Infinity;
|
||||||
|
let weatherPlace = '';
|
||||||
/**
|
/**
|
||||||
* Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes.
|
* Read `weather.json` (the page's own, next to config.json) into the weather the ridge sky is drawn for; at most once in ten minutes.
|
||||||
* Never throws: a missing, stale or broken file is a clear sky (`currentWeather`).
|
* Never throws: a missing, stale or broken file is a clear sky (`currentWeather`).
|
||||||
*/
|
*/
|
||||||
export async function loadWeather(url: string, now: Date = skyNow()): Promise<void> {
|
export async function loadWeather(url: string, place: Place, now: Date = skyNow()): Promise<void> {
|
||||||
if (now.getTime() - weatherAt < WEATHER_REFRESH_MS) return;
|
if (place.id === weatherPlace && now.getTime() - weatherAt < WEATHER_REFRESH_MS) return;
|
||||||
weatherAt = now.getTime();
|
weatherAt = now.getTime();
|
||||||
setFedWeather(currentWeather(await fetchWeatherFile(url), now));
|
weatherPlace = place.id;
|
||||||
|
setFedWeather(currentWeather(await fetchWeatherFile(url), place, now));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The ridge scene's `sky` option: the physical sky over Vienna for the state ('auto': the real sun now; a forced state: the
|
* The ridge scene's `sky` option: the physical sky over the View's place for the state ('auto': the real sun now; a forced state: the
|
||||||
* sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas
|
* sun of today at a moment inside it, `sunForState`), as a palette for the layers and stars plus the `physical` sky the host canvas
|
||||||
* is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms).
|
* is painted from. The atmosphere LUTs are baked here, once per scene start (tens of ms).
|
||||||
*/
|
*/
|
||||||
export function ridgeSkyFor(
|
export function ridgeSkyFor(
|
||||||
state: SkyState,
|
state: SkyState,
|
||||||
|
view: View,
|
||||||
weather: number = ridgeWeather(),
|
weather: number = ridgeWeather(),
|
||||||
now: Date = skyNow()
|
now: Date = skyNow()
|
||||||
): SkyColours {
|
): SkyColours {
|
||||||
const { ground } = skyColours();
|
|
||||||
const fixed = resolveSkyState(state, now);
|
const fixed = resolveSkyState(state, now);
|
||||||
const physical = makePhysicalSky(fixed, now, weather);
|
const physical = makePhysicalSky(fixed, now, weather, view);
|
||||||
return {
|
return {
|
||||||
...physical.stops,
|
...physical.stops,
|
||||||
ground,
|
|
||||||
band: SKY_BAND[fixed],
|
|
||||||
physical,
|
physical,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The terrain scene's `sky`, `sun` and `band` options. An explicit state draws its own sky and ignores the URL. 'auto'
|
|
||||||
* draws the sky it resolves to, unless the page URL steers (`?sun=` `?az=` `?sky=`, see `urlSky`): then the URL's sky,
|
|
||||||
* shaped into the band of the state the clock resolves to, which keeps any sun the URL picks inside that band.
|
|
||||||
*/
|
|
||||||
export function terrainSkyFor(state: SkyState): {
|
|
||||||
sky?: SkyName;
|
|
||||||
sun?: { elevation: number; azimuth?: number };
|
|
||||||
band: SkyBand;
|
|
||||||
} {
|
|
||||||
const fixed = resolveSkyState(state);
|
|
||||||
const band = SKY_BAND[fixed];
|
|
||||||
if (state === 'auto') {
|
|
||||||
const url = urlSky();
|
|
||||||
if (url) return { ...url, band };
|
|
||||||
}
|
|
||||||
switch (fixed) {
|
|
||||||
case 'day':
|
|
||||||
return { sky: 'noonday', band };
|
|
||||||
case 'night':
|
|
||||||
return { sky: 'midnight', band };
|
|
||||||
default:
|
|
||||||
return { sun: { elevation: DUSK_SUN_ELEVATION }, band };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Relative luminance (WCAG) of the darkest and lightest colour a scene can draw. */
|
/** Relative luminance (WCAG) of the darkest and lightest colour a scene can draw. */
|
||||||
export interface Range {
|
export interface Range {
|
||||||
readonly darkest: number;
|
readonly darkest: number;
|
||||||
|
|
@ -106,81 +72,3 @@ export function ridgeDrawn(state: SkyState): Range {
|
||||||
return { darkest: b.floor, lightest: b.ceiling };
|
return { darkest: b.floor, lightest: b.ceiling };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* How high the terrain camera can see, in degrees of elevation: it is frozen at a downward pitch and only turns
|
|
||||||
* (no pull-back), so the top edge of its view, at the centre column, is the pitch down subtracted from half the
|
|
||||||
* field of view (14.5 degrees; off-centre columns look lower). Plus a 1.5 degree margin. The terrain's range is
|
|
||||||
* over 0 to this, all azimuths, not the whole upper sphere; below the horizon the sky is the horizon's colour.
|
|
||||||
*/
|
|
||||||
export const TERRAIN_REACH_DEG = Math.ceil((CAMERA.fov / 2 - CAMERA.pitch) * (180 / Math.PI) + 1.5);
|
|
||||||
|
|
||||||
const SAMPLE_DEG = 3;
|
|
||||||
const SUN_DEG = 0.1;
|
|
||||||
const SUN_SPAN_DEG = 8;
|
|
||||||
const HORIZON_DEG = 0.5;
|
|
||||||
const REFINE_FROM = 6;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The terrain sky's range as the 8-bit screen shows it (`displayedLuminance`, read 'low' for the darkest and 'high' for the
|
|
||||||
* lightest: one 8-bit step each way, rounding and dither at their worst): `skyColour` (the CPU twin of its sky shader) over the part of the sky the camera reaches
|
|
||||||
* (0 to TERRAIN_REACH_DEG, every azimuth: it turns), for the sky the scene picks for this state. A 3 degree grid, a 0.5 degree
|
|
||||||
* ring of the horizon, the top of the reach and a 0.25 degree patch around the sun find where the extremes are; each of the
|
|
||||||
* best few is then refined by a compass search whose step halves from 1 degree to under 5e-7, because the sun's glow peaks
|
|
||||||
* (and the sky's darkest patch sits) between any fixed grid's samples.
|
|
||||||
*/
|
|
||||||
export function terrainDrawn(state: SkyState): Range {
|
|
||||||
const sky = chooseSky(terrainSkyFor(state));
|
|
||||||
const rad = Math.PI / 180;
|
|
||||||
type Point = { el: number; az: number; read: number; score: number };
|
|
||||||
const extreme = (reading: 'low' | 'high', sign: 1 | -1): number => {
|
|
||||||
const point = (el: number, az: number): Point => {
|
|
||||||
const e = Math.min(TERRAIN_REACH_DEG, Math.max(0, el)) * rad;
|
|
||||||
const a = az * rad;
|
|
||||||
const c = skyColour(sky, [
|
|
||||||
Math.cos(e) * Math.sin(a),
|
|
||||||
Math.sin(e),
|
|
||||||
-Math.cos(e) * Math.cos(a),
|
|
||||||
]);
|
|
||||||
const read = displayedLuminance(c, reading);
|
|
||||||
return { el, az, read, score: read };
|
|
||||||
};
|
|
||||||
const seen: Point[] = [];
|
|
||||||
const at = (el: number, az: number) => seen.push(point(el, az));
|
|
||||||
for (let el = 0; el <= TERRAIN_REACH_DEG; el += SAMPLE_DEG) {
|
|
||||||
for (let az = 0; az < 360; az += SAMPLE_DEG) at(el, az);
|
|
||||||
}
|
|
||||||
for (let az = 0; az < 360; az += HORIZON_DEG) at(0, az);
|
|
||||||
at(TERRAIN_REACH_DEG, 0);
|
|
||||||
for (let dEl = -SUN_SPAN_DEG; dEl <= SUN_SPAN_DEG; dEl += SUN_DEG) {
|
|
||||||
for (let dAz = -SUN_SPAN_DEG; dAz <= SUN_SPAN_DEG; dAz += SUN_DEG) {
|
|
||||||
at(sky.elevation + dEl, sky.azimuth + dAz);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const around = (p: Point, step: number): Point[] =>
|
|
||||||
[
|
|
||||||
[step, 0],
|
|
||||||
[-step, 0],
|
|
||||||
[0, step],
|
|
||||||
[0, -step],
|
|
||||||
].map(([dEl, dAz]) =>
|
|
||||||
point(Math.min(TERRAIN_REACH_DEG, Math.max(0, p.el + dEl)), p.az + dAz)
|
|
||||||
);
|
|
||||||
const refine = (from: Point) => {
|
|
||||||
let best = from;
|
|
||||||
for (let step = 1; step > 5e-7; step /= 2) {
|
|
||||||
let improved = true;
|
|
||||||
while (improved) {
|
|
||||||
const cur = best;
|
|
||||||
best = around(cur, step).reduce((b, c) => (sign * c.score > sign * b.score ? c : b), cur);
|
|
||||||
improved = best !== cur;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return best.read;
|
|
||||||
};
|
|
||||||
const ranked = [...seen].sort((p, q) => sign * (q.score - p.score));
|
|
||||||
return sign === 1
|
|
||||||
? Math.max(ranked[0].read, ...ranked.slice(0, REFINE_FROM).map(refine))
|
|
||||||
: Math.min(ranked[0].read, ...ranked.slice(0, REFINE_FROM).map(refine));
|
|
||||||
};
|
|
||||||
return { darkest: extreme('low', -1), lightest: extreme('high', 1) };
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
import chroma from 'chroma-js';
|
import chroma from 'chroma-js';
|
||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { baked } from '../../../sky/baked';
|
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 { indexColorMXID } from '../../../util/colorMXID';
|
||||||
import type { FixedSkyState } from './skyBand';
|
import type { FixedSkyState } from './skyState';
|
||||||
import {
|
import {
|
||||||
LIGHTEST_PATCH,
|
LIGHTEST_PATCH,
|
||||||
NIGHT_INK_MAX_L,
|
NIGHT_INK_MAX_L,
|
||||||
|
|
@ -115,8 +115,6 @@ describe('inkForState', () => {
|
||||||
expect(chroma(aqua).oklch()[0]).toBeLessThanOrEqual(NIGHT_INK_MAX_L);
|
expect(chroma(aqua).oklch()[0]).toBeLessThanOrEqual(NIGHT_INK_MAX_L);
|
||||||
expect(chroma(aqua).oklch()[1]).toBeGreaterThan(0.08);
|
expect(chroma(aqua).oklch()[1]).toBeGreaterThan(0.08);
|
||||||
expect(patchRatio(aqua, 'night', true)).toBeGreaterThan(3.9);
|
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', () => {
|
it('leaves a colour that already clears its patch untouched, and a non-colour alone', () => {
|
||||||
|
|
@ -138,29 +136,18 @@ describe('userColorInk', () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('sceneInk: an explicit theme wins over the auto ink', () => {
|
describe('sceneInk: the drawn sky decides the ink', () => {
|
||||||
it('is the sky state and viewport only while the sky theme is worn and a scene runs', () => {
|
it('is the sky state and viewport while a scene runs, and nothing without one', () => {
|
||||||
// auto, scene on, no theme of the person's own: the sky theme is worn.
|
expect(sceneInk(sceneThemeId('dusk', true), true, 'dusk', true)).toEqual({
|
||||||
expect(sceneInk(sceneThemeId('auto', 'dusk', true, false), true, 'dusk', true)).toEqual({
|
|
||||||
state: 'dusk',
|
state: 'dusk',
|
||||||
phone: true,
|
phone: true,
|
||||||
});
|
});
|
||||||
// auto, but the person chose a theme: it wins, the theme's own ink stands.
|
expect(sceneInk(sceneThemeId('night', true), true, 'night', false)).toEqual({
|
||||||
expect(sceneInk(sceneThemeId('auto', 'dusk', true, true), true, 'dusk', true)).toBeUndefined();
|
|
||||||
// a fixed sky state does not override the person's theme either: the theme's own ink stands.
|
|
||||||
expect(
|
|
||||||
sceneInk(sceneThemeId('night', 'night', true, true), true, 'night', false)
|
|
||||||
).toBeUndefined();
|
|
||||||
// a fixed sky state with no theme of the person's own: the sky theme's ink applies.
|
|
||||||
expect(sceneInk(sceneThemeId('night', 'night', true, false), true, 'night', false)).toEqual({
|
|
||||||
state: 'night',
|
state: 'night',
|
||||||
phone: false,
|
phone: false,
|
||||||
});
|
});
|
||||||
// no scene behind the page: nothing for the ink to be measured against.
|
// no scene behind the page: the person's theme and its ink stand.
|
||||||
expect(
|
expect(sceneInk(sceneThemeId('day', false), false, 'day', false)).toBeUndefined();
|
||||||
sceneInk(sceneThemeId('auto', 'day', false, false), false, 'day', false)
|
|
||||||
).toBeUndefined();
|
|
||||||
expect(sceneInk(sceneThemeId('day', 'day', true, false), false, 'day', false)).toBeUndefined();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -8,14 +8,14 @@
|
||||||
// until it clears 4.5:1 (WCAG) against the LIGHTEST 24x12 patch of terrain under the timeline in that state
|
// 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,
|
// 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
|
// 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
|
// 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
|
||||||
// timeline never shows, and at night the terrain's snow (0.103, phone 0.149) is lighter than the sky (0.0816).
|
// 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.
|
// The page wears this ink whenever the drawn sky decides its theme (a scene is on, sceneThemeId).
|
||||||
import chroma from 'chroma-js';
|
import chroma from 'chroma-js';
|
||||||
import { AA, luminance } from '../../../sky/skyTokens.js';
|
import { AA, luminance } from '../../../sky/skyTokens.js';
|
||||||
import { baked } from '../../../sky/baked';
|
import { baked } from '../../../sky/baked';
|
||||||
import { indexColorMXID } from '../../../util/colorMXID';
|
import { indexColorMXID } from '../../../util/colorMXID';
|
||||||
import type { FixedSkyState } from './skyBand';
|
import type { FixedSkyState } from './skyState';
|
||||||
import type { SkyThemeId } from './skyTheme';
|
import type { SkyThemeId } from './skyTheme';
|
||||||
|
|
||||||
export interface SkyInk {
|
export interface SkyInk {
|
||||||
|
|
@ -25,8 +25,8 @@ export interface SkyInk {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The ink in force: only while the page wears the sky's theme (`themeId`, from sceneThemeId, so a person's explicit
|
* The ink in force: only while the page wears the sky's theme (`themeId`, from sceneThemeId, defined only while a
|
||||||
* theme, which that function lets win over 'auto', keeps its own ink) and a scene runs behind it. Otherwise undefined.
|
* scene is on) and a scene runs behind it. With no scene the person's theme and its own ink stand: undefined.
|
||||||
*/
|
*/
|
||||||
export const sceneInk = (
|
export const sceneInk = (
|
||||||
themeId: SkyThemeId | undefined,
|
themeId: SkyThemeId | undefined,
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ export const SKY_PLATE_FALLBACK = {
|
||||||
* footer line. The footer is a blurred, tinted band with soft edges, not a plate: the scene shows through it. The
|
* footer line. The footer is a blurred, tinted band with soft edges, not a plate: the scene shows through it. The
|
||||||
* footer ink is the plate's, so the tint has to bring the scene behind it to where that ink clears 4.5:1. The browser
|
* footer ink is the plate's, so the tint has to bring the scene behind it to where that ink clears 4.5:1. The browser
|
||||||
* mixes in sRGB, so the test does too (skyTheme.test.ts): over pure black 0.80 gives 4.36 and 0.82 gives 4.55. The
|
* mixes in sRGB, so the test does too (skyTheme.test.ts): over pure black 0.80 gives 4.36 and 0.82 gives 4.55. The
|
||||||
* terrain is not black: in the shots at 390x844 (terrain scene, tier low) the darkest pixel in the footer's region is
|
* background is not black: in the shots at 390x844 (taken on the earlier terrain scene, tier low; not re-measured on the ridges) the darkest pixel in the footer's region is
|
||||||
* 0.0203 at Dusk, 0.0936 at Day (dark ink) and 0.0052 at Night (light ink). Measured on the drawn pixels with the band
|
* 0.0203 at Dusk, 0.0936 at Day (dark ink) and 0.0052 at Night (light ink). Measured on the drawn pixels with the band
|
||||||
* on, the worst link contrast is 5.0 at Dusk, 5.7 at Day and 11.2 at Night.
|
* on, the worst link contrast is 5.0 at Dusk, 5.7 at Day and 11.2 at Night.
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,8 @@
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { atStandardTime } from './standardTime.testkit';
|
import { atStandardTime } from './standardTime.testkit';
|
||||||
import { baked } from '../../../sky/baked';
|
|
||||||
import { luminance } from '../../../sky/skyTokens.js';
|
|
||||||
import {
|
import {
|
||||||
SKY_STATES,
|
|
||||||
SKY_STATE_KEY,
|
SKY_STATE_KEY,
|
||||||
resolveSkyState,
|
resolveSkyState,
|
||||||
setSkyClock,
|
|
||||||
skyBackdrop,
|
|
||||||
type SkyState,
|
type SkyState,
|
||||||
} from './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', () => {
|
describe('auto follows the clock', () => {
|
||||||
const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock
|
const local = (h: number, m = 0) => atStandardTime(h, m); // local solar time ~ local clock
|
||||||
let storage: ReturnType<typeof fakeStorage>;
|
let storage: ReturnType<typeof fakeStorage>;
|
||||||
|
|
@ -215,3 +177,69 @@ describe('auto follows the clock', () => {
|
||||||
expect(cb.mock.calls).toEqual([['night'], ['day']]);
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,8 @@
|
||||||
// Which sky the signed-out page is drawn against. The choice is one value, kept in one
|
// 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
|
// localStorage key; whoever draws the sky (the scene, the title bar's control) reads it here.
|
||||||
// `skyBackdrop` says how light or dark the sky behind the login text can be in each state, so the
|
// 'auto' is a choice, not a sky: it resolves from the clock to day, dusk or night
|
||||||
// text colours can be checked against it. 'auto' is a choice, not a sky: it resolves from the
|
// (`resolveSkyState`), and every sky drawn is one of those three.
|
||||||
// clock to day, dusk or night (`resolveSkyState`), and every sky drawn is one of those three.
|
|
||||||
import { sunElevation } from '../../../sky/sun.js';
|
import { sunElevation } from '../../../sky/sun.js';
|
||||||
import type { FixedSkyState } from './skyBand';
|
|
||||||
|
|
||||||
export type SkyState = 'auto' | 'day' | 'dusk' | 'night';
|
export type SkyState = 'auto' | 'day' | 'dusk' | 'night';
|
||||||
|
|
||||||
|
|
@ -22,7 +20,13 @@ function load(): SkyState {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export type { FixedSkyState };
|
/**
|
||||||
|
* The three skies ever drawn. Each has the luminance band its theme ink needs against bare sky (WCAG relative luminance,
|
||||||
|
* the `luminance` of src/sky/skyTokens.js): day, at least 0.2983 (the dark text ink #342d25); dusk, at least 0.4554 (the link
|
||||||
|
* #2a4f27); night, at most 0.0931 (the light text ink #aeccff). The ridge scene's display budgets (ridge/toneMap.ts `BUDGET`)
|
||||||
|
* sit inside them.
|
||||||
|
*/
|
||||||
|
export type FixedSkyState = 'day' | 'dusk' | 'night';
|
||||||
|
|
||||||
/** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */
|
/** Where the clock puts the sun: the latitude the skies are baked for (src/sky/skyTokens.js MOMENTS), the longitude of this timezone. */
|
||||||
const LAT = 45;
|
const LAT = 45;
|
||||||
|
|
@ -46,6 +50,22 @@ export function resolveSkyState(s: SkyState, now: Date = clock()): FixedSkyState
|
||||||
return el <= -DAY_FROM ? 'night' : 'dusk';
|
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;
|
let current: SkyState | undefined;
|
||||||
const listeners = new Set<(s: FixedSkyState) => void>();
|
const listeners = new Set<(s: FixedSkyState) => void>();
|
||||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
|
@ -104,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. */
|
/** 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 {
|
export function subscribe(cb: (s: FixedSkyState) => void): () => void {
|
||||||
if (listeners.size === 0) shown = getResolvedSkyState();
|
if (listeners.size === 0) shown = getResolvedSkyState();
|
||||||
|
|
@ -114,29 +152,3 @@ export function subscribe(cb: (s: FixedSkyState) => void): () => void {
|
||||||
sync();
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The union of every sky a scene draws for the state: the ridge sky and the terrain sky, each from
|
|
||||||
// the function its scene uses (`ridgeDrawn`, `terrainDrawn` in skyForState.ts). The ridge sky is the physical sky over Vienna, its
|
|
||||||
// display fitted to the state's budget (ridge/toneMap.ts `BUDGET`): the budget is its extreme, whatever the sun's elevation. Held as constants so
|
|
||||||
// this module, which the main chunk loads, does not pull in the terrain sky and the baked scattering
|
|
||||||
// tables with it; skyForState.test.ts fails when they drift from the computed union. The ridge sky counts
|
|
||||||
// over its whole range, the terrain sky over what its frozen camera reaches (TERRAIN_REACH_DEG, skyForState.ts).
|
|
||||||
// Night's lightest also covers a sky the page URL steers (shaped to the band ceiling, skyBand.ts).
|
|
||||||
// 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)];
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { atStandardTime } from './standardTime.testkit';
|
import { atStandardTime } from './standardTime.testkit';
|
||||||
import { baked } from '../../../sky/baked';
|
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 { Editor } from '../../components/editor/Editor.css';
|
||||||
import { PageContent, PageNavContent } from '../../components/page/style.css';
|
import { PageContent, PageNavContent } from '../../components/page/style.css';
|
||||||
import { CallStatus } from '../call-status/styles.css';
|
import { CallStatus } from '../call-status/styles.css';
|
||||||
|
|
@ -12,69 +12,38 @@ import { SkyPlate, plateRegions } from './skyPlate.css';
|
||||||
import {
|
import {
|
||||||
getResolvedSkyState,
|
getResolvedSkyState,
|
||||||
setSkyClock,
|
setSkyClock,
|
||||||
skyBackdrop,
|
|
||||||
subscribe as subscribeSky,
|
subscribe as subscribeSky,
|
||||||
} from './skyState';
|
} from './skyState';
|
||||||
import type { SkyBackdrop } from './skyState';
|
import { sceneThemeId } from './skyTheme';
|
||||||
import type { FixedSkyState } from './skyBand';
|
|
||||||
import { sceneThemeId, skyThemeId } from './skyTheme';
|
|
||||||
|
|
||||||
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
|
const SKY = { 'midnight-sky': baked.midnight, 'noonday-sky': baked.noonday } as const;
|
||||||
const fixed = (['day', 'dusk', 'night'] as const).flatMap((s) => {
|
const r2 = (n: number) => n.toFixed(2);
|
||||||
const id = skyThemeId(s);
|
const fixed = (['day', 'dusk', 'night'] as const).flatMap((st) => {
|
||||||
return id ? [[s, id] as const] : [];
|
const id = sceneThemeId(st, true);
|
||||||
|
return id ? [[st, id] as const] : [];
|
||||||
});
|
});
|
||||||
|
|
||||||
// WCAG contrast of an ink against the sky it is worst on, measured as skyState.test.ts does: the
|
describe('sceneThemeId, the theme the page wears', () => {
|
||||||
// sky can show any luminance between its darkest and lightest, and contrast is lowest where the
|
it('with a scene on, the drawn sky gives its theme, whatever theme a person stored', () => {
|
||||||
// backdrop is closest to the ink, which is the ink's own luminance clamped into that range.
|
expect(sceneThemeId('day', true)).toBe('noonday-sky');
|
||||||
const against = (ink: string, bg: number) => {
|
expect(sceneThemeId('dusk', true)).toBe('noonday-sky');
|
||||||
const li = luminance(ink);
|
expect(sceneThemeId('night', true)).toBe('midnight-sky');
|
||||||
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');
|
|
||||||
expect(skyThemeId('dusk')).toBe('noonday-sky');
|
|
||||||
expect(skyThemeId('night')).toBe('midnight-sky');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('picks none for auto, at any hour: auto never overrides a signed-in theme', () => {
|
it('auto draws the clock sky and that sky decides', () => {
|
||||||
[0, 6, 12, 18, 23].forEach((h) => {
|
[0, 12, 23].forEach((h) => {
|
||||||
setSkyClock(() => atStandardTime(h, 10));
|
setSkyClock(() => atStandardTime(h, 10));
|
||||||
expect(skyThemeId('auto')).toBeUndefined();
|
expect(sceneThemeId(getResolvedSkyState(), true)).toBe(
|
||||||
|
h === 12 ? 'noonday-sky' : 'midnight-sky'
|
||||||
|
);
|
||||||
});
|
});
|
||||||
setSkyClock();
|
setSkyClock();
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('sceneThemeId, the theme the page wears', () => {
|
it('with the scene off no sky is drawn, so the person theme stands', () => {
|
||||||
it('a fixed state picks its theme, whatever the scene, while the person chose no theme', () => {
|
(['day', 'dusk', 'night'] as const).forEach((st) =>
|
||||||
[true, false].forEach((scene) => {
|
expect(sceneThemeId(st, false)).toBeUndefined()
|
||||||
expect(sceneThemeId('day', 'night', scene, false)).toBe('noonday-sky');
|
);
|
||||||
expect(sceneThemeId('night', 'day', scene, false)).toBe('midnight-sky');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a theme the person chose wins over every sky state, fixed or auto', () => {
|
|
||||||
(['auto', 'day', 'dusk', 'night'] as const).forEach((state) =>
|
|
||||||
[true, false].forEach((scene) =>
|
|
||||||
expect(sceneThemeId(state, 'night', scene, true)).toBeUndefined()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('auto follows the resolved sky only while a scene is on and the person chose no theme', () => {
|
|
||||||
expect(sceneThemeId('auto', 'day', true, false)).toBe('noonday-sky');
|
|
||||||
expect(sceneThemeId('auto', 'dusk', true, false)).toBe('noonday-sky');
|
|
||||||
expect(sceneThemeId('auto', 'night', true, false)).toBe('midnight-sky');
|
|
||||||
expect(sceneThemeId('auto', 'day', false, false)).toBeUndefined();
|
|
||||||
expect(sceneThemeId('auto', 'day', true, true)).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => {
|
it('the resolved sky a hook subscribes to changes as the clock crosses, so theme classes follow', () => {
|
||||||
|
|
@ -93,69 +62,6 @@ describe('skyThemeId', () => {
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
setSkyClock();
|
setSkyClock();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('is what a wiring that follows the sky reads: the resolved state names a theme', () => {
|
|
||||||
setSkyClock(() => atStandardTime(12));
|
|
||||||
expect(skyThemeId(getResolvedSkyState())).toBe('noonday-sky');
|
|
||||||
setSkyClock(() => atStandardTime(0));
|
|
||||||
expect(skyThemeId(getResolvedSkyState())).toBe('midnight-sky');
|
|
||||||
setSkyClock();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
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', () => {
|
describe('the plate, where text cannot rest on bare sky', () => {
|
||||||
|
|
@ -218,7 +124,7 @@ describe('regions that sit on the plate', () => {
|
||||||
describe('the sign-in footer band', () => {
|
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,
|
// 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
|
// as the browser does: per channel, in encoded sRGB (not in linear light, which flatters dark scenes). The scene
|
||||||
// behind it is the terrain, 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.
|
// 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 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);
|
const channels = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
|
||||||
|
|
@ -236,7 +142,7 @@ describe('the sign-in footer band', () => {
|
||||||
'%s: the ink clears AA over the darkest and the lightest scene behind it',
|
'%s: the ink clears AA over the darkest and the lightest scene behind it',
|
||||||
(state, id) => {
|
(state, id) => {
|
||||||
const { Other, OtherText } = SKY[id].bubbles;
|
const { Other, OtherText } = SKY[id].bubbles;
|
||||||
[0, skyBackdrop(state).lightest].forEach((behind) => {
|
[0, 1].forEach((behind) => {
|
||||||
expect(contrast(OtherText, bandOver(Other, behind))).toBeGreaterThanOrEqual(AA);
|
expect(contrast(OtherText, bandOver(Other, behind))).toBeGreaterThanOrEqual(AA);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,8 @@
|
||||||
// Which theme a sky state lights the page with. 'auto' picks none: it never overrides a person's theme
|
// Which theme the drawn sky lights the page with. While a scene is on, the sky being drawn (the fixed pick, or the
|
||||||
// (the stored one when signed in, Midnight Sky when signed out). A wiring that follows the sky when no theme
|
// clock's state under 'auto'; `useResolvedSkyState`) alone decides the theme and, with it, the ink: Day and Dusk
|
||||||
// is stored reads `getResolvedSkyState` (skyState.ts) and passes that fixed state here.
|
// wear Noonday Sky, Night wears Midnight Sky. A person's own theme (the theme menu) stands only where no sky is
|
||||||
//
|
// drawn, that is with the scene off.
|
||||||
// Day and Dusk take the dark ink of Noonday Sky, Night the light ink of Midnight Sky. Each state's
|
import type { FixedSkyState } from './skyState';
|
||||||
// drawn sky is shaped into a luminance band (skyBand.ts) in which that ink's TEXT clears 4.5:1 on
|
|
||||||
// bare sky: Day at least 0.2983 (dark ink), Night at most 0.0931 (light ink). Dusk's floor is higher, the bound of
|
|
||||||
// the dark link (0.4554), so its link clears as well. skyTheme.test.ts pins the measured text and link ratios. Night's
|
|
||||||
// link ink is not in the band, and the themes' link colours are derived outside this code (src/sky/skyTokens.js).
|
|
||||||
// Midnight Sky's link is derived there against the lightest Night sky
|
|
||||||
// (4.53 on it, 5.43 on the darkest). The plate (skyPlate.css.ts) is still in the shell, pending
|
|
||||||
// its removal.
|
|
||||||
import type { FixedSkyState, SkyState } from './skyState';
|
|
||||||
|
|
||||||
export type SkyThemeId = 'midnight-sky' | 'noonday-sky';
|
export type SkyThemeId = 'midnight-sky' | 'noonday-sky';
|
||||||
|
|
||||||
|
|
@ -20,21 +12,6 @@ const BY_STATE: Record<FixedSkyState, SkyThemeId> = {
|
||||||
night: 'midnight-sky',
|
night: 'midnight-sky',
|
||||||
};
|
};
|
||||||
|
|
||||||
export const skyThemeId = (state: SkyState): SkyThemeId | undefined =>
|
/** The theme the page wears: the drawn sky's while a scene is on, otherwise none (the person's theme stands). */
|
||||||
state === 'auto' ? undefined : BY_STATE[state];
|
export const sceneThemeId = (resolved: FixedSkyState, sceneOn: boolean): SkyThemeId | undefined =>
|
||||||
|
sceneOn ? BY_STATE[resolved] : undefined;
|
||||||
/**
|
|
||||||
* The theme the page wears: a theme the person chose always wins, and picks none here. Otherwise a fixed sky state
|
|
||||||
* picks its theme, and 'auto' follows the resolved sky (`resolved`, the clock's state) only while a scene is on.
|
|
||||||
* Signed-out pages choose no theme, so they pass `userChoseTheme: false`.
|
|
||||||
*/
|
|
||||||
export const sceneThemeId = (
|
|
||||||
state: SkyState,
|
|
||||||
resolved: FixedSkyState,
|
|
||||||
sceneOn: boolean,
|
|
||||||
userChoseTheme: boolean
|
|
||||||
): SkyThemeId | undefined => {
|
|
||||||
if (userChoseTheme) return undefined;
|
|
||||||
if (state !== 'auto') return BY_STATE[state];
|
|
||||||
return sceneOn ? BY_STATE[resolved] : undefined;
|
|
||||||
};
|
|
||||||
|
|
|
||||||
|
|
@ -1,385 +0,0 @@
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-empty-function -- fake GL and DOM stubs, as the other scene tests */
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
import { createTerrainScene } from './Terrain';
|
|
||||||
import { GRID, triangleCount } from './terrainWorld';
|
|
||||||
import { groundLight, SKY, skyAtSun } from './terrainSky';
|
|
||||||
import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter';
|
|
||||||
import { SKY_FRAG } from './terrainShaders';
|
|
||||||
import { SKY_BAND } from '../skyBand';
|
|
||||||
import { terrainSkyFor } from '../skyForState';
|
|
||||||
import { startBackgroundScene } from '../index';
|
|
||||||
|
|
||||||
/** A GL context that accepts every call, remembers them, reports success for compile, link and framebuffer. */
|
|
||||||
function fakeGl(over: Record<string, unknown> = {}) {
|
|
||||||
const calls: Record<string, unknown[][]> = {};
|
|
||||||
const gl: any = new Proxy(
|
|
||||||
{},
|
|
||||||
{
|
|
||||||
get(_t, name: string) {
|
|
||||||
if (name in over) return over[name];
|
|
||||||
if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true;
|
|
||||||
if (name === 'getAttribLocation' || name === 'getUniformLocation') return () => 1;
|
|
||||||
if (name === 'checkFramebufferStatus') return () => 1;
|
|
||||||
if (name === 'getParameter') return () => 16;
|
|
||||||
if (/^[A-Z_0-9]+$/.test(name)) return 1;
|
|
||||||
return (...args: unknown[]) => {
|
|
||||||
(calls[name] ??= []).push(args);
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
return { gl, calls };
|
|
||||||
}
|
|
||||||
|
|
||||||
let rafQueue: Array<(t: number) => void>;
|
|
||||||
let visibility: string;
|
|
||||||
let search: string;
|
|
||||||
beforeEach(() => {
|
|
||||||
rafQueue = [];
|
|
||||||
visibility = 'visible';
|
|
||||||
search = '';
|
|
||||||
vi.stubGlobal('document', {
|
|
||||||
addEventListener: vi.fn(),
|
|
||||||
removeEventListener: vi.fn(),
|
|
||||||
get visibilityState() {
|
|
||||||
return visibility;
|
|
||||||
},
|
|
||||||
createElement: () => ({ style: {}, remove() {} }),
|
|
||||||
});
|
|
||||||
vi.stubGlobal('window', {
|
|
||||||
devicePixelRatio: 1,
|
|
||||||
innerWidth: 400,
|
|
||||||
innerHeight: 800,
|
|
||||||
matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),
|
|
||||||
addEventListener: vi.fn(),
|
|
||||||
removeEventListener: vi.fn(),
|
|
||||||
get location() {
|
|
||||||
return { search };
|
|
||||||
},
|
|
||||||
setTimeout,
|
|
||||||
});
|
|
||||||
vi.stubGlobal('performance', { now: () => 0 });
|
|
||||||
vi.stubGlobal('requestAnimationFrame', (cb: (t: number) => void) => rafQueue.push(cb));
|
|
||||||
vi.stubGlobal('cancelAnimationFrame', () => {
|
|
||||||
rafQueue = [];
|
|
||||||
});
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
|
||||||
vi.unstubAllGlobals();
|
|
||||||
});
|
|
||||||
|
|
||||||
function canvasWith(gl: unknown) {
|
|
||||||
return {
|
|
||||||
width: 0,
|
|
||||||
height: 0,
|
|
||||||
clientWidth: 400,
|
|
||||||
clientHeight: 800,
|
|
||||||
parentElement: { appendChild: vi.fn() },
|
|
||||||
getContext: vi.fn(() => gl),
|
|
||||||
addEventListener: vi.fn(),
|
|
||||||
removeEventListener: vi.fn(),
|
|
||||||
} as any;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('createTerrainScene', () => {
|
|
||||||
it("returns null at tier 'off' and touches nothing", () => {
|
|
||||||
const canvas = canvasWith(null);
|
|
||||||
expect(createTerrainScene({ canvas, tier: 'off' })).toBeNull();
|
|
||||||
expect(canvas.getContext).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns null without WebGL2, so the host keeps its CSS ground', () => {
|
|
||||||
const canvas = canvasWith(null);
|
|
||||||
expect(createTerrainScene({ canvas, tier: 'full' })).toBeNull();
|
|
||||||
expect(canvas.getContext).toHaveBeenCalledWith('webgl2', expect.anything());
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns null with no vertex texture units, or an incomplete bake target', () => {
|
|
||||||
expect(
|
|
||||||
createTerrainScene({ canvas: canvasWith(fakeGl({ getParameter: () => 0 }).gl), tier: 'full' })
|
|
||||||
).toBeNull();
|
|
||||||
const { gl, calls } = fakeGl({ checkFramebufferStatus: () => 0 });
|
|
||||||
expect(createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })).toBeNull();
|
|
||||||
expect(calls.deleteProgram).toHaveLength(3);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('reports a shader that does not compile to onCompileFail and returns null', () => {
|
|
||||||
const { gl } = fakeGl({ getShaderParameter: () => false, getShaderInfoLog: () => 'bad' });
|
|
||||||
const onCompileFail = vi.fn();
|
|
||||||
expect(createTerrainScene({ canvas: canvasWith(gl), tier: 'full', onCompileFail })).toBeNull();
|
|
||||||
expect(onCompileFail).toHaveBeenCalledOnce();
|
|
||||||
expect(onCompileFail.mock.calls[0][0].log).toContain('terrain height');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('bakes the height map once, then draws sky and grid each frame and keeps turning', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'low' })!;
|
|
||||||
expect(scene).not.toBeNull();
|
|
||||||
const bakes = calls.drawArrays.length;
|
|
||||||
expect(bakes).toBe(1);
|
|
||||||
rafQueue.shift()!(16);
|
|
||||||
rafQueue.shift()!(32);
|
|
||||||
expect(calls.drawArrays).toHaveLength(bakes + 2); // one sky draw per frame
|
|
||||||
expect(calls.drawElements).toHaveLength(2);
|
|
||||||
expect(calls.drawElements[0][1]).toBe(triangleCount(GRID.low.grid) * 3);
|
|
||||||
expect(calls.texImage2D).toHaveLength(1); // the baked map is never re-uploaded
|
|
||||||
expect(rafQueue).toHaveLength(1);
|
|
||||||
scene.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("'still' draws one frame and queues nothing", () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'still' })!;
|
|
||||||
expect(calls.drawElements).toHaveLength(1);
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
scene.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('lights with the sky chosen: option, then ?sky=, then the night default', () => {
|
|
||||||
const uploaded = (opts: { sky?: 'midnight' | 'noonday' }) => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose();
|
|
||||||
// every vec3 uniform draw() sets: right, up, forward, sun, sunColour, glow, ambient, camera, soil...
|
|
||||||
return calls.uniform3fv
|
|
||||||
.filter((a) => (a[1] as ArrayLike<number>).length === 3)
|
|
||||||
.map((a) => Array.from(a[1] as ArrayLike<number>));
|
|
||||||
};
|
|
||||||
const night = uploaded({});
|
|
||||||
const day = uploaded({ sky: 'noonday' });
|
|
||||||
const nightA = Array.from(groundLight(SKY.midnight).ambient);
|
|
||||||
const dayA = Array.from(groundLight(SKY.noonday).ambient);
|
|
||||||
const has = (all: number[][], v: number[]) =>
|
|
||||||
all.some((a) => a.every((x, i) => Math.abs(x - v[i]) < 1e-6));
|
|
||||||
expect(has(night, nightA)).toBe(true);
|
|
||||||
expect(has(night, dayA)).toBe(false);
|
|
||||||
expect(has(day, dayA)).toBe(true);
|
|
||||||
search = '?sky=noonday';
|
|
||||||
expect(has(uploaded({}), dayA)).toBe(true);
|
|
||||||
search = '?sky=garbage';
|
|
||||||
expect(has(uploaded({}), nightA)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(['day', 'dusk', 'night'] as const)(
|
|
||||||
'uploads the %s band as uBand (floor, ceiling) and uLift, in the sky pass and the grid pass',
|
|
||||||
(state) => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
const opts = terrainSkyFor(state);
|
|
||||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose();
|
|
||||||
const { floor, ceiling, lift } = SKY_BAND[state];
|
|
||||||
const pairs = calls.uniform2fv.filter(
|
|
||||||
(a) =>
|
|
||||||
Math.abs((a[1] as number[])[0] - floor) < 1e-6 &&
|
|
||||||
Math.abs((a[1] as number[])[1] - ceiling) < 1e-6
|
|
||||||
);
|
|
||||||
expect(pairs).toHaveLength(2);
|
|
||||||
const lifts = calls.uniform3fv.filter((a) =>
|
|
||||||
Array.from(a[1] as ArrayLike<number>).every((x, i) => Math.abs(x - lift[i]) < 1e-6)
|
|
||||||
);
|
|
||||||
expect(lifts).toHaveLength(2);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
it('uploads no band (0, 1) and a zero lift without one', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'still' })!.dispose();
|
|
||||||
expect(calls.uniform2fv.filter((a) => (a[1] as number[])[1] === 1)).toHaveLength(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a sun elevation (option or ?sun=&az=) lights between the bakes, and wins over ?sky=', () => {
|
|
||||||
const ambients = (opts: Record<string, unknown>) => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose();
|
|
||||||
return calls.uniform3fv.map((a) => Array.from(a[1] as ArrayLike<number>));
|
|
||||||
};
|
|
||||||
const dusk = skyAtSun(-1, 300);
|
|
||||||
const has = (all: number[][], v: readonly number[]) =>
|
|
||||||
all.some((a) => a.length === 3 && a.every((x, i) => Math.abs(x - v[i]) < 1e-6));
|
|
||||||
expect(has(ambients({ sun: { elevation: -1, azimuth: 300 } }), groundLight(dusk).ambient)).toBe(
|
|
||||||
true
|
|
||||||
);
|
|
||||||
search = '?sky=noonday&sun=-1&az=300';
|
|
||||||
expect(has(ambients({}), groundLight(dusk).ambient)).toBe(true);
|
|
||||||
search = '?sun=garbage';
|
|
||||||
expect(has(ambients({}), groundLight(SKY.midnight).ambient)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('uploads the baked sky table and the aerial perspective volume once each, as half floats, to 3D textures', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose();
|
|
||||||
expect(calls.texImage3D).toHaveLength(2);
|
|
||||||
const a = calls.texImage3D[0];
|
|
||||||
expect([a[3], a[4], a[5]]).toEqual([SKY_VIEW.width, SKY_VIEW.height, SKY_VIEW.depth]);
|
|
||||||
expect(a[9]).toEqual(skyViewWords());
|
|
||||||
const ap = calls.texImage3D[1];
|
|
||||||
expect([ap[3], ap[4], ap[5]]).toEqual([AP_VOLUME.width, AP_VOLUME.height, AP_VOLUME.depth]);
|
|
||||||
expect(ap[9]).toEqual(apVolumeWords());
|
|
||||||
expect(calls.deleteTexture).toHaveLength(3);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('dithers the sky output by half an 8-bit step either way, and the terrain not at all', () => {
|
|
||||||
expect(SKY_FRAG).toContain('- 0.5');
|
|
||||||
expect(SKY_FRAG).toContain('dither / 255.0');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to a still frame when the measured p95 is over 33 ms', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
const onProbe = vi.fn();
|
|
||||||
const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'full', onProbe })!;
|
|
||||||
let t = 0;
|
|
||||||
for (let i = 0; i < 400 && rafQueue.length; i += 1) rafQueue.shift()!((t += 50));
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
expect(onProbe).toHaveBeenLastCalledWith(expect.objectContaining({ still: true }));
|
|
||||||
expect(calls.drawElements.length).toBeLessThan(400);
|
|
||||||
scene.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not draw while the tab is hidden, or under reduced motion', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
const scene = createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!;
|
|
||||||
const before = (calls.drawElements ?? []).length;
|
|
||||||
visibility = 'hidden';
|
|
||||||
rafQueue.shift()!(16);
|
|
||||||
expect((calls.drawElements ?? []).length).toBe(before);
|
|
||||||
scene.dispose();
|
|
||||||
vi.stubGlobal('window', {
|
|
||||||
...(window as object),
|
|
||||||
matchMedia: () => ({ matches: true, addEventListener() {}, removeEventListener() {} }),
|
|
||||||
});
|
|
||||||
visibility = 'visible';
|
|
||||||
const g2 = fakeGl();
|
|
||||||
const still = createTerrainScene({ canvas: canvasWith(g2.gl), tier: 'full' })!;
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
expect(g2.calls.drawElements).toHaveLength(1); // one frame, then still
|
|
||||||
still.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a lost context stops the scene and tells the host', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
const canvas = canvasWith(gl);
|
|
||||||
const onContextLost = vi.fn();
|
|
||||||
createTerrainScene({ canvas, tier: 'full', onContextLost })!;
|
|
||||||
const handler = canvas.addEventListener.mock.calls.find(
|
|
||||||
(c: unknown[]) => c[0] === 'webglcontextlost'
|
|
||||||
)[1];
|
|
||||||
handler({ preventDefault() {} });
|
|
||||||
expect(onContextLost).toHaveBeenCalledOnce();
|
|
||||||
const n = (calls.drawElements ?? []).length;
|
|
||||||
rafQueue.splice(0).forEach((f) => f(16));
|
|
||||||
expect((calls.drawElements ?? []).length).toBe(n);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('dispose frees its programs, buffers and texture and queues nothing more', () => {
|
|
||||||
const { gl, calls } = fakeGl();
|
|
||||||
createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose();
|
|
||||||
expect(calls.deleteProgram).toHaveLength(3);
|
|
||||||
expect(calls.deleteBuffer).toHaveLength(2);
|
|
||||||
expect(calls.deleteTexture).toHaveLength(3);
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("startBackgroundScene style 'terrain'", () => {
|
|
||||||
it('requests webgl2 and returns a scene once the tier is on', async () => {
|
|
||||||
const { gl } = fakeGl();
|
|
||||||
const canvas = canvasWith(gl);
|
|
||||||
const scene = await startBackgroundScene({ tier: 'still', style: 'terrain' }, {}, { canvas });
|
|
||||||
expect(scene).not.toBeNull();
|
|
||||||
expect(canvas.getContext).toHaveBeenCalledWith('webgl2', expect.anything());
|
|
||||||
scene!.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('stays off by default, and the default style is still the ridge (no WebGL2)', async () => {
|
|
||||||
const canvas = canvasWith(null);
|
|
||||||
expect(await startBackgroundScene({ style: 'terrain' }, {}, { canvas })).toBeNull();
|
|
||||||
expect(canvas.getContext).not.toHaveBeenCalled();
|
|
||||||
const { gl } = fakeGl();
|
|
||||||
const c2 = { ...canvasWith(gl), getContext: vi.fn(() => null) };
|
|
||||||
await startBackgroundScene({ tier: 'still' }, {}, { canvas: c2 });
|
|
||||||
expect(c2.getContext).not.toHaveBeenCalledWith('webgl2', expect.anything());
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('stars in the terrain scene', () => {
|
|
||||||
let overlays: any[];
|
|
||||||
let arcs: number;
|
|
||||||
const withOverlays = () => {
|
|
||||||
overlays = [];
|
|
||||||
arcs = 0;
|
|
||||||
(document as any).createElement = () => {
|
|
||||||
const el: any = {
|
|
||||||
style: {},
|
|
||||||
remove: vi.fn(),
|
|
||||||
setAttribute() {},
|
|
||||||
getContext: () => ({
|
|
||||||
clearRect() {},
|
|
||||||
beginPath() {},
|
|
||||||
fill() {},
|
|
||||||
arc: () => (arcs += 1),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
overlays.push(el);
|
|
||||||
return el;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
const scene = (sky: 'midnight' | 'noonday', tier: 'still' | 'low' = 'low') => {
|
|
||||||
withOverlays();
|
|
||||||
const canvas = canvasWith(fakeGl().gl);
|
|
||||||
const s = createTerrainScene({ canvas, tier, sky })!;
|
|
||||||
return { s, canvas };
|
|
||||||
};
|
|
||||||
|
|
||||||
it('a midnight sky gets one star overlay beside the canvas, painted with the terrain', () => {
|
|
||||||
const { s, canvas } = scene('midnight');
|
|
||||||
expect(overlays).toHaveLength(1);
|
|
||||||
expect(canvas.parentElement.appendChild).toHaveBeenCalledWith(overlays[0]);
|
|
||||||
rafQueue.shift()!(16);
|
|
||||||
expect(arcs).toBeGreaterThan(0);
|
|
||||||
s.dispose();
|
|
||||||
expect(overlays[0].remove).toHaveBeenCalledOnce();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a noonday sky gets no overlay and paints no stars', () => {
|
|
||||||
const { s } = scene('noonday');
|
|
||||||
expect(overlays).toHaveLength(0);
|
|
||||||
expect(arcs).toBe(0);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("'still' paints the stars once at base and queues nothing", () => {
|
|
||||||
const { s } = scene('midnight', 'still');
|
|
||||||
expect(arcs).toBeGreaterThan(0);
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a hidden tab or reduced motion paints no more stars than the first frame', () => {
|
|
||||||
visibility = 'hidden';
|
|
||||||
const { s } = scene('midnight');
|
|
||||||
const n = arcs;
|
|
||||||
expect(n).toBeGreaterThan(0);
|
|
||||||
expect(rafQueue).toHaveLength(0); // the terrain loop never starts, so nothing repaints the stars
|
|
||||||
s.dispose();
|
|
||||||
visibility = 'visible';
|
|
||||||
(window as any).matchMedia = () => ({
|
|
||||||
matches: true,
|
|
||||||
addEventListener() {},
|
|
||||||
removeEventListener() {},
|
|
||||||
});
|
|
||||||
const r = scene('midnight');
|
|
||||||
expect(rafQueue).toHaveLength(0);
|
|
||||||
expect(arcs).toBe(n);
|
|
||||||
r.s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('stars turn with the terrain: a later frame is painted at a later heading', () => {
|
|
||||||
let clock = 0;
|
|
||||||
vi.stubGlobal('performance', { now: () => (clock += 1000) });
|
|
||||||
const { s } = scene('midnight');
|
|
||||||
rafQueue.shift()!(16);
|
|
||||||
const first = arcs;
|
|
||||||
rafQueue.shift()!(1000);
|
|
||||||
expect(arcs).toBeGreaterThan(first);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,443 +0,0 @@
|
||||||
import type { Scene, SceneOptions } from '../Scene';
|
|
||||||
import type { SkyBand } from '../skyBand';
|
|
||||||
import { FrameSampler, FrameStats } from '../ridge/probe';
|
|
||||||
import { albedoPalette } from './terrainAlbedo';
|
|
||||||
import { sunIndex } from '../../../../sky/scatter.js';
|
|
||||||
import { AP_VOLUME, apVolumeWords, SKY_VIEW, skyViewWords } from './terrainScatter';
|
|
||||||
import {
|
|
||||||
nightness,
|
|
||||||
glowColour,
|
|
||||||
groundLight,
|
|
||||||
chooseSky,
|
|
||||||
SkyName,
|
|
||||||
START_TURNS,
|
|
||||||
sunDirection,
|
|
||||||
} from './terrainSky';
|
|
||||||
import { buildGrid, CAMERA, GRID, seedOffset, TERRAIN, triangleCount, view } from './terrainWorld';
|
|
||||||
import {
|
|
||||||
FULLSCREEN_VERT,
|
|
||||||
GRID_FRAG,
|
|
||||||
GRID_VERT,
|
|
||||||
heightFragmentSource,
|
|
||||||
SKY_FRAG,
|
|
||||||
} from './terrainShaders';
|
|
||||||
import { createTerrainStars } from './terrainStars';
|
|
||||||
import { overlayRequested } from '../debugOverlays';
|
|
||||||
import { showTierLabel } from './tierLabel';
|
|
||||||
|
|
||||||
export type TerrainOptions = Pick<
|
|
||||||
SceneOptions,
|
|
||||||
'canvas' | 'tier' | 'onCompileFail' | 'onContextLost'
|
|
||||||
> & {
|
|
||||||
/** Which baked sky lights and hazes the terrain. Default: `?sky=` in the page URL, else midnight. */
|
|
||||||
sky?: SkyName;
|
|
||||||
/** Put the sun at this elevation (degrees) and azimuth (clockwise from north; default: noonday's) instead of at the baked sky's: `?sun=` and `?az=` in the page URL. Lights between the two bakes, for dusk. */
|
|
||||||
sun?: { elevation: number; azimuth?: number };
|
|
||||||
/** The luminance band the sky is shaped into (skyBand.ts), in the sky pass and in the haze that fades into it. Default: none. */
|
|
||||||
band?: SkyBand;
|
|
||||||
/** Terrain seed: the height map is sampled at an offset taken from it. Default 0. */
|
|
||||||
seed?: number;
|
|
||||||
/** Show the rAF median/p95 readout (plus triangle count). Default: the page URL has `?probe=1`, where `debug` allows it. */
|
|
||||||
probe?: boolean;
|
|
||||||
/** The diagnostic overlays (readout, tier label) may be asked for by URL (debugOverlays.ts). Default: no. */
|
|
||||||
debug?: boolean;
|
|
||||||
onProbe?: (s: FrameStats & { still: boolean; triangles: number }) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Same shape as Scene.ts's ShaderCompileError, redeclared so this chunk does not import the ray-march scene. */
|
|
||||||
class ShaderCompileError extends Error {
|
|
||||||
constructor(readonly stage: 'vertex', readonly log: string) {
|
|
||||||
super(`${stage} shader failed to compile:\n${log}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function program(gl: WebGL2RenderingContext, name: string, vs: string, fs: string): WebGLProgram {
|
|
||||||
const make = (type: number, src: string, which: string) => {
|
|
||||||
const s = gl.createShader(type);
|
|
||||||
if (!s) throw new Error('createShader failed');
|
|
||||||
gl.shaderSource(s, src);
|
|
||||||
gl.compileShader(s);
|
|
||||||
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
|
|
||||||
const log = gl.getShaderInfoLog(s) ?? '';
|
|
||||||
gl.deleteShader(s);
|
|
||||||
throw new ShaderCompileError('vertex', `terrain ${name} ${which} shader: ${log}`);
|
|
||||||
}
|
|
||||||
return s;
|
|
||||||
};
|
|
||||||
const v = make(gl.VERTEX_SHADER, vs, 'vertex');
|
|
||||||
const f = make(gl.FRAGMENT_SHADER, fs, 'fragment');
|
|
||||||
const p = gl.createProgram();
|
|
||||||
if (!p) throw new Error('createProgram failed');
|
|
||||||
gl.attachShader(p, v);
|
|
||||||
gl.attachShader(p, f);
|
|
||||||
gl.linkProgram(p);
|
|
||||||
gl.deleteShader(v);
|
|
||||||
gl.deleteShader(f);
|
|
||||||
if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
|
|
||||||
const log = gl.getProgramInfoLog(p) ?? '';
|
|
||||||
gl.deleteProgram(p);
|
|
||||||
throw new ShaderCompileError('vertex', `terrain ${name} link: ${log}`);
|
|
||||||
}
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The terrain scene: same contract as `createRidgeScene`/`createScene` ({ login, dispose }, null for "keep the
|
|
||||||
* CSS ground"). WebGL2 only. The height map is baked once on the GPU (Phacelle, see terrainShaders.ts) into an
|
|
||||||
* RGBA8 texture; each frame is two draws: the sky from the baked scattering table, then a displaced grid lit by the
|
|
||||||
* baked sun and ambient and hazed toward that sky at the horizon. Cadence guard, pauses and the `?probe=1` readout match the
|
|
||||||
* ridge scene.
|
|
||||||
*/
|
|
||||||
export function createTerrainScene(opts: TerrainOptions): Scene | null {
|
|
||||||
const tier = opts.tier ?? 'full';
|
|
||||||
if (tier === 'off') return null;
|
|
||||||
const { canvas } = opts;
|
|
||||||
const probe = opts.probe ?? overlayRequested('probe', opts.debug === true);
|
|
||||||
const gl = canvas.getContext('webgl2', {
|
|
||||||
antialias: false,
|
|
||||||
alpha: false,
|
|
||||||
}) as WebGL2RenderingContext | null;
|
|
||||||
if (!gl) return null;
|
|
||||||
const units = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
|
|
||||||
if (typeof units === 'number' && units < 1) return null;
|
|
||||||
|
|
||||||
const sky = chooseSky(opts);
|
|
||||||
const spec = GRID[tier];
|
|
||||||
|
|
||||||
let skyProg: WebGLProgram;
|
|
||||||
let gridProg: WebGLProgram;
|
|
||||||
let bakeProg: WebGLProgram;
|
|
||||||
try {
|
|
||||||
bakeProg = program(gl, 'height', FULLSCREEN_VERT, heightFragmentSource());
|
|
||||||
skyProg = program(gl, 'sky', FULLSCREEN_VERT, SKY_FRAG);
|
|
||||||
gridProg = program(gl, 'grid', GRID_VERT, GRID_FRAG);
|
|
||||||
} catch (e) {
|
|
||||||
opts.onCompileFail?.(e as ShaderCompileError);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The height map, baked once.
|
|
||||||
const heightTex = gl.createTexture();
|
|
||||||
const fbo = gl.createFramebuffer();
|
|
||||||
gl.bindTexture(gl.TEXTURE_2D, heightTex);
|
|
||||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, spec.tex, spec.tex, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
|
||||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
|
||||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
|
||||||
// The baked scattering table, RGB16F, uploaded as it is stored (half floats); the shader divides by the store scale.
|
|
||||||
const skyTex = gl.createTexture();
|
|
||||||
gl.bindTexture(gl.TEXTURE_3D, skyTex);
|
|
||||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
|
|
||||||
gl.texImage3D(
|
|
||||||
gl.TEXTURE_3D,
|
|
||||||
0,
|
|
||||||
gl.RGB16F,
|
|
||||||
SKY_VIEW.width,
|
|
||||||
SKY_VIEW.height,
|
|
||||||
SKY_VIEW.depth,
|
|
||||||
0,
|
|
||||||
gl.RGB,
|
|
||||||
gl.HALF_FLOAT,
|
|
||||||
skyViewWords()
|
|
||||||
);
|
|
||||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
|
||||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
|
||||||
[gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) =>
|
|
||||||
gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE)
|
|
||||||
);
|
|
||||||
// The aerial perspective volume, RGBA16F, half floats as stored (src/sky/scatter.js).
|
|
||||||
const apTex = gl.createTexture();
|
|
||||||
gl.bindTexture(gl.TEXTURE_3D, apTex);
|
|
||||||
gl.texImage3D(
|
|
||||||
gl.TEXTURE_3D,
|
|
||||||
0,
|
|
||||||
gl.RGBA16F,
|
|
||||||
AP_VOLUME.width,
|
|
||||||
AP_VOLUME.height,
|
|
||||||
AP_VOLUME.depth,
|
|
||||||
0,
|
|
||||||
gl.RGBA,
|
|
||||||
gl.HALF_FLOAT,
|
|
||||||
apVolumeWords()
|
|
||||||
);
|
|
||||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
|
|
||||||
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
|
|
||||||
[gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) =>
|
|
||||||
gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE)
|
|
||||||
);
|
|
||||||
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
|
|
||||||
gl.bindTexture(gl.TEXTURE_2D, heightTex);
|
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
|
|
||||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, heightTex, 0);
|
|
||||||
const complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
|
|
||||||
const free: Array<() => void> = [];
|
|
||||||
const release = () => {
|
|
||||||
free.forEach((f) => f());
|
|
||||||
gl.deleteTexture(heightTex);
|
|
||||||
gl.deleteTexture(skyTex);
|
|
||||||
gl.deleteTexture(apTex);
|
|
||||||
gl.deleteFramebuffer(fbo);
|
|
||||||
gl.deleteProgram(bakeProg);
|
|
||||||
gl.deleteProgram(skyProg);
|
|
||||||
gl.deleteProgram(gridProg);
|
|
||||||
};
|
|
||||||
if (!complete) {
|
|
||||||
release();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
gl.viewport(0, 0, spec.tex, spec.tex);
|
|
||||||
gl.disable(gl.DEPTH_TEST);
|
|
||||||
gl.useProgram(bakeProg);
|
|
||||||
gl.uniform1f(gl.getUniformLocation(bakeProg, 'uSpan'), TERRAIN.span);
|
|
||||||
gl.uniform1f(gl.getUniformLocation(bakeProg, 'uTexels'), spec.tex);
|
|
||||||
gl.uniform2fv(gl.getUniformLocation(bakeProg, 'uSeed'), seedOffset(opts.seed ?? 0));
|
|
||||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
|
||||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
|
||||||
|
|
||||||
// The displaced grid.
|
|
||||||
const g = buildGrid(spec.grid);
|
|
||||||
const vao = gl.createVertexArray();
|
|
||||||
const vbuf = gl.createBuffer();
|
|
||||||
const ibuf = gl.createBuffer();
|
|
||||||
gl.bindVertexArray(vao);
|
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, vbuf);
|
|
||||||
gl.bufferData(gl.ARRAY_BUFFER, g.uv, gl.STATIC_DRAW);
|
|
||||||
gl.enableVertexAttribArray(0);
|
|
||||||
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
|
|
||||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibuf);
|
|
||||||
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, g.indices, gl.STATIC_DRAW);
|
|
||||||
gl.bindVertexArray(null);
|
|
||||||
free.push(
|
|
||||||
() => gl.deleteVertexArray(vao),
|
|
||||||
() => gl.deleteBuffer(vbuf),
|
|
||||||
() => gl.deleteBuffer(ibuf)
|
|
||||||
);
|
|
||||||
|
|
||||||
const sun = [...sunDirection(sky)];
|
|
||||||
const sunLight = [...sky.direct];
|
|
||||||
const ground = groundLight(sky);
|
|
||||||
const ambient = [...ground.ambient];
|
|
||||||
const heading = START_TURNS;
|
|
||||||
const glow = [...glowColour(sky)];
|
|
||||||
const band: [number, number] = sky.band ? [sky.band.floor, sky.band.ceiling] : [0, 1];
|
|
||||||
const lift = [...(sky.band?.lift ?? [0, 0, 0])];
|
|
||||||
const sunTexel = sunIndex(sky.elevation);
|
|
||||||
const night = nightness(sky.elevation);
|
|
||||||
const moonTexel = sunIndex(Math.abs(sky.elevation));
|
|
||||||
const palette = albedoPalette(sky);
|
|
||||||
const triangles = triangleCount(spec.grid);
|
|
||||||
|
|
||||||
const stars = createTerrainStars(canvas, sky);
|
|
||||||
const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)');
|
|
||||||
const sampler = new FrameSampler();
|
|
||||||
let still = tier === 'still';
|
|
||||||
let disposed = false;
|
|
||||||
let lost = false;
|
|
||||||
let raf = 0;
|
|
||||||
let readout: HTMLElement | undefined;
|
|
||||||
let resizeTimer = 0;
|
|
||||||
let turnsAtPause = 0;
|
|
||||||
let playedFrom: number | undefined;
|
|
||||||
|
|
||||||
/** Size the canvas: low renders at 0.75 of the CSS size; full at device pixel ratio capped to 2. */
|
|
||||||
const size = () => {
|
|
||||||
const dpr = Math.min(window.devicePixelRatio || 1, 2) * (tier === 'low' ? 0.75 : 1);
|
|
||||||
canvas.width = Math.max(1, Math.round((canvas.clientWidth || window.innerWidth) * dpr));
|
|
||||||
canvas.height = Math.max(1, Math.round((canvas.clientHeight || window.innerHeight) * dpr));
|
|
||||||
};
|
|
||||||
|
|
||||||
const draw = (turns: number) => {
|
|
||||||
if (lost) return;
|
|
||||||
gl.viewport(0, 0, canvas.width, canvas.height);
|
|
||||||
const v = view(canvas.width / canvas.height, (turns + heading) % 1);
|
|
||||||
gl.disable(gl.DEPTH_TEST);
|
|
||||||
gl.useProgram(skyProg);
|
|
||||||
const us = (n: string) => gl.getUniformLocation(skyProg, n);
|
|
||||||
gl.uniform3fv(us('uSun'), sun);
|
|
||||||
gl.uniform3fv(us('uSunColour'), sunLight);
|
|
||||||
gl.uniform3fv(us('uGlow'), glow);
|
|
||||||
gl.uniform2fv(us('uBand'), band);
|
|
||||||
gl.uniform3fv(us('uLift'), lift);
|
|
||||||
gl.uniform1f(us('uSunIndex'), sunTexel);
|
|
||||||
gl.activeTexture(gl.TEXTURE1);
|
|
||||||
gl.bindTexture(gl.TEXTURE_3D, skyTex);
|
|
||||||
gl.uniform1i(us('uSky'), 1);
|
|
||||||
gl.uniform3fv(us('uRight'), v.right);
|
|
||||||
gl.uniform3fv(us('uUp'), v.up);
|
|
||||||
gl.uniform3fv(us('uForward'), v.forward);
|
|
||||||
gl.uniform2f(us('uSize'), canvas.width, canvas.height);
|
|
||||||
gl.uniform1f(us('uTanHalf'), Math.tan(CAMERA.fov / 2));
|
|
||||||
gl.drawArrays(gl.TRIANGLES, 0, 3);
|
|
||||||
|
|
||||||
gl.enable(gl.DEPTH_TEST);
|
|
||||||
gl.clear(gl.DEPTH_BUFFER_BIT);
|
|
||||||
gl.useProgram(gridProg);
|
|
||||||
const u = (n: string) => gl.getUniformLocation(gridProg, n);
|
|
||||||
gl.uniformMatrix4fv(u('uViewProj'), false, v.viewProj);
|
|
||||||
gl.uniform3fv(u('uCamera'), v.eye);
|
|
||||||
gl.uniform1f(u('uSpan'), TERRAIN.span);
|
|
||||||
gl.uniform1i(u('uTex'), spec.tex);
|
|
||||||
gl.uniform3fv(u('uSun'), sun);
|
|
||||||
gl.uniform3fv(u('uLightDir'), ground.dir);
|
|
||||||
gl.uniform3fv(u('uLight'), ground.colour);
|
|
||||||
gl.uniform3fv(u('uAmbient'), ambient);
|
|
||||||
gl.uniform3fv(u('uGlow'), glow);
|
|
||||||
gl.uniform2fv(u('uBand'), band);
|
|
||||||
gl.uniform3fv(u('uLift'), lift);
|
|
||||||
gl.uniform1f(u('uSunIndex'), sunTexel);
|
|
||||||
gl.activeTexture(gl.TEXTURE1);
|
|
||||||
gl.bindTexture(gl.TEXTURE_3D, skyTex);
|
|
||||||
gl.uniform1i(u('uSky'), 1);
|
|
||||||
gl.uniform1f(u('uNight'), night);
|
|
||||||
gl.uniform1f(u('uMoonIndex'), moonTexel);
|
|
||||||
gl.activeTexture(gl.TEXTURE2);
|
|
||||||
gl.bindTexture(gl.TEXTURE_3D, apTex);
|
|
||||||
gl.uniform1i(u('uAP'), 2);
|
|
||||||
gl.uniform3fv(u('uSoil'), palette.soil);
|
|
||||||
gl.uniform3fv(u('uScree'), palette.scree);
|
|
||||||
gl.uniform3fv(u('uRock'), palette.rock);
|
|
||||||
gl.uniform3fv(u('uSnow'), palette.snow);
|
|
||||||
gl.uniform1f(u('uSnowLine'), palette.snowLine);
|
|
||||||
gl.activeTexture(gl.TEXTURE0);
|
|
||||||
gl.bindTexture(gl.TEXTURE_2D, heightTex);
|
|
||||||
gl.uniform1i(u('uHeight'), 0);
|
|
||||||
gl.bindVertexArray(vao);
|
|
||||||
gl.drawElements(gl.TRIANGLES, g.indices.length, gl.UNSIGNED_INT, 0);
|
|
||||||
gl.bindVertexArray(null);
|
|
||||||
stars?.draw((turns + heading) % 1, moving() ? performance.now() / 1000 : undefined);
|
|
||||||
};
|
|
||||||
|
|
||||||
const moving = () =>
|
|
||||||
!still &&
|
|
||||||
!disposed &&
|
|
||||||
!lost &&
|
|
||||||
!(reducedMotion?.matches ?? false) &&
|
|
||||||
document.visibilityState === 'visible';
|
|
||||||
|
|
||||||
const turnsNow = (now: number) =>
|
|
||||||
turnsAtPause + (playedFrom === undefined ? 0 : (now - playedFrom) / (CAMERA.seconds * 1000));
|
|
||||||
|
|
||||||
const report = (stillNow: boolean) => {
|
|
||||||
const s = { ...sampler.stats(), still: stillNow, triangles };
|
|
||||||
opts.onProbe?.(s);
|
|
||||||
if (readout) {
|
|
||||||
readout.textContent = `terrain · ${s.triangles} tris · n ${s.n} · median ${s.medianMs.toFixed(
|
|
||||||
1
|
|
||||||
)} ms · p95 ${s.p95Ms.toFixed(1)} ms${stillNow ? ' · STILL' : ''}`;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const settleToStill = () => {
|
|
||||||
if (playedFrom !== undefined) turnsAtPause = turnsNow(performance.now());
|
|
||||||
playedFrom = undefined;
|
|
||||||
still = true;
|
|
||||||
cancelAnimationFrame(raf);
|
|
||||||
raf = 0;
|
|
||||||
draw(turnsAtPause);
|
|
||||||
report(true);
|
|
||||||
};
|
|
||||||
|
|
||||||
let sinceReport = 0;
|
|
||||||
// The first window is measured (guard against a slow device); after it the loop only draws.
|
|
||||||
let measuring = true;
|
|
||||||
const frame = (now: number) => {
|
|
||||||
raf = 0;
|
|
||||||
if (!moving()) return;
|
|
||||||
draw(turnsNow(now));
|
|
||||||
if (!measuring) {
|
|
||||||
raf = requestAnimationFrame(frame);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const full = sampler.push(now);
|
|
||||||
if (full) {
|
|
||||||
measuring = false;
|
|
||||||
if (sampler.slow()) {
|
|
||||||
settleToStill();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (probe) report(false);
|
|
||||||
} else if (probe && now - sinceReport > 500) {
|
|
||||||
sinceReport = now;
|
|
||||||
report(false);
|
|
||||||
}
|
|
||||||
raf = requestAnimationFrame(frame);
|
|
||||||
};
|
|
||||||
const wake = () => {
|
|
||||||
if (!moving()) {
|
|
||||||
if (playedFrom !== undefined) turnsAtPause = turnsNow(performance.now());
|
|
||||||
playedFrom = undefined;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (raf) return;
|
|
||||||
playedFrom = performance.now();
|
|
||||||
if (measuring) sampler.reset();
|
|
||||||
raf = requestAnimationFrame(frame);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onLost = (e: Event) => {
|
|
||||||
e.preventDefault();
|
|
||||||
lost = true;
|
|
||||||
cancelAnimationFrame(raf);
|
|
||||||
raf = 0;
|
|
||||||
opts.onContextLost?.();
|
|
||||||
};
|
|
||||||
canvas.addEventListener('webglcontextlost', onLost);
|
|
||||||
|
|
||||||
size();
|
|
||||||
if (probe && canvas.parentElement) {
|
|
||||||
readout = document.createElement('div');
|
|
||||||
Object.assign(readout.style, {
|
|
||||||
position: 'absolute',
|
|
||||||
left: '8px',
|
|
||||||
top: '8px',
|
|
||||||
font: '12px monospace',
|
|
||||||
color: '#fff',
|
|
||||||
background: 'rgba(0,0,0,.55)',
|
|
||||||
padding: '2px 6px',
|
|
||||||
borderRadius: '3px',
|
|
||||||
pointerEvents: 'none',
|
|
||||||
});
|
|
||||||
canvas.parentElement.appendChild(readout);
|
|
||||||
}
|
|
||||||
const removeLabel = showTierLabel(canvas, tier, opts.debug === true);
|
|
||||||
if (still) settleToStill();
|
|
||||||
else wake();
|
|
||||||
if (!still && !moving()) draw(0);
|
|
||||||
|
|
||||||
const onVisibility = () => {
|
|
||||||
sampler.reset();
|
|
||||||
wake();
|
|
||||||
};
|
|
||||||
const onResize = () => {
|
|
||||||
clearTimeout(resizeTimer);
|
|
||||||
resizeTimer = window.setTimeout(() => {
|
|
||||||
if (disposed || lost) return;
|
|
||||||
size();
|
|
||||||
stars?.resize();
|
|
||||||
draw(turnsNow(performance.now()));
|
|
||||||
sampler.reset();
|
|
||||||
}, 250);
|
|
||||||
};
|
|
||||||
document.addEventListener('visibilitychange', onVisibility);
|
|
||||||
window.addEventListener('resize', onResize);
|
|
||||||
reducedMotion?.addEventListener?.('change', onVisibility);
|
|
||||||
|
|
||||||
return {
|
|
||||||
login() {
|
|
||||||
// The camera is the same before and after.
|
|
||||||
},
|
|
||||||
dispose() {
|
|
||||||
if (disposed) return;
|
|
||||||
disposed = true;
|
|
||||||
cancelAnimationFrame(raf);
|
|
||||||
clearTimeout(resizeTimer);
|
|
||||||
document.removeEventListener('visibilitychange', onVisibility);
|
|
||||||
window.removeEventListener('resize', onResize);
|
|
||||||
reducedMotion?.removeEventListener?.('change', onVisibility);
|
|
||||||
canvas.removeEventListener('webglcontextlost', onLost);
|
|
||||||
readout?.remove();
|
|
||||||
removeLabel?.();
|
|
||||||
stars?.dispose();
|
|
||||||
release();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
@ -1,286 +0,0 @@
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-function -- DOM stubs, as the other scene tests */
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
import { createTerrainSkyScene, SKY_WIDTH } from './TerrainSky2D';
|
|
||||||
import { startBackgroundScene } from '../index';
|
|
||||||
import { terrainSkyFor } from '../skyForState';
|
|
||||||
|
|
||||||
let search: string;
|
|
||||||
let arcs: number;
|
|
||||||
let overlay: { remove: ReturnType<typeof vi.fn> };
|
|
||||||
let windowListeners: Record<string, () => void>;
|
|
||||||
beforeEach(() => {
|
|
||||||
search = '';
|
|
||||||
arcs = 0;
|
|
||||||
windowListeners = {};
|
|
||||||
vi.stubGlobal('document', {
|
|
||||||
createElement: () => {
|
|
||||||
overlay = {
|
|
||||||
remove: vi.fn(),
|
|
||||||
style: {},
|
|
||||||
setAttribute() {},
|
|
||||||
getContext: () => ({
|
|
||||||
clearRect() {},
|
|
||||||
beginPath() {},
|
|
||||||
fill() {},
|
|
||||||
arc: () => {
|
|
||||||
arcs += 1;
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
} as any;
|
|
||||||
return overlay;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
vi.stubGlobal('window', {
|
|
||||||
devicePixelRatio: 1,
|
|
||||||
innerWidth: 400,
|
|
||||||
innerHeight: 800,
|
|
||||||
addEventListener: (n: string, f: () => void) => {
|
|
||||||
windowListeners[n] = f;
|
|
||||||
},
|
|
||||||
removeEventListener: (n: string) => {
|
|
||||||
delete windowListeners[n];
|
|
||||||
},
|
|
||||||
get location() {
|
|
||||||
return { search };
|
|
||||||
},
|
|
||||||
setTimeout,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
|
||||||
vi.unstubAllGlobals();
|
|
||||||
});
|
|
||||||
|
|
||||||
/** A canvas with a recording 2D context; `gl` is what 'webgl2' answers. */
|
|
||||||
function canvasWith(opts: { twoD?: boolean; gl?: unknown } = {}) {
|
|
||||||
const painted: { data: Uint8ClampedArray; width: number; height: number }[] = [];
|
|
||||||
const ctx = {
|
|
||||||
createImageData: (width: number, height: number) => ({
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
data: new Uint8ClampedArray(width * height * 4),
|
|
||||||
}),
|
|
||||||
putImageData: (image: any) => painted.push(image),
|
|
||||||
};
|
|
||||||
const parentAppend = vi.fn();
|
|
||||||
const canvas: any = {
|
|
||||||
width: 0,
|
|
||||||
height: 0,
|
|
||||||
clientWidth: 400,
|
|
||||||
clientHeight: 800,
|
|
||||||
parentElement: { appendChild: parentAppend },
|
|
||||||
getContext: vi.fn((kind: string) => {
|
|
||||||
if (kind !== '2d') return opts.gl ?? null;
|
|
||||||
return opts.twoD === false ? null : ctx;
|
|
||||||
}),
|
|
||||||
addEventListener: vi.fn(),
|
|
||||||
removeEventListener: vi.fn(),
|
|
||||||
};
|
|
||||||
return { canvas, painted, parentAppend };
|
|
||||||
}
|
|
||||||
|
|
||||||
const pixel = (img: { data: Uint8ClampedArray; width: number }, x: number, y: number) =>
|
|
||||||
Array.from(img.data.slice((y * img.width + x) * 4, (y * img.width + x) * 4 + 3));
|
|
||||||
const mean = (img: { data: Uint8ClampedArray }) => {
|
|
||||||
let s = 0;
|
|
||||||
for (let i = 0; i < img.data.length; i += 4) s += img.data[i] + img.data[i + 1] + img.data[i + 2];
|
|
||||||
return s / (img.data.length / 4) / 3;
|
|
||||||
};
|
|
||||||
|
|
||||||
describe('createTerrainSkyScene', () => {
|
|
||||||
it("returns null at tier 'off' and touches nothing", () => {
|
|
||||||
const { canvas } = canvasWith();
|
|
||||||
expect(createTerrainSkyScene({ canvas, tier: 'off' })).toBeNull();
|
|
||||||
expect(canvas.getContext).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns null when the canvas gives no 2D context (the CSS ground stays)', () => {
|
|
||||||
const { canvas } = canvasWith({ twoD: false });
|
|
||||||
expect(createTerrainSkyScene({ canvas, tier: 'low' })).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('paints one opaque, graded sky: the horizon end of the image is not the zenith end', () => {
|
|
||||||
const { canvas, painted } = canvasWith();
|
|
||||||
const s = createTerrainSkyScene({ canvas, tier: 'low', sky: 'noonday' })!;
|
|
||||||
expect(painted).toHaveLength(1);
|
|
||||||
const img = painted[0];
|
|
||||||
expect(img.width).toBe(SKY_WIDTH);
|
|
||||||
expect(canvas.width).toBe(SKY_WIDTH);
|
|
||||||
expect(canvas.height).toBe(img.height);
|
|
||||||
for (let i = 3; i < img.data.length; i += 4) expect(img.data[i]).toBe(255);
|
|
||||||
const x = Math.floor(SKY_WIDTH / 2);
|
|
||||||
expect(pixel(img, x, 0)).not.toEqual(pixel(img, x, img.height - 1));
|
|
||||||
expect(mean(img)).toBeGreaterThan(20);
|
|
||||||
s.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('follows the baked sky: noon is brighter than midnight, and ?sun= / ?az= move it', () => {
|
|
||||||
const noon = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: noon.canvas, tier: 'low', sky: 'noonday' })!.dispose();
|
|
||||||
const night = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: night.canvas, tier: 'low', sky: 'midnight' })!.dispose();
|
|
||||||
expect(mean(noon.painted[0])).toBeGreaterThan(mean(night.painted[0]) * 1.5);
|
|
||||||
|
|
||||||
const low = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: low.canvas, tier: 'low', sun: { elevation: 30 } })!.dispose();
|
|
||||||
const down = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: down.canvas, tier: 'low', sun: { elevation: -20 } })!.dispose();
|
|
||||||
expect(mean(low.painted[0])).toBeGreaterThan(mean(down.painted[0]));
|
|
||||||
|
|
||||||
search = '?sun=30&az=0';
|
|
||||||
const q0 = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: q0.canvas, tier: 'low' })!.dispose();
|
|
||||||
search = '?sun=30&az=180';
|
|
||||||
const q1 = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: q1.canvas, tier: 'low' })!.dispose();
|
|
||||||
expect(Array.from(q0.painted[0].data)).not.toEqual(Array.from(q1.painted[0].data));
|
|
||||||
});
|
|
||||||
|
|
||||||
it('stars only on a dark sky', () => {
|
|
||||||
const night = canvasWith();
|
|
||||||
const a = createTerrainSkyScene({ canvas: night.canvas, tier: 'low', sky: 'midnight' })!;
|
|
||||||
expect(night.parentAppend).toHaveBeenCalledTimes(1);
|
|
||||||
expect(arcs).toBeGreaterThan(0);
|
|
||||||
a.dispose();
|
|
||||||
expect(overlay.remove).toHaveBeenCalled();
|
|
||||||
arcs = 0;
|
|
||||||
const day = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: day.canvas, tier: 'low', sky: 'noonday' })!.dispose();
|
|
||||||
expect(day.parentAppend).not.toHaveBeenCalled();
|
|
||||||
expect(arcs).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('repaints on resize, and dispose stops listening', () => {
|
|
||||||
vi.useFakeTimers();
|
|
||||||
vi.stubGlobal('window', {
|
|
||||||
...(window as any),
|
|
||||||
setTimeout,
|
|
||||||
addEventListener: (window as any).addEventListener,
|
|
||||||
});
|
|
||||||
const { canvas, painted } = canvasWith();
|
|
||||||
const s = createTerrainSkyScene({ canvas, tier: 'low', sky: 'noonday' })!;
|
|
||||||
expect(windowListeners.resize).toBeDefined();
|
|
||||||
windowListeners.resize();
|
|
||||||
vi.advanceTimersByTime(300);
|
|
||||||
expect(painted).toHaveLength(2);
|
|
||||||
s.dispose();
|
|
||||||
expect(windowListeners.resize).toBeUndefined();
|
|
||||||
vi.useRealTimers();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the sky-only tier label', () => {
|
|
||||||
const labels = (parentAppend: ReturnType<typeof vi.fn>) =>
|
|
||||||
parentAppend.mock.calls.filter(([e]) => e?.textContent === 'terrain · sky-only');
|
|
||||||
|
|
||||||
it('shows for ?tierlabel=1 only where the overlays are allowed', () => {
|
|
||||||
search = '?tierlabel=1';
|
|
||||||
const off = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: off.canvas, tier: 'low' })!.dispose();
|
|
||||||
expect(labels(off.parentAppend)).toHaveLength(0);
|
|
||||||
const on = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: on.canvas, tier: 'low', debug: true })!.dispose();
|
|
||||||
expect(labels(on.parentAppend)).toHaveLength(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('the door allows it from the config flag, and not from a plain production config', async () => {
|
|
||||||
vi.stubEnv('DEV', false);
|
|
||||||
vi.stubEnv('VITE_PREVIEW_DEMO', '');
|
|
||||||
search = '?tierlabel=1';
|
|
||||||
const plain = canvasWith();
|
|
||||||
(
|
|
||||||
await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas: plain.canvas })
|
|
||||||
)?.dispose();
|
|
||||||
expect(labels(plain.parentAppend)).toHaveLength(0);
|
|
||||||
const flagged = canvasWith();
|
|
||||||
(
|
|
||||||
await startBackgroundScene(
|
|
||||||
{ tier: 'low', style: 'terrain', debugOverlays: true },
|
|
||||||
{},
|
|
||||||
{ canvas: flagged.canvas }
|
|
||||||
)
|
|
||||||
)?.dispose();
|
|
||||||
expect(labels(flagged.parentAppend)).toHaveLength(1);
|
|
||||||
vi.unstubAllEnvs();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('startBackgroundScene, terrain style', () => {
|
|
||||||
it('without WebGL2 mounts the sky on the same canvas instead of returning null', async () => {
|
|
||||||
const { canvas, painted } = canvasWith({ gl: null });
|
|
||||||
const scene = await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas });
|
|
||||||
expect(scene).not.toBeNull();
|
|
||||||
expect(canvas.getContext.mock.calls.map((c: unknown[]) => c[0])).toEqual(['webgl2', '2d']);
|
|
||||||
expect(painted).toHaveLength(1);
|
|
||||||
scene!.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('with WebGL2 the terrain runs and the 2D sky is never requested', async () => {
|
|
||||||
const gl: any = new Proxy(
|
|
||||||
{},
|
|
||||||
{
|
|
||||||
get(_t, name: string) {
|
|
||||||
if (name === 'getShaderParameter' || name === 'getProgramParameter') return () => true;
|
|
||||||
if (name === 'checkFramebufferStatus') return () => 1;
|
|
||||||
if (name === 'getParameter') return () => 16;
|
|
||||||
if (/^[A-Z_0-9]+$/.test(name)) return 1;
|
|
||||||
return () => ({});
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
Object.assign(document, {
|
|
||||||
addEventListener() {},
|
|
||||||
removeEventListener() {},
|
|
||||||
visibilityState: 'visible',
|
|
||||||
});
|
|
||||||
vi.stubGlobal('requestAnimationFrame', () => 1);
|
|
||||||
vi.stubGlobal('cancelAnimationFrame', () => {});
|
|
||||||
vi.stubGlobal('performance', { now: () => 0 });
|
|
||||||
(window as any).matchMedia = () => ({
|
|
||||||
matches: false,
|
|
||||||
addEventListener() {},
|
|
||||||
removeEventListener() {},
|
|
||||||
});
|
|
||||||
const { canvas, painted } = canvasWith({ gl });
|
|
||||||
const scene = await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas });
|
|
||||||
expect(scene).not.toBeNull();
|
|
||||||
expect(canvas.getContext.mock.calls.map((c: unknown[]) => c[0])).toEqual(['webgl2']);
|
|
||||||
expect(painted).toHaveLength(0);
|
|
||||||
scene!.dispose();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a canvas that took a GL context but gives no scene still ends as null: no 2D context to paint on', async () => {
|
|
||||||
const { canvas } = canvasWith({ gl: null, twoD: false });
|
|
||||||
expect(
|
|
||||||
await startBackgroundScene({ tier: 'low', style: 'terrain' }, {}, { canvas })
|
|
||||||
).toBeNull();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('the 2D sky lies in the band of its state', () => {
|
|
||||||
// The painted pixels, read back through the sRGB curve as a screen shows them.
|
|
||||||
const lumOf = (rgb: number[]) => {
|
|
||||||
const [r, g, b] = rgb.map((v) => {
|
|
||||||
const e = v / 255;
|
|
||||||
return e <= 0.04045 ? e / 12.92 : ((e + 0.055) / 1.055) ** 2.4;
|
|
||||||
});
|
|
||||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
||||||
};
|
|
||||||
const painted = (state: 'day' | 'dusk' | 'night') => {
|
|
||||||
const c = canvasWith();
|
|
||||||
createTerrainSkyScene({ canvas: c.canvas, tier: 'low', ...terrainSkyFor(state) })!.dispose();
|
|
||||||
const img = c.painted[0];
|
|
||||||
const out: number[] = [];
|
|
||||||
for (let y = 0; y < img.height; y += 1) {
|
|
||||||
for (let x = 0; x < img.width; x += 1) out.push(lumOf(pixel(img, x, y)));
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
};
|
|
||||||
|
|
||||||
it.each([['day'], ['dusk']] as const)('%s: no pixel below the text bound 0.2983', (state) => {
|
|
||||||
expect(Math.min(...painted(state))).toBeGreaterThanOrEqual(0.2983);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('night: no pixel above the text bound 0.0931', () => {
|
|
||||||
expect(Math.max(...painted('night'))).toBeLessThanOrEqual(0.0931);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
@ -1,90 +0,0 @@
|
||||||
import type { Scene } from '../Scene';
|
|
||||||
import type { TerrainOptions } from './Terrain';
|
|
||||||
import { chooseSky, skyColour, START_TURNS, Vec3 } from './terrainSky';
|
|
||||||
import { createTerrainStars } from './terrainStars';
|
|
||||||
import { showTierLabel } from './tierLabel';
|
|
||||||
import { CAMERA, view } from './terrainWorld';
|
|
||||||
|
|
||||||
/** The sky is smooth, so it is painted this many px wide and stretched by the canvas's CSS size. */
|
|
||||||
export const SKY_WIDTH = 96;
|
|
||||||
|
|
||||||
/** The sky of the terrain scene without WebGL2: the camera's first frame of `skyColour`, once, on a 2D canvas, with the star layer on top. */
|
|
||||||
export type TerrainSkyOptions = Pick<
|
|
||||||
TerrainOptions,
|
|
||||||
'canvas' | 'tier' | 'sky' | 'sun' | 'band' | 'debug'
|
|
||||||
>;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Same contract as `createTerrainScene`. Paints the terrain scene's sky (the CPU twin of its sky shader, from the
|
|
||||||
* same baked tables and the same `?sun=` `?az=` `?sky=` choice) for the camera at its start, still: nothing moves, so
|
|
||||||
* a device that cannot run WebGL2 pays one paint and one resize repaint. Below the horizon there is no terrain, so
|
|
||||||
* the image continues with the horizon's colour. Null for "keep the CSS ground": tier off, or the canvas already
|
|
||||||
* holds a WebGL context and gives no 2D one.
|
|
||||||
*/
|
|
||||||
export function createTerrainSkyScene(opts: TerrainSkyOptions): Scene | null {
|
|
||||||
if ((opts.tier ?? 'full') === 'off') return null;
|
|
||||||
const { canvas } = opts;
|
|
||||||
const ctx = canvas.getContext('2d');
|
|
||||||
if (!ctx) return null;
|
|
||||||
const sky = chooseSky(opts);
|
|
||||||
const stars = createTerrainStars(canvas, sky);
|
|
||||||
const heading = START_TURNS;
|
|
||||||
const tanHalf = Math.tan(CAMERA.fov / 2);
|
|
||||||
let disposed = false;
|
|
||||||
let resizeTimer = 0;
|
|
||||||
|
|
||||||
const paint = () => {
|
|
||||||
const w = SKY_WIDTH;
|
|
||||||
const cw = canvas.clientWidth || window.innerWidth;
|
|
||||||
const ch = canvas.clientHeight || window.innerHeight;
|
|
||||||
const h = Math.max(1, Math.round((w * ch) / cw));
|
|
||||||
canvas.width = w;
|
|
||||||
canvas.height = h;
|
|
||||||
const v = view(cw / ch, heading);
|
|
||||||
const image = ctx.createImageData(w, h);
|
|
||||||
for (let y = 0; y < h; y += 1) {
|
|
||||||
const ny = 1 - ((y + 0.5) / h) * 2;
|
|
||||||
for (let x = 0; x < w; x += 1) {
|
|
||||||
const nx = ((x + 0.5) / w) * 2 - 1;
|
|
||||||
const d = [0, 1, 2].map(
|
|
||||||
(i) => v.forward[i] + nx * tanHalf * (cw / ch) * v.right[i] + ny * tanHalf * v.up[i]
|
|
||||||
);
|
|
||||||
const len = Math.hypot(d[0], d[1], d[2]);
|
|
||||||
const c: Vec3 = skyColour(sky, [d[0] / len, d[1] / len, d[2] / len]);
|
|
||||||
const at = (y * w + x) * 4;
|
|
||||||
for (let i = 0; i < 3; i += 1) {
|
|
||||||
image.data[at + i] = Math.round(255 * Math.min(1, Math.max(0, c[i])) ** (1 / 2.2));
|
|
||||||
}
|
|
||||||
image.data[at + 3] = 255;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ctx.putImageData(image, 0, 0);
|
|
||||||
stars?.draw(heading);
|
|
||||||
};
|
|
||||||
|
|
||||||
const onResize = () => {
|
|
||||||
clearTimeout(resizeTimer);
|
|
||||||
resizeTimer = window.setTimeout(() => {
|
|
||||||
if (disposed) return;
|
|
||||||
stars?.resize();
|
|
||||||
paint();
|
|
||||||
}, 250);
|
|
||||||
};
|
|
||||||
window.addEventListener('resize', onResize);
|
|
||||||
paint();
|
|
||||||
const removeLabel = showTierLabel(canvas, 'sky-only', opts.debug === true);
|
|
||||||
|
|
||||||
return {
|
|
||||||
login() {
|
|
||||||
// Nothing moves, so there is no pull-back to start.
|
|
||||||
},
|
|
||||||
dispose() {
|
|
||||||
if (disposed) return;
|
|
||||||
disposed = true;
|
|
||||||
clearTimeout(resizeTimer);
|
|
||||||
window.removeEventListener('resize', onResize);
|
|
||||||
removeLabel?.();
|
|
||||||
stars?.dispose();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue