diff --git a/README.md b/README.md index e669304..f12dde0 100644 --- a/README.md +++ b/README.md @@ -70,3 +70,5 @@ just lab-new harbor_dawn 53.5511 9.9937 2026-04-11T06:14Z --visibility 18 ``` See [the celsius-lab guide](tools/celsius-lab/README.md) for the scene and output layout. + +Weather data by [Open-Meteo.com](https://open-meteo.com/) ([CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)). Place names from [GeoNames](https://www.geonames.org/). diff --git a/benches/render.rs b/benches/render.rs index 7175ae7..c2057d5 100644 --- a/benches/render.rs +++ b/benches/render.rs @@ -337,8 +337,9 @@ fn week_long(base: &Forecast) -> Forecast { }; let hourly = &mut forecast.hourly; + let base_unix = src.time[0]; hourly.time = (0..WEEK_HOURS) - .map(|i| format!("2026-04-{:02}T{:02}:00", 11 + i / 24, i % 24)) + .map(|i| base_unix + i as i64 * 3_600) .collect(); hourly.temperature_2m = cycle(&src.temperature_2m); hourly.cloud_cover = cycle(&src.cloud_cover); @@ -356,14 +357,12 @@ fn week_long(base: &Forecast) -> Forecast { let days = WEEK_HOURS / 24; let src_daily = base.daily.as_ref().expect("cloned from Some"); let m = src_daily.time.len(); - daily.time = (0..days) - .map(|d| format!("2026-04-{:02}", 11 + d)) - .collect(); + daily.time = (0..days).map(|d| base_unix + d as i64 * 86_400).collect(); daily.sunrise = (0..days) - .map(|d| format!("2026-04-{:02}T04:38", 11 + d)) + .map(|d| base_unix + d as i64 * 86_400 + 16_680) .collect(); daily.sunset = (0..days) - .map(|d| format!("2026-04-{:02}T18:14", 11 + d)) + .map(|d| base_unix + d as i64 * 86_400 + 65_640) .collect(); daily.daylight_duration = (0..days) .map(|d| src_daily.daylight_duration[d % m]) diff --git a/justfile b/justfile index af1bef0..1357365 100644 --- a/justfile +++ b/justfile @@ -110,6 +110,11 @@ lock: bench: cargo bench --bench render +# Where the time goes inside a frame, in the Firefox Profiler. Profiles the render bench so runs are repeatable. +profile: + cargo bench --bench render --profile profiling --no-run + samply record -o target/profiling/profile.json.gz $(ls -t target/profiling/deps/render-* | rg -v "\.d$" | head -1) --bench --profile-time 10 + # Config lives in .cargo/mutants.toml. The whole crate is ~3600 mutants and hours of # wall clock, so reach for `mutants-file` or `mutants-diff` unless you mean it. # Every mutant the suite fails to kill: code a test runs but nothing asserts on. diff --git a/src/atmosphere.rs b/src/atmosphere.rs index 7faad52..427a9f3 100644 --- a/src/atmosphere.rs +++ b/src/atmosphere.rs @@ -15,7 +15,7 @@ pub struct Atmosphere { } impl Atmosphere { - /// The live path, where everything follows from what the forecast reported. + /// The live path when only visibility is known. #[must_use] pub fn from_visibility(visibility_m: Option) -> Self { Self { @@ -24,6 +24,18 @@ impl Atmosphere { } } + /// The live path with both readings. Turbidity is a column quantity and optical depth measures the column, so it wins whenever the air-quality forecast covered the hour; visibility is kept for the haze layer, which is a near-ground effect and reads it directly. + #[must_use] + pub fn from_readings(visibility_m: Option, aod_550: Option) -> Self { + Self { + visibility_m, + turbidity: aod_550.map_or_else( + || turbidity_from_visibility(visibility_m), + turbidity_from_aod, + ), + } + } + /// 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 { @@ -41,3 +53,37 @@ 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) } + +/// Map aerosol optical depth at 550 nm to Preetham turbidity. +/// +/// Preetham relates turbidity to the Angstrom coefficient by `beta = 0.04608 T - 0.04586`, and with the Angstrom exponent of 1.3 the paper assumes, `AOD_550 = beta * 0.55^-1.3 = 2.176 beta`. Inverting gives AOD 0.1, 0.3 and 0.6 as T 2, 4 and 7, which matches the visibility curve's clear and hazy ends. The floor is the lowest turbidity the analytic tests exercise; above 9 the Perez fit is outside its published range. +#[must_use] +pub fn turbidity_from_aod(aod_550: f64) -> f64 { + ((aod_550 / 2.176 + 0.04586) / 0.04608).clamp(1.5, 9.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn aod_mapping_meets_the_visibility_curve_at_both_ends() { + assert!((turbidity_from_aod(0.1) - 2.0).abs() < 0.05); + assert!((turbidity_from_aod(0.3) - 4.0).abs() < 0.05); + assert!((turbidity_from_aod(0.6) - 7.0).abs() < 0.05); + assert_eq!(turbidity_from_aod(0.0), 1.5); + assert_eq!(turbidity_from_aod(3.0), 9.0); + } + + #[test] + fn readings_prefer_optical_depth_and_keep_visibility() { + let both = Atmosphere::from_readings(Some(4_000.0), Some(0.1)); + assert!( + (both.turbidity - 2.0).abs() < 0.05, + "a clear column beats a misty surface" + ); + assert_eq!(both.visibility_m, Some(4_000.0)); + let fallback = Atmosphere::from_readings(Some(4_000.0), None); + assert_eq!(fallback.turbidity, turbidity_from_visibility(Some(4_000.0))); + } +} diff --git a/src/main.rs b/src/main.rs index aa3ecad..3cb1e89 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ use clap::builder::styling::{AnsiColor, Styles}; use celsius::config::{self, LocationPref}; use celsius::raster::{ColorDepth, Geometry, RasterOpts, detect_depth}; use celsius::tui::{RunOutcome, Timeline}; -use celsius::weather::{ComposeOpts, compose, compose_at, error_sky, forecast, location}; +use celsius::weather::{ComposeOpts, aerosol, compose, compose_at, error_sky, forecast, location}; use celsius::{SkyState, builtin_names, load_builtin_scene, load_scene, tui}; #[cfg(feature = "png")] use celsius::{render, terminal}; @@ -393,8 +393,17 @@ fn build_live_timeline(params: &FetchParams, location: &location::GeoResult) -> None => now_unix, }; - let forecast = forecast::fetch(location.latitude, location.longitude) - .with_context(|| format!("fetching forecast for {}", location.label()))?; + // Two hosts, one round trip of latency: the aerosol request runs beside the forecast and is optional, so a failure there leaves the field unattached and turbidity falls back to visibility. Nothing reports it, because the app has no log channel and the sky is correct without it. + let (forecast, aerosol) = std::thread::scope(|scope| { + let aerosol_task = scope.spawn(|| aerosol::fetch(location.latitude, location.longitude)); + let forecast = forecast::fetch(location.latitude, location.longitude); + (forecast, aerosol_task.join()) + }); + let mut forecast = + forecast.with_context(|| format!("fetching forecast for {}", location.label()))?; + if let Ok(Ok(aerosol)) = aerosol { + forecast.attach_aerosol(&aerosol); + } let hours = forecast.hourly.len(); if hours == 0 { bail!("forecast returned zero hours for {}", location.label()); @@ -592,12 +601,7 @@ fn parse_relative(s: &str, now_unix: i64) -> Result { fn nearest_hour_index(forecast: &forecast::Forecast, target_unix: i64) -> usize { let mut best = 0usize; let mut best_dist = i64::MAX; - for (i, t) in forecast.hourly.time.iter().enumerate() { - let Ok(naive) = NaiveDateTime::parse_from_str(t, "%Y-%m-%dT%H:%M") else { - continue; - }; - // Forecast times are local (timezone=auto); shift to UTC to compare. - let unix = naive.and_utc().timestamp() - forecast.utc_offset_seconds; + for (i, &unix) in forecast.hourly.time.iter().enumerate() { let dist = (unix - target_unix).abs(); if dist < best_dist { best_dist = dist; diff --git a/src/render.rs b/src/render.rs index 8a28f4e..f50a738 100644 --- a/src/render.rs +++ b/src/render.rs @@ -267,7 +267,7 @@ pub fn render_supersampled(state: &SkyState, width: u32, height: u32, factor: u3 let dx = (px as f64 - sun_px) / width as f64; let dy = (py as f64 - sun_py) / height as f64; let d = (dx * dx + dy * dy * 3.2).sqrt(); - let glow = (1.0 - d / 0.60).max(0.0).powi(2); + let glow = (1.0 - d / 0.60).max(0.0).powi(2) * sun.strength; l += glow * 0.11; a += glow * 0.020; b += glow * 0.055; @@ -350,7 +350,7 @@ pub fn render_supersampled(state: &SkyState, width: u32, height: u32, factor: u3 let ey = py as f64 - sun_py; let sd = (ex * ex + ey * ey).sqrt(); if sd < sun_r { - let k = (1.0 - (sd / sun_r).powi(2)).max(0.0); + let k = (1.0 - (sd / sun_r).powi(2)).max(0.0) * sun.strength; let inv = 1.0 - k; l = l * inv + sun_disc.l * k; a = a * inv + sun_disc.a * k; diff --git a/src/scene.rs b/src/scene.rs index efd13f2..7244887 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -53,6 +53,9 @@ pub struct Sun { pub radius: f64, #[serde(default = "default_true")] pub visible: bool, + /// How much of the disc and its glow to draw, 0 to 1. Live skies set it from the share of the direct beam the forecast says reaches the ground, so the sun behind a deck is a faint patch rather than a crisp disc painted over the cloud. Scenes are hand-lit and default to full strength. + #[serde(default = "default_one")] + pub strength: f64, } /// Cloud morphology class. Drives noise detail, edge sharpness, and the lit/shadow colors so a thin cirrus veil, a flat stratus deck, and a dark storm tower no longer share one texture. `Generic` reproduces the pre-morphology render exactly, which keeps vendored scenes and the oracle goldens unchanged. @@ -403,6 +406,10 @@ fn parse_scene(path: &Path, text: &str) -> Result { }) } +fn default_one() -> f64 { + 1.0 +} + fn default_true() -> bool { true } diff --git a/src/tui/app.rs b/src/tui/app.rs index 058b840..e29dc96 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -1245,6 +1245,7 @@ mod tests { y_frac: 0.5, radius: 2.0, visible: true, + strength: 1.0, }, clouds: vec![CloudLayer { cover: 1.0, diff --git a/src/weather/aerosol.rs b/src/weather/aerosol.rs new file mode 100644 index 0000000..7d6625d --- /dev/null +++ b/src/weather/aerosol.rs @@ -0,0 +1,50 @@ +//! Aerosol optical depth from Open-Meteo's air-quality endpoint, the column measure the analytic sky's turbidity actually describes. +//! +//! Visibility is a boundary-layer number that most models cap near 24 km, so on most days it sits at the cap and turbidity sits at 2 whatever the air is doing above the first kilometre. Optical depth at 550 nm from CAMS is the whole column, hourly and worldwide, and it moves with haze, dust and smoke. It comes from a different host with a shorter horizon, about five days, so it is a second request that the sky can do without: a failure here leaves `Forecast::attach_aerosol` uncalled and turbidity falls back to visibility. + +use serde::Deserialize; + +use super::WeatherError; +use super::forecast::{FORECAST_HOURS, PAST_HOURS}; + +const ENDPOINT: &str = "https://air-quality-api.open-meteo.com/v1/air-quality"; + +#[derive(Debug, Clone, Deserialize)] +pub struct AerosolForecast { + pub hourly: AerosolHourly, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct AerosolHourly { + /// Unix seconds, UTC, on the same hourly grid as the forecast. + pub time: Vec, + /// Dimensionless; 0.05 is alpine air, 0.3 a hazy summer afternoon, above 1 is smoke or a dust storm. + pub aerosol_optical_depth: Vec>, +} + +/// Fetch the aerosol optical depth over the same window as the forecast. +/// +/// # Errors +/// +/// [`WeatherError::Network`] if the request does not complete, [`WeatherError::Http`] for a non-success status, and [`WeatherError::Decode`] if the body is not the JSON shape this crate expects. +pub fn fetch(lat: f64, lon: f64) -> Result { + let mut response = super::AGENT + .get(ENDPOINT) + .query("latitude", lat.to_string()) + .query("longitude", lon.to_string()) + .query("hourly", "aerosol_optical_depth") + .query("timeformat", "unixtime") + .query("past_hours", PAST_HOURS) + .query("forecast_hours", FORECAST_HOURS) + .call()?; + let status = response.status(); + if !status.is_success() { + let body = response.body_mut().read_to_string().unwrap_or_default(); + return Err(WeatherError::Http { + status: status.as_u16(), + body, + }); + } + let body: AerosolForecast = response.body_mut().read_json()?; + Ok(body) +} diff --git a/src/weather/forecast.rs b/src/weather/forecast.rs index bb5ecd4..ebe2f60 100644 --- a/src/weather/forecast.rs +++ b/src/weather/forecast.rs @@ -1,15 +1,21 @@ //! The Open-Meteo forecast client and its response types. //! -//! One request fetches a seven-day, 168-hour window: temperature, the three cloud-cover bands, precipitation, wind, visibility and WMO weather code hourly, plus sunrise, sunset and the day's high and low. That window is also the hard limit on `--at`, since a sky can only be synthesized for an hour the forecast actually covers. +//! One request fetches a 192-hour window, 24 hours back and 168 forward from the current hour, rather than seven calendar days from local midnight: with the old window a launch at 22:00 had spent most of its first day already and could scrub only six days ahead. Hourly: temperature, humidity, the three cloud-cover bands, precipitation split into rain, showers and snowfall, the direct beam reaching the ground, convective energy, wind, visibility and WMO weather code. Daily: sunrise, sunset and the day's high and low. That window is also the hard limit on `--at`, since a sky can only be synthesized for an hour the forecast actually covers. +//! +//! Timestamps are unix seconds in UTC (`timeformat=unixtime`), so nothing downstream parses a local wall-clock string. `timezone=auto` stays in the request for `utc_offset_seconds`, which the chrome needs for display, and for the daily block, whose rows are local days. //! //! Every hourly field is `Option`, because Open-Meteo genuinely returns nulls for some variables at some locations rather than omitting them, and treating a missing visibility as zero would render fog on a clear day. use serde::Deserialize; use super::WeatherError; +use super::aerosol::AerosolForecast; const ENDPOINT: &str = "https://api.open-meteo.com/v1/forecast"; +pub(super) const PAST_HOURS: &str = "24"; +pub(super) const FORECAST_HOURS: &str = "168"; + const HOURLY_FIELDS: &str = concat!( "temperature_2m,", "relative_humidity_2m,", @@ -18,7 +24,12 @@ const HOURLY_FIELDS: &str = concat!( "cloud_cover_mid,", "cloud_cover_high,", "precipitation,", + "rain,", + "showers,", "snowfall,", + "precipitation_probability,", + "cape,", + "direct_normal_irradiance_instant,", "wind_speed_10m,", "wind_direction_10m,", "visibility,", @@ -41,9 +52,34 @@ pub struct Forecast { pub daily: Option, } +impl Forecast { + /// Copy the aerosol optical depth for every hour this forecast covers, matched by timestamp. Hours the aerosol forecast does not cover (its horizon is shorter) stay `None`, and the sky falls back to visibility there. + pub fn attach_aerosol(&mut self, aerosol: &AerosolForecast) { + let times = &aerosol.hourly.time; + let depths = &aerosol.hourly.aerosol_optical_depth; + let mut j = 0; + self.hourly.aerosol_optical_depth = self + .hourly + .time + .iter() + .map(|&t| { + while j < times.len() && times[j] < t { + j += 1; + } + if times.get(j) == Some(&t) { + depths.get(j).copied().flatten() + } else { + None + } + }) + .collect(); + } +} + #[derive(Debug, Clone, Deserialize)] pub struct HourlyArrays { - pub time: Vec, + /// Unix seconds, UTC. + 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)] @@ -54,13 +90,31 @@ pub struct HourlyArrays { pub cloud_cover_mid: Vec>, pub cloud_cover_high: Vec>, pub precipitation: Vec>, + /// The liquid part of `precipitation` that fell from stratiform cloud, in mm. With `showers` it decides whether an hour draws rain streaks at all, which the total cannot, since the total also counts snow. + #[serde(default)] + pub rain: Vec>, + /// Convective liquid precipitation in mm. Any showers at all make the low deck a cumulonimbus tower, whatever the weather code says. + #[serde(default)] + pub showers: 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>, + /// Percent. Scales how much precipitation is drawn, so a twenty percent chance on day six does not paint the same downpour as certain rain in an hour. + #[serde(default)] + pub precipitation_probability: Vec>, + /// Convective available potential energy in J/kg: how violent a storm the code is announcing. + #[serde(default)] + pub cape: Vec>, + /// W/m2 at the indicated instant. Against the solar constant this is the share of the beam that reaches the ground, which is what says whether the sun disc is visible and how much of the clear-sky model to draw. + #[serde(default)] + pub direct_normal_irradiance_instant: Vec>, pub wind_speed_10m: Vec>, pub wind_direction_10m: Vec>, pub visibility: Vec>, pub weather_code: Vec>, + /// Aerosol optical depth at 550 nm. Never present in the forecast response; [`Forecast::attach_aerosol`] fills it from the air-quality endpoint, and it stays empty when that request failed. + #[serde(default)] + pub aerosol_optical_depth: Vec>, } impl HourlyArrays { @@ -75,9 +129,11 @@ impl HourlyArrays { #[derive(Debug, Clone, Deserialize)] pub struct DailyArrays { - pub time: Vec, - pub sunrise: Vec, - pub sunset: Vec, + /// Unix seconds of local midnight starting each row's day. Add `utc_offset_seconds` before dividing by 86400 to recover the local date. + pub time: Vec, + /// Unix seconds, UTC. Polar day and night are sentinels rather than nulls: see `daylight_duration`. + pub sunrise: Vec, + pub sunset: Vec, pub daylight_duration: Vec, #[serde(default)] pub temperature_2m_max: Vec>, @@ -85,7 +141,7 @@ pub struct DailyArrays { pub temperature_2m_min: Vec>, } -/// Fetch the 7-day, 168-hour forecast for a coordinate from Open-Meteo. +/// Fetch the 192-hour forecast for a coordinate from Open-Meteo: the past 24 hours and the next 168. /// /// # Errors /// @@ -98,7 +154,12 @@ pub fn fetch(lat: f64, lon: f64) -> Result { .query("hourly", HOURLY_FIELDS) .query("daily", DAILY_FIELDS) .query("timezone", "auto") - .query("forecast_days", "7") + .query("timeformat", "unixtime") + .query("past_hours", PAST_HOURS) + .query("forecast_hours", FORECAST_HOURS) + // The daily block is windowed by days, not hours; one day back and eight forward is the smallest span that covers every hourly row whatever the launch hour. + .query("past_days", "1") + .query("forecast_days", "8") .call()?; let status = response.status(); if !status.is_success() { diff --git a/src/weather/gradients.rs b/src/weather/gradients.rs index 0a58a35..deebbab 100644 --- a/src/weather/gradients.rs +++ b/src/weather/gradients.rs @@ -15,6 +15,7 @@ pub(super) enum Palette { Night, CloudyDay, Overcast, + Fog, } const DAY: &[(f64, [u8; 3])] = &[ @@ -92,6 +93,15 @@ const OVERCAST: &[(f64, [u8; 3])] = &[ (1.00, [190, 182, 168]), ]; +// Dense daytime fog: the sky collapses to one luminous grey with the warmest band where the sun sits, and the horizon is lost. Taken from the fog scene draft. +const FOG: &[(f64, [u8; 3])] = &[ + (0.00, [190, 192, 195]), + (0.30, [204, 204, 203]), + (0.55, [212, 210, 205]), + (0.78, [208, 206, 201]), + (1.00, [200, 198, 193]), +]; + pub(super) fn gradient_for(palette: Palette) -> Gradient { let stops: &[(f64, [u8; 3])] = match palette { Palette::Day => DAY, @@ -101,6 +111,7 @@ pub(super) fn gradient_for(palette: Palette) -> Gradient { Palette::Night => NIGHT, Palette::CloudyDay => CLOUDY_DAY, Palette::Overcast => OVERCAST, + Palette::Fog => FOG, }; Gradient::from_rgb_stops(stops) } @@ -152,6 +163,15 @@ pub(super) fn sky_gradient(sun_alt_deg: f64, total_cover: f64) -> Gradient { clear.blend(&clouded, daylight) } +/// Fog pulls the sky toward one luminous grey. The pull fades with daylight because the fog palette is a daytime colour; at night the veil, a full-frame haze layer, carries the fog and the gradient stays the night sky it is drawn over. +pub(super) fn fog_gradient(base: &Gradient, sun_alt_deg: f64, density: f64) -> Gradient { + let daylight = smoothstep01((sun_alt_deg + 3.0) / 9.0); + base.blend( + &gradient_for(Palette::Fog), + (density * daylight).clamp(0.0, 1.0), + ) +} + fn smoothstep01(x: f64) -> f64 { let x = x.clamp(0.0, 1.0); x * x * (3.0 - 2.0 * x) diff --git a/src/weather/mod.rs b/src/weather/mod.rs index a36d5d4..22e145e 100644 --- a/src/weather/mod.rs +++ b/src/weather/mod.rs @@ -1,9 +1,10 @@ //! Live weather: fetch a forecast, resolve a place, synthesize a sky. //! -//! Three stages, each its own module. `location` turns a place name into coordinates, `forecast` fetches a seven-day hourly window from Open-Meteo, and `state` composes those into a `SkyState` for any instant in that window. `gradients` and `bortle` supply the palettes and the light-pollution model the composer draws on. +//! Three stages, each its own module. `location` turns a place name into coordinates, `forecast` fetches a 192-hour window from Open-Meteo (24 hours back, 168 forward) and `aerosol` the matching optical depth from the air-quality endpoint, and `state` composes those into a `SkyState` for any instant in that window. `gradients` and `bortle` supply the palettes and the light-pollution model the composer draws on. //! //! `WeatherError` distinguishes network, HTTP and decode failures, because the caller's response differs: a network blip is worth retrying, a schema change is not. Nothing here panics on bad input; a failed fetch becomes a dark sky carrying the error message in its footer. +pub mod aerosol; pub mod bortle; pub mod forecast; mod gradients; diff --git a/src/weather/state.rs b/src/weather/state.rs index 9040ed4..0a566d3 100644 --- a/src/weather/state.rs +++ b/src/weather/state.rs @@ -1,12 +1,12 @@ //! 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; and one `Atmosphere` built from the reported visibility feeds both the haze layer and the analytic sky. +//! `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; the rain, showers and snowfall fields decide what falls and the WMO code whether a storm gets lightning; the model's own direct beam decides how much of the sun and of the clear-sky model to draw; and one `Atmosphere` built from optical depth, or visibility when that is missing, 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. //! -//! Times are UTC everywhere inside. Open-Meteo returns local strings under `timezone=auto`, so they are converted in at the boundary and back out only for display. +//! Times are unix UTC seconds straight from the forecast. The location's offset is applied only for display and for finding the local day in the daily block. -use chrono::{Datelike, NaiveDateTime, TimeZone, Timelike, Utc}; +use chrono::{Datelike, TimeZone, Timelike, Utc}; use crate::analytic_sky::AnalyticSky; use crate::astro::{self, AltAz}; @@ -22,7 +22,7 @@ use crate::snow::{self, FlakeForm, Snowfall}; use super::WeatherError; use super::bortle; use super::forecast::{DailyArrays, Forecast}; -use super::gradients::{Palette, gradient_for, sky_gradient}; +use super::gradients::{Palette, fog_gradient, gradient_for, sky_gradient}; use super::location::GeoResult; const KEYS_HINT: &str = "<- -> scrub tab day t now l location ? help q quit"; @@ -44,7 +44,13 @@ struct HourSample { cover_mid: f64, cover_high: f64, precip_mm: Option, + rain_mm: Option, + showers_mm: Option, snowfall_cm: Option, + precip_probability: Option, + cape: Option, + dni: Option, + aod_550: Option, wind_speed: Option, wind_dir: Option, visibility_m: Option, @@ -62,7 +68,17 @@ impl HourSample { 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], + rain_mm: hr.rain.get(h).copied().flatten(), + showers_mm: hr.showers.get(h).copied().flatten(), snowfall_cm: hr.snowfall.get(h).copied().flatten(), + precip_probability: hr.precipitation_probability.get(h).copied().flatten(), + cape: hr.cape.get(h).copied().flatten(), + dni: hr + .direct_normal_irradiance_instant + .get(h) + .copied() + .flatten(), + aod_550: hr.aerosol_optical_depth.get(h).copied().flatten(), wind_speed: hr.wind_speed_10m[h], wind_dir: hr.wind_direction_10m[h], visibility_m: hr.visibility[h], @@ -81,7 +97,13 @@ impl HourSample { 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), + rain_mm: lerp_opt(a.rain_mm, b.rain_mm, frac), + showers_mm: lerp_opt(a.showers_mm, b.showers_mm, frac), snowfall_cm: lerp_opt(a.snowfall_cm, b.snowfall_cm, frac), + precip_probability: lerp_opt(a.precip_probability, b.precip_probability, frac), + cape: lerp_opt(a.cape, b.cape, frac), + dni: lerp_opt(a.dni, b.dni, frac), + aod_550: lerp_opt(a.aod_550, b.aod_550, 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), @@ -146,7 +168,7 @@ impl Default for ComposeOpts { /// /// # Errors /// -/// [`WeatherError::Decode`] if the forecast's hour timestamp cannot be parsed. The hourly measurements are all optional, so a forecast with gaps in them still composes. +/// None today. The hourly measurements are all optional, so a forecast with gaps in them still composes; the `Result` stays so a forecast shape that cannot compose has somewhere to go without changing every caller. pub fn compose( forecast: &Forecast, location: &GeoResult, @@ -155,7 +177,7 @@ pub fn compose( opts: ComposeOpts, ) -> Result { let h = hour_index.min(forecast.hourly.len().saturating_sub(1)); - let unix_utc = parse_hour_to_unix(&forecast.hourly.time[h], forecast.utc_offset_seconds)?; + let unix_utc = forecast.hourly.time[h]; let sample = HourSample::at(forecast, h); Ok(build_sky( &sample, @@ -172,7 +194,7 @@ pub fn compose( /// /// # Errors /// -/// [`WeatherError::Decode`] if the forecast timestamps bracketing `target_unix` cannot be parsed. +/// None today, for the same reason as [`compose`]. pub fn compose_at( forecast: &Forecast, location: &GeoResult, @@ -180,7 +202,7 @@ pub fn compose_at( now_unix: i64, opts: ComposeOpts, ) -> Result { - let (h0, h1, frac) = bracket_hours(forecast, target_unix)?; + let (h0, h1, frac) = bracket_hours(forecast, target_unix); let sample = HourSample::interpolated(forecast, h0, h1, frac); Ok(build_sky( &sample, @@ -194,29 +216,16 @@ pub fn compose_at( } // Locate the two forecast hours straddling target_unix and the 0..1 fraction between them. Clamps to the ends when the target falls outside the range. -fn bracket_hours( - forecast: &Forecast, - target_unix: i64, -) -> Result<(usize, usize, f64), WeatherError> { +fn bracket_hours(forecast: &Forecast, target_unix: i64) -> (usize, usize, f64) { let times = &forecast.hourly.time; - let offset = forecast.utc_offset_seconds; let last = times.len().saturating_sub(1); - let mut h0 = 0usize; - for (i, t) in times.iter().enumerate() { - if parse_hour_to_unix(t, offset)? <= target_unix { - h0 = i; - } else { - break; - } - } + let h0 = times.iter().rposition(|&t| t <= target_unix).unwrap_or(0); if h0 >= last { - return Ok((last, last, 0.0)); + return (last, last, 0.0); } - let t0 = parse_hour_to_unix(×[h0], offset)?; - let t1 = parse_hour_to_unix(×[h0 + 1], offset)?; - let span = (t1 - t0).max(1) as f64; - let frac = ((target_unix - t0) as f64 / span).clamp(0.0, 1.0); - Ok((h0, h0 + 1, frac)) + let span = (times[h0 + 1] - times[h0]).max(1) as f64; + let frac = ((target_unix - times[h0]) as f64 / span).clamp(0.0, 1.0); + (h0, h0 + 1, frac) } fn build_sky( @@ -238,33 +247,54 @@ 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 atmosphere = Atmosphere::from_readings(sample.visibility_m, sample.aod_550); let total_cover = total_cover( sample.reported_cover, sample.cover_low, sample.cover_mid, sample.cover_high, ); + let sun_through = sun_transmission(sun_altaz.altitude, sample.dni, total_cover); + let fog = fog_density( + sample.weather_code, + sample.relative_humidity, + sample.visibility_m, + ); + let socked_in = fog.is_some_and(|density| density > 0.5); let mut gradient = sky_gradient(sun_altaz.altitude, total_cover); + if let Some(density) = fog { + gradient = fog_gradient(&gradient, sun_altaz.altitude, density); + } bortle::apply_glow(&mut gradient, bortle, sun_altaz.altitude); let day_ordinal = unix_utc.div_euclid(86_400); - let sun = build_sun(&sun_altaz, center_az); + let sun = build_sun(&sun_altaz, center_az, sun_through); let moon = build_moon(&moon_state, center_az); - let stars = build_stars(sun_altaz.altitude, lat, lon, day_ordinal, bortle); + let stars = if socked_in { + None + } else { + build_stars(sun_altaz.altitude, lat, lon, day_ordinal, bortle) + }; + let low_kind = low_cloud_kind( + sample.weather_code.unwrap_or(0), + sample.cover_low, + sample.showers_mm.unwrap_or(0.0), + ); let clouds = build_clouds( sample.cover_low, sample.cover_mid, sample.cover_high, - sample.weather_code, + low_kind, lat, lon, day_ordinal, ); // A bright-but-clouded daytime sky needs its own horizon haze regardless of reported visibility; this matches the old CloudyDay palette regime. let cloudy_day = sun_altaz.altitude > 3.0 && (0.50..0.80).contains(&total_cover); - let haze = if cloudy_day { + let haze = if let Some(density) = fog { + Some(fog_veil(density, sun_altaz.altitude)) + } else if cloudy_day { Some(Haze { rgb: [178, 174, 165], onset_t: 0.55, @@ -274,9 +304,17 @@ fn build_sky( } else { build_haze(&atmosphere) }; + // Rain and showers are the liquid share of the total; when neither was reported the total stands in and the code has to say whether it fell as snow. + let (liquid_mm, split_reported) = match (sample.rain_mm, sample.showers_mm) { + (None, None) => (sample.precip_mm, false), + (rain, showers) => (Some(rain.unwrap_or(0.0) + showers.unwrap_or(0.0)), true), + }; + let certainty = precipitation_certainty(sample.precip_probability); let precipitation = build_precipitation( sample.weather_code, - sample.precip_mm, + liquid_mm, + split_reported, + certainty, sample.wind_dir, lat, lon, @@ -286,6 +324,7 @@ fn build_sky( let snowfall = build_snowfall( sample.weather_code, sample.snowfall_cm, + certainty, sample.temperature_c, sample.relative_humidity, sample.wind_dir, @@ -296,20 +335,30 @@ fn build_sky( 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, - total_cover, + let lightning = build_lightning( + sample.weather_code, + sample.precip_mm, + sample.cape, lat, lon, unix_utc, - center_az, - opts.bortle, ); + let meteors = if socked_in { + None + } else { + build_meteors( + sun_altaz.altitude, + total_cover, + lat, + lon, + unix_utc, + center_az, + opts.bortle, + ) + }; - let date_iso = utc_date_iso(unix_utc + offset); - let sun_day = daily.and_then(|d| sun_day_for(d, &date_iso, offset)); - let high_low = daily.and_then(|d| daily_high_low(d, &date_iso)); + let sun_day = daily.and_then(|d| sun_day_for(d, unix_utc, offset)); + let high_low = daily.and_then(|d| daily_high_low(d, unix_utc, offset)); let chrome = build_chrome( location, unix_utc, now_unix, offset, sample, sun_day, high_low, @@ -321,8 +370,8 @@ fn build_sky( sun_az: sun_altaz.azimuth, center_az, 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), + // 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; Preetham's zenith formula is not to be trusted that low anyway. And it is weighted by how much of the beam gets through, 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. Cover used to do that job and did it too well, since a veil of cirrus reports full cover and hides nothing; the beam fraction lets the clear sky show through exactly as much as the sun does. + blend: (sun_altaz.altitude / 8.0).clamp(0.0, 1.0) * sun_through, }); SkyState { @@ -374,6 +423,7 @@ fn lerp_angle_opt(a: Option, b: Option, f: f64) -> Option { fn build_lightning( weather_code: Option, precip_mm: Option, + cape: Option, lat: f64, lon: f64, unix_utc: i64, @@ -383,14 +433,76 @@ fn build_lightning( return None; } let with_bolts = matches!(code, 95 | 96 | 99); - let mm = precip_mm.unwrap_or(0.4); - let intensity = (mm / 5.0).clamp(0.20, 0.85); + let intensity = storm_intensity(cape, precip_mm); let hour = unix_utc.div_euclid(3_600) as u64; let day_ordinal = unix_utc.div_euclid(86_400) as u64; let seed = mix_seed(&[hash_lat_lon(lat, lon), day_ordinal, hour, 0x1167_8175]) as u32; Some(Lightning::new(seed, intensity, 3_600.0, with_bolts)) } +// The code only says a storm exists; CAPE is its fuel, and 2500 J/kg is the conventional mark for large instability. Without it the rain rate stands in, which makes a wet stratiform storm flash harder than a dry violent one. +fn storm_intensity(cape: Option, precip_mm: Option) -> f64 { + match cape { + Some(cape) => (cape / 2500.0).clamp(0.20, 0.85), + None => (precip_mm.unwrap_or(0.4) / 5.0).clamp(0.20, 0.85), + } +} + +// Extraterrestrial normal irradiance in W/m2. The 3.3 percent annual swing from the earth-sun distance is far below the clear-sky model's own error, so it is not tracked. +const SOLAR_CONSTANT: f64 = 1361.0; + +/// How much of the sun gets through, 0 under a deck and 1 on a clear day: the model's direct beam against what a clean atmosphere would pass at this elevation. +/// +/// This is the quantity the analytic sky's weight and the sun disc both want, and it beats cloud cover for both because cover is opaque by definition: a full sky of thin cirrus reports 100 percent and lets most of the beam through. The clean-atmosphere reference is Meinel's fit, `0.7^(m^0.678)` with Kasten-Young air mass, which lands on measured clear-sky DNI within about ten percent above ten degrees of elevation. Below that both the fit and the model drift, and that is the band the altitude ramp on the analytic blend already fades. Without a beam reading the old cover fade stands in. +fn sun_transmission(sun_alt_deg: f64, dni: Option, total_cover: f64) -> f64 { + match dni { + Some(dni) if sun_alt_deg > 0.0 => { + (dni / SOLAR_CONSTANT / clear_sky_beam(sun_alt_deg)).clamp(0.0, 1.0) + } + _ => (1.0 - total_cover).clamp(0.0, 1.0), + } +} + +fn clear_sky_beam(sun_alt_deg: f64) -> f64 { + let alt = sun_alt_deg.max(0.0); + let air_mass = 1.0 / (alt.to_radians().sin() + 0.50572 * (alt + 6.07995).powf(-1.6364)); + 0.7f64.powf(air_mass.powf(0.678)) +} + +// A twenty percent chance on day six must not paint the same downpour as certain rain in an hour. The floor keeps light-but-certain rain from vanishing when a model reports low probabilities for drizzle. +fn precipitation_certainty(probability_pct: Option) -> f64 { + probability_pct.map_or(1.0, |p| (p / 100.0).clamp(0.3, 1.0)) +} + +/// Fog as a density in 0.4..=1, or `None` when the air is merely humid. Either the code says fog (45, 48) or the hour is saturated with under a kilometre of visibility, which is the WMO definition. Mist, one to four kilometres, stays with the ordinary haze curve, which is already at 0.8 by two. +fn fog_density( + weather_code: Option, + relative_humidity: Option, + visibility_m: Option, +) -> Option { + let coded = matches!(weather_code, Some(45 | 48)); + let saturated = + relative_humidity.is_some_and(|rh| rh >= 97.0) && visibility_m.is_some_and(|v| v < 1000.0); + if !coded && !saturated { + return None; + } + Some(visibility_m.map_or(0.8, |v| (1.0 - v / 1000.0).clamp(0.4, 1.0))) +} + +// The fog scene's veil: a full-frame haze, daylight grey, going dark with the sun, since fog at night is lit only by whatever the ground throws up. +fn fog_veil(density: f64, sun_alt_deg: f64) -> Haze { + let night = bortle::night_factor(sun_alt_deg); + let day = [208.0, 207.0, 202.0]; + let dark = [60.0, 62.0, 66.0]; + let rgb = [0, 1, 2].map(|i| (day[i] + (dark[i] - day[i]) * night).round() as u8); + Haze { + rgb, + onset_t: 0.0, + strength: 0.55 + 0.30 * density, + exponent: 1.15, + } +} + // Meteors show on a dark, clear-enough sky: sun well below the horizon and not overcast. Seeded per (place, day) like the clouds and lightning. fn build_meteors( sun_alt: f64, @@ -413,13 +525,6 @@ fn build_meteors( )) } -// Open-Meteo returns its time strings already in the location's local zone (timezone=auto), so subtract the location's UTC offset to recover true UTC; the whole internal pipeline then runs in UTC. -fn parse_hour_to_unix(time_str: &str, offset: i64) -> Result { - let naive = NaiveDateTime::parse_from_str(time_str, "%Y-%m-%dT%H:%M") - .map_err(|e| WeatherError::Decode(format!("hour timestamp '{time_str}': {e}")))?; - Ok(naive.and_utc().timestamp() - offset) -} - #[derive(Debug, Clone, PartialEq)] enum SunDay { Times { rise_unix: i64, set_unix: i64 }, @@ -427,16 +532,22 @@ enum SunDay { PolarNight, } -fn utc_date_iso(unix_utc: i64) -> String { - Utc.timestamp_opt(unix_utc, 0) - .single() - .map(|dt| dt.date_naive().to_string()) - .unwrap_or_default() +fn local_day(unix: i64, offset: i64) -> i64 { + (unix + offset).div_euclid(86_400) +} + +// Daily rows are local days and carry the instant of their local midnight, so the row for an hour is the one whose midnight falls on the same local date. +fn daily_row(daily: &DailyArrays, unix_utc: i64, offset: i64) -> Option { + let day = local_day(unix_utc, offset); + daily + .time + .iter() + .position(|&midnight| local_day(midnight, offset) == day) } -// Open-Meteo encodes polar day/night as sentinel values, not nulls: polar day -> daylight_duration == 86400, sunrise YYYY-MM-DDT00:00, sunset next-day T00:00. polar night -> daylight_duration == 0, sunrise == sunset == YYYY-MM-DDT00:00. Slop guards (>= 86_399, <= 1) are insurance against future float drift, not currently needed. -fn sun_day_for(daily: &DailyArrays, date_iso: &str, offset: i64) -> Option { - let i = daily.time.iter().position(|d| d == date_iso)?; +// Open-Meteo encodes polar day/night as sentinel values, not nulls: polar day -> daylight_duration == 86400, sunrise at local midnight, sunset at the next one. polar night -> daylight_duration == 0, sunrise == sunset == local midnight. Slop guards (>= 86_399, <= 1) are insurance against future float drift, not currently needed. +fn sun_day_for(daily: &DailyArrays, unix_utc: i64, offset: i64) -> Option { + let i = daily_row(daily, unix_utc, offset)?; let dur = daily.daylight_duration.get(i).copied()?; if dur >= 86_399.0 { return Some(SunDay::PolarDay); @@ -444,17 +555,15 @@ fn sun_day_for(daily: &DailyArrays, date_iso: &str, offset: i64) -> Option Option<(f64, f64)> { - let i = daily.time.iter().position(|d| d == date_iso)?; +fn daily_high_low(daily: &DailyArrays, unix_utc: i64, offset: i64) -> Option<(f64, f64)> { + let i = daily_row(daily, unix_utc, offset)?; let high = daily.temperature_2m_max.get(i).copied().flatten()?; let low = daily.temperature_2m_min.get(i).copied().flatten()?; Some((high, low)) @@ -484,7 +593,7 @@ fn format_sun_segment(sun_day: Option<&SunDay>, offset: i64) -> String { } } -fn build_sun(altaz: &AltAz, center_az: f64) -> Sun { +fn build_sun(altaz: &AltAz, center_az: f64, strength: f64) -> Sun { // Behind the viewing plane there is no screen position at all; park the disc off-frame and let `visible` do the hiding. let (x_frac, y_frac) = astro::to_sky_fracs(altaz, center_az).unwrap_or((-1.0, -1.0)); let in_view = astro::in_view(altaz, center_az); @@ -492,7 +601,8 @@ fn build_sun(altaz: &AltAz, center_az: f64) -> Sun { x_frac, y_frac, radius: 3.5, - visible: altaz.altitude > -2.0 && in_view, + visible: altaz.altitude > -2.0 && in_view && strength > 0.02, + strength, } } @@ -576,25 +686,17 @@ fn build_clouds( cover_low: f64, cover_mid: f64, cover_high: f64, - weather_code: Option, + low_kind: CloudKind, lat: f64, lon: f64, day_ordinal: i64, ) -> Vec { let pos_hash = hash_lat_lon(lat, lon); - let code = weather_code.unwrap_or(0); let mut layers = Vec::new(); let bands = [ (cover_high, 0.20, 4.5, 2.4, 0u32, CloudKind::Cirrus), (cover_mid, 0.40, 3.6, 2.4, 1, CloudKind::Altocumulus), - ( - cover_low, - 0.60, - 3.0, - 2.2, - 2, - low_cloud_kind(code, cover_low), - ), + (cover_low, 0.60, 3.0, 2.2, 2, low_kind), ]; for (cover, altitude_t, scale_x, scale_y, idx, kind) in bands { let seed = mix_seed(&[pos_hash, day_ordinal as u64, 0xC10D_5EED ^ idx as u64]); @@ -605,9 +707,9 @@ fn build_clouds( layers } -// The low band carries the weather: showers and thunderstorms are convective towers (dark cumulonimbus), light/partly-cloudy skies are fair-weather cumulus, and anything else is a flat stratus deck. -fn low_cloud_kind(weather_code: u32, cover_low: f64) -> CloudKind { - if (80..=82).contains(&weather_code) || (95..=99).contains(&weather_code) { +// The low band carries the weather: showers and thunderstorms are convective towers (dark cumulonimbus), light/partly-cloudy skies are fair-weather cumulus, and anything else is a flat stratus deck. Any convective rain at all is a tower whatever the code says, since the code reports the dominant weather and an hour of rain with showers in it is still built of cumulonimbus. +fn low_cloud_kind(weather_code: u32, cover_low: f64, showers_mm: f64) -> CloudKind { + if showers_mm >= 0.1 || (80..=82).contains(&weather_code) || (95..=99).contains(&weather_code) { CloudKind::Cumulonimbus } else if matches!(weather_code, 1 | 2) && cover_low < 0.6 { CloudKind::Cumulus @@ -679,6 +781,7 @@ fn is_snow_code(weather_code: Option) -> bool { fn build_snowfall( weather_code: Option, snowfall_cm: Option, + certainty: f64, temperature_c: Option, relative_humidity: Option, wind_dir: Option, @@ -701,7 +804,9 @@ fn build_snowfall( ); Some(Snowfall { form, - count: snow::flake_count(rate), + count: (f64::from(snow::flake_count(rate)) * certainty) + .round() + .max(1.0) as u32, seed: mix_seed(&[ hash_lat_lon(lat, lon), day_ordinal as u64, @@ -724,23 +829,27 @@ fn snow_drift(wind_dir: Option, wind_speed: Option, center_az: f64) -> (lateral * speed * 0.0025).clamp(-0.12, 0.12) } +/// Rain streaks for this hour, from the liquid share of what fell. `split_reported` says whether that share came from the rain and showers fields or is the whole total, in which case the code has to keep snow hours away from the rain renderer; with the split, a sleet hour draws both. +#[allow(clippy::too_many_arguments)] fn build_precipitation( weather_code: Option, - precip_mm: Option, + liquid_mm: Option, + split_reported: bool, + certainty: f64, wind_dir: Option, lat: f64, lon: f64, day_ordinal: i64, center_az: f64, ) -> Option { - let mm = precip_mm.unwrap_or(0.0); + let mm = liquid_mm.unwrap_or(0.0); if mm < 0.10 { return None; } - if is_snow_code(weather_code) { + if !split_reported && is_snow_code(weather_code) { return None; } - let intensity = (mm / 5.0).clamp(0.10, 0.85); + let intensity = (mm / 5.0).clamp(0.10, 0.85) * certainty; 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); @@ -919,6 +1028,7 @@ pub fn error_sky(msg: &str) -> SkyState { y_frac: 1.5, radius: 0.0, visible: false, + strength: 0.0, }, clouds: vec![], chrome: Chrome { @@ -968,24 +1078,14 @@ mod tests { assert_eq!(mix_seed(&[1, 2]), 0x7717_9803_63c8_e066); } - #[test] - fn parse_hour_round_trip() { - let unix = parse_hour_to_unix("2026-04-11T00:00", 0).unwrap(); - // 2026-04-11T00:00:00Z, verified against `date -u -d @1775865600` - assert_eq!(unix, 1_775_865_600); - } - - #[test] - fn parse_hour_subtracts_local_offset() { - // Under timezone=auto the string is local; UTC+8 02:00 is 18:00Z prior. - let local = parse_hour_to_unix("2026-06-16T02:00", 8 * 3600).unwrap(); - let utc = parse_hour_to_unix("2026-06-15T18:00", 0).unwrap(); - assert_eq!(local, utc); - } + // 2026-06-15T18:00Z, verified against `date -u -r 1781546400`. + const JUNE_15_18Z: i64 = 1_781_546_400; + // 2026-04-11T00:00Z, the forecast fixture's first hour. + const APRIL_11: i64 = 1_775_865_600; #[test] fn local_hhmm_applies_offset() { - let unix = parse_hour_to_unix("2026-06-15T18:00", 0).unwrap(); + let unix = JUNE_15_18Z; assert_eq!(local_hhmm(unix, 8 * 3600), "02:00"); assert_eq!(local_hhmm(unix, 0), "18:00"); } @@ -993,7 +1093,7 @@ mod tests { #[test] fn format_label_uses_location_offset_not_machine() { // 18:00Z is 02:00 the next local day at UTC+8; with "now" at the same instant the header reads the location's wall clock, not the machine's. - let unix = parse_hour_to_unix("2026-06-15T18:00", 0).unwrap(); + let unix = JUNE_15_18Z; assert_eq!(format_label(unix, unix, 8 * 3600), "today 02:00"); let next = unix + 86_400; assert_eq!(format_label(next, unix, 8 * 3600), "tomorrow 02:00"); @@ -1059,15 +1159,15 @@ mod tests { } fn daily_one_day( - date: &str, - sunrise: &str, - sunset: &str, + midnight: i64, + sunrise: i64, + sunset: i64, daylight_duration: f64, ) -> DailyArrays { DailyArrays { - time: vec![date.to_string()], - sunrise: vec![sunrise.to_string()], - sunset: vec![sunset.to_string()], + time: vec![midnight], + sunrise: vec![sunrise], + sunset: vec![sunset], daylight_duration: vec![daylight_duration], temperature_2m_max: vec![], temperature_2m_min: vec![], @@ -1076,18 +1176,13 @@ mod tests { #[test] fn sun_day_normal_returns_times() { - let daily = daily_one_day( - "2026-04-11", - "2026-04-11T04:38", - "2026-04-11T18:14", - 48_960.0, - ); - match sun_day_for(&daily, "2026-04-11", 0) { + // +4h38m = +16_680, +18h14m = +65_640. + let daily = daily_one_day(APRIL_11, APRIL_11 + 16_680, APRIL_11 + 65_640, 48_960.0); + match sun_day_for(&daily, APRIL_11 + 12 * 3_600, 0) { Some(SunDay::Times { rise_unix, set_unix, }) => { - // 2026-04-11T00:00Z = 1_775_865_600 (per parse_hour_round_trip); +4h38m = +16_680, +18h14m = +65_640. assert_eq!(rise_unix, 1_775_882_280); assert_eq!(set_unix, 1_775_931_240); } @@ -1097,40 +1192,48 @@ mod tests { #[test] fn sun_day_polar_day_from_full_daylight() { - let daily = daily_one_day( - "2026-05-09", - "2026-05-09T00:00", - "2026-05-10T00:00", - 86_400.0, + let may_9 = APRIL_11 + 28 * 86_400; + let daily = daily_one_day(may_9, may_9, may_9 + 86_400, 86_400.0); + assert_eq!( + sun_day_for(&daily, may_9 + 3_600, 0), + Some(SunDay::PolarDay) ); - assert_eq!(sun_day_for(&daily, "2026-05-09", 0), Some(SunDay::PolarDay)); } #[test] fn sun_day_polar_night_from_zero_daylight() { - let daily = daily_one_day("2025-12-22", "2025-12-22T00:00", "2025-12-22T00:00", 0.0); + let dec_22 = APRIL_11 - 110 * 86_400; + let daily = daily_one_day(dec_22, dec_22, dec_22, 0.0); assert_eq!( - sun_day_for(&daily, "2025-12-22", 0), + sun_day_for(&daily, dec_22 + 3_600, 0), Some(SunDay::PolarNight) ); } #[test] fn sun_day_unknown_date_returns_none() { - let daily = daily_one_day( - "2026-04-11", - "2026-04-11T04:38", - "2026-04-11T18:14", - 48_960.0, + let daily = daily_one_day(APRIL_11, APRIL_11 + 16_680, APRIL_11 + 65_640, 48_960.0); + assert_eq!(sun_day_for(&daily, APRIL_11 + 86_400, 0), None); + } + + #[test] + fn daily_row_follows_the_local_date_not_the_utc_one() { + // Local midnight at UTC+2 is 22:00Z the evening before. 23:00 local is still that row; 00:30 local the next day is not, though it is the same UTC date. + let offset = 2 * 3_600; + let midnight = APRIL_11 - offset; + let daily = daily_one_day(midnight, midnight + 16_680, midnight + 65_640, 48_960.0); + assert_eq!(daily_row(&daily, midnight + 23 * 3_600, offset), Some(0)); + assert_eq!( + daily_row(&daily, midnight + 24 * 3_600 + 1_800, offset), + None ); - assert_eq!(sun_day_for(&daily, "2026-04-12", 0), None); } - fn daily_with_high_low(date: &str, high: Option, low: Option) -> DailyArrays { + fn daily_with_high_low(midnight: i64, high: Option, low: Option) -> DailyArrays { DailyArrays { - time: vec![date.to_string()], - sunrise: vec![format!("{date}T06:00")], - sunset: vec![format!("{date}T20:00")], + time: vec![midnight], + sunrise: vec![midnight + 6 * 3_600], + sunset: vec![midnight + 20 * 3_600], daylight_duration: vec![48_960.0], temperature_2m_max: vec![high], temperature_2m_min: vec![low], @@ -1139,23 +1242,104 @@ mod tests { #[test] fn daily_high_low_reads_matching_day() { - let daily = daily_with_high_low("2026-06-15", Some(22.4), Some(14.6)); - assert_eq!(daily_high_low(&daily, "2026-06-15"), Some((22.4, 14.6))); + let daily = daily_with_high_low(APRIL_11, Some(22.4), Some(14.6)); + assert_eq!( + daily_high_low(&daily, APRIL_11 + 15 * 3_600, 0), + Some((22.4, 14.6)) + ); } #[test] fn daily_high_low_missing_end_returns_none() { - let daily = daily_with_high_low("2026-06-15", Some(22.0), None); - assert_eq!(daily_high_low(&daily, "2026-06-15"), None); - assert_eq!(daily_high_low(&daily, "2026-06-16"), None); + let daily = daily_with_high_low(APRIL_11, Some(22.0), None); + assert_eq!(daily_high_low(&daily, APRIL_11, 0), None); + assert_eq!(daily_high_low(&daily, APRIL_11 + 86_400, 0), None); } #[test] - fn utc_date_iso_round_trip() { - // 2026-04-11T00:00Z - assert_eq!(utc_date_iso(1_775_865_600), "2026-04-11"); - // 2026-04-11T23:59Z still resolves to the same UTC date - assert_eq!(utc_date_iso(1_775_865_600 + 86_399), "2026-04-11"); + fn sun_transmission_reads_the_beam_when_there_is_one() { + // A clean noon: Meinel passes about two thirds of the constant at 60 degrees, and the model reports exactly that much. + let clear_noon = clear_sky_beam(60.0); + assert!(clear_noon > 0.62 && clear_noon < 0.72, "got {clear_noon}"); + assert!( + (sun_transmission(60.0, Some(SOLAR_CONSTANT * clear_noon), 0.0) - 1.0).abs() < 1e-9 + ); + assert_eq!( + sun_transmission(60.0, Some(0.0), 0.0), + 0.0, + "no beam under a deck" + ); + let cirrus = sun_transmission(45.0, Some(400.0), 1.0); + assert!( + cirrus > 0.3 && cirrus < 0.8, + "a veil reports full cover and still passes some sun, got {cirrus}" + ); + assert_eq!( + sun_transmission(45.0, None, 0.25), + 0.75, + "no beam reading falls back to cover" + ); + assert_eq!( + sun_transmission(-1.0, Some(0.0), 0.25), + 0.75, + "below the horizon the beam says nothing" + ); + } + + #[test] + fn storm_intensity_prefers_cape() { + assert_eq!(storm_intensity(Some(3_000.0), Some(0.2)), 0.85); + assert_eq!(storm_intensity(Some(400.0), Some(4.0)), 0.20); + assert_eq!(storm_intensity(None, Some(2.5)), 0.5); + } + + #[test] + fn fog_needs_saturation_and_a_short_view_or_the_code() { + assert_eq!(fog_density(Some(0), Some(99.0), Some(300.0)), Some(0.7)); + assert_eq!(fog_density(Some(0), Some(99.0), Some(8_000.0)), None); + assert_eq!(fog_density(Some(0), Some(80.0), Some(300.0)), None); + assert_eq!(fog_density(Some(45), None, None), Some(0.8)); + assert_eq!(fog_density(Some(48), Some(90.0), Some(5_000.0)), Some(0.4)); + } + + #[test] + fn showers_make_the_low_deck_convective() { + assert_eq!(low_cloud_kind(61, 0.8, 0.5), CloudKind::Cumulonimbus); + assert_eq!(low_cloud_kind(61, 0.8, 0.0), CloudKind::Stratus); + assert_eq!(low_cloud_kind(1, 0.3, 0.0), CloudKind::Cumulus); + } + + #[test] + fn precipitation_scales_with_its_probability() { + let certain = + build_precipitation(Some(61), Some(2.0), true, 1.0, None, 53.5, 10.0, 0, 180.0) + .expect("rain"); + let unlikely = build_precipitation( + Some(61), + Some(2.0), + true, + precipitation_certainty(Some(20.0)), + None, + 53.5, + 10.0, + 0, + 180.0, + ) + .expect("still drawn, fainter"); + assert!((unlikely.intensity - certain.intensity * 0.3).abs() < 1e-9); + assert_eq!(precipitation_certainty(None), 1.0); + } + + #[test] + fn a_split_total_lets_sleet_rain_while_a_bare_total_defers_to_the_code() { + assert!( + build_precipitation(Some(73), Some(1.0), true, 1.0, None, 53.5, 10.0, 0, 180.0) + .is_some() + ); + assert!( + build_precipitation(Some(73), Some(1.0), false, 1.0, None, 53.5, 10.0, 0, 180.0) + .is_none() + ); } #[test] diff --git a/tests/open-meteo-air-quality-hamburg.json b/tests/open-meteo-air-quality-hamburg.json new file mode 100644 index 0000000..71fb776 --- /dev/null +++ b/tests/open-meteo-air-quality-hamburg.json @@ -0,0 +1,31 @@ +{ + "latitude": 53.6, + "longitude": 10.0, + "generationtime_ms": 0.22113323211669922, + "utc_offset_seconds": 0, + "timezone": "GMT", + "timezone_abbreviation": "GMT", + "elevation": 3.0, + "hourly_units": { + "time": "unixtime", + "aerosol_optical_depth": "" + }, + "hourly": { + "time": [ + 1788721200, + 1788724800, + 1788728400, + 1788732000, + 1788735600, + 1788739200 + ], + "aerosol_optical_depth": [ + 0.19, + 0.21, + 0.22, + 0.19, + 0.16, + 0.13 + ] + } +} diff --git a/tests/open-meteo-forecast-hamburg.json b/tests/open-meteo-forecast-hamburg.json index 6c29f60..5c1e91e 100644 --- a/tests/open-meteo-forecast-hamburg.json +++ b/tests/open-meteo-forecast-hamburg.json @@ -7,27 +7,32 @@ "timezone_abbreviation": "GMT", "elevation": 3.0, "hourly_units": { - "time": "iso8601", - "temperature_2m": "\u00b0C", + "time": "unixtime", + "temperature_2m": "°C", + "relative_humidity_2m": "%", "cloud_cover_low": "%", "cloud_cover_mid": "%", "cloud_cover_high": "%", "precipitation": "mm", + "rain": "mm", + "showers": "mm", + "snowfall": "cm", + "precipitation_probability": "%", + "cape": "J/kg", + "direct_normal_irradiance_instant": "W/m²", "wind_speed_10m": "km/h", - "wind_direction_10m": "\u00b0", + "wind_direction_10m": "°", "visibility": "m", - "weather_code": "wmo code", - "relative_humidity_2m": "%", - "snowfall": "cm" + "weather_code": "wmo code" }, "hourly": { "time": [ - "2026-04-11T00:00", - "2026-04-11T01:00", - "2026-04-11T02:00", - "2026-04-11T03:00", - "2026-04-11T04:00", - "2026-04-11T05:00" + 1775865600, + 1775869200, + 1775872800, + 1775876400, + 1775880000, + 1775883600 ], "temperature_2m": [ 4.8, @@ -77,6 +82,22 @@ 0.0, 0.0 ], + "rain": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "showers": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], "snowfall": [ 0.0, 0.0, @@ -85,6 +106,30 @@ 0.0, 0.0 ], + "precipitation_probability": [ + 0, + 0, + 0, + 0, + 0, + 0 + ], + "cape": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "direct_normal_irradiance_instant": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 93.3 + ], "wind_speed_10m": [ 4.0, 4.0, @@ -119,22 +164,22 @@ ] }, "daily_units": { - "time": "iso8601", - "sunrise": "iso8601", - "sunset": "iso8601", + "time": "unixtime", + "sunrise": "unixtime", + "sunset": "unixtime", "daylight_duration": "s", - "temperature_2m_max": "\u00b0C", - "temperature_2m_min": "\u00b0C" + "temperature_2m_max": "°C", + "temperature_2m_min": "°C" }, "daily": { "time": [ - "2026-04-11" + 1775865600 ], "sunrise": [ - "2026-04-11T04:38" + 1775882280 ], "sunset": [ - "2026-04-11T18:14" + 1775931240 ], "daylight_duration": [ 48960.0 diff --git a/tests/open-meteo-forecast-with-nulls.json b/tests/open-meteo-forecast-with-nulls.json index 24f31fd..6e81d6c 100644 --- a/tests/open-meteo-forecast-with-nulls.json +++ b/tests/open-meteo-forecast-with-nulls.json @@ -7,24 +7,29 @@ "timezone_abbreviation": "GMT", "elevation": 0.0, "hourly_units": { - "time": "iso8601", - "temperature_2m": "\u00b0C", + "time": "unixtime", + "temperature_2m": "°C", + "relative_humidity_2m": "%", "cloud_cover_low": "%", "cloud_cover_mid": "%", "cloud_cover_high": "%", "precipitation": "mm", + "rain": "mm", + "showers": "mm", + "snowfall": "cm", + "precipitation_probability": "%", + "cape": "J/kg", + "direct_normal_irradiance_instant": "W/m²", "wind_speed_10m": "km/h", - "wind_direction_10m": "\u00b0", + "wind_direction_10m": "°", "visibility": "m", - "weather_code": "wmo code", - "relative_humidity_2m": "%", - "snowfall": "cm" + "weather_code": "wmo code" }, "hourly": { "time": [ - "2026-04-11T00:00", - "2026-04-11T01:00", - "2026-04-11T02:00" + 1775865600, + 1775869200, + 1775872800 ], "temperature_2m": [ 4.8, @@ -56,11 +61,36 @@ 0.0, 0.0 ], + "rain": [ + 0.0, + 0.0, + 0.0 + ], + "showers": [ + 0.0, + 0.0, + 0.0 + ], "snowfall": [ 0.0, 0.0, 0.0 ], + "precipitation_probability": [ + 0, + 0, + 0 + ], + "cape": [ + 0.0, + 0.0, + 0.0 + ], + "direct_normal_irradiance_instant": [ + 0.0, + 0.0, + 0.0 + ], "wind_speed_10m": [ 4.0, 4.0, diff --git a/tests/weather.rs b/tests/weather.rs index f63e35b..bdd8ef1 100644 --- a/tests/weather.rs +++ b/tests/weather.rs @@ -1,3 +1,4 @@ +use celsius::weather::aerosol::{AerosolForecast, AerosolHourly}; use celsius::weather::forecast::Forecast; use celsius::weather::location::GeoResult; use serde::Deserialize; @@ -11,6 +12,7 @@ struct GeoResponse { const GEOCODING_HAMBURG: &str = include_str!("open-meteo-geocoding-hamburg.json"); const FORECAST_HAMBURG: &str = include_str!("open-meteo-forecast-hamburg.json"); const FORECAST_NULLS: &str = include_str!("open-meteo-forecast-with-nulls.json"); +const AIR_QUALITY_HAMBURG: &str = include_str!("open-meteo-air-quality-hamburg.json"); #[test] fn geocoding_response_parses_hamburg() { @@ -80,10 +82,10 @@ fn forecast_response_parses_hamburg() { assert!((parsed.latitude - 53.56).abs() < 0.1); assert!((parsed.longitude - 10.0).abs() < 0.1); assert_eq!(parsed.timezone, "GMT"); - // Fixture predates timezone=auto and carries no offset; serde defaults it to 0, so its UTC times survive the local->UTC boundary unchanged. + // Fixture predates timezone=auto and carries no offset; serde defaults it to 0. assert_eq!(parsed.utc_offset_seconds, 0); assert_eq!(parsed.hourly.len(), 6); - assert_eq!(parsed.hourly.time[0], "2026-04-11T00:00"); + assert_eq!(parsed.hourly.time[0], 1_775_865_600, "2026-04-11T00:00Z"); assert_eq!(parsed.hourly.temperature_2m[0], Some(4.8)); assert_eq!(parsed.hourly.weather_code[0], Some(0)); let daily = parsed.daily.expect("daily block present"); @@ -100,7 +102,7 @@ fn forecast_captures_utc_offset_when_present() { "timezone": "Asia/Hong_Kong", "utc_offset_seconds": 28800, "hourly": { - "time": ["2026-06-16T02:00"], + "time": [1781546400], "temperature_2m": [28.0], "cloud_cover_low": [10.0], "cloud_cover_mid": [0.0], @@ -130,6 +132,125 @@ fn forecast_equal_length_across_variables() { assert_eq!(h.wind_direction_10m.len(), n); assert_eq!(h.visibility.len(), n); assert_eq!(h.weather_code.len(), n); + assert_eq!(h.rain.len(), n); + assert_eq!(h.showers.len(), n); + assert_eq!(h.cape.len(), n); + assert_eq!(h.direct_normal_irradiance_instant.len(), n); + assert_eq!(h.precipitation_probability.len(), n); + assert!( + h.aerosol_optical_depth.is_empty(), + "optical depth never arrives in the forecast response; it is attached" + ); +} + +/// The air-quality endpoint answers on the forecast's hourly grid but with its own horizon, so attaching is a timestamp match and every hour it does not cover stays unknown. +#[test] +fn aerosol_response_parses_and_attaches_by_timestamp() { + let parsed: AerosolForecast = + serde_json::from_str(AIR_QUALITY_HAMBURG).expect("air-quality fixture must deserialize"); + assert_eq!(parsed.hourly.time.len(), 6); + assert_eq!(parsed.hourly.aerosol_optical_depth[0], Some(0.19)); + + let mut forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + let t0 = forecast.hourly.time[0]; + let partial = AerosolForecast { + hourly: AerosolHourly { + time: vec![t0 - 3_600, t0, t0 + 3_600, t0 + 3 * 3_600], + aerosol_optical_depth: vec![Some(0.9), Some(0.1), None, Some(0.6)], + }, + }; + forecast.attach_aerosol(&partial); + assert_eq!( + forecast.hourly.aerosol_optical_depth, + vec![Some(0.1), None, None, Some(0.6), None, None] + ); +} + +/// Optical depth is the column the analytic sky's turbidity describes, so when it is attached it wins over the visibility curve, and when it is not the visibility curve still stands. +#[test] +fn optical_depth_sets_the_analytic_turbidity() { + let mut forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + let opts = celsius::weather::ComposeOpts::default().with_analytic(true); + let t05 = 1_775_865_600 + 5 * 3_600; // sun just up, so an analytic sky is attached + let from_visibility = celsius::weather::compose_at(&forecast, &hamburg_geo(), t05, t05, opts) + .unwrap() + .analytic + .expect("daytime attaches the analytic sky") + .atmosphere + .turbidity; + assert_eq!( + from_visibility, + celsius::atmosphere::turbidity_from_visibility(forecast.hourly.visibility[5]) + ); + + let hazy = AerosolForecast { + hourly: AerosolHourly { + time: forecast.hourly.time.clone(), + aerosol_optical_depth: vec![Some(0.6); 6], + }, + }; + forecast.attach_aerosol(&hazy); + let from_aod = celsius::weather::compose_at(&forecast, &hamburg_geo(), t05, t05, opts) + .unwrap() + .analytic + .unwrap() + .atmosphere + .turbidity; + assert!( + (from_aod - 7.0).abs() < 0.05, + "AOD 0.6 is turbidity 7, got {from_aod}" + ); +} + +/// The beam is what says whether you can see the sun. At the fixture's hour 5 the model passes 93 W/m2 of a low sun, which is a visible but softened disc; with the beam zeroed the disc goes with it, whatever the cover fields say. +#[test] +fn the_sun_dims_with_the_beam() { + let mut forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + let facing_east = celsius::weather::ComposeOpts::new(90.0); + let t05 = 1_775_865_600 + 5 * 3_600; + let lit = celsius::weather::compose_at(&forecast, &hamburg_geo(), t05, t05, facing_east) + .unwrap() + .sun; + assert!(lit.visible, "the morning sun is in an east-facing frame"); + assert!( + lit.strength > 0.3 && lit.strength < 0.9, + "a low clear sun passes part of Meinel's beam, got {}", + lit.strength + ); + + for h in 0..forecast.hourly.time.len() { + forecast.hourly.direct_normal_irradiance_instant[h] = Some(0.0); + } + let hidden = celsius::weather::compose_at(&forecast, &hamburg_geo(), t05, t05, facing_east) + .unwrap() + .sun; + assert!(!hidden.visible, "no beam, no disc"); + assert_eq!(hidden.strength, 0.0); +} + +/// Fog is the one condition that has to reach the whole frame: a saturated hour with a few hundred metres of visibility becomes a full-frame veil and takes the stars with it, while the same humidity with a long view is the ordinary horizon haze. +#[test] +fn fog_hours_veil_the_frame_and_hide_the_stars() { + let mut forecast: Forecast = serde_json::from_str(FORECAST_HAMBURG).unwrap(); + let opts = celsius::weather::ComposeOpts::default(); + let t00 = 1_775_865_600; // night + for h in 0..forecast.hourly.time.len() { + forecast.hourly.relative_humidity_2m[h] = Some(99.0); + forecast.hourly.visibility[h] = Some(300.0); + } + let fogged = celsius::weather::compose_at(&forecast, &hamburg_geo(), t00, t00, opts).unwrap(); + let veil = fogged.haze.expect("fog is a haze layer"); + assert_eq!(veil.onset_t, 0.0, "the veil starts at the top of the frame"); + assert!(veil.strength > 0.7); + assert!(fogged.stars.is_none(), "no stars through fog"); + + for h in 0..forecast.hourly.time.len() { + forecast.hourly.visibility[h] = Some(8_000.0); + } + let humid = celsius::weather::compose_at(&forecast, &hamburg_geo(), t00, t00, opts).unwrap(); + let haze = humid.haze.expect("8 km is still hazy"); + assert!(haze.onset_t > 0.0, "ordinary haze rises from the horizon"); + assert!(humid.stars.is_some()); } #[test] @@ -288,7 +409,7 @@ fn live_geocoding_returns_hamburg() { #[test] #[ignore] -fn live_forecast_returns_168_hours() { +fn live_forecast_returns_192_hours() { let forecast = celsius::weather::forecast::fetch(53.5511, 9.9937).expect("live request"); // timezone=auto resolves the zone from the coordinates: Hamburg is Berlin, CET (+3600) in winter or CEST (+7200) under summer time. assert_eq!(forecast.timezone, "Europe/Berlin"); @@ -297,10 +418,10 @@ fn live_forecast_returns_168_hours() { "Berlin offset should be CET or CEST, got {}", forecast.utc_offset_seconds ); - assert_eq!( - forecast.hourly.len(), - 168, - "7 days x 24 hours = 168 hourly samples" + assert_eq!(forecast.hourly.len(), 192, "24 hours back plus 168 forward"); + assert!( + forecast.hourly.direct_normal_irradiance_instant[0].is_some(), + "the beam field must be a real array, not a serde default" ); assert_eq!(forecast.hourly.temperature_2m.len(), forecast.hourly.len()); } diff --git a/tools/celsius-lab/src/lib.rs b/tools/celsius-lab/src/lib.rs index 374797e..b6e1655 100644 --- a/tools/celsius-lab/src/lib.rs +++ b/tools/celsius-lab/src/lib.rs @@ -441,6 +441,7 @@ pub fn analytic_state(sun_alt: f64, turbidity: f64, sun_az_offset: f64) -> SkySt y_frac: sun_y, radius: 4.0, visible: sun_alt > 0.0, + strength: 1.0, }, clouds: Vec::new(), chrome: Chrome {