From b23f44375e9ed3b39b900ac5cf16106c268f8ac7 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 28 Aug 2026 21:57:48 +0200 Subject: [PATCH 1/5] refactor!: hold the atmosphere in one type rather than deriving it twice Turbidity lived on AnalyticSky, which is the Preetham parameter block. Hosek-Wilkie replaces that block, so anything parked on it dies with the model, and which air the sky is rendered through is not a property of whichever model happens to be reading it. Atmosphere carries that state instead, and AnalyticSky reads turbidity through it. The type is #[non_exhaustive] from the first commit, which is the whole reason to have it. Ground albedo is the next axis and Hosek-Wilkie fits it where Preetham has nowhere to put it; aerosol species is the one after, and nothing in the Perez family carries it at all. Each would otherwise break every caller writing a struct literal. ComposeOpts gets the same marker for the same reason, following Config, with new() taking the one option that has no universal default since which way is worth facing depends on the hemisphere. It also puts a disagreement where it can be seen. turbidity_from_visibility ramps across 2 to 24 km while build_haze switches off entirely above 12, so at 13 km reported visibility the analytic sky is told the air is fairly hazy and the haze layer is told there is none. Both curves are unchanged here and both now read one value, so the next person deciding what to do about that is looking at one type rather than two functions that never met. Nothing renders differently: every golden holds, and the analytic properties hold with no assertion relaxed. --- benches/render.rs | 7 +++--- src/analytic_sky.rs | 5 ++-- src/atmosphere.rs | 43 +++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 10 ++++---- src/weather/mod.rs | 1 - src/weather/state.rs | 45 +++++++++++++++++++++++++---------- tests/analytic.rs | 5 ++-- tests/weather.rs | 24 ++++--------------- tools/celsius-lab/src/lib.rs | 5 ++-- tools/celsius-lab/src/main.rs | 2 +- 11 files changed, 100 insertions(+), 48 deletions(-) create mode 100644 src/atmosphere.rs diff --git a/benches/render.rs b/benches/render.rs index df24c0c..82d8d11 100644 --- a/benches/render.rs +++ b/benches/render.rs @@ -8,6 +8,7 @@ use ratatui::layout::Rect; use celsius::analytic_sky::{self, AnalyticSky}; use celsius::astro; +use celsius::atmosphere::Atmosphere; use celsius::colorspace::{Oklab, oklab_to_rgb, rgb_u8_to_oklab}; use celsius::lightning::{self, Lightning}; use celsius::noise::Noise; @@ -104,14 +105,14 @@ fn bench_render(c: &mut Criterion) { g.finish(); } -/// `base` with a midday analytic sky attached at crossfade weight `blend`. Turbidity 2.0 is what `turbidity_from_visibility` yields at full visibility. +/// `base` with a midday analytic sky attached at crossfade weight `blend`. Turbidity 2.0 is what `Atmosphere::from_visibility` yields at full visibility. fn with_analytic(base: &SkyState, blend: f64) -> SkyState { let mut sky = base.clone(); sky.analytic = Some(AnalyticSky { sun_alt: 55.0, sun_az: 180.0, center_az: 180.0, - turbidity: 2.0, + atmosphere: Atmosphere::from_turbidity(2.0), blend, }); sky @@ -435,7 +436,7 @@ fn bench_micro(c: &mut Criterion) { sun_alt: 55.0, sun_az: 180.0, center_az: 180.0, - turbidity: 2.0, + atmosphere: Atmosphere::from_turbidity(2.0), blend: 1.0, }); // A frame's worth of Perez evaluations, which is what a daytime render pays: `sample` runs once per pixel and roughly triples a clear 104x50 frame. Batched for the same reason as `warped_fbm_5200`, a single call being short enough that the reported number was the harness. diff --git a/src/analytic_sky.rs b/src/analytic_sky.rs index 58af5ee..728368f 100644 --- a/src/analytic_sky.rs +++ b/src/analytic_sky.rs @@ -2,6 +2,7 @@ use std::f64::consts::PI; +use crate::atmosphere::Atmosphere; use crate::colorspace::Oklab; /// Where a sky's own mean luminance is placed on the tone curve. @@ -18,7 +19,7 @@ pub struct AnalyticSky { pub sun_alt: f64, pub sun_az: f64, pub center_az: f64, - pub turbidity: f64, + pub atmosphere: Atmosphere, /// Crossfade weight toward the analytic sky, 0..1. Ramps up from 0 at the horizon to 1 a few degrees above it, so the model fades into the palette through twilight instead of popping in at sunrise. render lerps the palette gradient toward `sample()` by this amount. pub blend: f64, } @@ -115,7 +116,7 @@ fn dir_from_altaz(alt_deg: f64, az_deg: f64, center_az: f64) -> [f64; 3] { } pub fn prepare(sky: &AnalyticSky) -> Prepared { - let t = sky.turbidity; + let t = sky.atmosphere.turbidity; let theta_sun = (90.0 - sky.sun_alt).to_radians(); let lum = lum_coeffs(t); let cx = cx_coeffs(t); diff --git a/src/atmosphere.rs b/src/atmosphere.rs new file mode 100644 index 0000000..7faad52 --- /dev/null +++ b/src/atmosphere.rs @@ -0,0 +1,43 @@ +//! What the air is doing, held once so every sky model reads the same state instead of each deriving its own. +//! +//! Turbidity and horizon haze are one aerosol loading seen two ways, and both were computed from the same reported visibility in two places on two unrelated curves: turbidity ramps across 2 to 24 km while haze switches off entirely above 12 km. At 13 km the analytic sky is told the air is fairly hazy and the haze layer is told there is none. Both curves are unchanged here; what changes is that they now read one value and that disagreement sits in one type rather than split across two functions. +//! +//! `#[non_exhaustive]` is the reason this type exists at all, rather than a precaution. Turbidity lived on `AnalyticSky`, which is the Preetham parameter block and does not survive the move to Hosek-Wilkie; ground albedo is the next axis (Hosek-Wilkie fits it, Preetham has no place to put it) and aerosol species the one after (no model in the Perez family carries it). Each of those would otherwise break every caller writing a struct literal. + +/// The atmospheric state one sky is rendered through. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub struct Atmosphere { + /// Horizontal visibility in metres, when a forecast reported one. `None` for a sky whose turbidity was chosen directly, which is every sweep the lab renders. + pub visibility_m: Option, + /// Preetham turbidity: total optical thickness over its molecular part, so 1 is a pure Rayleigh atmosphere and 2 to 3 is a clear day. + pub turbidity: f64, +} + +impl Atmosphere { + /// The live path, where everything follows from what the forecast reported. + #[must_use] + pub fn from_visibility(visibility_m: Option) -> Self { + Self { + visibility_m, + turbidity: turbidity_from_visibility(visibility_m), + } + } + + /// The authored path, for sweeping a model across turbidities that no visibility reading has to justify. + #[must_use] + pub fn from_turbidity(turbidity: f64) -> Self { + Self { + visibility_m: None, + turbidity, + } + } +} + +// Open-Meteo visibility tops out near 24 km on clear days and falls to a few km in haze/fog. Map clear -> low turbidity (~2), hazy -> high (~9). +/// Map visibility in metres to the turbidity range used by the analytic sky. +#[must_use] +pub fn turbidity_from_visibility(vis_m: Option) -> f64 { + let vis_km = vis_m.unwrap_or(24_000.0) / 1000.0; + (2.0 + (24.0 - vis_km.clamp(2.0, 24.0)) / 22.0 * 7.0).clamp(2.0, 9.0) +} diff --git a/src/lib.rs b/src/lib.rs index 2d2a786..793aea4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,6 +14,7 @@ pub mod analytic_sky; pub mod astro; +pub mod atmosphere; pub mod colorspace; pub mod config; pub mod gradient; diff --git a/src/main.rs b/src/main.rs index 1dca917..aa3ecad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -401,14 +401,14 @@ fn build_live_timeline(params: &FetchParams, location: &location::GeoResult) -> } let saved = config::load(); - let opts = ComposeOpts { - center_az: params + let opts = ComposeOpts::new( + params .facing .or(saved.facing) .unwrap_or_else(|| default_facing(location.latitude)), - bortle: params.bortle.or(saved.bortle), - analytic: params.analytic, - }; + ) + .with_bortle(params.bortle.or(saved.bortle)) + .with_analytic(params.analytic); let mut states: Vec<_> = (0..hours) .map(|h| compose(&forecast, location, h, now_unix, opts)) .collect::>() diff --git a/src/weather/mod.rs b/src/weather/mod.rs index 37546f7..a36d5d4 100644 --- a/src/weather/mod.rs +++ b/src/weather/mod.rs @@ -15,7 +15,6 @@ pub use state::ComposeOpts; pub use state::compose; pub use state::compose_at; pub use state::error_sky; -pub use state::turbidity_from_visibility; use std::sync::LazyLock; use std::time::Duration; diff --git a/src/weather/state.rs b/src/weather/state.rs index fb1c7c3..237623f 100644 --- a/src/weather/state.rs +++ b/src/weather/state.rs @@ -1,6 +1,6 @@ //! Forecast plus coordinates in, [`SkyState`] out. The synthesis layer. //! -//! `compose` is where numbers become a sky. Solar and lunar position come from the `astro` module; a palette is chosen by sun altitude with overcast overrides; cloud layers are built from the low/mid/high cover triple at fixed altitudes; stars fade in below -3 degrees; WMO weather codes decide rain versus snow and whether the storm gets lightning; visibility drives both haze and the analytic sky's turbidity. +//! `compose` is where numbers become a sky. Solar and lunar position come from the `astro` module; a palette is chosen by sun altitude with overcast overrides; cloud layers are built from the low/mid/high cover triple at fixed altitudes; stars fade in below -3 degrees; WMO weather codes decide rain versus snow and whether the storm gets lightning; and one `Atmosphere` built from the reported visibility feeds both the haze layer and the analytic sky. //! //! The judgement calls worth knowing. Cloud seeds mix `(lat, lon, day)` so a sky reshapes once per UTC day rather than every hour, which stops clouds boiling as you scrub the timeline. `compose_at` interpolates between forecast hours for scalars but snaps weather codes to the nearer hour, because a code is categorical and half of "thunderstorm" is not a thing. Wind direction becomes a lateral offset from the facing bearing, so rain leans the way the wind is actually blowing relative to the viewer. //! @@ -10,6 +10,7 @@ use chrono::{Datelike, NaiveDateTime, TimeZone, Timelike, Utc}; use crate::analytic_sky::AnalyticSky; use crate::astro::{self, AltAz}; +use crate::atmosphere::Atmosphere; use crate::lightning::Lightning; use crate::meteors::Meteors; use crate::scene::{ @@ -88,7 +89,10 @@ impl HourSample { } /// View options shared by every sky in a timeline: where the camera points, how dark the site is, and which model paints the daytime background. +/// +/// Not exhaustively constructible from outside, for the same reason `Config` is not: this is the surface the atmosphere work extends, and every axis added to it (ground albedo, aerosol species) would otherwise break each caller writing a struct literal. Start from [`ComposeOpts::new`], or from `default()` when the facing does not matter. #[derive(Clone, Copy, Debug)] +#[non_exhaustive] pub struct ComposeOpts { /// Azimuth at the horizontal center of the frame, in degrees (180 = south). pub center_az: f64, @@ -98,6 +102,29 @@ pub struct ComposeOpts { pub analytic: bool, } +impl ComposeOpts { + /// Facing is the one option with no universal default, since which way is worth looking depends on the hemisphere. The rest have real defaults and are set through the `with_` methods. + #[must_use] + pub fn new(center_az: f64) -> Self { + Self { + center_az, + ..Self::default() + } + } + + #[must_use] + pub fn with_bortle(mut self, bortle: Option) -> Self { + self.bortle = bortle; + self + } + + #[must_use] + pub fn with_analytic(mut self, analytic: bool) -> Self { + self.analytic = analytic; + self + } +} + impl Default for ComposeOpts { fn default() -> Self { Self { @@ -185,13 +212,6 @@ fn bracket_hours( Ok((h0, h0 + 1, frac)) } -// Open-Meteo visibility tops out near 24 km on clear days and falls to a few km in haze/fog. Map clear -> low turbidity (~2), hazy -> high (~9). -/// Map visibility in metres to the turbidity range used by the analytic sky. -pub fn turbidity_from_visibility(vis_m: Option) -> f64 { - let vis_km = vis_m.unwrap_or(24_000.0) / 1000.0; - (2.0 + (24.0 - vis_km.clamp(2.0, 24.0)) / 22.0 * 7.0).clamp(2.0, 9.0) -} - fn build_sky( sample: &HourSample, location: &GeoResult, @@ -211,6 +231,7 @@ fn build_sky( let sun_altaz = astro::sun_position(lat, lon, unix_utc); let moon_state = astro::moon_state(lat, lon, unix_utc); + let atmosphere = Atmosphere::from_visibility(sample.visibility_m); let total_cover = total_cover( sample.reported_cover, sample.cover_low, @@ -244,7 +265,7 @@ fn build_sky( exponent: 1.4, }) } else { - build_haze(sample.visibility_m) + build_haze(&atmosphere) }; let precipitation = build_precipitation( sample.weather_code, @@ -279,7 +300,7 @@ fn build_sky( sun_alt: sun_altaz.altitude, sun_az: sun_altaz.azimuth, center_az, - turbidity: turbidity_from_visibility(sample.visibility_m), + atmosphere, // Two things hold the model back. It ramps in over the first 8 degrees of solar elevation, so it crossfades out of the palette through twilight with no seam at sunrise. And it fades out under cloud, because Preetham describes a *clear* sky: run at full strength under an overcast deck it paints a clean blue-to-pale gradient and calls it a grey day. The overcast palette exists precisely for the sky you can actually see when the clear one is hidden. blend: (sun_altaz.altitude / 8.0).clamp(0.0, 1.0) * (1.0 - total_cover).clamp(0.0, 1.0), }); @@ -610,8 +631,8 @@ fn cloud_layer( }) } -fn build_haze(visibility_m: Option) -> Option { - let viz_km = visibility_m? / 1000.0; +fn build_haze(atmosphere: &Atmosphere) -> Option { + let viz_km = atmosphere.visibility_m? / 1000.0; if viz_km >= 12.0 { return None; } diff --git a/tests/analytic.rs b/tests/analytic.rs index f1e51cc..60fafa9 100644 --- a/tests/analytic.rs +++ b/tests/analytic.rs @@ -4,6 +4,7 @@ use celsius::analytic_sky::{self, AnalyticSky}; use celsius::astro::{self, AltAz}; +use celsius::atmosphere::Atmosphere; const CENTER_AZ: f64 = 180.0; @@ -12,7 +13,7 @@ fn sky(sun_alt: f64, sun_az: f64, turbidity: f64) -> analytic_sky::Prepared { sun_alt, sun_az, center_az: CENTER_AZ, - turbidity, + atmosphere: Atmosphere::from_turbidity(turbidity), blend: 1.0, }) } @@ -166,7 +167,7 @@ fn the_crossfade_weight_is_clamped() { sun_alt: 30.0, sun_az: CENTER_AZ, center_az: CENTER_AZ, - turbidity: 2.5, + atmosphere: Atmosphere::from_turbidity(2.5), blend: given, }); assert_eq!( diff --git a/tests/weather.rs b/tests/weather.rs index 8ca3bbc..588f14b 100644 --- a/tests/weather.rs +++ b/tests/weather.rs @@ -158,11 +158,7 @@ fn compose_at_interpolates_between_hours() { // Halfway between 01:00 and 02:00 UTC. wind_speed_10m is 4.0 then 4.1, so the interpolated sky must read 4.05, proving it didn't snap to the top of hour. let t01 = 1_775_869_200; // 2026-04-11T01:00Z let mid = t01 + 1_800; // 01:30Z - let opts = celsius::weather::ComposeOpts { - center_az: 180.0, - bortle: None, - analytic: false, - }; + let opts = celsius::weather::ComposeOpts::default().with_analytic(false); let sky = celsius::weather::compose_at(&forecast, &geo, mid, t01, opts) .expect("compose_at on fixture"); assert!( @@ -195,11 +191,7 @@ fn hamburg_geo() -> GeoResult { #[test] fn compose_at_locks_clear_night_mapping() { let forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); - let opts = celsius::weather::ComposeOpts { - center_az: 180.0, - bortle: None, - analytic: true, - }; + let opts = celsius::weather::ComposeOpts::default().with_analytic(true); let t00 = 1_775_865_600; // 2026-04-11T00:00Z, ~4.5h before sunrise let sky = celsius::weather::compose_at(&forecast, &hamburg_geo(), t00, t00, opts) .expect("compose_at on fixture"); @@ -232,11 +224,7 @@ fn compose_at_locks_clear_night_mapping() { #[test] fn compose_at_post_sunrise_attaches_analytic_sky() { let forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); - let opts = celsius::weather::ComposeOpts { - center_az: 180.0, - bortle: None, - analytic: true, - }; + let opts = celsius::weather::ComposeOpts::default().with_analytic(true); let t05 = 1_775_865_600 + 5 * 3_600; // 2026-04-11T05:00Z, ~22m after sunrise let sky = celsius::weather::compose_at(&forecast, &hamburg_geo(), t05, t05, opts) .expect("compose_at on fixture"); @@ -257,11 +245,7 @@ fn compose_at_post_sunrise_attaches_analytic_sky() { #[test] fn compose_locks_clear_night_via_hour_index() { let forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); - let opts = celsius::weather::ComposeOpts { - center_az: 180.0, - bortle: None, - analytic: true, - }; + let opts = celsius::weather::ComposeOpts::default().with_analytic(true); let t00 = 1_775_865_600; // 2026-04-11T00:00Z, the fixture's first hour let sky = celsius::weather::compose(&forecast, &hamburg_geo(), 0, t00, opts) .expect("compose on fixture"); diff --git a/tools/celsius-lab/src/lib.rs b/tools/celsius-lab/src/lib.rs index 181bc55..7c2c15a 100644 --- a/tools/celsius-lab/src/lib.rs +++ b/tools/celsius-lab/src/lib.rs @@ -5,6 +5,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail, ensure}; use celsius::analytic_sky::{AnalyticSky, prepare}; use celsius::astro::{moon_state, sun_position, to_sky_fracs}; +use celsius::atmosphere::Atmosphere; use celsius::colorspace::{oklab_to_rgb, rgb_u8_to_oklab}; use celsius::scene::{Chrome, SkyState, Sun}; use celsius::{Gradient, load_scene, render}; @@ -91,7 +92,7 @@ pub fn scene_toml(spec: &SceneSpec<'_>) -> Result { sun_alt: sun.altitude, sun_az: sun.azimuth, center_az: spec.facing, - turbidity: spec.turbidity, + atmosphere: Atmosphere::from_turbidity(spec.turbidity), blend: 1.0, }) }); @@ -462,7 +463,7 @@ pub fn analytic_state(sun_alt: f64, turbidity: f64, sun_az_offset: f64) -> SkySt sun_alt, sun_az, center_az, - turbidity, + atmosphere: Atmosphere::from_turbidity(turbidity), blend: 1.0, }), wind_speed_kmh: 0.0, diff --git a/tools/celsius-lab/src/main.rs b/tools/celsius-lab/src/main.rs index 92599f3..1450617 100644 --- a/tools/celsius-lab/src/main.rs +++ b/tools/celsius-lab/src/main.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail, ensure}; use celsius::astro::{moon_state, sun_position, to_sky_fracs}; -use celsius::weather::turbidity_from_visibility; +use celsius::atmosphere::turbidity_from_visibility; use celsius_lab::{ SKY_HEIGHT, SKY_WIDTH, SceneSpec, analytic_state, compare_images, contact_sheet, load_reference, parse_at, render_scene, render_state, repo_root, save_scaled, scene_path, From 14e0cc2eb98dd4561b7ef05f985e853175588f22 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 28 Aug 2026 22:26:09 +0200 Subject: [PATCH 2/5] feat!: expose each sky for its own brightness, not away from it adapted_exposure divided a frame's own log-average luminance into a fixed target, which is full auto-exposure. Measured across the domain the model actually renders, turbidity 2 to 9 with the sun above the horizon, 4.9 stops of real sky luminance arrived on screen inside 0.012 of Oklab lightness. Every sky was the same brightness. The one absolute quantity Preetham computes was surveyed and then divided straight back out, so a dim sky was not something this renderer could draw, and every property in tests/analytic.rs had to be phrased as contrast within one sky because comparing two of them measured the tone curve instead of the atmosphere. The exposure is a partial adaptation now, g * (Lref / Lbar)^p at p = 0.7, the shape photographic tone reproduction calls incomplete adaptation. 1 - p is the fraction of a stop of real difference that reaches the terminal, and it is the only quantity the constant controls: p = 1 is the old behaviour exactly and p = 0 is the fixed gain that came before it. The same domain now spans 0.126, roughly ten times more, with nothing crushed to black or blown to white. The curve itself is untouched, against what TODO.md asked for. BRU17 renders all nine models it surveys with exactly the 1 - exp(-kL) that note wanted replaced, and its perceptual study puts the realism gain in white balance rather than in the curve's shape. The shape was never it. Anchoring turned up a second thing. 0.045 * 2.35 was one constant, and under full adaptation only the product is observable, so neither factor had to describe anything real: a clear noon measures Lbar = 12.858, not 2.35, because the projection went rectilinear in v0.5.0 and the frame stopped reaching the zenith. Both are measured from that sky now and a unit test re-measures it, so the next projection change says so instead of leaving a stale number nothing can see. Three tests this makes possible and one it does not. Two skies of different real brightness must not render alike, no sky in the domain may be crushed or blown, and the palette-to-analytic handover must not step, which measures 0.041 of lightness against the 0.107 dawn itself moves in a quarter hour. Frame-mean lightness is deliberately not asserted to rise with the sun: Lbar peaks near 45 degrees and falls after, because past about 69 the sun leaves the top of the frame and takes the aureole with it, so that is the geometry rather than the curve. The colour tests are unrelated repair. Nothing here asserted on chromaticity, and every mutant that survived a run over this module lived in cx_coeffs or cy_coeffs: the arithmetic deciding what colour the sky is could be corrupted with the whole suite still green. --- src/analytic_sky.rs | 69 +++++++++++++++++++++++++++++++++--- tests/analytic.rs | 86 +++++++++++++++++++++++++++++++++++++++++++++ tests/weather.rs | 44 +++++++++++++++++++++++ 3 files changed, 194 insertions(+), 5 deletions(-) diff --git a/src/analytic_sky.rs b/src/analytic_sky.rs index 728368f..b833e6a 100644 --- a/src/analytic_sky.rs +++ b/src/analytic_sky.rs @@ -5,10 +5,20 @@ use std::f64::consts::PI; use crate::atmosphere::Atmosphere; use crate::colorspace::Oklab; -/// Where a sky's own mean luminance is placed on the tone curve. +/// The sky every other sky is exposed relative to: a clear noon, sun 55 degrees up at turbidity 2, which is the sky the gain was originally tuned against by eye. Both numbers are measured from that frame rather than recalled, and the pair is what keeps it rendering exactly as it does today. /// -/// Preetham radiance is in kcd/m^2 and spans orders of magnitude between a low sun and a high one, so a fixed gain can only be correct at one solar elevation. It was tuned against a clear noon zenith, which meant every low sun came out under-exposed and muddy, and that is what forced the crossfade to hand twilight back to a hand-tuned palette. Exposure is now derived per sky from a coarse survey of the frame, and this constant is the target that survey is mapped onto. Its value is the old gain times the mean luminance of the sky it was tuned on, so a clear noon still lands where it always did. -const ADAPT_KEY: f64 = 0.045 * 2.35; +/// These were one constant, `0.045 * 2.35`, and that product is what made the exposure a pure auto-exposure. Dividing a frame's own log-average into a fixed target normalises every sky to the same mean lightness, so the one absolute quantity Preetham computes, radiance in kcd/m^2 spanning orders of magnitude between a low sun and a high one, was surveyed and then divided straight back out. The renderer could not draw a dim sky. +/// +/// The factors are also why `2.35` was wrong and could stay wrong. Under full adaptation only the product is observable, so neither number alone had to describe anything; a clear noon measures 12.858 here, and 2.35 is a survey of some frame that stopped existing when the projection went rectilinear in v0.5.0 and the view stopped reaching the zenith. Splitting the product is what makes each factor load-bearing enough to be checked. +const REFERENCE_GAIN: f64 = 0.008_225; +const REFERENCE_LUMINANCE: f64 = 12.858; + +/// How much of its own brightness a sky is exposed for, from 0 to 1. +/// +/// At 1 the exposure follows the sky exactly and this is the old behaviour, byte for byte. At 0 it is the fixed gain that came before that, which under-exposed every low sun into mud. In between, `1 - ADAPTATION` is the fraction of a stop of real brightness difference that survives to the terminal, which is the only quantity this constant controls. +/// +/// Photographic tone reproduction calls the same idea incomplete adaptation, and the reason to want it here is not fidelity for its own sake: a sky that cannot be dim cannot be compared with another sky, which is why every assertion about this model had to be phrased as contrast until now. +const ADAPTATION: f64 = 0.7; /// How many samples across the frame the luminance survey takes, per axis. const ADAPT_GRID: u32 = 5; @@ -144,7 +154,16 @@ pub fn prepare(sky: &AnalyticSky) -> Prepared { } /// Survey the frame's luminance so the tone curve can be placed against the sky actually being drawn rather than against one remembered clear noon. A coarse grid is enough: this decides an exposure, not a pixel, and it runs once per sky rather than once per pixel. +/// +/// What it returns is a partial adaptation rather than a normalisation; see `ADAPTATION`. fn adapted_exposure(sun: &[f64; 3], lum_z: f64, lum: &Coeffs, denom_lum: f64) -> f64 { + let mean = frame_log_average(sun, lum_z, lum, denom_lum); + // e = g * (Lref / Lbar)^p, so the rendered level scales as (Lbar / Lref)^(1 - p) and a brighter sky arrives brighter. At p = 1 this is a plain normalisation, and at Lbar = Lref it is g whatever p is, which is what holds the reference sky still. + REFERENCE_GAIN * (REFERENCE_LUMINANCE / mean).powf(ADAPTATION) +} + +/// The luminance this frame reads as, which is the quantity `REFERENCE_LUMINANCE` is a measurement of. +fn frame_log_average(sun: &[f64; 3], lum_z: f64, lum: &Coeffs, denom_lum: f64) -> f64 { let mut total = 0.0; for iy in 0..ADAPT_GRID { for ix in 0..ADAPT_GRID { @@ -158,8 +177,7 @@ fn adapted_exposure(sun: &[f64; 3], lum_z: f64, lum: &Coeffs, denom_lum: f64) -> total += (sample.max(0.0) + 1e-4).ln(); } } - let mean = (total / f64::from(ADAPT_GRID * ADAPT_GRID)).exp().max(1e-6); - ADAPT_KEY / mean + (total / f64::from(ADAPT_GRID * ADAPT_GRID)).exp().max(1e-6) } impl Prepared { @@ -207,3 +225,44 @@ fn lin_rgb_to_oklab(lr: f64, lg: f64, lb: f64) -> Oklab { b: 0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766_0 * s, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// `REFERENCE_LUMINANCE` is a measurement of one specific frame, and a frame is only fixed while the projection is. This is the test the previous constant did not have: `2.35` survived the v0.5.0 move from an orthographic view to a rectilinear one that stops short of the zenith, describing a frame that no longer existed, and nothing could tell because full adaptation made only the product of the two factors observable. + #[test] + fn the_reference_sky_still_reads_as_the_reference_luminance() { + let (alt, turbidity) = (55.0f64, 2.0); + let theta_sun = (90.0 - alt).to_radians(); + let lum = lum_coeffs(turbidity); + let measured = frame_log_average( + &dir_from_altaz(alt, 180.0, 180.0), + zenith_luminance(turbidity, theta_sun), + &lum, + perez(1.0, theta_sun, &lum), + ); + assert!( + (measured / REFERENCE_LUMINANCE - 1.0).abs() < 1e-3, + "a clear noon now reads as {measured:.4}, not the {REFERENCE_LUMINANCE} the exposure is anchored to; re-measure both constants against the current projection rather than adjusting one" + ); + } + + /// The anchor is the whole of the compatibility claim: whatever the adaptation exponent is set to, the sky the gain was tuned on must come out at that gain. + #[test] + fn the_anchor_holds_at_any_adaptation() { + let (alt, turbidity) = (55.0f64, 2.0); + let theta_sun = (90.0 - alt).to_radians(); + let lum = lum_coeffs(turbidity); + let exposure = adapted_exposure( + &dir_from_altaz(alt, 180.0, 180.0), + zenith_luminance(turbidity, theta_sun), + &lum, + perez(1.0, theta_sun, &lum), + ); + assert!( + (exposure / REFERENCE_GAIN - 1.0).abs() < 1e-3, + "the reference sky is exposed at {exposure:.6} rather than {REFERENCE_GAIN}" + ); + } +} diff --git a/tests/analytic.rs b/tests/analytic.rs index 60fafa9..9d05526 100644 --- a/tests/analytic.rs +++ b/tests/analytic.rs @@ -176,3 +176,89 @@ fn the_crossfade_weight_is_clamped() { ); } } + +/// Frame-mean lightness over the model's live domain: turbidity 2 to 9 is what visibility maps to, and the sun is above the horizon wherever the model is attached at all. +fn live_domain_means() -> Vec<(f64, f64, f64)> { + let mut out = Vec::new(); + for sun_alt in [0.5, 2.0, 4.0, 8.0, 15.0, 30.0, 45.0, 60.0, 75.0, 89.0] { + for turbidity in [2.0, 3.0, 5.0, 7.0, 9.0] { + let prepared = sky(sun_alt, CENTER_AZ, turbidity); + let mut sum = 0.0; + for iy in 0..25 { + for ix in 0..25 { + sum += prepared + .sample(f64::from(ix) / 24.0, f64::from(iy) / 24.0) + .l; + } + } + out.push((sun_alt, turbidity, sum / 625.0)); + } + } + out +} + +/// The property the exposure was rebuilt to have, and the one no assertion here could state before. +/// +/// Dividing a frame's own log-average into a fixed target normalises every sky to the same output level, which is what `adapted_exposure` used to do: the same grid measured below spans 4.9 stops of real sky luminance and came out inside 0.012 of Oklab lightness end to end. Every sky looked equally bright, so a dim sky was not something the renderer could draw, and every property here had to be phrased as contrast within one sky rather than as brightness across two. +/// +/// The floor is far above that 0.012 and far below what partial adaptation measures, so this fails if the adaptation exponent is ever quietly returned to 1. +#[test] +fn skies_of_different_brightness_do_not_all_render_alike() { + let means = live_domain_means(); + let lo = means + .iter() + .map(|&(_, _, m)| m) + .fold(f64::INFINITY, f64::min); + let hi = means + .iter() + .map(|&(_, _, m)| m) + .fold(f64::NEG_INFINITY, f64::max); + assert!( + hi - lo > 0.08, + "the live domain spans only {:.4} of lightness ({lo:.4} to {hi:.4}); at full adaptation it spanned 0.012 and every sky rendered equally bright", + hi - lo + ); +} + +/// The other end of the same knob. Partial adaptation buys range by letting skies drift from the anchor, and enough of it drives a hazy sunrise to black or a high sun to white, which is a worse failure than the flatness it fixes because it destroys the frame rather than levelling it. +#[test] +fn no_sky_in_the_live_domain_is_crushed_or_blown() { + for (sun_alt, turbidity, mean) in live_domain_means() { + assert!( + (0.20..=0.80).contains(&mean), + "sun {sun_alt} deg at turbidity {turbidity} renders at mean lightness {mean:.4}, outside the range a terminal can show as sky" + ); + } +} + +/// Nothing here asserted on colour, only on brightness and on where the sun is, and the chromaticity half of the model went untested as a result: every one of the eighteen mutants that survived a `cargo mutants` run over this module lived in `cx_coeffs` or `cy_coeffs`. You could corrupt the arithmetic that decides what colour the sky is and the whole suite stayed green. +/// +/// The far side of the sky at a moderate sun is the one place the answer is not in doubt. It is blue, which in Oklab means a negative b, and this is an absolute rather than a comparison for the reason `rules/determinism.md` gives: a relative claim cannot pin arithmetic, only its direction. +#[test] +fn a_clear_daytime_sky_is_blue() { + let prepared = sky(35.0, CENTER_AZ + 45.0, 2.0); + for y in [0.2, 0.4, 0.6] { + let lab = prepared.sample(0.05, y); + assert!( + lab.b < -0.02, + "the far side of a clear sky has Oklab b = {:.4} at y={y}, which is not blue", + lab.b + ); + } +} + +/// Turbidity is aerosol, and aerosol scatters near-neutrally where air molecules scatter blue, so more of it whitens the sky. It is the milky sky HW12 describes over a desert, and it is the one chromaticity claim strong enough to state as a direction across turbidities rather than within one sky. +#[test] +fn a_hazier_sky_is_a_less_blue_sky() { + let blueness = |turbidity: f64| sky(35.0, CENTER_AZ + 45.0, turbidity).sample(0.05, 0.4).b; + + let mut previous = f64::NEG_INFINITY; + for turbidity in [2.0, 3.0, 5.0, 7.0, 9.0] { + let b = blueness(turbidity); + assert!( + b > previous, + "turbidity {turbidity} leaves the sky at Oklab b = {b:.4}, no less blue than the {previous:.4} of the clearer sky before it" + ); + previous = b; + } +} diff --git a/tests/weather.rs b/tests/weather.rs index 588f14b..292c5ef 100644 --- a/tests/weather.rs +++ b/tests/weather.rs @@ -304,3 +304,47 @@ fn live_forecast_returns_168_hours() { ); assert_eq!(forecast.hourly.temperature_2m.len(), forecast.hourly.len()); } + +/// The handover from the palette to the analytic sky, which is the one place two different models paint the same sky and can disagree about how bright it is. +/// +/// `blend` ramps from 0 at the horizon to full at 8 degrees of solar elevation, and across that ramp the palette is the brighter of the two, so the frame dims slightly while the sun is still rising. That dip is 0.041 of Oklab lightness on this fixture and it is not new: it measured 0.031 before the exposure carried any absolute brightness at all. What matters is that it stays far below what dawn itself does, which moves the frame by up to 0.107 in a single quarter hour, because a step only reads as a seam when it beats the change around it. +/// +/// The ceiling is deliberately loose. Closing the gap properly means retuning the palettes to meet the model, and doing that against Preetham means calibrating on the elevation band Hosek-Wilkie exists to fix, so it is A1's to close. This is here to stop it widening unnoticed in the meantime. +#[test] +fn the_palette_to_analytic_handover_does_not_step() { + let forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + let geo = hamburg_geo(); + let opts = celsius::weather::ComposeOpts::default().with_analytic(true); + let sunrise = 1_775_865_600 + 3 * 3_600; // 2026-04-11T03:00Z, an hour before the sun clears the horizon + + let mut peak: f64 = 0.0; + let mut drawdown: f64 = 0.0; + let mut worst = (0.0, 0.0); + for step in 0..24 { + let t = sunrise + step * 900; + let sky = celsius::weather::compose_at(&forecast, &geo, t, t, opts).unwrap(); + let alt = celsius::astro::sun_position(geo.latitude, geo.longitude, t).altitude; + if alt < 0.0 { + continue; + } + let pixels = celsius::render(&sky, 104, 50); + let mean = pixels + .pixels + .iter() + .map(|p| celsius::colorspace::rgb_u8_to_oklab(p.r, p.g, p.b).l) + .sum::() + / pixels.pixels.len() as f64; + peak = peak.max(mean); + if peak - mean > drawdown { + drawdown = peak - mean; + worst = (alt, mean); + } + } + + assert!( + drawdown < 0.06, + "the sky dims by {drawdown:.4} of lightness across the crossfade, bottoming at {:.4} with the sun already {:.2} degrees up; the palette and the analytic model disagree by more than dawn itself changes", + worst.1, + worst.0 + ); +} From c961e98761ac784b458072da8b28c687c3813141 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 28 Aug 2026 22:40:58 +0200 Subject: [PATCH 3/5] test: state what the colour assertions cover, and what they do not The three colour tests were written after a mutation run showed every survivor in this module sitting in cx_coeffs or cy_coeffs, and the doc comment read as though they closed that. They do not. Four of those survivors were reapplied by hand with all three tests in place and every one still passed. Those are Perez distribution coefficients, and prepare() normalises by perez(1, theta_sun), so a mutated coefficient moves the numerator and the denominator together and sampling one direction cannot see it. The measurements, and the two survivors that do change the sky substantially, are written up as item 10 in QUALITY-GATES.md. The tests stay, because what the sky's colour is was worth pinning on its own and nothing pinned it before. The claim about why they exist is what was wrong. --- tests/analytic.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/analytic.rs b/tests/analytic.rs index 9d05526..59d39ea 100644 --- a/tests/analytic.rs +++ b/tests/analytic.rs @@ -231,9 +231,11 @@ fn no_sky_in_the_live_domain_is_crushed_or_blown() { } } -/// Nothing here asserted on colour, only on brightness and on where the sun is, and the chromaticity half of the model went untested as a result: every one of the eighteen mutants that survived a `cargo mutants` run over this module lived in `cx_coeffs` or `cy_coeffs`. You could corrupt the arithmetic that decides what colour the sky is and the whole suite stayed green. +/// Nothing here asserted on colour at all, only on brightness and on where the sun is, so the chromaticity half of the model went untested: every mutant that survived a `cargo mutants` run over this module lived in `cx_coeffs` or `cy_coeffs`. /// -/// The far side of the sky at a moderate sun is the one place the answer is not in doubt. It is blue, which in Oklab means a negative b, and this is an absolute rather than a comparison for the reason `rules/determinism.md` gives: a relative claim cannot pin arithmetic, only its direction. +/// The far side of the sky at a moderate sun is the one place the answer is not in doubt. It is blue, which in Oklab means a negative b, and this is stated as an absolute rather than a comparison for the reason `rules/determinism.md` gives: a relative claim cannot pin arithmetic, only its direction. +/// +/// It does not close those survivors, and neither do the two tests below; that is measured rather than assumed, and the finding is written up in `QUALITY-GATES.md`. These pin what the sky's colour *is*, which was worth pinning on its own. #[test] fn a_clear_daytime_sky_is_blue() { let prepared = sky(35.0, CENTER_AZ + 45.0, 2.0); @@ -262,3 +264,19 @@ fn a_hazier_sky_is_a_less_blue_sky() { previous = b; } } + +/// `cx_coeffs` and `cy_coeffs` are Perez *distribution* coefficients: they decide how chromaticity varies across the sky, not what it is anywhere in particular, and `prepare` divides by `perez(1, theta_sun)` so a mutation moves numerator and denominator together. Sampling one direction, at any number of turbidities, therefore cannot see them. What can is the shape of the field itself. +/// +/// A clear sky is bluest well above the horizon and washes out as it approaches it, because a horizontal line of sight looks through far more air and the aerosol scattering along it is near-neutral. That is the first thing anyone notices looking at a sky, and it is a statement about the gradient rather than about a point. +#[test] +fn the_sky_washes_out_toward_the_horizon() { + for turbidity in [2.0, 4.0] { + let prepared = sky(35.0, CENTER_AZ + 45.0, turbidity); + let high = prepared.sample(0.05, 0.2).b; + let horizon = prepared.sample(0.05, 1.0).b; + assert!( + horizon - high > 0.015, + "at turbidity {turbidity} the horizon sits at Oklab b = {horizon:.4} against {high:.4} well above it, so the sky does not wash out as it comes down" + ); + } +} From 523b615936cc39ceef6d32baf093ec0c6342b077 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 28 Aug 2026 22:42:39 +0200 Subject: [PATCH 4/5] docs: say in the module doc that exposure decides what reaches the terminal The module doc described the radiance model and stopped there, but the model's output is in kcd/m^2 across orders of magnitude and the exposure is what decides which of that range a terminal actually shows. That is the load-bearing half for anyone reading this on docs.rs, and the reasoning for it was only visible on a private constant. --- src/analytic_sky.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/analytic_sky.rs b/src/analytic_sky.rs index b833e6a..0063a92 100644 --- a/src/analytic_sky.rs +++ b/src/analytic_sky.rs @@ -1,4 +1,6 @@ //! Prototype: an analytic daytime sky (Preetham et al. 1999), the closed-form member of the Hosek-Wilkie family. Sky radiance is computed per pixel from the sun's position and an atmospheric turbidity via the Perez function, so the zenith-to-horizon falloff and the sun-side brightening fall out of one physical model instead of hand-tuned palettes. Daytime only: `build_sky` attaches this only when the sun is above the horizon, and `render` falls back to the gradient otherwise (Preetham's zenith formula is undefined once the solar zenith angle passes 90 degrees). +//! +//! Radiance comes out in kcd/m^2 and spans orders of magnitude between a low sun and a high one, so what reaches a terminal is decided by the exposure rather than by the model. It is a partial adaptation, anchored so that a clear noon renders as it always has while dimmer skies stay dimmer; a full adaptation, which is what this had, flattens every sky to one brightness and throws that range away. See `ADAPTATION`. use std::f64::consts::PI; From 8fb0f433564ab1cf65562f3dd6bcf2bee96993ab Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Sat, 29 Aug 2026 11:43:49 +0200 Subject: [PATCH 5/5] feat!: snow gets its own renderer, and its shape from the weather Snow was rain with the colour swapped. That is wrong in the way that matters most: a raindrop draws as a line because it falls fast enough to smear across an exposure, and a flake does not. What a flake looks like instead is set by the air it grew in, and the Nakaya morphology diagram (Libbrecht 2006) is that relationship: temperature picks the habit, supersaturation picks how branched it is. FlakeForm::select is the diagram as a lookup, so a -15 C sky snows dendrites and a -5 C sky snows needles. Getting there needs a conversion that is easy to skip. Open-Meteo reports relative humidity over water and the diagram is drawn against excess vapour density over ice, and near freezing the two curves nearly meet: at -1 C, ice saturation alone needs 99.05 percent relative humidity. Reading the forecast value straight onto the diagram's axis reports a blizzard as dry air and every flake comes out faceted. The Magnus pair and the conversion are in snow.rs with the arithmetic stated, and the test table walks both columns of every temperature band. Density comes from the forecast's snowfall in cm, not from precipitation in mm, which reports the same fall as liquid water and understates it about tenfold, and not from buffer area, which is what the old drop count used. Count is an absolute over the frame's fixed field of view and the drawn flake grows with the buffer, per rules/reference-size.md. The seed carries the hour, so scrubbing a forecast day shows different snow; precipitation seeds on the UTC day alone and shows one frozen layout for twenty-four hours. This is the first effect drawn in both stills and motion, and the reason is the opposite of lightning's. A still that catches a flash mid-strike is wrong, so lightning stays outside render(); a snowfall scene with no flakes in its PNG is not a scene, so snow is inside it, at t = 0. The TUI calls the same function on its own clock. The risk that creates is snow baked into the cached base *and* animated on top, at double density with half of it standing still, which is why App lifts snowfall off display at both points display is built and a test asserts it. BREAKING CHANGE: PrecipKind::Snow is removed; snow is celsius::snow. Also breaking: SkyState gains snowfall, and HourlyArrays gains relative_humidity_2m and snowfall. --- Cargo.toml | 3 +- benches/render.rs | 25 ++ justfile | 2 +- scenes/snowfall.toml | 43 ++++ src/lib.rs | 3 + src/precipitation.rs | 19 +- src/render.rs | 6 + src/scene.rs | 35 ++- src/snow.rs | 296 ++++++++++++++++++++++ src/tui/app.rs | 68 ++++- src/weather/forecast.rs | 8 + src/weather/state.rs | 91 ++++++- tests/open-meteo-forecast-hamburg.json | 26 +- tests/open-meteo-forecast-with-nulls.json | 78 +++++- tests/snow.rs | 229 +++++++++++++++++ tests/weather.rs | 71 ++++++ tools/celsius-lab/src/lib.rs | 1 + 17 files changed, 959 insertions(+), 45 deletions(-) create mode 100644 scenes/snowfall.toml create mode 100644 src/snow.rs create mode 100644 tests/snow.rs diff --git a/Cargo.toml b/Cargo.toml index 8f033e0..5f4c996 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,9 +14,10 @@ categories = ["command-line-utilities", "visualization"] # so excluding them would break the publish verification build. exclude = [ "demos/", - # dawn and cloudy_day are WIP: reachable by path in a checkout, deliberately not built in, so editing them stays a test: change that cuts no release. + # dawn, cloudy_day and snowfall are WIP: reachable by path in a checkout, deliberately not built in, so editing them stays a test: change that cuts no release. "scenes/dawn.toml", "scenes/cloudy_day.toml", + "scenes/snowfall.toml", "scripts/", # Bootstraps a binary from GitHub Releases, so it is dead weight to anyone installing from the tarball, and shipping it would make every installer edit cut a release. "install.sh", diff --git a/benches/render.rs b/benches/render.rs index 82d8d11..7175ae7 100644 --- a/benches/render.rs +++ b/benches/render.rs @@ -13,6 +13,7 @@ use celsius::colorspace::{Oklab, oklab_to_rgb, rgb_u8_to_oklab}; use celsius::lightning::{self, Lightning}; use celsius::noise::Noise; use celsius::precipitation; +use celsius::snow::{self, FlakeForm, Snowfall}; use celsius::tui::{App, Timeline, draw_frame, write_frame}; use celsius::weather::forecast::Forecast; use celsius::weather::location::GeoResult; @@ -254,6 +255,22 @@ fn bench_overlay(c: &mut Criterion) { ) }); + // A dendrite is the most expensive form (centre plus four arms) at a heavy-snow count. Unlike the rain pair below, the count is an absolute, so the two sizes measure the per-flake draw against the buffer rather than against a density that grows with it. + let heavy = Snowfall { + form: FlakeForm::Dendrite, + count: 320, + seed: 2749, + drift: 0.02, + opacity: 0.75, + }; + g.bench_function("snow_104x50", |b| { + b.iter_batched_ref( + || base.clone(), + |px| snow::overlay(px, &heavy, 3.0), + BatchSize::SmallInput, + ) + }); + let stormy = load_scene(scene_path("stormy_afternoon_advancing")).unwrap(); let precip = stormy .precipitation @@ -270,6 +287,14 @@ fn bench_overlay(c: &mut Criterion) { }); let wide = render(&clear, 320, 100); + g.bench_function("snow_320x100", |b| { + b.iter_batched_ref( + || wide.clone(), + |px| snow::overlay(px, &heavy, 3.0), + BatchSize::SmallInput, + ) + }); + g.bench_function("precip_320x100", |b| { b.iter_batched_ref( || wide.clone(), diff --git a/justfile b/justfile index 81f89d7..af1bef0 100644 --- a/justfile +++ b/justfile @@ -6,7 +6,7 @@ scenes := "golden_hour_cumulus blue_hour_calm high_noon_clear moonlit_clear_wint # Vendored in scenes/ but intentionally NOT locked yet: not pretty enough to bless. # Render with `just render-wip`, and promote a name into `scenes` once it is good. -wip_scenes := "dawn cloudy_day" +wip_scenes := "dawn cloudy_day snowfall" default: check diff --git a/scenes/snowfall.toml b/scenes/snowfall.toml new file mode 100644 index 0000000..2191b22 --- /dev/null +++ b/scenes/snowfall.toml @@ -0,0 +1,43 @@ +# snowfall +# Hamburg, 15 January at 09:48 local; low winter daylight beneath a flat overcast, air at -1 C in near-saturated cloud. +# Visibility about 1 km, which is WMO 73 moderate-to-heavy continuous snow: the haze here is the falling snow itself, not fog, so it is a soft wash rather than the near-total extinction fog.toml carries. +# Heavy snow under a flat overcast deck. The sky during snowfall is a dull medium grey, not bright white; the brightness people picture is the snow on the ground, not the sky. A medium tone is also what lets the near-white flakes show at all (snow is painted around 242,244,248), and it dodges the engine's cloud palette, which only spans warm cream to cool purple: any deck near the hidden sun picks up an off-genre warm cast. So, no cloud layers. A flat cold gradient plus dense falling snow reads as heavy snowfall far better than a textured and warm-tinged deck would. +# The gradient is darker than it looks like it should be, and the contact sheet is why. Flakes cover about a quarter of the frame and every one of them is near white, so they carry a lot of the tone: the first version of this scene measured brighter than cloudy_day and high_noon_clear both, which made a snowstorm the most luminous sky in the library. It sits between them now. Judge this one beside its siblings rather than alone, because on its own a too-bright version still looks like snow. +# The flake form is not decoration and is not free to choose: at -1 C in dense cloud the Nakaya morphology diagram gives sectored plates, so that is what this scene pins. Its own chrome is the check. A scene claiming -1 C and snowing dendrites would be claiming -15 C weather, and dendrites are the flake everyone pictures, which is exactly why it is the wrong one to reach for here. +# If this breaks, it looks like: flakes clumped in the left third of a wide terminal (frame fractions lost, see rules/reference-size.md), or a sky that reads white rather than grey, at which point the flakes vanish into it and the scene is just fog. + +[gradient] +stops = [ + { t = 0.00, rgb = [104, 111, 122] }, # cool dull grey zenith + { t = 0.35, rgb = [119, 126, 136] }, + { t = 0.65, rgb = [136, 142, 150] }, + { t = 0.88, rgb = [148, 153, 159] }, + { t = 1.00, rgb = [155, 159, 164] }, # lighter toward the snowy murk, still grey +] + +[sun] +x_frac = 0.50 +y_frac = 1.20 +radius = 2.0 +visible = false + +[haze] +# The murk of falling snow, and the one parameter here that was doing nothing at all. It used to pull toward [180, 184, 189], which is *darker* than the gradient's own horizon stop, so raising its strength from 0.45 to 0.85 moved no pixel by more than 5 of 255 and what it did move it made dimmer. The low visibility was written in the chrome and encoded nowhere. Distance in snow washes pale, so the target has to sit above the horizon stop, not below it. +# onset_t, exponent and strength are the documented mapping from docs/literature/README.md at 1 km visibility, where the formula clamps to 0.85. The colour is the deliberate departure: [188, 180, 168] there is warm aerosol haze in daylight, and snow murk is cool and bright. +rgb = [178, 182, 188] +onset_t = 0.10 +strength = 0.85 +exponent = 1.6 + +[snowfall] +form = "sectored_plate" +count = 240 # about 1 cm/h through flake_count, which is heavy but still legible +seed = 2749 +drift = -0.02 # NE wind at 11 km/h, of which only the across-view component moves anything +opacity = 0.75 + +[chrome] +header_left = "celsius" +header_right = "hamburg thu 15 jan 09:48" +footer = "-1 C snow wind ne 11 visibility 1 km" +keys = "m map space pause <- -> scrub q quit" diff --git a/src/lib.rs b/src/lib.rs index 793aea4..e2b76b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,8 @@ //! Two rules explain most of the design. **All compositing happens in Oklab**, converting to sRGB only at the final pixel write, because linear interpolation in Oklab is what keeps a dawn gradient from banding. And **the PRNG is bit-compatible with CPython's `random.Random`**, so a given seed produces identical noise, stars and precipitation on every platform; the golden-image tests depend on that exactness. //! //! Time-varying effects deliberately live *outside* [`render()`]. Lightning, meteors and the easter egg composite onto a rendered buffer from an app clock, so a still image never catches a flash mid-strike and the expensive pixel pipeline stays cacheable across frames. +//! +//! Snow is the exception, and the exception has a reason. A still that catches lightning mid-strike is wrong, but a snowfall scene with no flakes in its PNG is not a scene at all, so [`snow::overlay`] is called by `render()` at `t = 0` and by the TUI on its own clock. One function serves both, which is what makes the still an instant the animation actually passes through. pub mod analytic_sky; pub mod astro; @@ -28,6 +30,7 @@ pub mod precipitation; pub mod raster; pub mod render; pub mod scene; +pub mod snow; pub mod stars; pub mod terminal; pub mod tui; diff --git a/src/precipitation.rs b/src/precipitation.rs index 6daf487..f999161 100644 --- a/src/precipitation.rs +++ b/src/precipitation.rs @@ -1,12 +1,12 @@ -//! Rain and snow, drawn as angled streaks over a finished sky. +//! Rain, drawn as angled streaks over a finished sky. //! -//! A streak is not a drop, it is a drop's motion blur over an exposure, which is why length is a parameter rather than a physical fall distance. Rain draws long, cool, near-vertical streaks that fade with height; snow draws short bright flakes. Positions come from the seeded MT19937, so a given scene always produces the same fall. +//! A streak is not a drop, it is a drop's motion blur over an exposure, which is why length is a parameter rather than a physical fall distance. That is also why snow is not here: a flake is slow enough not to smear, and what it looks like instead depends on the air it grew in, which is `snow`. Positions come from the seeded MT19937, so a given scene always produces the same fall. //! //! This runs as a full-buffer pass after per-pixel compositing, because one streak spans many pixels and the loop is per streak, not per pixel. use crate::colorspace::{Oklab, PixelBuffer, lerp_oklab, oklab_to_rgb, rgb_u8_to_oklab}; use crate::noise::Mt19937; -use crate::scene::{PrecipKind, Precipitation}; +use crate::scene::Precipitation; fn rain_top() -> Oklab { rgb_u8_to_oklab(208, 218, 230) @@ -14,10 +14,6 @@ fn rain_top() -> Oklab { fn rain_bot() -> Oklab { rgb_u8_to_oklab(150, 160, 172) } -fn snow() -> Oklab { - rgb_u8_to_oklab(242, 244, 248) -} - pub fn overlay(pixels: &mut PixelBuffer, precip: &Precipitation) { let area = pixels.width * pixels.height; overlay_scaled(pixels, precip, area); @@ -31,10 +27,9 @@ pub fn overlay_scaled(pixels: &mut PixelBuffer, precip: &Precipitation, logical_ let height = pixels.height; let mut rng = Mt19937::init_by_array(&[precip.seed as u32]); let n = ((logical_area as f64 * precip.intensity * 0.025) as usize).max(1); - let is_rain = precip.kind == PrecipKind::Rain; let angle_rad = precip.angle_deg.to_radians(); let dx = angle_rad.tan(); - let (top, bot, flake) = (rain_top(), rain_bot(), snow()); + let (top, bot) = (rain_top(), rain_bot()); for _ in 0..n { let px = rng.randint(0, width as i32 - 1); @@ -51,11 +46,7 @@ pub fn overlay_scaled(pixels: &mut PixelBuffer, precip: &Precipitation, logical_ let vt = sy as f64 / height as f64; let depth_fade = 0.55 + 0.45 * vt; let alpha = precip.opacity * depth_fade; - let color_lab = if is_rain { - lerp_oklab(top, bot, vt) - } else { - flake - }; + let color_lab = lerp_oklab(top, bot, vt); let orig = pixels.get(sx as usize, sy as usize); let orig_lab = crate::colorspace::rgb_u8_to_oklab(orig.r, orig.g, orig.b); let inv = 1.0 - alpha; diff --git a/src/render.rs b/src/render.rs index 225f21f..8a28f4e 100644 --- a/src/render.rs +++ b/src/render.rs @@ -5,6 +5,8 @@ //! Everything that can be hoisted out of the per-pixel loop already has been: noise grids are cached per seed, the gradient is sampled once per row, and each cloud layer's altitude mask is a row term rather than a pixel term. That is what keeps a 104x50 frame in the hundreds of microseconds. //! //! Note what is *absent*: no time parameter. Animation is expressed by mutating the `SkyState` between calls (cloud drift) or by compositing overlays onto the result (lightning, meteors), never by rendering a different frame for a different instant. +//! +//! Snow is the one exception and it is drawn here at `t = 0`. The rule those others follow is that a still must not catch a moment, and a flash caught mid-strike is exactly that; a snowfall scene with an empty sky is not the same kind of error, it is a missing scene. The TUI calls the same `snow::overlay` with a real clock, so the still is a frame the animation passes through rather than an arrangement of its own. use std::cell::RefCell; use std::collections::HashMap; @@ -373,6 +375,10 @@ pub fn render_supersampled(state: &SkyState, width: u32, height: u32, factor: u3 precipitation::overlay_scaled(&mut pixels, p, logical_area); } + if let Some(s) = state.snowfall.as_ref() { + crate::snow::overlay(&mut pixels, s, 0.0); + } + pixels } diff --git a/src/scene.rs b/src/scene.rs index 70b42d6..efd13f2 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -16,6 +16,7 @@ use crate::analytic_sky::AnalyticSky; use crate::gradient::Gradient; use crate::lightning::Lightning; use crate::meteors::Meteors; +use crate::snow::Snowfall; #[derive(Debug, Error)] #[non_exhaustive] @@ -36,6 +37,13 @@ pub enum SceneError { NoStem { path: PathBuf }, #[error("scene {path} declares an empty gradient (needs at least one stop)")] EmptyGradient { path: PathBuf }, + #[error("scene {path} sets {field} to {value}, outside the documented range {range}")] + OutOfRange { + path: PathBuf, + field: &'static str, + value: f64, + range: &'static str, + }, } #[derive(Clone, Debug, Deserialize)] @@ -177,12 +185,11 @@ pub struct Chrome { pub keys_tiers: Vec, } -/// Two kinds only, enforced at parse: a typo like `kind = "Rain"` used to slip through the old stringly field and silently render as snow. +/// One kind, enforced at parse. It was two until snow got its own renderer: a flake is not a short raindrop, its shape comes from the air it grew in, and `snow::Snowfall` is where that lives now. Keeping the enum rather than deleting it is deliberate, since hail and sleet are the same shape of problem as rain and will want it back. #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum PrecipKind { Rain, - Snow, } #[derive(Clone, Debug, Deserialize)] @@ -216,6 +223,8 @@ pub struct SkyState { pub stars: Option, pub moon: Option, pub precipitation: Option, + /// Falling snow. Unlike lightning and meteors this one *is* drawn by `render()`, at `t = 0`; see `snow` for why. + pub snowfall: Option, pub lightning: Option, pub meteors: Option, pub horizon_glow: Option, @@ -237,6 +246,7 @@ struct SceneToml { stars: Option, moon: Option, precipitation: Option, + snowfall: Option, } #[derive(Deserialize)] @@ -337,6 +347,26 @@ fn parse_scene(path: &Path, text: &str) -> Result { }); } + // The draft this validation exists for set `intensity = 2.8` against a documented 0..1 and rendered anyway, because the value was multiplied straight into a count and nothing ever compared it to its own documentation. + if let Some(snow) = &raw.snowfall { + if !(0.0..=1.0).contains(&snow.opacity) { + return Err(SceneError::OutOfRange { + path: path.to_path_buf(), + field: "snowfall.opacity", + value: snow.opacity, + range: "0.0..=1.0", + }); + } + if snow.count > 2000 { + return Err(SceneError::OutOfRange { + path: path.to_path_buf(), + field: "snowfall.count", + value: f64::from(snow.count), + range: "0..=2000", + }); + } + } + let stops: Vec<(f64, [u8; 3])> = raw .gradient .stops @@ -363,6 +393,7 @@ fn parse_scene(path: &Path, text: &str) -> Result { stars: raw.stars, moon: raw.moon, precipitation: raw.precipitation, + snowfall: raw.snowfall, lightning: None, meteors: None, horizon_glow: None, diff --git a/src/snow.rs b/src/snow.rs new file mode 100644 index 0000000..d511b51 --- /dev/null +++ b/src/snow.rs @@ -0,0 +1,296 @@ +//! Falling snow: flake form from the weather, motion from the clock. +//! +//! Snow used to be rain with the colour swapped, which is wrong in the way that matters most: a raindrop is a blurred line because it falls fast enough to smear across an exposure, and a snowflake is not, because it does not. What a flake looks like instead is set by the air it grew in, and the relationship is the Nakaya morphology diagram (Libbrecht 2006): temperature picks the habit and supersaturation picks how branched it is. [`FlakeForm::select`] is that diagram as a lookup, so a -15 C sky snows dendrites and a -5 C sky snows needles. +//! +//! This is the one effect drawn both in stills and in motion, and the reason is worth stating because it is the opposite of lightning's. A still that catches a flash mid-strike is wrong, so lightning lives outside `render()`; a snowfall scene with no flakes in its PNG is not a scene, so snow lives inside it, at `t = 0`. The TUI takes the same function with a real clock. One function, two callers, so the frozen instant a PNG shows is a frame the animation actually passes through. +//! +//! Flakes are held as frame fractions rather than buffer pixels, per `rules/reference-size.md`: `count` is an absolute over a fixed field of view, so a wider terminal shows the same snowfall in bigger flakes rather than more of them. It is the drawn size that follows the buffer, which is the correction that rule spells out for `Stars.count` and that the old area-scaled drop count had backwards. + +use std::f64::consts::TAU; + +use crate::colorspace::{Oklab, PixelBuffer, oklab_to_rgb, rgb_u8_to_oklab}; +use crate::noise::Mt19937; + +/// Gas constant for water vapour, J/(kg K). +const R_V: f64 = 461.5; + +/// Where the diagram's humidity axis is cut in two. The morphology diagram's y axis runs from ice saturation up to the water-saturation line, which Libbrecht gives as the humidity inside dense winter clouds, so half way up it is the honest split between "low" and "high" for a two-column table. +const BRANCHING_FRACTION: f64 = 0.5; + +/// Snowfall rate that anchors `flake_count`, in cm/h. Moderate snow. +const REFERENCE_RATE_CM_H: f64 = 0.5; + +/// Flakes in shot at the reference rate, over the frame's fixed field of view. +const REFERENCE_COUNT: f64 = 140.0; + +fn flake_color() -> Oklab { + rgb_u8_to_oklab(242, 244, 248) +} + +/// The crystal habits the morphology diagram separates, plus the one it does not: `Aggregate` is several flakes stuck together on the way down, which is what falls when the air is near or above freezing and is why wet snow arrives in clumps rather than crystals. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FlakeForm { + Plate, + SectoredPlate, + Column, + Needle, + Dendrite, + Aggregate, +} + +/// Saturation vapour pressure over water, hPa, from Alduchov and Eskridge (1996). +#[must_use] +pub fn vapour_pressure_water(t_c: f64) -> f64 { + 6.1094 * (17.625 * t_c / (t_c + 243.04)).exp() +} + +/// Saturation vapour pressure over ice, hPa. Below freezing it sits under the water curve, and that gap is the whole reason a crystal in a cloud of supercooled droplets grows at all. +#[must_use] +pub fn vapour_pressure_ice(t_c: f64) -> f64 { + 6.1121 * (22.587 * t_c / (t_c + 273.86)).exp() +} + +/// Excess water vapour over ice saturation, g/m^3, which is the morphology diagram's y axis. +/// +/// Open-Meteo reports relative humidity over *water*, and the diagram is drawn against excess density over *ice*, so the conversion is not optional: at -15 C, air at 90 percent relative humidity is already well supersaturated with respect to ice. +#[must_use] +pub fn supersaturation(t_c: f64, relative_humidity: f64) -> f64 { + let vapour = relative_humidity / 100.0 * vapour_pressure_water(t_c); + (vapour - vapour_pressure_ice(t_c)) * 100.0 / (R_V * (t_c + 273.15)) * 1000.0 +} + +impl FlakeForm { + /// The morphology diagram, read as a table. Temperature is the primary axis and supersaturation the secondary one, exactly as Libbrecht draws it: "complex, branched crystals appear when the humidity is high, while low humidity levels yield simpler, faceted crystals". + /// + /// The bands come from the diagram itself: plates just below freezing, columns and needles a few degrees colder, the large branched crystals at the -15 C peak, and smaller plates and columns colder still. + #[must_use] + pub fn select(temperature_c: f64, relative_humidity: f64) -> Self { + if temperature_c > 0.5 { + return Self::Aggregate; + } + // Against the water-saturation line rather than against a fixed density, because the amount of vapour the air can hold collapses as it cools: one absolute threshold would call every cold sky dry. + let ceiling = supersaturation(temperature_c, 100.0); + let branched = ceiling > 0.0 + && supersaturation(temperature_c, relative_humidity) > ceiling * BRANCHING_FRACTION; + + match temperature_c { + t if t > -3.5 => { + if branched { + Self::SectoredPlate + } else { + Self::Plate + } + } + t if t > -8.0 => { + if branched { + Self::Needle + } else { + Self::Column + } + } + t if t > -12.0 => { + if branched { + Self::Plate + } else { + Self::Column + } + } + t if t > -18.0 => { + if branched { + Self::Dendrite + } else { + Self::Plate + } + } + t if t > -25.0 => { + if branched { + Self::SectoredPlate + } else { + Self::Plate + } + } + _ => { + if branched { + Self::Plate + } else { + Self::Column + } + } + } + } + + /// Fall speed in frame heights per second. + /// + /// The ordering is the measured terminal velocities: a dendrite falls at 0.3 to 0.5 m/s where a wet aggregate manages 1 to 2, because drag scales with area and mass does not. The range between them is deliberately compressed rather than reproduced, since a frame is about ten metres of sky and a true 4x spread puts the fastest flake through it faster than a 30fps terminal can draw it moving. + fn fall_speed(self) -> f64 { + match self { + Self::Dendrite => 1.0 / 7.0, + Self::SectoredPlate => 1.0 / 6.0, + Self::Plate => 1.0 / 5.5, + Self::Column => 1.0 / 4.2, + Self::Needle => 1.0 / 3.8, + Self::Aggregate => 1.0 / 3.0, + } + } + + /// Side-to-side flutter as (amplitude in frame widths, frequency in Hz). + /// + /// A flake flutters because it is a light thing with a large face, so it stalls and slips rather than falling straight. That is a drag-to-mass ordering, not a simulation: a dendrite is nearly all area and wanders visibly, a needle is a splinter and drops almost straight, and an aggregate is heavy enough to swing slowly rather than quickly. + fn flutter(self) -> (f64, f64) { + match self { + Self::Dendrite => (0.035, 0.35), + Self::SectoredPlate => (0.028, 0.40), + Self::Plate => (0.020, 0.45), + Self::Aggregate => (0.012, 0.30), + Self::Column => (0.008, 0.60), + Self::Needle => (0.003, 0.70), + } + } +} + +/// Snow falling over a finished sky. +#[derive(Clone, Debug, serde::Deserialize)] +pub struct Snowfall { + pub form: FlakeForm, + /// Flakes in shot. An absolute over the frame's fixed field of view, not a density over its pixels. + pub count: u32, + pub seed: u64, + /// Sideways travel in frame widths per second, signed, from the crosswind. + #[serde(default)] + pub drift: f64, + #[serde(default = "default_snow_opacity")] + pub opacity: f64, +} + +fn default_snow_opacity() -> f64 { + 0.75 +} + +/// How much a flake's rate of fall varies between the nearest and furthest in shot. Parallax stands in for depth: a flake close to the viewer crosses faster and reads brighter, which is what stops a field of identical flakes looking like a moving wallpaper. +const DEPTH_RANGE: (f64, f64) = (0.65, 1.15); + +/// Composite `snow` onto `pixels` at `t_seconds` since the fall started. +/// +/// `t = 0` is what `render()` passes, so a still is the instant the animation begins rather than a separate arrangement. +pub fn overlay(pixels: &mut PixelBuffer, snow: &Snowfall, t_seconds: f64) { + if snow.count == 0 || snow.opacity <= 0.0 { + return; + } + let (w, h) = (pixels.width as f64, pixels.height as f64); + // One pixel at the 104-wide reference, growing with the buffer so a flake keeps roughly the angular size it was drawn at instead of shrinking into the grid. + let scale = (w / 104.0).max(1.0); + let radius = scale.round().max(1.0) as i32; + + let mut rng = Mt19937::init_by_array(&[snow.seed as u32]); + let (amplitude, frequency) = snow.form.flutter(); + let base_fall = snow.form.fall_speed(); + let color = flake_color(); + + for _ in 0..snow.count { + let x0 = rng.next_f64(); + let y0 = rng.next_f64(); + let phase = rng.next_f64() * TAU; + let depth = DEPTH_RANGE.0 + (DEPTH_RANGE.1 - DEPTH_RANGE.0) * rng.next_f64(); + + let sway = amplitude * (TAU * frequency * t_seconds + phase).sin(); + let fx = (x0 + snow.drift * t_seconds + sway).rem_euclid(1.0); + let fy = (y0 + base_fall * depth * t_seconds).rem_euclid(1.0); + + let alpha = (snow.opacity * depth).clamp(0.0, 1.0); + draw_flake( + pixels, + snow.form, + (fx * w) as i32, + (fy * h) as i32, + radius, + snow.drift, + alpha, + color, + ); + } +} + +/// One flake, as much of its shape as a terminal cell can carry. +/// +/// A flake at this size is a few pixels, so the forms are told apart by silhouette rather than by structure: a column is longer than it is wide, a needle leans into the wind, and the branched habits get a halo their faceted counterparts do not. That is the part of the diagram a viewer can actually see. +#[allow(clippy::too_many_arguments)] +fn draw_flake( + pixels: &mut PixelBuffer, + form: FlakeForm, + x: i32, + y: i32, + radius: i32, + drift: f64, + alpha: f64, + color: Oklab, +) { + body(pixels, x, y, radius, alpha, color); + match form { + FlakeForm::Plate => {} + FlakeForm::Column => { + body(pixels, x, y + radius, radius, alpha, color); + } + FlakeForm::Needle => { + // Leaning with the drift rather than straight down: a needle is the one habit whose long axis is visibly set by the wind carrying it. + let lean = if drift < 0.0 { -radius } else { radius }; + body(pixels, x + lean, y + radius, radius, alpha * 0.8, color); + body(pixels, x - lean, y - radius, radius, alpha * 0.8, color); + } + FlakeForm::SectoredPlate | FlakeForm::Dendrite => { + let arm = if form == FlakeForm::Dendrite { + 0.55 + } else { + 0.4 + }; + body(pixels, x + radius, y, radius, alpha * arm, color); + body(pixels, x - radius, y, radius, alpha * arm, color); + body(pixels, x, y + radius, radius, alpha * arm, color); + body(pixels, x, y - radius, radius, alpha * arm, color); + } + FlakeForm::Aggregate => { + body(pixels, x + radius, y, radius, alpha * 0.7, color); + body(pixels, x, y + radius, radius, alpha * 0.7, color); + body(pixels, x + radius, y + radius, radius, alpha * 0.5, color); + } + } +} + +/// One mark of the flake, at whatever size this buffer draws a flake. +/// +/// A flake subtends a fixed angle, so its size on screen has to follow the buffer or a wide terminal renders it as a speck and the snow disappears into the grid. This is the same correction `rules/reference-size.md` prescribes for a star's halo, and it is why `count` must *not* follow the buffer: bigger flakes, not more of them. +fn body(pixels: &mut PixelBuffer, x: i32, y: i32, radius: i32, alpha: f64, color: Oklab) { + let half = radius / 2; + for dy in -half..=half { + for dx in -half..=half { + blend(pixels, x + dx, y + dy, alpha, color); + } + } +} + +fn blend(pixels: &mut PixelBuffer, x: i32, y: i32, alpha: f64, color: Oklab) { + if alpha <= 0.0 + || !(0..pixels.width as i32).contains(&x) + || !(0..pixels.height as i32).contains(&y) + { + return; + } + let idx = (y as usize) * pixels.width + (x as usize); + let base = pixels.pixels[idx]; + let lab = rgb_u8_to_oklab(base.r, base.g, base.b); + let inv = 1.0 - alpha; + pixels.pixels[idx] = oklab_to_rgb(Oklab::new( + lab.l * inv + color.l * alpha, + lab.a * inv + color.a * alpha, + lab.b * inv + color.b * alpha, + )); +} + +/// Flakes in shot for a snowfall rate in cm/h. +/// +/// The exponent compresses the tail so a blizzard reads as dense rather than as a white screen: at four times the reference rate the count not quite triples. The floor keeps light snow visible at all, and the ceiling is where more flakes stop adding anything a 104x50 frame can resolve. +#[must_use] +pub fn flake_count(snowfall_cm_h: f64) -> u32 { + let ratio = (snowfall_cm_h.max(0.0) / REFERENCE_RATE_CM_H).powf(0.75); + (REFERENCE_COUNT * ratio).round().clamp(24.0, 420.0) as u32 +} diff --git a/src/tui/app.rs b/src/tui/app.rs index b19a08c..058b840 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -29,6 +29,7 @@ use crate::pigs; use crate::raster::{self, RasterOpts}; use crate::render::render_supersampled; use crate::scene::{Chrome, SkyState}; +use crate::snow::{self, Snowfall}; use crate::tui::widget::SkyWidget; use crate::weather::location::{GeoResult, geocode, rank}; @@ -142,6 +143,8 @@ pub struct App<'a> { /// Cloud motion accumulated since the last repaint, as a fraction of the frame. Compared against `DRIFT_REPAINT_PX` once scaled by the rendered width. drift_debt: f64, overlay: Overlay, + /// Lifted off `display` so the cached base render has no snow baked into it. Left in place it would be drawn once by `render()` and again by the per-frame overlay, at double density, with the baked half standing still. + snow: Option, overlay_elapsed: Duration, egg_frame: u64, egg_prev: bool, @@ -165,11 +168,13 @@ impl std::fmt::Debug for App<'_> { impl<'a> App<'a> { pub fn new(timeline: &'a Timeline) -> Self { let index = timeline.home; - let display = timeline.states[index].clone(); + let mut display = timeline.states[index].clone(); + let snow = display.snowfall.take(); Self { timeline, index, display, + snow, drift_paused: false, drift_debt: 0.0, overlay: Overlay::None, @@ -242,6 +247,7 @@ impl<'a> App<'a> { changed || self.display.lightning.is_some() || self.display.meteors.is_some() + || self.snow.is_some() || egg || egg_changed } @@ -273,6 +279,7 @@ impl<'a> App<'a> { if new != self.index { self.index = new; self.display = self.timeline.states[new].clone(); + self.snow = self.display.snowfall.take(); self.sky_dirty = true; } } @@ -785,12 +792,16 @@ fn draw_sky(buf: &mut Buffer, area: Rect, app: &mut App) { }) } }; - // Lightning, meteors, and the pigs egg composite onto a copy so the cached base stays reusable; their timing is per-frame state, not part of the sky render. `overlay_elapsed` is the shared real-time clock every tick overlay reads. - if app.display.lightning.is_some() || app.display.meteors.is_some() || egg { + // Lightning, snow, meteors, and the pigs egg composite onto a copy so the cached base stays reusable; their timing is per-frame state, not part of the sky render. `overlay_elapsed` is the shared real-time clock every tick overlay reads. + if app.display.lightning.is_some() || app.snow.is_some() || app.display.meteors.is_some() || egg + { let mut pixels = cache.pixels.clone(); if let Some(lt) = &app.display.lightning { lightning::overlay(&mut pixels, lt, app.overlay_elapsed.as_secs_f64()); } + if let Some(sn) = &app.snow { + snow::overlay(&mut pixels, sn, app.overlay_elapsed.as_secs_f64()); + } if let Some(m) = &app.display.meteors { meteors::overlay(&mut pixels, m, app.overlay_elapsed.as_secs_f64()); } @@ -1261,6 +1272,7 @@ mod tests { stars: None, moon: None, precipitation: None, + snowfall: None, lightning: None, meteors: None, horizon_glow: None, @@ -1279,6 +1291,56 @@ mod tests { ) } + fn snowy_timeline() -> Timeline { + let states = (0..50) + .map(|i| { + let mut st = sky(&format!("s{i}")); + st.snowfall = Some(crate::snow::Snowfall { + form: crate::snow::FlakeForm::Dendrite, + count: 80, + seed: 2749, + drift: 0.0, + opacity: 0.75, + }); + st + }) + .collect(); + Timeline::new(states, 10, None, 0) + } + + /// Snow is the one overlay `render()` also draws, so the app has to take it off the sky before caching the base or the same fall is composited twice: once baked into the cache and standing still, once animating on top, at double density. Nothing about the frame would look obviously broken, which is why this is a test and not an eyeball. + #[test] + fn the_app_takes_snow_off_the_cached_sky() { + let timeline = snowy_timeline(); + let mut app = App::new(&timeline); + assert!( + app.display.snowfall.is_none(), + "the cached sky must not carry snow for render() to bake in" + ); + assert!(app.snow.is_some(), "and the app must have taken it"); + + // Scrubbing replaces `display` wholesale, which is the second place the lift has to happen. + app.handle_key(press(KeyCode::Right)); + assert!( + app.display.snowfall.is_none(), + "scrubbing must lift snow off the newly cloned sky too" + ); + assert!(app.snow.is_some(), "and keep it on the app"); + } + + /// A snowy sky is never still, so the drift gate must not stop repainting it the way it correctly stops repainting a clear one. + #[test] + fn a_snowy_sky_keeps_repainting() { + let timeline = snowy_timeline(); + let mut app = App::new(&timeline); + app.display.wind_speed_kmh = 0.0; + app.display.clouds.clear(); + assert!( + app.tick(Duration::from_millis(33)), + "falling snow is a visible change on every tick" + ); + } + fn press(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) } diff --git a/src/weather/forecast.rs b/src/weather/forecast.rs index 8933d6f..bb5ecd4 100644 --- a/src/weather/forecast.rs +++ b/src/weather/forecast.rs @@ -12,11 +12,13 @@ const ENDPOINT: &str = "https://api.open-meteo.com/v1/forecast"; const HOURLY_FIELDS: &str = concat!( "temperature_2m,", + "relative_humidity_2m,", "cloud_cover,", "cloud_cover_low,", "cloud_cover_mid,", "cloud_cover_high,", "precipitation,", + "snowfall,", "wind_speed_10m,", "wind_direction_10m,", "visibility,", @@ -43,12 +45,18 @@ pub struct Forecast { pub struct HourlyArrays { pub time: Vec, pub temperature_2m: Vec>, + /// Over water, which is what Open-Meteo reports and not what the snow morphology diagram is drawn against; `snow::supersaturation` is the conversion. + #[serde(default)] + pub relative_humidity_2m: Vec>, #[serde(default)] pub cloud_cover: Vec>, pub cloud_cover_low: Vec>, pub cloud_cover_mid: Vec>, pub cloud_cover_high: Vec>, pub precipitation: Vec>, + /// Snow depth accumulating this hour, in cm. Separate from `precipitation`, which reports the same fall as liquid water equivalent and so understates it by roughly ten to one. + #[serde(default)] + pub snowfall: Vec>, pub wind_speed_10m: Vec>, pub wind_direction_10m: Vec>, pub visibility: Vec>, diff --git a/src/weather/state.rs b/src/weather/state.rs index 237623f..9040ed4 100644 --- a/src/weather/state.rs +++ b/src/weather/state.rs @@ -17,6 +17,7 @@ use crate::scene::{ Chrome, CloudKind, CloudLayer, Haze, HorizonGlow, Moon, PrecipKind, Precipitation, SkyState, Stars, Sun, }; +use crate::snow::{self, FlakeForm, Snowfall}; use super::WeatherError; use super::bortle; @@ -37,11 +38,13 @@ const KEYS_TIERS: [&str; 4] = [ // The weather fields the sky is built from, already resolved (and possibly interpolated between two hours) so the builder never indexes the forecast. struct HourSample { temperature_c: Option, + relative_humidity: Option, reported_cover: Option, cover_low: f64, cover_mid: f64, cover_high: f64, precip_mm: Option, + snowfall_cm: Option, wind_speed: Option, wind_dir: Option, visibility_m: Option, @@ -53,11 +56,13 @@ impl HourSample { let hr = &forecast.hourly; HourSample { temperature_c: hr.temperature_2m[h], + relative_humidity: hr.relative_humidity_2m.get(h).copied().flatten(), reported_cover: hr.cloud_cover.get(h).copied().flatten(), cover_low: hr.cloud_cover_low[h].unwrap_or(0.0) / 100.0, cover_mid: hr.cloud_cover_mid[h].unwrap_or(0.0) / 100.0, cover_high: hr.cloud_cover_high[h].unwrap_or(0.0) / 100.0, precip_mm: hr.precipitation[h], + snowfall_cm: hr.snowfall.get(h).copied().flatten(), wind_speed: hr.wind_speed_10m[h], wind_dir: hr.wind_direction_10m[h], visibility_m: hr.visibility[h], @@ -70,11 +75,13 @@ impl HourSample { let b = Self::at(forecast, h1); HourSample { temperature_c: lerp_opt(a.temperature_c, b.temperature_c, frac), + relative_humidity: lerp_opt(a.relative_humidity, b.relative_humidity, frac), reported_cover: lerp_opt(a.reported_cover, b.reported_cover, frac), cover_low: lerp(a.cover_low, b.cover_low, frac), cover_mid: lerp(a.cover_mid, b.cover_mid, frac), cover_high: lerp(a.cover_high, b.cover_high, frac), precip_mm: lerp_opt(a.precip_mm, b.precip_mm, frac), + snowfall_cm: lerp_opt(a.snowfall_cm, b.snowfall_cm, frac), wind_speed: lerp_opt(a.wind_speed, b.wind_speed, frac), wind_dir: lerp_angle_opt(a.wind_dir, b.wind_dir, frac), visibility_m: lerp_opt(a.visibility_m, b.visibility_m, frac), @@ -276,6 +283,19 @@ fn build_sky( day_ordinal, center_az, ); + let snowfall = build_snowfall( + sample.weather_code, + sample.snowfall_cm, + sample.temperature_c, + sample.relative_humidity, + sample.wind_dir, + sample.wind_speed, + lat, + lon, + day_ordinal, + unix_utc.rem_euclid(86_400) as u64 / 3_600, + center_az, + ); let lightning = build_lightning(sample.weather_code, sample.precip_mm, lat, lon, unix_utc); let meteors = build_meteors( sun_altaz.altitude, @@ -319,6 +339,7 @@ fn build_sky( stars, moon, precipitation, + snowfall, lightning, meteors, horizon_glow: build_horizon_glow(&sun_altaz, center_az, total_cover), @@ -645,6 +666,64 @@ fn build_haze(atmosphere: &Atmosphere) -> Option { }) } +/// WMO codes for snow and snow showers. The single place the split between the two precipitation renderers is decided, so neither can claim an hour the other is also drawing. +fn is_snow_code(weather_code: Option) -> bool { + let code = weather_code.unwrap_or(0); + (71..=77).contains(&code) || (85..=86).contains(&code) +} + +/// Falling snow for this hour, or `None` when it is not snowing. +/// +/// The hour is in the seed, which precipitation's is not. A rain seed carries only the place and the UTC day, so scrubbing a whole forecast day past shows one frozen arrangement of drops for twenty-four hours; clouds get away with that because they are meant to reshape once a day, and falling precipitation is not. +#[allow(clippy::too_many_arguments)] +fn build_snowfall( + weather_code: Option, + snowfall_cm: Option, + temperature_c: Option, + relative_humidity: Option, + wind_dir: Option, + wind_speed: Option, + lat: f64, + lon: f64, + day_ordinal: i64, + hour_of_day: u64, + center_az: f64, +) -> Option { + if !is_snow_code(weather_code) { + return None; + } + // A snow code with no reported accumulation is still snow; fall back to something light rather than drawing an empty sky. + let rate = snowfall_cm.unwrap_or(0.0).max(0.05); + // The diagram is drawn against the humidity where the crystal grew, and the forecast reports it at 2 m, so this is an approximation and not a measurement: what is below the cloud is drier than what is inside it. The fallback is 95 rather than a round 90 because it only fires when the field is missing during an hour already coded as snow, and the split between faceted and branched sits at 93 percent at -15 C, so 90 would quietly report every sky as faceted. + let form = FlakeForm::select( + temperature_c.unwrap_or(-3.0), + relative_humidity.unwrap_or(95.0), + ); + Some(Snowfall { + form, + count: snow::flake_count(rate), + seed: mix_seed(&[ + hash_lat_lon(lat, lon), + day_ordinal as u64, + hour_of_day, + 0x0F1E_ECE5, + ]), + drift: snow_drift(wind_dir, wind_speed, center_az), + opacity: 0.75, + }) +} + +/// Sideways travel in frame widths per second. +/// +/// Only the across-view component moves a flake on screen: wind blowing away from the viewer changes nothing a flat frame can show. Scaled so a 20 km/h crosswind carries a flake across the frame in about twenty seconds, and capped, because a gale should lean the snow rather than fire it sideways faster than the eye can follow. +fn snow_drift(wind_dir: Option, wind_speed: Option, center_az: f64) -> f64 { + let speed = wind_speed.unwrap_or(0.0); + let lateral = lateral_offset_deg(wind_dir.unwrap_or(180.0), center_az) + .to_radians() + .sin(); + (lateral * speed * 0.0025).clamp(-0.12, 0.12) +} + fn build_precipitation( weather_code: Option, precip_mm: Option, @@ -658,19 +737,16 @@ fn build_precipitation( if mm < 0.10 { return None; } - let code = weather_code.unwrap_or(0); - let kind = if (71..=77).contains(&code) || (85..=86).contains(&code) { - PrecipKind::Snow - } else { - PrecipKind::Rain - }; + if is_snow_code(weather_code) { + return None; + } let intensity = (mm / 5.0).clamp(0.10, 0.85); let dir = wind_dir.unwrap_or(180.0); let delta = lateral_offset_deg(dir, center_az); let angle_deg = (delta * 0.30).clamp(-25.0, 25.0); let seed = mix_seed(&[hash_lat_lon(lat, lon), day_ordinal as u64, 0xBA17_DA75]); Some(Precipitation { - kind, + kind: PrecipKind::Rain, intensity, angle_deg, seed, @@ -858,6 +934,7 @@ pub fn error_sky(msg: &str) -> SkyState { stars: None, moon: None, precipitation: None, + snowfall: None, lightning: None, meteors: None, horizon_glow: None, diff --git a/tests/open-meteo-forecast-hamburg.json b/tests/open-meteo-forecast-hamburg.json index ac7cb03..6c29f60 100644 --- a/tests/open-meteo-forecast-hamburg.json +++ b/tests/open-meteo-forecast-hamburg.json @@ -16,7 +16,9 @@ "wind_speed_10m": "km/h", "wind_direction_10m": "\u00b0", "visibility": "m", - "weather_code": "wmo code" + "weather_code": "wmo code", + "relative_humidity_2m": "%", + "snowfall": "cm" }, "hourly": { "time": [ @@ -35,6 +37,14 @@ 2.9, 2.6 ], + "relative_humidity_2m": [ + 88.0, + 88.0, + 88.0, + 88.0, + 88.0, + 88.0 + ], "cloud_cover_low": [ 0, 0, @@ -67,6 +77,14 @@ 0.0, 0.0 ], + "snowfall": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], "wind_speed_10m": [ 4.0, 4.0, @@ -105,8 +123,8 @@ "sunrise": "iso8601", "sunset": "iso8601", "daylight_duration": "s", - "temperature_2m_max": "°C", - "temperature_2m_min": "°C" + "temperature_2m_max": "\u00b0C", + "temperature_2m_min": "\u00b0C" }, "daily": { "time": [ @@ -128,4 +146,4 @@ 5.8 ] } -} \ No newline at end of file +} diff --git a/tests/open-meteo-forecast-with-nulls.json b/tests/open-meteo-forecast-with-nulls.json index 0c768db..24f31fd 100644 --- a/tests/open-meteo-forecast-with-nulls.json +++ b/tests/open-meteo-forecast-with-nulls.json @@ -8,26 +8,78 @@ "elevation": 0.0, "hourly_units": { "time": "iso8601", - "temperature_2m": "°C", + "temperature_2m": "\u00b0C", "cloud_cover_low": "%", "cloud_cover_mid": "%", "cloud_cover_high": "%", "precipitation": "mm", "wind_speed_10m": "km/h", - "wind_direction_10m": "°", + "wind_direction_10m": "\u00b0", "visibility": "m", - "weather_code": "wmo code" + "weather_code": "wmo code", + "relative_humidity_2m": "%", + "snowfall": "cm" }, "hourly": { - "time": ["2026-04-11T00:00", "2026-04-11T01:00", "2026-04-11T02:00"], - "temperature_2m": [4.8, null, 4.2], - "cloud_cover_low": [0, 0, null], - "cloud_cover_mid": [0, 0, 0], - "cloud_cover_high": [0, 0, 0], - "precipitation": [0.0, 0.0, 0.0], - "wind_speed_10m": [4.0, 4.0, 4.1], - "wind_direction_10m": [90, 90, 135], - "visibility": [26600.0, 29020.0, 29360.0], - "weather_code": [0, 0, 0] + "time": [ + "2026-04-11T00:00", + "2026-04-11T01:00", + "2026-04-11T02:00" + ], + "temperature_2m": [ + 4.8, + null, + 4.2 + ], + "relative_humidity_2m": [ + 88.0, + null, + 88.0 + ], + "cloud_cover_low": [ + 0, + 0, + null + ], + "cloud_cover_mid": [ + 0, + 0, + 0 + ], + "cloud_cover_high": [ + 0, + 0, + 0 + ], + "precipitation": [ + 0.0, + 0.0, + 0.0 + ], + "snowfall": [ + 0.0, + 0.0, + 0.0 + ], + "wind_speed_10m": [ + 4.0, + 4.0, + 4.1 + ], + "wind_direction_10m": [ + 90, + 90, + 135 + ], + "visibility": [ + 26600.0, + 29020.0, + 29360.0 + ], + "weather_code": [ + 0, + 0, + 0 + ] } } diff --git a/tests/snow.rs b/tests/snow.rs new file mode 100644 index 0000000..9719c51 --- /dev/null +++ b/tests/snow.rs @@ -0,0 +1,229 @@ +// Snow is the first effect drawn in both stills and motion, and the first whose *form* is computed from the weather rather than chosen by an author. Both of those are properties rather than pixels, so this asserts them directly. A hash could not tell a dendrite from a needle, and the thing most worth catching here is the morphology table being read off by one band. + +use celsius::colorspace::{PixelBuffer, Rgb}; +use celsius::snow::{ + FlakeForm, Snowfall, flake_count, overlay, supersaturation, vapour_pressure_ice, + vapour_pressure_water, +}; + +fn buffer(w: usize, h: usize) -> PixelBuffer { + PixelBuffer::filled(w, h, Rgb::new(40, 44, 52)) +} + +fn snowfall(form: FlakeForm, count: u32) -> Snowfall { + Snowfall { + form, + count, + seed: 2749, + drift: 0.0, + opacity: 0.75, + } +} + +/// The diagram's water-saturation line, which Libbrecht gives as the humidity inside dense winter cloud. It has to be 100 and not a plausible-looking 98: near freezing the ice and water curves nearly meet, so ice saturation alone needs 99.05 percent at -1 C and anything below that can only grow a faceted plate however much it looks like a snowstorm. +const IN_CLOUD: f64 = 100.0; +/// Cold air that is not producing much: below the branching threshold at every temperature in the table. +const DRY: f64 = 60.0; + +/// The morphology diagram as Libbrecht draws it: temperature picks the habit, supersaturation picks how branched it is. Every band is checked on both sides of the humidity split, because reading the table off by one column is exactly as wrong as reading it off by one row and neither shows up in a render as anything but "the snow looks odd". +#[test] +fn the_morphology_table_matches_the_diagram() { + let cases = [ + (2.0, IN_CLOUD, FlakeForm::Aggregate), + (2.0, DRY, FlakeForm::Aggregate), + (-1.0, DRY, FlakeForm::Plate), + (-1.0, IN_CLOUD, FlakeForm::SectoredPlate), + (-5.0, DRY, FlakeForm::Column), + (-5.0, IN_CLOUD, FlakeForm::Needle), + (-10.0, DRY, FlakeForm::Column), + (-10.0, IN_CLOUD, FlakeForm::Plate), + (-15.0, DRY, FlakeForm::Plate), + (-15.0, IN_CLOUD, FlakeForm::Dendrite), + (-20.0, DRY, FlakeForm::Plate), + (-20.0, IN_CLOUD, FlakeForm::SectoredPlate), + (-30.0, DRY, FlakeForm::Column), + (-30.0, IN_CLOUD, FlakeForm::Plate), + ]; + for (t, rh, expected) in cases { + let got = FlakeForm::select(t, rh); + assert_eq!( + got, expected, + "{t} C at {rh}% relative humidity should grow {expected:?}, not {got:?}" + ); + } +} + +/// The -15 C fernlike peak is the one feature of the diagram a viewer would actually recognise, and it is a narrow band with plates on both sides of it. An off-by-one on the band edges would move the most photogenic flake there is to a temperature it does not occur at. +#[test] +fn the_dendrite_peak_sits_where_the_diagram_puts_it() { + assert_eq!(FlakeForm::select(-15.0, IN_CLOUD), FlakeForm::Dendrite); + assert_eq!(FlakeForm::select(-12.5, IN_CLOUD), FlakeForm::Dendrite); + assert_eq!(FlakeForm::select(-17.5, IN_CLOUD), FlakeForm::Dendrite); + // Just outside, on both sides, the branched column of the table is not a dendrite. + assert_eq!(FlakeForm::select(-11.5, IN_CLOUD), FlakeForm::Plate); + assert_eq!(FlakeForm::select(-18.5, IN_CLOUD), FlakeForm::SectoredPlate); +} + +/// Above freezing nothing keeps its shape on the way down, whatever the cloud grew. +#[test] +fn wet_snow_overrides_the_diagram() { + for rh in [40.0, 70.0, 100.0] { + assert_eq!(FlakeForm::select(1.0, rh), FlakeForm::Aggregate); + assert_eq!(FlakeForm::select(5.0, rh), FlakeForm::Aggregate); + } +} + +/// Ice holds vapour less readily than supercooled water at every temperature below freezing, and that gap is the entire reason a crystal in a cloud of droplets grows instead of evaporating. If the two Magnus forms were ever swapped, `select` would report a dry sky in the middle of a snowstorm and every flake would come out faceted. +#[test] +fn the_magnus_pair_is_ordered_and_monotone() { + let mut previous_w = 0.0; + let mut previous_i = 0.0; + for t in [-40.0, -30.0, -20.0, -15.0, -10.0, -5.0, -1.0] { + let (w, i) = (vapour_pressure_water(t), vapour_pressure_ice(t)); + assert!(w > i, "at {t} C water saturation {w} must exceed ice {i}"); + assert!( + w > previous_w, + "water saturation must rise with temperature" + ); + assert!(i > previous_i, "ice saturation must rise with temperature"); + previous_w = w; + previous_i = i; + } +} + +/// The conversion the forecast forces on us: Open-Meteo reports humidity over water and the diagram is drawn over ice, so air well below 100 percent is already supersaturated for a growing crystal. Reading the relative humidity straight onto the diagram's axis would call a snowstorm dry. +#[test] +fn air_below_water_saturation_is_still_supersaturated_over_ice() { + assert!( + supersaturation(-15.0, 90.0) > 0.0, + "90 percent humidity at -15 C is supersaturated with respect to ice" + ); + assert!( + supersaturation(-15.0, 100.0) > supersaturation(-15.0, 90.0), + "more vapour must mean more supersaturation" + ); + assert!( + supersaturation(-15.0, 60.0) < supersaturation(-15.0, 90.0), + "less vapour must mean less" + ); +} + +/// Snow is drawn by `render()` as well as by the TUI, so unlike lightning it has to be a function of its clock and nothing else. Two calls at one instant must agree exactly, or a still and the first animated frame would disagree. +#[test] +fn one_instant_gives_one_arrangement() { + let snow = snowfall(FlakeForm::Dendrite, 120); + let (mut a, mut b) = (buffer(104, 50), buffer(104, 50)); + overlay(&mut a, &snow, 2.5); + overlay(&mut b, &snow, 2.5); + assert_eq!(a, b, "the same instant must produce the same frame"); + + let mut later = buffer(104, 50); + overlay(&mut later, &snow, 2.6); + assert_ne!(a, later, "a tenth of a second later the snow has moved"); +} + +/// The bug `rules/reference-size.md` exists for, in the shape `tests/meteors.rs` states it: geometry baked at the reference size leaves the effect stranded in one corner of a wide terminal and does not survive a resize. +#[test] +fn flakes_fill_the_frame_at_any_buffer_size() { + for (w, h) in [(104, 50), (380, 180)] { + let mut pixels = buffer(w, h); + overlay(&mut pixels, &snowfall(FlakeForm::Plate, 400), 1.0); + + let untouched = Rgb::new(40, 44, 52); + let touched = |x: usize, y: usize| pixels.get(x, y) != untouched; + let band = |xs: std::ops::Range, ys: std::ops::Range| { + ys.flat_map(|y| xs.clone().map(move |x| (x, y))) + .any(|(x, y)| touched(x, y)) + }; + let (qw, qh) = (w / 8, h / 8); + assert!(band(0..qw, 0..h), "nothing drawn against the left edge"); + assert!( + band(w - qw..w, 0..h), + "nothing drawn against the right edge" + ); + assert!(band(0..w, 0..qh), "nothing drawn against the top edge"); + assert!(band(0..w, h - qh..h), "nothing drawn against the bottom"); + } +} + +/// The correction `rules/reference-size.md` spells out for `Stars.count` and that the old area-scaled drop count had backwards. The frame subtends a fixed field of view however many pixels are in it, so the number of flakes in shot is set by the weather; what a bigger buffer buys is a bigger flake, not more of them. +#[test] +fn count_is_absolute_while_the_drawn_flake_grows() { + let snow = snowfall(FlakeForm::Plate, 200); + + // A plate is a single pixel per flake at the reference, so touched pixels count flakes directly (bar the odd collision, which is why this compares against a generous bound rather than an exact figure). + let touched = |w: usize, h: usize| { + let mut pixels = buffer(w, h); + overlay(&mut pixels, &snow, 0.0); + pixels + .pixels + .iter() + .filter(|p| **p != Rgb::new(40, 44, 52)) + .count() + }; + + let small = touched(104, 50); + let large = touched(416, 200); + assert!( + small <= 200, + "a plate is one pixel at the reference size, so it cannot mark more pixels than there are flakes" + ); + assert!( + large > small * 2, + "at four times the width a flake must cover more pixels, not the same one: {small} then {large}" + ); + assert!( + large < 416 * 200 / 4, + "growing the flake must not blanket the frame: {large} of {} pixels", + 416 * 200 + ); +} + +/// Density comes from the forecast's snowfall rate, and the compression matters as much as the direction: without it a blizzard fills every pixel and stops reading as snow at all. +#[test] +fn count_follows_the_snowfall_rate_and_saturates() { + let mut previous = 0; + for rate in [0.1, 0.25, 0.5, 1.0, 2.0] { + let n = flake_count(rate); + assert!( + n >= previous, + "more snow must not mean fewer flakes: {rate} cm/h gave {n} after {previous}" + ); + previous = n; + } + assert_eq!(flake_count(0.0), 24, "the floor keeps light snow visible"); + assert_eq!(flake_count(1000.0), 420, "and the ceiling holds"); + assert_eq!( + flake_count(0.5), + 140, + "moderate snow is the reference the rest is measured from" + ); +} + +/// A sky with no snow in it must be left exactly as it was, which is what lets `render()` call the overlay unconditionally without any golden moving. +#[test] +fn no_flakes_is_a_no_op() { + let before = buffer(104, 50); + let mut after = before.clone(); + overlay(&mut after, &snowfall(FlakeForm::Plate, 0), 4.0); + assert_eq!(before, after, "zero flakes must not touch the buffer"); + + let mut transparent = before.clone(); + let mut invisible = snowfall(FlakeForm::Plate, 200); + invisible.opacity = 0.0; + overlay(&mut transparent, &invisible, 4.0); + assert_eq!(before, transparent, "zero opacity must not touch it either"); +} + +/// The crosswind is the only part of the wind a flat frame can show, and it is what separates snow drifting past from snow falling straight down. +#[test] +fn drift_carries_flakes_sideways() { + let still = snowfall(FlakeForm::Plate, 200); + let mut blown = still.clone(); + blown.drift = 0.08; + + let (mut a, mut b) = (buffer(104, 50), buffer(104, 50)); + overlay(&mut a, &still, 3.0); + overlay(&mut b, &blown, 3.0); + assert_ne!(a, b, "a crosswind must move the snow across the frame"); +} diff --git a/tests/weather.rs b/tests/weather.rs index 292c5ef..f63e35b 100644 --- a/tests/weather.rs +++ b/tests/weather.rs @@ -348,3 +348,74 @@ fn the_palette_to_analytic_handover_does_not_step() { worst.0 ); } + +/// The two hourly fields the snow morphology needs. Both are `#[serde(default)]` so an older cached response still parses, which means a silent empty vector is the failure mode and only a fixture that actually carries them can tell the difference. +#[test] +fn forecast_carries_humidity_and_snowfall() { + let parsed: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + let hours = parsed.hourly.time.len(); + assert_eq!( + parsed.hourly.relative_humidity_2m.len(), + hours, + "humidity must arrive for every hour, not default to empty" + ); + assert_eq!(parsed.hourly.snowfall.len(), hours); + assert!( + parsed.hourly.relative_humidity_2m[0].is_some(), + "the fixture must carry a real humidity reading" + ); +} + +/// Snow and rain are drawn by different renderers now, so exactly one of them may claim any given hour. Overlap would double the precipitation; a gap would drop it. +#[test] +fn a_snow_hour_belongs_to_snow_and_not_to_rain() { + let mut forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + for h in 0..forecast.hourly.time.len() { + forecast.hourly.weather_code[h] = Some(73); // moderate snowfall + forecast.hourly.precipitation[h] = Some(1.2); + forecast.hourly.snowfall[h] = Some(0.8); + forecast.hourly.temperature_2m[h] = Some(-6.0); + forecast.hourly.relative_humidity_2m[h] = Some(99.0); + } + let opts = celsius::weather::ComposeOpts::default(); + let t = 1_775_865_600; + let sky = celsius::weather::compose_at(&forecast, &hamburg_geo(), t, t, opts).unwrap(); + + assert!(sky.snowfall.is_some(), "a snow code must produce snow"); + assert!( + sky.precipitation.is_none(), + "and must not also produce rain streaks" + ); + assert_eq!( + sky.snowfall.unwrap().form, + celsius::snow::FlakeForm::Needle, + "-6 C in near-saturated air is the needle band of the diagram" + ); +} + +/// Precipitation seeds on place and UTC day only, so a whole forecast day of rain scrubs past as one frozen arrangement. Snow carries the hour, which is what makes scrubbing show different snow. +#[test] +fn snow_relayouts_each_hour() { + let mut forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + for h in 0..forecast.hourly.time.len() { + forecast.hourly.weather_code[h] = Some(73); + forecast.hourly.snowfall[h] = Some(0.8); + forecast.hourly.temperature_2m[h] = Some(-6.0); + forecast.hourly.relative_humidity_2m[h] = Some(99.0); + } + let opts = celsius::weather::ComposeOpts::default(); + let geo = hamburg_geo(); + let base = 1_775_865_600; + let first = celsius::weather::compose(&forecast, &geo, 0, base, opts) + .unwrap() + .snowfall + .expect("hour 0 snows"); + let second = celsius::weather::compose(&forecast, &geo, 1, base, opts) + .unwrap() + .snowfall + .expect("hour 1 snows"); + assert_ne!( + first.seed, second.seed, + "consecutive hours must not share a flake layout" + ); +} diff --git a/tools/celsius-lab/src/lib.rs b/tools/celsius-lab/src/lib.rs index 7c2c15a..374797e 100644 --- a/tools/celsius-lab/src/lib.rs +++ b/tools/celsius-lab/src/lib.rs @@ -456,6 +456,7 @@ pub fn analytic_state(sun_alt: f64, turbidity: f64, sun_az_offset: f64) -> SkySt stars: None, moon: None, precipitation: None, + snowfall: None, lightning: None, meteors: None, horizon_glow: None,