diff --git a/harness/scene/bundle.cjs b/harness/scene/bundle.cjs index 31accf37..9d3079cd 100644 --- a/harness/scene/bundle.cjs +++ b/harness/scene/bundle.cjs @@ -29,6 +29,7 @@ esbuild plugins: [rawPlugin], format: 'iife', target: 'es2020', + define: { 'import.meta.env.BASE_URL': '"/"' }, }) .then(() => { if (ridge) { diff --git a/scripts/refresh-weather.mjs b/scripts/refresh-weather.mjs new file mode 100644 index 00000000..03a6517a --- /dev/null +++ b/scripts/refresh-weather.mjs @@ -0,0 +1,50 @@ +#!/usr/bin/env node +// Reference refresher for the ridge scene's weather.json: one GeoSphere Austria TAWES request (station 11035, Wien Hohe Warte; no key; credit as GeoSphere's legal page asks), the +// current 10-minute observation written as the file the client reads (src/app/features/scene/ridge/weatherFeed.ts). No dependencies. +// Eureka hosts the timer; run it no more often than every 5 minutes. The service allows 5 requests/s and 240/hour per client: this +// makes one request per run and, on any failure or a 429, leaves the previous file in place (the client treats a file older than 30 min +// as clear sky) and exits 1. +// node scripts/refresh-weather.mjs +import { renameSync, writeFileSync } from 'node:fs'; + +export const STATION = 11035; +export const URL_TAWES = `https://dataset.api.hub.geosphere.at/v1/station/current/tawes-v1-10min?parameters=RR¶meters=RF¶meters=GLOW¶meters=SO&station_ids=${STATION}`; +export const ATTRIBUTION = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at'; + +/** The file's content from a TAWES `station/current` response; null when there is no observation time. Missing measurements are null. */ +export function fileFromTawes(json, fetchedAt = new Date()) { + const observed = json?.timestamps?.[0]; + if (typeof observed !== 'string' || Number.isNaN(Date.parse(observed))) return null; + const p = json?.features?.[0]?.properties?.parameters ?? {}; + const val = (k) => { + const v = p[k]?.data?.[0]; + return typeof v === 'number' && Number.isFinite(v) ? v : null; + }; + return { + fetched_at: fetchedAt.toISOString(), + observed_at: new Date(observed).toISOString(), + station: STATION, + precip_mm_10min: val('RR'), + humidity_pct: val('RF'), + glow_wm2: val('GLOW'), + sunshine_s_10min: val('SO'), + attribution: ATTRIBUTION, + }; +} + +async function main(out) { + if (!out) throw new Error('usage: refresh-weather.mjs '); + const res = await fetch(URL_TAWES, { signal: AbortSignal.timeout(15_000) }); + if (!res.ok) throw new Error(`TAWES answered ${res.status}`); + const file = fileFromTawes(await res.json()); + if (!file) throw new Error('TAWES answered without an observation'); + writeFileSync(`${out}.tmp`, `${JSON.stringify(file)}\n`); + renameSync(`${out}.tmp`, out); +} + +if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { + main(process.argv[2]).catch((e) => { + console.error(String(e.message ?? e)); + process.exit(1); + }); +} diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 957f1a42..307a7aaf 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -78,6 +78,23 @@ holds a GL context gives no 2D one, so a GL failure after context creation (comp 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 +(`ridge/vienna.ts`). Its farthest layer is the real horizon of that viewpoint, standing still under the sun: `ridge/viennaHorizon.json`, +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 browser never calls a weather service. `weather.json` is written by a refresher outside the client (`scripts/refresh-weather.mjs` is the +reference; run no more often than every 5 minutes) from GeoSphere Austria's TAWES station 11035 (Wien Hohe Warte), credit +"Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at". Shape: `{fetched_at, observed_at, station, precip_mm_10min, humidity_pct, +glow_wm2, sunshine_s_10min, attribution}`, null for a missing measurement. A file whose `observed_at` is more than 30 minutes old 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 +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). + ## Entry points - `index.ts` `startBackgroundScene(config.backgroundScene, capabilities, options)` is the host's diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index 3ef62465..36010b40 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -16,6 +16,9 @@ export type StartOptions = Omit void; }; +/** 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`; + async function create( config: BackgroundSceneConfig | undefined, options: StartOptions & { tier: SceneTier; debug?: boolean }, @@ -23,7 +26,7 @@ async function create( ): Promise { try { // Loaded here, with the scenes, so the main chunk does not carry the terrain sky or the baked tables. - const { ridgeSkyFor, terrainSkyFor } = await import('./skyForState'); + const { loadWeather, ridgeSkyFor, terrainSkyFor } = await import('./skyForState'); if (config?.style === 'raymarch') return (await import('./Scene')).createScene(options); if (config?.style === 'terrain') { const { createTerrainScene } = await import('./terrain/Terrain'); @@ -35,6 +38,7 @@ async function create( return createTerrainSkyScene({ ...options, ...sky }); } const { createRidgeScene } = await import('./ridge/Ridge'); + await loadWeather(weatherUrl()); return createRidgeScene({ ...options, sky: ridgeSkyFor(state) }); } catch (e) { options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); @@ -52,8 +56,10 @@ async function skyKey( state: SkyState ): Promise { try { - const { ridgeSkyKey, terrainSkyFor } = await import('./skyForState'); - return config?.style === 'terrain' ? JSON.stringify(terrainSkyFor(state)) : ridgeSkyKey(state); + const { loadWeather, ridgeSkyKey, terrainSkyFor } = await import('./skyForState'); + if (config?.style === 'terrain') return JSON.stringify(terrainSkyFor(state)); + await loadWeather(weatherUrl()); + return ridgeSkyKey(state); } catch { // The chunk failed to load: no key, so every change rebuilds (and `create` reports the failure). return null; diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 864491f1..0234e558 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -17,6 +17,7 @@ import { } from './ridgeWorld'; import { skyColours, SkyColours } from './skyColour'; import { makeStars } from './stars'; +import { makePhysicalSky } from './physicalSky'; import { startBackgroundScene } from '../index'; describe('noise', () => { @@ -208,6 +209,7 @@ function fakeEl(tag = 'div') { this.attrs[k] = v; }, getContext: vi.fn(() => ctx()), + toDataURL: () => 'data:,', remove() { if (this.parentElement) this.parentElement.children = this.parentElement.children.filter((c: any) => c !== this); @@ -273,6 +275,8 @@ function ctx(withFilter = false) { putImageData: (img: any) => puts.push(img), beginPath() {}, moveTo() {}, + stroke() {}, + createRadialGradient: () => ({ addColorStop: vi.fn() }), lineTo() {}, closePath() {}, // Stars: arc+fill is one draw. A context that has cleared a rect is the twinkle overlay's. @@ -378,9 +382,9 @@ describe('createRidgeScene', () => { expect(s).not.toBeNull(); const tracks = tracksOf(parent); expect(tracks).toHaveLength(LAYERS.length); - tracks.forEach((t: any) => { + tracks.forEach((t: any, i: number) => { expect(t.children).toHaveLength(3); - expect(t.animate).toHaveBeenCalledTimes(1); + 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); @@ -428,7 +432,7 @@ describe('createRidgeScene', () => { const { canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!; const anims = animsOf(canvas.parentElement); - expect(anims.length).toBe(LAYERS.length + 1); // one drift per layer and the sway + 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); @@ -759,7 +763,7 @@ describe('endless drift: chunks baked on demand and recycled', () => { 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)[0]; + 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. @@ -777,8 +781,8 @@ describe('endless drift: chunks baked on demand and recycled', () => { 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)[0]; - const done = () => records.filter((r) => r.layer === 0).map((r) => r.chunk); + 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)); @@ -786,9 +790,9 @@ describe('endless drift: chunks baked on demand and recycled', () => { 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 layer0 = imgs.filter((_, i) => records[i].layer === 0); - [3, 4, 5].forEach((m, k) => expect(layer0[3 + k].equals(expected(0, m))).toBe(true)); - expect(layer0[3].equals(layer0[0])).toBe(false); + 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(); }); @@ -812,3 +816,43 @@ describe('endless drift: chunks baked on demand and recycled', () => { s.dispose(); }); }); + +describe('rain in the scene', () => { + const rainy = (w: number): SkyColours => ({ ...DAY, physical: makePhysicalSky('day', new Date('2026-06-21T10:40:00Z'), w) }); + const rainEls = (parent: any) => 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', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: rainy(1) })!; + const els = rainEls(parent); + expect(els).toHaveLength(2); + els.forEach((e: any) => { + expect(e.anims).toHaveLength(1); + expect(e.anims[0].options.iterations).toBe(Infinity); + }); + s.dispose(); + expect(rainEls(parent)).toHaveLength(0); + els.forEach((e: any) => expect(e.anims[0].cancel).toHaveBeenCalled()); + }); + + it('draws no rain in dry weather, and none in a still', () => { + const dry = host(); + createRidgeScene({ canvas: dry.canvas, tier: 'full', sky: rainy(0.3) })!.dispose(); + const a = host(); + const sa = createRidgeScene({ canvas: a.canvas, tier: 'full', sky: rainy(0.3) })!; + expect(rainEls(a.parent)).toHaveLength(0); + sa.dispose(); + const still = host(); + const ss = createRidgeScene({ canvas: still.canvas, tier: 'still', sky: rainy(1) })!; + expect(rainEls(still.parent)).toHaveLength(0); + ss.dispose(); + }); + + it('pauses with the rest when motion is reduced', () => { + motion.matches = true; + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: rainy(1) })!; + rainEls(parent).forEach((e: any) => expect(e.anims[0].play).not.toHaveBeenCalled()); + s.dispose(); + }); +}); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index f13340b5..8590a833 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -6,7 +6,10 @@ import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars'; import { bakeSlice, BakeParams, layerPaint } from './ridgeBake'; -import { LAYERS, LayerSpec, edgeBlur, layerSize, scatterAlpha, transmittance } from './ridgeWorld'; +import { LAYERS, 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'; /** 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 { @@ -35,6 +38,25 @@ function context2d(c: HTMLCanvasElement): CanvasRenderingContext2D | null { return c.getContext('2d'); } +/** The sun: a bright core of its true angular size (at least 2.5 px) and a short soft falloff, in the colour the air leaves it. */ +function drawSun( + ctx: CanvasRenderingContext2D, + d: NonNullable['sunDisc']>, + w: number, + h: number +): void { + const r = Math.max(2.5, d.radius * h); + const x = d.x * w; + const y = d.y * h; + const g = ctx.createRadialGradient(x, y, 0, x, y, r * 3.5); + const [cr, cg, cb] = d.rgb; + g.addColorStop(0, `rgba(${cr},${cg},${cb},${d.alpha})`); + g.addColorStop(1 / 3.5, `rgba(${cr},${cg},${cb},${d.alpha})`); + g.addColorStop(1, `rgba(${cr},${cg},${cb},0)`); + ctx.fillStyle = g; + ctx.fillRect(x - r * 3.5, y - r * 3.5, r * 7, r * 7); +} + /** * The host canvas's sky: the physical sky (`physicalSky.ts`) as a small grid of display pixels, scaled up smoothly (it is a soft * field); without one, the three-stop gradient. @@ -61,6 +83,7 @@ function paintSky( ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(small, 0, 0, canvas.width, canvas.height); + if (px.sunDisc) drawSun(ctx, px.sunDisc, canvas.width, canvas.height); return true; } } @@ -138,6 +161,13 @@ function chunkJob( 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, @@ -264,6 +294,8 @@ interface Built { makeCanvas: () => HTMLCanvasElement; /** The twinkling stars' own canvas, between the sky and the ridges; absent in a day sky and in 'still'. */ twinkle?: HTMLCanvasElement; + /** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */ + rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] }; } /** Yaw and pitch: the camera's slow sway, a loop of this many seconds over the whole rig. */ @@ -318,6 +350,8 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { built?.layers.forEach((l) => l.anim?.cancel()); built?.rig.remove(); built?.twinkle?.remove(); + built?.rain?.anims.forEach((a) => a?.cancel()); + built?.rain?.els.forEach((e) => e.remove()); cancelAnimationFrame(twRaf); twRaf = 0; built = undefined; @@ -382,7 +416,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { /** 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) return; + if (!built || !Number.isFinite(l.spec.seconds)) return; // the horizon layer does not drift const { size, scale } = built; l.anim = l.track.animate?.( [ @@ -433,6 +467,47 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { ); }; + /** + * The rain over everything: per tile, a div of the tile's texture (drawn once) taller than the viewport by one tile, slid down one + * tile height per loop on the compositor. 'still' draws none (a settled still has no animation to carry it). + */ + const startRain = (rain: number, colour: Srgb, w: number, h: number, scale: number): NonNullable => { + const els: HTMLElement[] = []; + const anims: (Animation | undefined)[] = []; + RAIN_TILES.forEach((t, k) => { + const tile = document.createElement('canvas'); + tile.width = t.size; + tile.height = t.size; + const tctx = context2d(tile); + if (!tctx) return; + drawRainTile(tctx, t, rain, colour, scale, k * 41); + const px = t.size / scale; + const el = document.createElement('div'); + el.setAttribute('aria-hidden', 'true'); + Object.assign(el.style, { + position: 'absolute', + left: '0', + top: `${-px}px`, + width: '100%', + height: `${h + px}px`, + backgroundImage: `url(${tile.toDataURL()})`, + backgroundSize: `${px}px ${px}px`, + pointerEvents: 'none', + willChange: 'transform', + }); + parent.appendChild(el); + els.push(el); + anims.push( + el.animate?.([{ transform: 'translate3d(0,0,0)' }, { transform: `translate3d(0,${px}px,0)` }], { + duration: t.seconds * 1000, + iterations: Infinity, + easing: 'linear', + }) + ); + }); + return { els, anims }; + }; + /** Bake the sky, then the layers. Returns false when a 2D context is missing or there is no area yet. */ const build = (): boolean => { teardownLayers(); @@ -481,7 +556,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const track = document.createElement('div'); Object.assign(track.style, { position: 'absolute', - left: '0', + left: spec.horizon ? `${(-HORIZON_TRACK_SHIFT * size.period) / scale}px` : '0', bottom: '0', width: `${size.period / scale}px`, height: `${size.height / scale}px`, @@ -531,6 +606,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { 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) built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale); pump(); syncPlayState(); return true; @@ -564,7 +640,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { }; function syncPlayState() { - const anims = built ? [built.sway, ...built.layers.map((l) => l.anim)] : []; + const anims = built ? [built.sway, ...built.layers.map((l) => l.anim), ...(built.rain?.anims ?? [])] : []; anims.forEach((a) => (moving() ? a?.play() : a?.pause())); if (!built?.twinkle) return; if (moving()) { diff --git a/src/app/features/scene/ridge/clouds.ts b/src/app/features/scene/ridge/clouds.ts new file mode 100644 index 00000000..1b4e8757 --- /dev/null +++ b/src/app/features/scene/ridge/clouds.ts @@ -0,0 +1,74 @@ +/* eslint-disable no-param-reassign -- `cloudRadiance` fills the caller's array */ +// A cloud deck over the sky dome: per texel, the view ray hits a plane at cloud height, a three-octave value noise there is the +// deck's thickness, `cover` says how much of it is cloud, and a cloudy texel is the cloud's own radiance (lit by the sun through the +// air and by the sky, thinned for the thickness of the deck) in place of the sky behind it. One noise sample per octave per texel on +// the dome's small grid: no march, no texture, nothing per frame. +import { hash2 } from './noise'; +import type { Weather } from './weather'; + +const smooth = (t: number): number => t * t * (3 - 2 * t); +const smoothstep = (a: number, b: number, v: number): number => { + const t = Math.min(1, Math.max(0, (v - a) / (b - a))); + return smooth(t); +}; + +/** 2D value noise in [0, 1). */ +export function noise2(x: number, y: number): number { + const cx = Math.floor(x); + const cy = Math.floor(y); + const u = smooth(x - cx); + const v = smooth(y - cy); + const a = hash2(cx, cy); + const b = hash2(cx + 1, cy); + const c = hash2(cx, cy + 1); + const d = hash2(cx + 1, cy + 1); + return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v; +} + +/** Plane-projected texels per unit of ray slope, and the octave gain. */ +const SCALE = 1.6; +/** Below this ray elevation (sine) the deck fades into the horizon haze. */ +const HORIZON_FADE: readonly [number, number] = [0.02, 0.22]; + +/** + * Cloud amount 0..1 along a ray with horizontal direction (`dx`, `dy`) and vertical sine `vz`. At cover 0 there is none and at 1 + * the sky is solid overcast; between, the noise thresholds into puffs with soft edges. `drift` offsets the pattern (the weather's + * wind, in plane units). + */ +export function cloudAmount(dx: number, dy: number, vz: number, cover: number, drift = 0): number { + if (cover <= 0 || vz <= 0) return 0; + const px = (dx / (vz + 0.1)) * SCALE + drift; + const py = (dy / (vz + 0.1)) * SCALE; + let n = 0; + let amp = 0.55; + let f = 1; + let norm = 0; + for (let k = 0; k < 3; k += 1) { + n += amp * noise2(px * f + k * 17.3, py * f + k * 5.1); + norm += amp; + amp *= 0.5; + f *= 2.1; + } + n /= norm; + // cover 1 puts the threshold below every value: solid; cover 0 above every value: none. + const thr = 1.05 - cover * 0.95; + return smoothstep(thr - 0.12, thr + 0.12, n) * smoothstep(HORIZON_FADE[0], HORIZON_FADE[1], vz); +} + +/** + * The radiance of cloud, per unit of sun irradiance, for a sun at sine `sunSin` seen through `sunTrans` (the air's transmittance to + * the sun) over a sky whose zenith radiance is `zenith`. A white scatterer (albedo 0.8): the sun's direct light, which thick cover + * blocks (`cover` 1 passes a fifth), and the sky's, which it does not. Written into `out`. + */ +export function cloudRadiance( + sunSin: number, + sunTrans: readonly number[], + zenith: readonly number[], + cover: number, + out: number[] +): void { + const direct = (Math.max(sunSin, 0) / Math.PI) * (1 - 0.8 * cover); + for (let i = 0; i < 3; i += 1) out[i] = 0.8 * (sunTrans[i] * direct + zenith[i]); +} + +export const hasClouds = (w: Weather): boolean => w.cover > 0.02; diff --git a/src/app/features/scene/ridge/horizon.ts b/src/app/features/scene/ridge/horizon.ts index 09e40fda..82265a77 100644 --- a/src/app/features/scene/ridge/horizon.ts +++ b/src/app/features/scene/ridge/horizon.ts @@ -31,3 +31,24 @@ export function horizonNormal(azimuth: number): [number, number, number] { 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; diff --git a/src/app/features/scene/ridge/horizonLayer.test.ts b/src/app/features/scene/ridge/horizonLayer.test.ts new file mode 100644 index 00000000..8ed27e4c --- /dev/null +++ b/src/app/features/scene/ridge/horizonLayer.test.ts @@ -0,0 +1,63 @@ +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); + }); +}); diff --git a/src/app/features/scene/ridge/physicalSky.test.ts b/src/app/features/scene/ridge/physicalSky.test.ts new file mode 100644 index 00000000..fe517fe9 --- /dev/null +++ b/src/app/features/scene/ridge/physicalSky.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { makePhysicalSky, paintSky } from './physicalSky'; +import { skyBackdrop } from '../skyState'; +import type { FixedSkyState } from '../skyBand'; + +// 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 +// viewports of different shape (the fit is made on one 16:9 grid and the paint on another). +const lin = (v: number): number => { + const c = v / 255; + return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; +}; +const luma = (d: Uint8ClampedArray, i: number): number => 0.2126 * lin(d[i]) + 0.7152 * lin(d[i + 1]) + 0.0722 * lin(d[i + 2]); + +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 VIEWPORTS: [number, number][] = [ + [1920, 1080], + [1024, 768], + [2560, 1080], + [390, 844], +]; + +describe.each(['day', 'dusk', 'night'] as FixedSkyState[])('the %s sky stays inside its backdrop bounds', (state) => { + it('over weather, season and viewport shape', () => { + const b = skyBackdrop(state); + let lo = 2; + let hi = -1; + for (const day of DAYS) { + for (const w of WEATHER) { + const sky = makePhysicalSky(state, new Date(`${day}T10:40:00Z`), w); + for (const [vw, vh] of VIEWPORTS) { + const px = paintSky(sky, vw, vh); + for (let i = 0; i < px.w * px.h * 4; i += 4) { + const l = luma(px.data, i); + lo = Math.min(lo, l); + hi = Math.max(hi, l); + } + } + } + } + expect(lo).toBeGreaterThanOrEqual(b.darkest); + expect(hi).toBeLessThanOrEqual(b.lightest); + }); +}); + +describe('weather in the sky', () => { + it('overcast is cloud: less blue and less contrast than clear air at the same sun', () => { + const at = new Date('2026-06-21T10:40:00Z'); + const clear = paintSky(makePhysicalSky('day', at, 0), 640, 360); + const grey = paintSky(makePhysicalSky('day', at, 0.7), 640, 360); + const spread = (p: typeof clear) => { + let lo = 2; + let hi = -1; + for (let i = 0; i < p.w * p.h * 4; i += 4) { + const l = luma(p.data, i); + lo = Math.min(lo, l); + hi = Math.max(hi, l); + } + return hi - lo; + }; + expect(spread(grey)).toBeLessThan(spread(clear)); + const mid = (p: typeof clear) => { + const i = (Math.floor(p.h * 0.3) * p.w + Math.floor(p.w / 2)) * 4; + return p.data[i + 2] - p.data[i]; + }; + expect(mid(grey)).toBeLessThan(mid(clear)); + }); +}); + +describe('the sun disc', () => { + 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', () => { + const d = paintSky(makePhysicalSky('day', noon, 0), 1280, 720).sunDisc; + expect(d).toBeDefined(); + expect(d!.x).toBeGreaterThan(0); + expect(d!.x).toBeLessThan(1); + expect(d!.y).toBeGreaterThan(0); + expect(d!.y).toBeLessThan(0.78); // above the horizon line + expect(d!.alpha).toBe(1); + expect(Math.min(...d!.rgb)).toBeGreaterThan(150); // a warm white at 21 degrees + }); + it('is hidden by overcast and absent at night', () => { + expect(paintSky(makePhysicalSky('day', noon, 0.7), 1280, 720).sunDisc).toBeUndefined(); + expect(paintSky(makePhysicalSky('night', noon, 0), 1280, 720).sunDisc).toBeUndefined(); + }); + it('is orange-tinted low in the sky', () => { + const d = paintSky(makePhysicalSky('dusk', noon, 0), 1280, 720).sunDisc; + expect(d).toBeDefined(); + expect(d!.rgb[0]).toBeGreaterThan(d!.rgb[2]); + }); +}); diff --git a/src/app/features/scene/ridge/physicalSky.ts b/src/app/features/scene/ridge/physicalSky.ts index 1e87bcd0..02ffb128 100644 --- a/src/app/features/scene/ridge/physicalSky.ts +++ b/src/app/features/scene/ridge/physicalSky.ts @@ -4,10 +4,10 @@ import type { FixedSkyState } from '../skyBand'; import { bakeAtmosphere } from './earthAtmosphere'; import type { Atmosphere } from './earthAtmosphere'; -import { domeSize, HORIZON_AT, renderDome, viewFor } from './skyDome'; +import { domeSize, HORIZON_AT, renderDome, SUN_RADIUS, sunOnScreen, viewFor, VFOV_DEG } from './skyDome'; import type { Dome, DomeView } from './skyDome'; import type { Srgb } from './skyColour'; -import { display8, fitDisplay } from './toneMap'; +import { display8, fitDisplay, holdBudget } from './toneMap'; import type { Display, Fit } from './toneMap'; import { sunForState, VIENNA } from './vienna'; import type { SunSample } from './vienna'; @@ -54,7 +54,7 @@ export function makePhysicalSky(state: FixedSkyState, now: Date, weatherValue: n mieScale: weather.mieScale, observerKm: VIENNA.altitudeKm, }); - const dome = renderDome(atm, sun, viewFor(sun, CANON.aspect), CANON.w, CANON.h); + const dome = renderDome(atm, sun, viewFor(sun, CANON.aspect), CANON.w, CANON.h, weather.cover); const fit = fitDisplay(state, dome.hdr, dome.meanLuma); const at = (f: number) => rowMean(dome, fit.display, Math.round(f * CANON.h)); return { @@ -75,21 +75,44 @@ export interface SkyPixels { data: Uint8ClampedArray; dome: Dome; view: DomeView; + /** 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 }; } /** The sky for a viewport, as a small RGBA grid the host canvas upscales smoothly. */ export function paintSky(p: PhysicalSky, cssW: number, cssH: number): SkyPixels { const { w, h } = domeSize(cssW, cssH); const view = viewFor(p.sun, cssW / cssH); - const dome = renderDome(p.atm, p.sun, view, w, h); + const dome = renderDome(p.atm, p.sun, view, w, h, p.weather.cover); const data = new Uint8ClampedArray(w * h * 4); const out = [0, 0, 0]; + const display = holdBudget(p.state, dome.hdr, p.fit.display); for (let i = 0; i < w * h; i += 1) { - display8(dome.hdr[i * 3], dome.hdr[i * 3 + 1], dome.hdr[i * 3 + 2], p.fit.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 + 1] = out[1]; data[i * 4 + 2] = out[2]; data[i * 4 + 3] = 255; } - return { w, h, data, dome, view }; + return { w, h, data, dome, view, sunDisc: sunDisc(p, view) }; +} + +const smooth01 = (a: number, b: number, v: number): number => { + const t = Math.min(1, Math.max(0, (v - a) / (b - a))); + return t * t * (3 - 2 * t); +}; + +/** + * 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. + */ +function sunDisc(p: PhysicalSky, view: DomeView): SkyPixels['sunDisc'] { + const at = sunOnScreen(p.sun, view); + const alpha = 1 - smooth01(0.1, 0.6, p.weather.cover); + if (!at || alpha <= 0) return undefined; + const trans = [0, 0, 0]; + p.atm.transmittanceToSpace(Math.max(Math.sin((p.sun.elevation * Math.PI) / 180), 0), trans); + const top = Math.max(...trans, 1e-9); + const rgb = trans.map((t) => Math.round(255 * (t / top) ** 0.6)) as unknown as Srgb; + return { ...at, rgb, radius: (SUN_RADIUS * 180) / Math.PI / VFOV_DEG, alpha }; } diff --git a/src/app/features/scene/ridge/rain.test.ts b/src/app/features/scene/ridge/rain.test.ts new file mode 100644 index 00000000..6575ea20 --- /dev/null +++ b/src/app/features/scene/ridge/rain.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import { drawRainTile, RAIN_TILES, streakCount } from './rain'; + +const recorder = () => { + const calls: string[] = []; + const ctx = new Proxy({} as Record, { + get: (t, k: string) => (k in t ? t[k] : (...a: unknown[]) => calls.push(`${k}(${a.join(',')})`)), + set: (t, k: string, v) => { + t[k] = v; + return true; + }, + }) as unknown as CanvasRenderingContext2D; + return { ctx, calls }; +}; + +describe('rain', () => { + it('draws no streaks without rain and more with more', () => { + expect(streakCount(RAIN_TILES[0], 0)).toBe(0); + expect(streakCount(RAIN_TILES[0], 0.3)).toBeLessThan(streakCount(RAIN_TILES[0], 1)); + const { ctx, calls } = recorder(); + drawRainTile(ctx, RAIN_TILES[0], 0, [200, 210, 220], 1); + expect(calls.filter((c) => c.startsWith('stroke'))).toHaveLength(0); + }); + it('is the same tile every time, and every streak is drawn in the nine wraps so the tile repeats without a seam', () => { + const a = recorder(); + const b = recorder(); + drawRainTile(a.ctx, RAIN_TILES[1], 1, [200, 210, 220], 1); + drawRainTile(b.ctx, RAIN_TILES[1], 1, [200, 210, 220], 1); + expect(a.calls).toEqual(b.calls); + expect(a.calls.filter((c) => c.startsWith('stroke'))).toHaveLength(streakCount(RAIN_TILES[1], 1) * 9); + }); +}); diff --git a/src/app/features/scene/ridge/rain.ts b/src/app/features/scene/ridge/rain.ts new file mode 100644 index 00000000..699130cf --- /dev/null +++ b/src/app/features/scene/ridge/rain.ts @@ -0,0 +1,54 @@ +// Rain as one tiled texture of slanted streaks, drawn once and slid down by the compositor (a CSS animation on a transform: no per-frame +// script, no per-frame paint). Two tiles of different size and speed read as depth. The streaks wear the sky's own horizon colour, so +// whatever they lighten stays inside the state's luminance bounds (a streak is a blend of two colours the sky already has). +import { hash2 } from './noise'; +import type { Srgb } from './skyColour'; + +export interface RainTile { + /** Tile edge, canvas px. */ + size: number; + /** Seconds for a tile to fall its own height. */ + seconds: number; + /** Streaks per tile at rain 1. */ + streaks: number; + /** Streak length, tile fractions. */ + length: number; + /** Peak alpha. */ + alpha: number; +} + +/** Far, fine and slow; near, long and quick. */ +export const RAIN_TILES: readonly RainTile[] = [ + { size: 192, seconds: 0.9, streaks: 46, length: 0.16, alpha: 0.32 }, + { size: 320, seconds: 0.6, streaks: 22, length: 0.24, alpha: 0.42 }, +]; + +/** Slant of a streak: pixels left per pixel down. */ +export const RAIN_SLANT = 0.18; + +/** Streaks to draw at a rain amount 0..1 (none at 0). */ +export const streakCount = (t: RainTile, rain: number): number => (rain <= 0 ? 0 : Math.max(4, Math.round(t.streaks * rain))); + +/** Draw one tile. The streaks wrap across the tile's edges so the tile repeats without a seam. */ +export function drawRainTile(ctx: CanvasRenderingContext2D, t: RainTile, rain: number, colour: Srgb, scale: number, seed = 0): void { + const n = streakCount(t, rain); + ctx.clearRect(0, 0, t.size, t.size); + ctx.lineCap = 'round'; + ctx.lineWidth = Math.max(1, scale); + for (let i = 0; i < n; i += 1) { + const x = hash2(i, seed + 3) * t.size; + const y = hash2(i, seed + 7) * t.size; + const len = t.length * t.size * (0.7 + 0.6 * hash2(i, seed + 11)); + const a = t.alpha * (0.5 + 0.5 * hash2(i, seed + 13)) * (0.5 + 0.5 * rain); + ctx.strokeStyle = `rgba(${colour[0]},${colour[1]},${colour[2]},${a.toFixed(3)})`; + // Draw each streak at its place and one tile over in each direction it can cross an edge. + [-t.size, 0, t.size].forEach((ox) => + [-t.size, 0, t.size].forEach((oy) => { + ctx.beginPath(); + ctx.moveTo(x + ox, y + oy); + ctx.lineTo(x + ox - len * RAIN_SLANT, y + oy + len); + ctx.stroke(); + }) + ); + } +} diff --git a/src/app/features/scene/ridge/refreshWeather.test.ts b/src/app/features/scene/ridge/refreshWeather.test.ts new file mode 100644 index 00000000..0fe7a18c --- /dev/null +++ b/src/app/features/scene/ridge/refreshWeather.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; +// @ts-ignore the refresher is a plain node script +import { fileFromTawes } from '../../../../../scripts/refresh-weather.mjs'; +import { parseWeatherFile } from './weatherFeed'; + +const live = { + timestamps: ['2026-11-11T22:40+00:00'], + features: [{ properties: { parameters: { RR: { data: [0.1] }, RF: { data: [100] }, GLOW: { data: [0] }, SO: { data: [0] } } } }], +}; + +describe('the reference refresher', () => { + it('turns a TAWES response into the file the client parses, unchanged', () => { + const f = fileFromTawes(live, new Date('2026-11-11T22:45:10Z')); + expect(f).toEqual({ + fetched_at: '2026-11-11T22:45:10.000Z', + observed_at: '2026-11-11T22:40:00.000Z', + station: 11035, + precip_mm_10min: 0.1, + humidity_pct: 100, + glow_wm2: 0, + sunshine_s_10min: 0, + attribution: 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at', + }); + expect(parseWeatherFile(f)).toEqual(f); + }); + it('keeps a missing measurement null and refuses a response with no observation time', () => { + const f = fileFromTawes({ ...live, features: [{ properties: { parameters: { RR: { data: [null] } } } }] }); + expect([f?.precip_mm_10min, f?.humidity_pct, f?.glow_wm2, f?.sunshine_s_10min]).toEqual([null, null, null, null]); + expect(fileFromTawes({ features: [] })).toBeNull(); + }); +}); diff --git a/src/app/features/scene/ridge/ridgeBake.ts b/src/app/features/scene/ridge/ridgeBake.ts index 770c30e0..72736d85 100644 --- a/src/app/features/scene/ridge/ridgeBake.ts +++ b/src/app/features/scene/ridge/ridgeBake.ts @@ -3,7 +3,7 @@ // 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, LayerSpec, profile, hazeColour, layerColour, transmittance } from './ridgeWorld'; +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'; @@ -45,6 +45,8 @@ export interface BakeParams { 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. */ @@ -67,6 +69,8 @@ export interface LayerPaint { 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 => { @@ -123,6 +127,7 @@ export function layerPaint(spec: LayerSpec, sky: SkyColours): LayerPaint { // 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), }; } @@ -132,7 +137,7 @@ function crestRows(p: BakeParams, c0: number, c1: number): Float64Array { 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 * profile(p.spec, (p.px0 + c) / p.period)); + 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; @@ -155,7 +160,7 @@ export function bakeSlice( const faceH = 0.45 * p.viewH; const rim = 2.2 * p.scale; const glow = 9 * p.scale; - const { base, haze, warm, contrast, sun, shift } = paint; + 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 @@ -182,7 +187,7 @@ export function bakeSlice( (clamp01(1 - d / rim) * 0.4 + (d < glow * 5 ? Math.exp(-d / glow) * 0.08 : 0)) * contrast * (0.3 + 0.7 * lit); - const mist = spec.mist * smoothstep(0, 1, dn); + 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); diff --git a/src/app/features/scene/ridge/ridgeWorld.ts b/src/app/features/scene/ridge/ridgeWorld.ts index 569b43bd..6bd8e3b1 100644 --- a/src/app/features/scene/ridge/ridgeWorld.ts +++ b/src/app/features/scene/ridge/ridgeWorld.ts @@ -1,6 +1,7 @@ // 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'; @@ -29,23 +30,40 @@ export interface LayerSpec { 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.24, + relief: 0.16, crag: 0.85, - base: 0.34, + base: 0.3, depth: 0.12, - seconds: 420, + seconds: Infinity, octaves: 5, warp: 0.6, gully: 0.3, gullyPx: 16, mist: 0.35, + horizon: true, }, { index: 1, @@ -128,6 +146,15 @@ export function profile(spec: LayerSpec, t: number): number { 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); @@ -198,7 +225,7 @@ export function layerSize(cssW: number, cssH: number, scale: number) { } /** 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): number { - const topFromBottom = spec.base * viewH + spec.relief * viewH * profile(spec, t); +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); } diff --git a/src/app/features/scene/ridge/skyDome.ts b/src/app/features/scene/ridge/skyDome.ts index f4cdda3c..41da66b8 100644 --- a/src/app/features/scene/ridge/skyDome.ts +++ b/src/app/features/scene/ridge/skyDome.ts @@ -1,8 +1,9 @@ // The sky as a camera sees it: for each texel of a small grid, the view ray, its radiance out of the atmosphere's sky-view -// LUT (`earthAtmosphere.ts`), the sun's disc, 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. import type { Atmosphere } from './earthAtmosphere'; import type { SunSample } from './vienna'; +import { cloudAmount, cloudRadiance } from './clouds'; const RAD = Math.PI / 180; /** The sun's angular radius in radians (Hillaire's/Bruneton's `sun_angular_radius`). */ @@ -40,11 +41,16 @@ 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). `sunVisible` false leaves the - * disc out (the glare it would add is still in the LUT); the disc is the transmittance-attenuated sun, its coverage of each - * texel computed from the angular distance, not a hard edge. + * 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. */ -export function renderDome(atm: Atmosphere, sun: SunSample, view: DomeView, w: number, h: number): Dome { +export function renderDome( + atm: Atmosphere, + sun: SunSample, + view: DomeView, + w: number, + h: number, + cover = 0 +): Dome { const hdr = new Float32Array(w * h * 3); const tanHalf = Math.tan((VFOV_DEG * RAD) / 2); const fa = view.azimuthDeg * RAD; @@ -54,15 +60,16 @@ export function renderDome(atm: Atmosphere, sun: SunSample, view: DomeView, w: n const ry = -Math.sin(fa); const sunAz = sun.azimuth * RAD; const sunEl = sun.elevation * RAD; - const sx = Math.cos(sunEl) * Math.sin(sunAz); - const sy = Math.cos(sunEl) * Math.cos(sunAz); const sz = Math.sin(sunEl); const trans = [0, 0, 0]; - atm.transmittanceToSpace(Math.max(sz, 0), trans); - // The disc's radiance for unit irradiance: 1 / (pi r^2), through the air to the sun. - const discRadiance = 1 / (Math.PI * SUN_RADIUS * SUN_RADIUS); - const texelAngle = (2 * tanHalf) / h; // radians per texel, small-angle + atm.transmittanceToSpace(Math.max(sz, 0), trans); // the cloud's sunlight const rgb = [0, 0, 0]; + const cloud = [0, 0, 0]; + if (cover > 0) { + const zenith = [0, 0, 0]; + atm.radiance(1, 1, zenith); + cloudRadiance(sz, trans, zenith, cover, cloud); + } let logSum = 0; for (let j = 0; j < h; j += 1) { const v = (HORIZON_AT - (j + 0.5) / h) * 2 * tanHalf; @@ -78,22 +85,38 @@ export function renderDome(atm: Atmosphere, sun: SunSample, view: DomeView, w: n let r = rgb[0]; let g = rgb[1]; let b = rgb[2]; - if (sz > -0.01 && vz > 0) { - const cosSun = (dx * sx + dy * sy + dz * sz) / n; - const ang = Math.acos(Math.max(-1, Math.min(1, cosSun))); - const cover = Math.max(0, Math.min(1, (SUN_RADIUS - ang) / texelAngle + 0.5)); - if (cover > 0) { - r += discRadiance * cover * trans[0]; - g += discRadiance * cover * trans[1]; - b += discRadiance * cover * trans[2]; - } + let lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]; + if (cover > 0) { + const c = cloudAmount(dx / n, dy / n, vz, cover); + lum += (0.2126 * cloud[0] + 0.7152 * cloud[1] + 0.0722 * cloud[2] - lum) * c; + r += (cloud[0] - r) * c; + g += (cloud[1] - g) * c; + b += (cloud[2] - b) * c; } const o = (j * w + i) * 3; hdr[o] = r; hdr[o + 1] = g; hdr[o + 2] = b; - logSum += Math.log(Math.max(1e-9, 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2])); + logSum += Math.log(Math.max(1e-9, lum)); } } 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. */ +export function sunOnScreen(sun: SunSample, view: DomeView): { x: number; y: number } | null { + if (sun.elevation < -0.3) return null; + const tanHalf = Math.tan((VFOV_DEG * RAD) / 2); + const fa = view.azimuthDeg * RAD; + const az = sun.azimuth * RAD; + 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 }; +} diff --git a/src/app/features/scene/ridge/toneMap.ts b/src/app/features/scene/ridge/toneMap.ts index ab51a95c..b91a4d6d 100644 --- a/src/app/features/scene/ridge/toneMap.ts +++ b/src/app/features/scene/ridge/toneMap.ts @@ -153,3 +153,42 @@ export function fitDisplay(state: FixedSkyState, hdr: Float32Array, meanLuma: nu } 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; +} diff --git a/src/app/features/scene/ridge/weather.ts b/src/app/features/scene/ridge/weather.ts index 4f277149..68ea88ea 100644 --- a/src/app/features/scene/ridge/weather.ts +++ b/src/app/features/scene/ridge/weather.ts @@ -1,9 +1,16 @@ -// One weather number, 0..1, and what it does to the sky. No network source yet: the number is a constant, or the page URL's -// `?weather=` for a still. 0 clear, about 0.3 fair (a few clouds), 0.55 overcast, 0.75 drizzle and mist, 1 steady rain. +// One weather number, 0..1, and what it does to the sky. It is the page URL's `?weather=` (for a still), else the number the +// observation file gives (`weatherFeed.ts`, set by `setFedWeather`), else a clear sky. 0 clear, about 0.3 fair (a few clouds), 0.55 overcast, 0.75 drizzle and mist, 1 steady rain. // What each part touches: haze multiplies the atmosphere's Mie coefficients before the LUTs are baked (`earthAtmosphere.ts`: // the same air, more aerosol); cloud cover, mist and rain are layers over the baked sky (`clouds.ts`, `Ridge.ts`). -export const DEFAULT_WEATHER = 0.3; +let fed: number | undefined; +/** The weather number read from `weather.json`, or undefined to forget it. */ +export const setFedWeather = (v: number | undefined): void => { + fed = v; +}; + +/** The weather the ridge sky is drawn for: the URL's, else the file's, else clear. */ +export const ridgeWeather = (): number => urlWeather() ?? fed ?? 0; export interface Weather { /** The number it was made from. */ @@ -25,7 +32,7 @@ const smooth = (a: number, b: number, v: number): number => { }; export function weatherOf(value: number): Weather { - const w = clamp01(Number.isFinite(value) ? value : DEFAULT_WEATHER); + const w = clamp01(Number.isFinite(value) ? value : 0); return { value: w, cover: smooth(0.1, 0.7, w), diff --git a/src/app/features/scene/ridge/weatherFeed.test.ts b/src/app/features/scene/ridge/weatherFeed.test.ts index 7019d9c6..4182ef3d 100644 --- a/src/app/features/scene/ridge/weatherFeed.test.ts +++ b/src/app/features/scene/ridge/weatherFeed.test.ts @@ -1,29 +1,130 @@ import { describe, expect, it } from 'vitest'; -import { fetchObservation, parseTawes, weatherFromObservation } from './weatherFeed'; +import { viennaSun } from './vienna'; +import { + CLEAR_SKY, + currentWeather, + fetchWeatherFile, + parseWeatherFile, + STALE_MS, + WEATHER_ATTRIBUTION, + weatherFromFile, + clearSkyGhi, + cloudEstimate, + cloudFromGlow, + WeatherFile, +} from './weatherFeed'; -const tawes = (RR: number | null, RF: number | null, SO: number | null) => ({ - features: [{ properties: { parameters: { RR: { data: [RR] }, RF: { data: [RF] }, SO: { data: [SO] } } } }], +const file = (over: Partial = {}): WeatherFile => ({ + fetched_at: '2026-11-11T10:45:00Z', + observed_at: '2026-11-11T10:40:00Z', + station: 11035, + precip_mm_10min: 0, + humidity_pct: 60, + glow_wm2: null, + sunshine_s_10min: null, + attribution: WEATHER_ATTRIBUTION, + ...over, }); +const NOW = new Date('2026-11-11T10:50:00Z'); -describe('weather from the TAWES observation', () => { +describe('weather from the file', () => { + it('credits GeoSphere as its legal page asks, and claims no licence', () => { + expect(WEATHER_ATTRIBUTION).toBe('Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at'); + expect(WEATHER_ATTRIBUTION).not.toMatch(/CC/); + }); it('rain is 0.8..1, by rate', () => { - expect(weatherFromObservation({ rainMm: 0.1, humidity: 100, sunshineS: 0 }, false)).toBeCloseTo(0.813, 2); - expect(weatherFromObservation({ rainMm: 3, humidity: 100, sunshineS: 0 }, true)).toBe(1); + expect(weatherFromFile(file({ precip_mm_10min: 0.1 }), 20)).toBeCloseTo(0.813, 2); + expect(weatherFromFile(file({ precip_mm_10min: 3 }), -20)).toBe(1); }); - it('a sunny dry day is clear and a sunless day overcast', () => { - expect(weatherFromObservation({ rainMm: 0, humidity: 40, sunshineS: 600 }, true)).toBe(0); - expect(weatherFromObservation({ rainMm: 0, humidity: 70, sunshineS: 0 }, true)).toBeCloseTo(0.55, 2); + it('the clear-sky radiation is Haurwitz: about 335 W/m2 at 21 degrees, none below the horizon', () => { + expect(clearSkyGhi(21)).toBeCloseTo(335, -1); + expect(clearSkyGhi(-5)).toBe(0); }); - it('a dry night is clear unless the air is saturated', () => { - expect(weatherFromObservation({ rainMm: 0, humidity: 60, sunshineS: 0 }, false)).toBe(0); - expect(weatherFromObservation({ rainMm: 0, humidity: 100, sunshineS: 0 }, false)).toBeCloseTo(0.75, 2); + it('noon clear: radiation at the clear-sky value is no cloud', () => { + expect(weatherFromFile(file({ glow_wm2: clearSkyGhi(21), sunshine_s_10min: 600, humidity_pct: 95 }), 21)).toBe(0); + expect(cloudFromGlow(300, 21)).toBeCloseTo(0.56, 1); // k = 0.9 is still a few oktas }); - it('parses the live response shape and rejects one without rain or humidity', () => { - expect(parseTawes(tawes(0.1, 100, 0))).toEqual({ rainMm: 0.1, humidity: 100, sunshineS: 0 }); - expect(parseTawes(tawes(null, 100, 0))).toBeNull(); - expect(parseTawes({})).toBeNull(); + it('noon overcast: a fifth of the clear-sky radiation is nearly full cloud, and with saturated air, mist', () => { + expect(cloudFromGlow(0.2 * clearSkyGhi(21), 21)).toBeGreaterThan(0.9); + expect(weatherFromFile(file({ glow_wm2: 0.2 * clearSkyGhi(21), humidity_pct: 80 }), 21)).toBeGreaterThan(0.6); + expect(weatherFromFile(file({ glow_wm2: 0.2 * clearSkyGhi(21), humidity_pct: 100 }), 21)).toBe(0.75); }); - it('a failed request is no observation', async () => { - expect(await fetchObservation((async () => ({ ok: false })) as unknown as typeof fetch)).toBeNull(); + it('the radiation, not the humidity, decides by day: humid air under a bright sky is clear', () => { + expect(weatherFromFile(file({ glow_wm2: clearSkyGhi(30), sunshine_s_10min: 600, humidity_pct: 98 }), 30)).toBe(0); + }); + it('dusk: with the sun at 3 degrees the humidity ramp speaks, cloud 0 at 60% and 1 at 95%', () => { + expect(weatherFromFile(file({ glow_wm2: 5, sunshine_s_10min: 0, humidity_pct: 60 }), 3)).toBe(0); + expect(weatherFromFile(file({ glow_wm2: 5, sunshine_s_10min: 0, humidity_pct: 77.5 }), 3)).toBeCloseTo(0.35, 2); + expect(weatherFromFile(file({ glow_wm2: 5, sunshine_s_10min: 0, humidity_pct: 95 }), 3)).toBeCloseTo(0.7, 2); + }); + it('night: the radiation and sunshine are 0.0 and the humidity speaks; saturated air is mist, 0.75', () => { + expect(weatherFromFile(file({ glow_wm2: 0, humidity_pct: 40 }), -20)).toBe(0); + 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', () => { + const nov = viennaSun(new Date('2026-11-10T10:40:00Z')).elevation; + const oct = viennaSun(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 [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: 560, sunshine_s_10min: 600, humidity_pct: 70 }), oct)).toBe(0); + }); + it('the sunshine cross-checks the radiation: agreement keeps the radiation, a half-sky disagreement splits it', () => { + expect(cloudEstimate(file({ glow_wm2: 0.2 * clearSkyGhi(21), sunshine_s_10min: 0 }), 21)).toBeGreaterThan(0.9); + // Radiation says clear, the sunshine says none: each is half trusted. + expect(cloudEstimate(file({ glow_wm2: clearSkyGhi(21), sunshine_s_10min: 0 }), 21)).toBe(0.5); + // No radiation reading by day: the sunshine speaks alone. + expect(cloudEstimate(file({ glow_wm2: null, sunshine_s_10min: 300 }), 21)).toBe(0.5); + expect(cloudEstimate(file({ glow_wm2: 0, sunshine_s_10min: 600 }), 21)).toBe(0); + }); + it('with the sun below the instruments\' reach there is no estimate: the humidity speaks', () => { + expect(cloudEstimate(file({ glow_wm2: 3, sunshine_s_10min: 0 }), 3)).toBeNull(); + }); + it('null: unknown measurements are not zero, and nothing known is a clear sky', () => { + expect(weatherFromFile(file({ glow_wm2: null, humidity_pct: null, precip_mm_10min: null, sunshine_s_10min: null }), 21)).toBe(CLEAR_SKY); + expect(weatherFromFile(file({ glow_wm2: null, humidity_pct: 95 }), 21)).toBeCloseTo(0.7, 2); + }); +}); + +describe('the weather now', () => { + it('uses the file while it is fresh', () => { + expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 95 }), NOW)).toBeCloseTo(0.7, 2); + }); + it('falls back to a clear sky when the observation is older than 30 minutes', () => { + const f = file({ humidity_pct: 100, observed_at: '2026-11-11T10:19:00Z' }); + expect(NOW.getTime() - Date.parse(f.observed_at)).toBeGreaterThan(STALE_MS); + expect(currentWeather(f, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-11T09:00:00Z' }), NOW)).toBe(CLEAR_SKY); + }); + it('the 30 minute mark itself is still fresh', () => { + expect(currentWeather(file({ glow_wm2: 0, humidity_pct: 100, observed_at: '2026-11-11T10:20:00Z' }), NOW)).toBe(0.75); + }); + it('falls back to a clear sky with no file, and with an observation from the future', () => { + expect(currentWeather(null, NOW)).toBe(CLEAR_SKY); + expect(currentWeather(file({ precip_mm_10min: 2, observed_at: '2026-11-12T10:40:00Z' }), NOW)).toBe(CLEAR_SKY); + }); +}); + +describe('reading weather.json', () => { + it('parses the agreed shape, keeping nulls and the sunshine it never reads', () => { + const raw = { ...file(), precip_mm_10min: null, glow_wm2: 12, sunshine_s_10min: 0 }; + expect(parseWeatherFile(raw)).toEqual(raw); + }); + it('rejects a body without usable times, and anything not an object', () => { + expect(parseWeatherFile({ ...file(), observed_at: 'yesterday' })).toBeNull(); + expect(parseWeatherFile({ ...file(), fetched_at: undefined })).toBeNull(); + expect(parseWeatherFile(null)).toBeNull(); + expect(parseWeatherFile('x')).toBeNull(); + }); + it('is no observation when the file is missing, fails, or is not JSON', async () => { + expect(await fetchWeatherFile('/weather.json', (async () => ({ ok: false })) as unknown as typeof fetch)).toBeNull(); + expect(await fetchWeatherFile('/weather.json', (async () => { throw new Error('offline'); }) as unknown as typeof fetch)).toBeNull(); + expect( + await fetchWeatherFile('/weather.json', (async () => ({ ok: true, json: async () => { throw new Error('bad'); } })) as unknown as typeof fetch) + ).toBeNull(); + }); + it('reads a good file', async () => { + const f = (async () => ({ ok: true, json: async () => file() })) as unknown as typeof fetch; + expect(await fetchWeatherFile('/weather.json', f)).toEqual(file()); }); }); diff --git a/src/app/features/scene/ridge/weatherFeed.ts b/src/app/features/scene/ridge/weatherFeed.ts index 19e40b2f..bd3e44c3 100644 --- a/src/app/features/scene/ridge/weatherFeed.ts +++ b/src/app/features/scene/ridge/weatherFeed.ts @@ -1,53 +1,113 @@ -// The weather over the viewpoint as one `weather.ts` number, from GeoSphere Austria's TAWES 10-minute observations -// (station 11035, Wien Innere Stadt; open data, CC BY 4.0, no key, CORS open; 5 requests/s and 240/hour per client). TAWES measures -// rain, humidity and sunshine duration, not cloud cover, so the number is what those three imply. Open-Meteo has cloud cover but its -// free API is for non-commercial use only, so it is not used. -export const TAWES_STATION = '11035'; -export const TAWES_URL = - `https://dataset.api.hub.geosphere.at/v1/station/current/tawes-v1-10min?parameters=RR¶meters=RF¶meters=SO&station_ids=${TAWES_STATION}`; -export const WEATHER_ATTRIBUTION = 'Weather: GeoSphere Austria (CC BY 4.0), station Wien Innere Stadt'; +// The weather over the viewpoint as one `weather.ts` number, read from a static `weather.json` next to the page (config.json's +// neighbour). The browser never calls a weather service: a refresher outside the client (scripts/refresh-weather.mjs is its +// reference, Eureka hosts the timer) writes the file from GeoSphere Austria's TAWES 10-minute observations (station 11035, Wien Hohe +// Warte). Rain is the gauge. CLOUD IS AN ESTIMATE: TAWES has no cloud cover. By day it is the measured global radiation (GLOW) against +// what a clear sky gives at the sun's position now (`clearSkyGhi`, Haurwitz), cross-checked by the sunshine duration (`SO`, seconds of +// 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 older than STALE_MS is no observation, and no observation is a clear sky. +import { viennaSun } from './vienna'; -export interface Observation { - /** Rain in the last 10 minutes, mm. */ - rainMm: number; - /** Relative humidity, %. */ - humidity: number; - /** Sunshine in the last 10 minutes, seconds (0..600). */ - sunshineS: number; +export const STALE_MS = 30 * 60_000; +const SKEW_MS = 5 * 60_000; +export const CLEAR_SKY = 0; +/** The credit GeoSphere's legal page asks for. */ +export const WEATHER_ATTRIBUTION = 'Datenquelle: GeoSphere Austria - https://data.hub.geosphere.at'; + +/** The file's shape; every measurement is null when the station did not report it. Times are ISO 8601. */ +export interface WeatherFile { + fetched_at: string; + observed_at: string; + station: number; + precip_mm_10min: number | null; + humidity_pct: number | null; + /** Global radiation, W/m2, last 10 minutes. */ + glow_wm2: number | null; + sunshine_s_10min: number | null; + attribution: string; } const clamp01 = (v: number): number => Math.min(1, Math.max(0, v)); +const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null); + +/** A `WeatherFile` from parsed JSON, or null when it does not have the shape (times missing or unparseable). */ +export function parseWeatherFile(json: unknown): WeatherFile | null { + const j = json as Record | null; + if (!j || typeof j !== 'object') return null; + if (typeof j.observed_at !== 'string' || Number.isNaN(Date.parse(j.observed_at))) return null; + if (typeof j.fetched_at !== 'string' || Number.isNaN(Date.parse(j.fetched_at))) return null; + return { + fetched_at: j.fetched_at, + observed_at: j.observed_at, + station: num(j.station) ?? 0, + precip_mm_10min: num(j.precip_mm_10min), + humidity_pct: num(j.humidity_pct), + glow_wm2: num(j.glow_wm2), + sunshine_s_10min: num(j.sunshine_s_10min), + attribution: typeof j.attribution === 'string' ? j.attribution : WEATHER_ATTRIBUTION, + }; +} + +/** Global horizontal radiation of a clear sky, W/m2, sun at `el` degrees: Haurwitz (1945), 1098 cos(z) exp(-0.057 / cos(z)). */ +export function clearSkyGhi(el: number): number { + const c = Math.sin((el * Math.PI) / 180); + return c <= 0 ? 0 : 1098 * c * Math.exp(-0.057 / c); +} + +/** Below this sun elevation the radiation says too little (clear-sky ~100 W/m2 at 8 degrees) and the humidity is read instead. */ +export const GLOW_FROM_DEG = 8; /** - * The weather number of an observation. Rain sets 0.8..1 by rate (0.1 mm in ten minutes is the gauge's step: drizzle). Without rain, - * sunshine says how much of the sky is open when the sun is up (`sunUp`); at night, or with the sun up and no sunshine, humidity - * says it: saturated air with no sun is overcast and misty. + * Cloud 0..1 from measured global radiation against the clear-sky value: the clearness ratio k inverted through Kasten and + * Czeplak (1980), k = 1 - 0.75 (N/8)^3.4, N the oktas. Null when the sun is too low or the reading is missing or 0. */ -export function weatherFromObservation(o: Observation, sunUp: boolean): number { - if (o.rainMm > 0) return clamp01(0.8 + 0.2 * Math.min(1, o.rainMm / 1.5)); - const mist = clamp01((o.humidity - 85) / 15) * 0.75; - if (!sunUp) return mist; - const sun = clamp01(o.sunshineS / 600); - return Math.max(mist * (1 - sun), 0.55 * (1 - sun)); +export function cloudFromGlow(glow: number | null, sunEl: number): number | null { + if (glow === null || glow <= 0 || sunEl < GLOW_FROM_DEG) return null; + const k = Math.min(1, glow / clearSkyGhi(sunEl)); + return clamp01(((1 - k) / 0.75) ** (1 / 3.4)); } -interface TawesFeature { - properties?: { parameters?: Record }; +/** The cloud the sunshine duration implies: the share of the ten minutes the sun did not shine. Null when the sun is too low or it is unreported. */ +export function cloudFromSunshine(so: number | null, sunEl: number): number | null { + if (so === null || sunEl < GLOW_FROM_DEG) return null; + return 1 - clamp01(so / 600); } -/** Parse a TAWES `station/current` response; null when a parameter is missing or has no value. */ -export function parseTawes(json: unknown): Observation | null { - const f = (json as { features?: TawesFeature[] } | null)?.features?.[0]; - const p = f?.properties?.parameters; - const val = (k: string): number | null => p?.[k]?.data?.[0] ?? null; - const rainMm = val('RR'); - const humidity = val('RF'); - const sunshineS = val('SO'); - if (rainMm === null || humidity === null) return null; - return { rainMm, humidity, sunshineS: sunshineS ?? 0 }; +/** The cloud estimate by day, or null when the sun is too low for either instrument (the caller reads the humidity). */ +export function cloudEstimate(f: WeatherFile, sunEl: number): number | null { + const g = cloudFromGlow(f.glow_wm2, sunEl); + const s = cloudFromSunshine(f.sunshine_s_10min, sunEl); + if (g !== null && s !== null) return Math.abs(g - s) > 0.5 ? (g + s) / 2 : g; // instruments that disagree by half a sky are each half trusted + return g ?? s; } -export async function fetchObservation(fetcher: typeof fetch = fetch, signal?: AbortSignal): Promise { - const res = await fetcher(TAWES_URL, { signal }); - return res.ok ? parseTawes(await res.json()) : null; +/** + * The weather number of an observation with the sun at `sunEl` degrees. Rain sets 0.8..1 by rate (0.1 mm in ten minutes is the + * gauge's step: drizzle). Without rain, cloud (above) puts the number up to 0.7 (overcast); where the instruments cannot give it + * (the sun low or down), cloud is a ramp of the humidity, 0 at 60% to 1 at 95%. Saturated air (92% to 100%) sets a mist floor of up to 0.75 when the sky is + * more than half cloud. + */ +export function weatherFromFile(f: WeatherFile, sunEl: number): number { + const rain = f.precip_mm_10min ?? 0; + if (rain > 0) return clamp01(0.8 + 0.2 * Math.min(1, rain / 1.5)); + const cloud = cloudEstimate(f, sunEl) ?? (f.humidity_pct === null ? 0 : clamp01((f.humidity_pct - 60) / 35)); + const mist = f.humidity_pct === null || cloud < 0.5 ? 0 : clamp01((f.humidity_pct - 92) / 8) * 0.75; + 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 (observed more than STALE_MS before `now`). */ +export function currentWeather(f: WeatherFile | null, now: Date = new Date()): number { + if (!f) return CLEAR_SKY; + const age = now.getTime() - Date.parse(f.observed_at); + if (!(age <= STALE_MS && age >= -SKEW_MS)) return CLEAR_SKY; // stale, or from further ahead of the clock than clocks differ + return weatherFromFile(f, viennaSun(now).elevation); +} + +/** Fetch and parse `weather.json`; null on any failure. */ +export async function fetchWeatherFile(url: string, fetcher: typeof fetch = fetch): Promise { + try { + const res = await fetcher(url, { cache: 'no-cache' }); + return res.ok ? parseWeatherFile(await res.json()) : null; + } catch { + return null; + } } diff --git a/src/app/features/scene/skyForState.ts b/src/app/features/scene/skyForState.ts index 5a2bfaf2..8a5f9768 100644 --- a/src/app/features/scene/skyForState.ts +++ b/src/app/features/scene/skyForState.ts @@ -10,7 +10,8 @@ import type { SkyColours, Srgb } from './ridge/skyColour'; import { skyColours } from './ridge/skyColour'; import { makePhysicalSky } from './ridge/physicalSky'; import { BUDGET } from './ridge/toneMap'; -import { DEFAULT_WEATHER, urlWeather } from './ridge/weather'; +import { ridgeWeather, setFedWeather } from './ridge/weather'; +import { currentWeather, fetchWeatherFile } from './ridge/weatherFeed'; import { resolveSkyState, skyNow } from './skyState'; import type { SkyState } from './skyState'; import { displayedLuminance, SKY_BAND } from './skyBand'; @@ -27,10 +28,22 @@ export const DUSK_SUN_ELEVATION = 2; */ export const ridgeSkyKey = ( state: SkyState, - weather: number = urlWeather() ?? DEFAULT_WEATHER, + weather: number = ridgeWeather(), now: Date = skyNow() ): string => `ridge:${resolveSkyState(state, now)}:${weather}`; +const WEATHER_REFRESH_MS = 10 * 60_000; +let weatherAt = -Infinity; +/** + * 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`). + */ +export async function loadWeather(url: string, now: Date = skyNow()): Promise { + if (now.getTime() - weatherAt < WEATHER_REFRESH_MS) return; + weatherAt = now.getTime(); + setFedWeather(currentWeather(await fetchWeatherFile(url), now)); +} + /** * The ridge scene's `sky` option: the physical sky over Vienna 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 @@ -38,7 +51,7 @@ export const ridgeSkyKey = ( */ export function ridgeSkyFor( state: SkyState, - weather: number = urlWeather() ?? DEFAULT_WEATHER, + weather: number = ridgeWeather(), now: Date = skyNow() ): SkyColours { const { ground } = skyColours();