Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/).
11 changes: 5 additions & 6 deletions benches/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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])
Expand Down
5 changes: 5 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 47 additions & 1 deletion src/atmosphere.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f64>) -> Self {
Self {
Expand All @@ -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<f64>, aod_550: Option<f64>) -> 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 {
Expand All @@ -41,3 +53,37 @@ pub fn turbidity_from_visibility(vis_m: Option<f64>) -> 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)));
}
}
22 changes: 13 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -592,12 +601,7 @@ fn parse_relative(s: &str, now_unix: i64) -> Result<i64> {
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;
Expand Down
4 changes: 2 additions & 2 deletions src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
7 changes: 7 additions & 0 deletions src/scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -403,6 +406,10 @@ fn parse_scene(path: &Path, text: &str) -> Result<SkyState, SceneError> {
})
}

fn default_one() -> f64 {
1.0
}

fn default_true() -> bool {
true
}
Expand Down
1 change: 1 addition & 0 deletions src/tui/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1245,6 +1245,7 @@ mod tests {
y_frac: 0.5,
radius: 2.0,
visible: true,
strength: 1.0,
},
clouds: vec![CloudLayer {
cover: 1.0,
Expand Down
50 changes: 50 additions & 0 deletions src/weather/aerosol.rs
Original file line number Diff line number Diff line change
@@ -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<i64>,
/// 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<Option<f64>>,
}

/// 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<AerosolForecast, WeatherError> {
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)
}
75 changes: 68 additions & 7 deletions src/weather/forecast.rs
Original file line number Diff line number Diff line change
@@ -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,",
Expand All @@ -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,",
Expand All @@ -41,9 +52,34 @@ pub struct Forecast {
pub daily: Option<DailyArrays>,
}

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<String>,
/// Unix seconds, UTC.
pub time: Vec<i64>,
pub temperature_2m: Vec<Option<f64>>,
/// 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)]
Expand All @@ -54,13 +90,31 @@ pub struct HourlyArrays {
pub cloud_cover_mid: Vec<Option<f64>>,
pub cloud_cover_high: Vec<Option<f64>>,
pub precipitation: Vec<Option<f64>>,
/// 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<Option<f64>>,
/// 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<Option<f64>>,
/// 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<Option<f64>>,
/// 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<Option<f64>>,
/// Convective available potential energy in J/kg: how violent a storm the code is announcing.
#[serde(default)]
pub cape: Vec<Option<f64>>,
/// 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<Option<f64>>,
pub wind_speed_10m: Vec<Option<f64>>,
pub wind_direction_10m: Vec<Option<f64>>,
pub visibility: Vec<Option<f64>>,
pub weather_code: Vec<Option<u32>>,
/// 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<Option<f64>>,
}

impl HourlyArrays {
Expand All @@ -75,17 +129,19 @@ impl HourlyArrays {

#[derive(Debug, Clone, Deserialize)]
pub struct DailyArrays {
pub time: Vec<String>,
pub sunrise: Vec<String>,
pub sunset: Vec<String>,
/// 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<i64>,
/// Unix seconds, UTC. Polar day and night are sentinels rather than nulls: see `daylight_duration`.
pub sunrise: Vec<i64>,
pub sunset: Vec<i64>,
pub daylight_duration: Vec<f64>,
#[serde(default)]
pub temperature_2m_max: Vec<Option<f64>>,
#[serde(default)]
pub temperature_2m_min: Vec<Option<f64>>,
}

/// 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
///
Expand All @@ -98,7 +154,12 @@ pub fn fetch(lat: f64, lon: f64) -> Result<Forecast, WeatherError> {
.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() {
Expand Down
Loading