diff --git a/harness/scene/README.md b/harness/scene/README.md index 514bb7dc..0871a6f6 100644 --- a/harness/scene/README.md +++ b/harness/scene/README.md @@ -46,4 +46,4 @@ Presets (`PRESETS` in `ridgeSheet.ts`; swiss and poster take every key not named | painterly | DEFAULT_LOOK: groundNoise 0.35, cloudShadows 0.5, nearWarm 0.6, hazeScale 2, inkScale 0.4, celBands 3, celSoftness 0.05, celAmbientAway 0.7 | | painterly-cel-2 / -3 / -4 | painterly with celBands 2 / 3 / 4 | -Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation). +Named moments (`ridgeSheet.html?named=1`): the six moments of the Sky menu (dawn, morning, noon, golden hour, dusk, night) at the baked place on the December and June solstices, drawn from `momentFor` as the app draws them (`SKY_MOMENTS` in `ridge/skyMoment.ts` is the table tuned by eye from this sheet). Night sets (`ridgeSheet.html`): `?moments=2026-11-24T22:00Z,2026-12-09T20:00Z` pins explicit UTC moments (the sun, moon and stars are those of the moment); `?night=1` renders the next new moon, first quarter and full moon from today (`&from=YYYY-MM-DD`) at four hours each (`&hours=18,21,0,4`, UTC) plus deep dusk of the full-moon evening; `&lines=1` draws the constellation lines (the Sky menu's hidden toggle). Use `&w=300` for the 13-column set. The night look's knobs: `NIGHT_LOOK` in `ridge/nightSky.ts` (star point spread, contrast exponents, moon size, earthshine, line opacity), `NIGHT_CEILING` and `SCOTOPIC` in `ridge/toneMap.ts`, the night `Budget` (key, targets, partial adaptation). diff --git a/harness/scene/ridgeSheet.ts b/harness/scene/ridgeSheet.ts index 3471e8be..9cb4b42b 100644 --- a/harness/scene/ridgeSheet.ts +++ b/harness/scene/ridgeSheet.ts @@ -17,8 +17,7 @@ import { nightBodies, onScreen, paintNightBodies } from '../../src/app/features/ import { sunAt } from '../../src/app/features/scene/ridge/sunAt'; import { linesAt } from '../../src/app/features/scene/ridge/starCatalogue'; import { moonPhase } from '../../src/sky/moon.js'; -import { DAY_FROM } from '../../src/app/features/scene/skyState'; -import type { FixedSkyState } from '../../src/app/features/scene/skyState'; +import { MOMENT_IDS, momentFor } from '../../src/app/features/scene/ridge/skyMoment'; const DIR = '/public/ridge/vienna-6815bb9dca99/'; @@ -38,7 +37,7 @@ interface Column { time?: Date; } -/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. Elevation picks the display budget (day from DAY_FROM, night below its negative). */ +/** Sun elevation and compass azimuth of each column; the cards look at 214 +- 36. The band of the elevation (`skyBand`) picks the display budget. */ const SKIES: Column[] = [ { label: 'dawn 2 deg', elevation: 2, azimuth: 100 }, { label: 'morning 15 deg', elevation: 15, azimuth: 135 }, @@ -138,6 +137,14 @@ function momentsFrom(params: URLSearchParams, place: Parameters[0] if (Number.isNaN(time.getTime())) throw new Error(`moments=: ${iso} is not a date`); return { label: fmt(time), time }; }); + // `named=1`: the six named moments of the sky menu (`momentFor`, as the app draws them) on both solstices at the place: the look sheet the elevation table is tuned from. + if (params.get('named')) + return ['2026-12-21', '2026-06-21'].flatMap((day) => + MOMENT_IDS.map((id) => { + const time = momentFor({ kind: 'named', id }, place, new Date(`${day}T12:00:00Z`)); + return { label: `${id} ${day.slice(5)} ${fmt(time)}`, time }; + }) + ); if (!params.get('night')) return undefined; const from = params.get('from') ? new Date(`${params.get('from')}T00:00:00Z`) : new Date(); const hours = (params.get('hours') ?? '18,21,0,4').split(',').map(Number); @@ -176,9 +183,6 @@ const W = Number(q.get('w') ?? 480); const H = q.get('h') ? Number(q.get('h')) : Math.round((W * 9) / 16); const root = document.getElementById('sheet') as HTMLElement; -const stateOf = (el: number): FixedSkyState => - el >= DAY_FROM ? 'day' : el <= -DAY_FROM ? 'night' : 'dusk'; - async function main() { const manifest = parseManifest(await (await fetch(`${DIR}manifest.json`)).json(), DIR); const blobs = await Promise.all( @@ -213,7 +217,7 @@ async function main() { col.time !== undefined ? sunAt(view.place, col.time) : { elevation: col.elevation as number, azimuth: col.azimuth as number, time }; - const physical = makePhysicalSky(stateOf(sun.elevation), time, 0, view, sun); + const physical = makePhysicalSky(sun, 0, view); const px = paintSky(physical, W, H, win.camera); const bodies = nightBodies(physical, px, withLines); const small = document.createElement('canvas'); diff --git a/public/ridge/vienna-6815bb9dca99/manifest.json b/public/ridge/vienna-6815bb9dca99/manifest.json index 935e5abd..b7772445 100644 --- a/public/ridge/vienna-6815bb9dca99/manifest.json +++ b/public/ridge/vienna-6815bb9dca99/manifest.json @@ -1,6 +1,6 @@ { "schema": 2, - "baker_version": 2, + "baker_version": 3, "bake_id": "6815bb9dca99", "place": { "id": "vienna", @@ -8,7 +8,8 @@ "lat": 48.1929826, "lon": 16.3534237, "altitude_km": 0.18330000000000002, - "eye_m": 213.3 + "eye_m": 213.3, + "tz": "Europe/Vienna" }, "view": { "look_az_deg": 214.0, diff --git a/scripts/ridge-bake/export.py b/scripts/ridge-bake/export.py index 0ace0244..03982d5d 100644 --- a/scripts/ridge-bake/export.py +++ b/scripts/ridge-bake/export.py @@ -7,11 +7,12 @@ The runtime reads manifest.json (SCHEMA is its contract) and nothing else about import no baker; bake_place imports ridge, which needs RIDGE_TILES and RIDGE_WORK (main sets them from --tiles / --work).""" import os, sys, json, math, shutil, hashlib, argparse, tempfile from pathlib import Path +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import numpy as np, imagecodecs -BAKER_VERSION = 2 +BAKER_VERSION = 3 WINDOW_DEG = 72 PLANE_W = 1280 # every card is the whole 72 deg window wide PLANE_W_MAX = 4096 @@ -35,11 +36,12 @@ ATTRIBUTION = dict( # ------------------------------------------------------------------------------------ schema (the one dict the schema file and the validator both come from) _num, _int, _str = {'type': 'number'}, {'type': 'integer'}, {'type': 'string'} _numnull = {'type': ['number', 'null']} +_tz = {'type': 'string', 'format': 'iana-tz'} # an IANA zone the system knows, as ridge.load_preset requires; validate() checks it def _obj(**props): return {'type': 'object', 'required': list(props), 'additionalProperties': False, 'properties': props} _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), + place=_obj(id=_str, name=_str, lat=_num, lon=_num, altitude_km=_num, eye_m=_num, tz=_tz), 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'}), @@ -55,6 +57,9 @@ def validate(x, s, path='$'): if '$ref' in s: return validate(x, SCHEMA['$defs'][s['$ref'].split('/')[-1]], path) tys = s.get('type'); tys = [tys] if isinstance(tys, str) else tys; py = {'object': dict, 'array': list, 'string': str, 'number': (int, float), 'integer': int, 'null': type(None)} if tys and not any(isinstance(x, py[t]) and not (isinstance(x, bool) and t != 'null') for t in tys): raise ValueError(f'{path}: not a {"/".join(tys)}') + if s.get('format') == 'iana-tz': + try: ZoneInfo(x) + except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f'{path}: {x!r} is not a time zone the system knows') if 'const' in s and x != s['const']: raise ValueError(f"{path}: must be {s['const']!r}") if 'enum' in s and x not in s['enum']: raise ValueError(f'{path}: not one of {s["enum"]}') if 'maximum' in s and x > s['maximum']: raise ValueError(f'{path}: above {s["maximum"]}') @@ -153,7 +158,7 @@ def bake_place(pid): 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']) + place = dict(id=p['id'], name=p['name'], lat=p['lat'], lon=p['lon'], altitude_km=p['ground_m'] / 1000.0, eye_m=p['eye_m'], tz=p['tz']) view = dict(look_az_deg=p['az_center'], plane_h=ridge.H, px_per_deg_h=ridge.HPX_DEG, px_per_deg_v=v['px_per_deg'], exaggeration=v['exaggeration'], horizon_row=v['horizon_row'], sky_row=v['sky_row'] * ridge.H, near_row=v['near_row'] * ridge.H) meta = dict(curvature=dict(r_earth_m=ridge.R_EARTH, k_ref=ridge.KREF), encoding=dict(log_d_min=math.log(d[0]), log_d_max=math.log(d[-1])), camera=dict(r_m=float(p.get('camera_r_m', CAMERA_R_M)), heading_max_deg=HEADING_MAX_DEG)) return dict(place=place, view=view, meta=meta, cards=ridge.cards(d, aw, hw, sm, nrm), splits_km=list(p['card_split_km']), seams=sm, cov=cov, opaque=ridge.opaque(aw), edges=ridge.log_edges(d)) diff --git a/scripts/ridge-bake/places.json b/scripts/ridge-bake/places.json index c6dde613..c94d6119 100644 --- a/scripts/ridge-bake/places.json +++ b/scripts/ridge-bake/places.json @@ -1,8 +1,9 @@ { - "_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).", + "_doc": "Place presets for the A+D baker (ridge.py). eye = observer lat/lon; eye_h_m = eye above the local DEM surface (ground_override_m replaces the DEM ground elevation, used for Vienna to keep round 1's 183.3 m); look_at = target lat/lon whose bearing centres the 72 deg window (or az_deg); tz = the place's IANA time zone (required, never defaulted: the runtime draws named sky moments in the place's local day); rmax_km = ring radius (decides the tile list: every 1x1 deg GLO-30 tile whose rectangle intersects the circle); card_split_km = the ordered list of 1 to MAX_CARDS - 1 authored seam depths in km (the seam search refines each per column; K splits make K+1 cards; required, never defaulted); prefilter_m = Gaussian sigma in metres of the height low-pass before the cards are cut (default 0).", "presets": [ { "id": "vienna", + "tz": "Europe/Vienna", "name": "Vienna, looking SW to Rax/Schneeberg", "kind": "far range over a flat foreground", "lat": 48.1929826, @@ -22,6 +23,7 @@ }, { "id": "matterhorn", + "tz": "Europe/Zurich", "name": "Matterhorn from the Gornergrat (photo cell, 9.7 km)", "kind": "lone horn, close, 27 deg of relief", "lat": 45.983139, @@ -151,6 +153,7 @@ }, { "id": "fuji", + "tz": "Asia/Tokyo", "name": "Fuji from the Shiraito Falls side, 13.8 km WSW (photo cell)", "kind": "lone cone, smooth", "lat": 35.312467222222494, @@ -297,6 +300,7 @@ }, { "id": "halfdome", + "tz": "America/Los_Angeles", "name": "Half Dome from the Yosemite Valley floor (Sentinel Bridge photo cell)", "kind": "granite wall across a valley", "lat": 37.745833333333, @@ -454,6 +458,7 @@ }, { "id": "amadablam", + "tz": "Asia/Kathmandu", "name": "Ama Dablam and the Everest massif, 4 km WSW of Tengboche near Khumjung (photo cell)", "kind": "far high range behind a near spire", "lat": 27.822000000000003, @@ -528,6 +533,7 @@ }, { "id": "trecime", + "tz": "Europe/Rome", "name": "Tre Cime di Lavaredo from the Dreizinnenhuette area, 2.4 km N (photo cell)", "kind": "cirque wall, spires", "lat": 46.636906, diff --git a/scripts/ridge-bake/ridge-bake.schema.json b/scripts/ridge-bake/ridge-bake.schema.json index b58a6c69..e32238f0 100644 --- a/scripts/ridge-bake/ridge-bake.schema.json +++ b/scripts/ridge-bake/ridge-bake.schema.json @@ -38,7 +38,8 @@ "lat", "lon", "altitude_km", - "eye_m" + "eye_m", + "tz" ], "additionalProperties": false, "properties": { @@ -59,6 +60,10 @@ }, "eye_m": { "type": "number" + }, + "tz": { + "type": "string", + "format": "iana-tz" } } }, diff --git a/scripts/ridge-bake/ridge.py b/scripts/ridge-bake/ridge.py index 80d38e4c..4c29ecb5 100644 --- a/scripts/ridge-bake/ridge.py +++ b/scripts/ridge-bake/ridge.py @@ -10,6 +10,7 @@ Offline baker for the ridge backdrop (scripts/ridge-bake); export.py drives it. Vertical exaggeration is AUTHORED and derived per view by set_view (printed on the page). The client owns lighting, haze and ink (ruling ridge-cards-runtime-lit).""" import sys, time, math, json import os, hashlib +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import numpy as np, tifffile @@ -31,11 +32,15 @@ P = {} # configured preset rowang = np.zeros(H); PXDEG_V = 100.0; TOP_DEG = 2.6; BOTTOM_DEG = -3.4 def load_preset(pid, path=Path(__file__).resolve().parent / 'places.json'): - """The preset dict. card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march.""" + """The preset dict. tz is required, an IANA zone the system knows (the runtime draws named sky moments in the place's local day). card_split_km is the ordered list of authored seam depths (km): required, strictly increasing, at most export.MAX_CARDS - 1 (the cap is export's, which owns the budget); refused here, before any march.""" d = json.load(open(path)); p = dict(next(x for x in d['presets'] if x['id'] == pid)); sp = p.get('card_split_km') from export import MAX_CARDS if not sp: raise ValueError(f"preset {pid}: card_split_km is required (an ordered list of 1 to {MAX_CARDS - 1} depths in km)") if len(sp) > MAX_CARDS - 1 or any(b <= a for a, b in zip(sp, sp[1:])): raise ValueError(f"preset {pid}: card_split_km {sp} must be strictly increasing with at most {MAX_CARDS - 1} entries") + tz = p.get('tz') + if not isinstance(tz, str) or not tz: raise ValueError(f"preset {pid}: tz is required (an IANA time zone name such as Europe/Vienna)") + try: ZoneInfo(tz) + except (ZoneInfoNotFoundError, ValueError, OSError): raise ValueError(f"preset {pid}: tz {tz!r} is not a time zone the system knows") return p # ====================================================================== configuration, DEM diff --git a/scripts/ridge-bake/tests/test_ridge.py b/scripts/ridge-bake/tests/test_ridge.py index 8a323cf5..4780ae1b 100644 --- a/scripts/ridge-bake/tests/test_ridge.py +++ b/scripts/ridge-bake/tests/test_ridge.py @@ -49,7 +49,7 @@ 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) + place = dict(id='synthetic', name='Synthetic', lat=48.0, lon=16.0, altitude_km=0.05, eye_m=EYE, tz='Europe/Vienna') 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) @@ -189,6 +189,9 @@ def test_manifest_v2_writer(): 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 + bad = json.loads(json.dumps(m)); bad['place']['tz'] = 'Mars/Olympus' + try: export.validate(bad, export.SCHEMA['$defs']['manifest']); raise AssertionError('a zone the system does not know validated') + except ValueError as e: assert 'time zone' in str(e), e 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' @@ -233,8 +236,13 @@ def test_card_cap_refusals(): try: ridge.load_preset('x', os.path.join(d, 'q.json')) except ValueError: pass else: assert False, 'a preset without card_split_km was defaulted' - json.dump(dict(presets=[dict(id='x', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5] - place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), camera=dict(r_m=0.0, heading_max_deg=1.0)); view = dict(look_az_deg=0.0, plane_h=H, px_per_deg_h=1.0, px_per_deg_v=1.0, exaggeration=1.0, horizon_row=1.0, sky_row=1.0, near_row=1.0) + json.dump(dict(presets=[dict(id='x', tz='Europe/Vienna', card_split_km=[1, 2, 3, 4, 5])]), open(os.path.join(d, 'r.json'), 'w')); assert ridge.load_preset('x', os.path.join(d, 'r.json'))['card_split_km'] == [1, 2, 3, 4, 5] + for bad_tz in (None, '', 'Not/AZone'): + p = os.path.join(d, 'tz.json'); json.dump(dict(presets=[dict(id='x', card_split_km=[6], **({} if bad_tz is None else dict(tz=bad_tz)))]), open(p, 'w')) + try: ridge.load_preset('x', p) + except ValueError: pass + else: assert False, ('a preset with tz', bad_tz, 'was accepted') + place = dict(id='synthetic', name='S', lat=0.0, lon=0.0, altitude_km=0.0, eye_m=1.0, tz='UTC'); meta = dict(curvature=dict(r_earth_m=1.0, k_ref=0.1), encoding=dict(log_d_min=0.0, log_d_max=1.0), 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 diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 1c6c5ad6..0f9f9e14 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -50,8 +50,24 @@ callbacks and the creature sizing rule. Nothing has drawn a creature. ## Ridge scene: Vienna and the weather -The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the real sun over the viewpoint, 48.1929826 N, 16.3534237 E -(`ridge/vienna.ts`). +The ridge sky is the physical atmosphere (`ridge/earthAtmosphere.ts`) lit by the sun over the viewpoint (Vienna's is 48.1929826 N, 16.3534237 E, from the manifest). + +### The sky choice + +The viewer's choice is Auto, one of six named moments (Dawn, Morning, Noon, Golden hour, Dusk, Night) or a free moment (a place-local date and +minute of the day). `ridge/skyMoment.ts` is the one owner of what it draws: `momentFor(choice, place, now)` returns the instant and `skyBand(elevation)` +turns the sun at that instant into day, dusk or night (day from 6 degrees up, night from 6 down), which the ink theme (`skyTheme.ts`, `skyInk.ts`), the +display budget (`ridge/toneMap.ts`) and the rebuild key (`skyForState.ts`) all read. Auto is the real sun over the loaded place now. A named moment is +today's at the place (Night tonight's: the solar midnight nearest, before the day's noon the one just passed or coming, after it the one coming), from the sun's elevation crossings of the place-local day (`SKY_MOMENTS`, one row each: dawn and dusk at -3 degrees, golden hour at ++4, morning at the lesser of 15 degrees and half the noon elevation, noon the day's maximum, night solar midnight). Place-local time comes only from +`place.tz`, the IANA zone the baker writes into the manifest (`scripts/ridge-bake/places.json`); the viewer's own zone decides nothing. Auto and the +named moments draw today's weather; a free moment draws a clear sky. + +`skyState.ts` holds the stores (choice, place, constellation lines) and tells listeners; the choice persists in `ratatoskr.skyChoice`. The key +of the old four-state menu is read once by `skyState.ts` (Day became Noon) and removed. `skyPlace.ts` is the one writer of the place: a scene start loads the manifest of the configured place (nothing else fetches it, so a page with no scene fetches nothing) and the build +settles what it draws, the manifest's place when the cards load, `FALLBACK_VIEW`'s when they do not (a failed manifest, a card that will not decode), so the sky, the weather, the ink and the Auto +timer read the place that is drawn. Until a scene has settled it no sky is drawn for ink and the theme's own ink stands. The one timer (Auto, a named moment) tells listeners when the band +changes or a named moment's place-local day rolls over. The weather is one number (`ridge/weather.ts`), from the page URL's `?weather=`, else `weather.json` beside `config.json`, else clear. The browser never calls a weather service. `weather.json` is written by Eureka's refresher (gamecult-ops `docs/weather-feed.md`, a 5-minute timer; the only writer) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit diff --git a/src/app/features/scene/SkyStateControl.test.tsx b/src/app/features/scene/SkyStateControl.test.tsx new file mode 100644 index 00000000..df06280b --- /dev/null +++ b/src/app/features/scene/SkyStateControl.test.tsx @@ -0,0 +1,173 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { SkyChoice } from './ridge/skyMoment'; +import { FALLBACK_VIEW } from './ridge/view'; +import { + MENU_CHOICES, + SkyMomentPicker, + SkyStateControl, + choiceLabel, + useNativeChange, +} from './SkyStateControl'; + +// The component's hooks are held still, as in RoomOutbox.actions.test.tsx: state is its initial value, refs are plain boxes, effects are +// kept to be run once the test has put an element in each ref. The element tree it returns is read and its native events are dispatched +// on a fake input, so no DOM is needed. +const held = vi.hoisted(() => ({ + effects: [] as Array<() => unknown>, + choice: { kind: 'auto' } as unknown, +})); +vi.mock('react', async (importOriginal) => { + const actual = await importOriginal(); + const useState = (init: unknown) => [ + typeof init === 'function' ? (init as () => unknown)() : init, + () => undefined, + ]; + const useRef = (init: unknown) => ({ current: init }); + const useEffect = (fn: () => unknown) => { + held.effects.push(fn); + }; + return { + ...actual, + default: { ...actual, useState, useRef, useEffect }, + useState, + useRef, + useEffect, + }; +}); +vi.mock('../../hooks/useSkyState', () => ({ + useSkyChoice: () => held.choice, + useDrawnPlace: () => FALLBACK_VIEW.place, +})); +vi.mock('../../hooks/useClientConfig', () => ({ useClientConfig: () => ({}) })); + +type El = { type?: unknown; ref?: unknown; props?: Record }; +/** Every element reachable through any prop (children, `content`, `after`). */ +const walk = (node: unknown): El[] => { + if (Array.isArray(node)) return node.flatMap(walk); + if (node && typeof node === 'object' && 'props' in node) { + const el = node as El; + return [el, ...Object.values(el.props ?? {}).flatMap(walk)]; + } + return []; +}; +const textOf = (node: unknown): string => { + if (typeof node === 'string' || typeof node === 'number') return String(node); + if (Array.isArray(node)) return node.map(textOf).join(''); + if (node && typeof node === 'object' && 'props' in node) { + return textOf((node as El).props?.children); + } + return ''; +}; +/** A stand-in input: a real EventTarget with a value. */ +const fakeInput = (value: string) => Object.assign(new EventTarget(), { value }); +const fire = (el: EventTarget, type: 'input' | 'change') => el.dispatchEvent(new Event(type)); + +beforeEach(() => { + held.effects.length = 0; + held.choice = { kind: 'auto' }; +}); + +describe('the sky menu choices', () => { + const tree = () => walk(SkyStateControl()); + const radios = () => tree().filter((e) => e.props?.role === 'menuitemradio'); + + it('lists Auto and the six named moments, then Pick a moment', () => { + expect(MENU_CHOICES.map(choiceLabel)).toEqual([ + 'Auto', + 'Dawn', + 'Morning', + 'Noon', + 'Golden hour', + 'Dusk', + 'Night', + ]); + expect(radios().map((e) => textOf(e))).toEqual([ + 'Auto', + 'Dawn', + 'Morning', + 'Noon', + 'Golden hour', + 'Dusk', + 'Night', + 'Pick a moment', + ]); + }); + + it.each([ + [{ kind: 'auto' }, 0], + [{ kind: 'named', id: 'dawn' }, 1], + [{ kind: 'named', id: 'night' }, 6], + [{ kind: 'free', date: '2026-12-21', minutes: 400 }, 7], + ] as Array<[SkyChoice, number]>)('aria-checked follows the choice %j', (choice, checked) => { + held.choice = choice; + radios().forEach((e, i) => expect(e.props?.['aria-checked'], `item ${i}`).toBe(i === checked)); + }); + + it("the button reads 'Sky: Auto', 'Sky: Dawn' or 'Sky: