Skip to main content

ballistics_engine/
atmosphere.rs

1//! Enhanced atmospheric calculations for ballistics.
2//!
3//! This module provides Rust-accelerated implementations of atmospheric calculations
4//! with full ICAO Standard Atmosphere support for improved accuracy at all altitudes.
5//!
6//! # Humid air: one model, one lookup (0.50.0)
7//!
8//! Every solver family flies the same humid air. [`TrajectorySolver`](crate::TrajectorySolver),
9//! the kernels (`compute_derivatives`, `try_integrate_trajectory`, `try_solve_trajectory_rust`,
10//! `fast_integrate*`) and the lean Monte Carlo all take their per-step air from [`air_at`], over
11//! a [`KernelAtmosphere`] that carries the station's relative humidity, so a station's density
12//! and its sound speed cannot disagree about the humidity.
13//!
14//! - **At the station.** [`StationAir::new`] calls [`calculate_atmosphere`]: the CIPM-2007
15//!   moist-air density ([`calculate_air_density_cimp`]: the virial compressibility `Z` and the
16//!   enhancement factor `f`) and the moist speed of sound ([`moist_speed_of_sound`]). Both use
17//!   one water-vapour mole fraction, `x_v = (RH/100) f p_sv / p`, with `p_sv` from the
18//!   Wagner-Pruss saturation-pressure equation over liquid water. The sound speed is first order
19//!   in `x_v`: `gamma = 1.4 (1 - 0.062 x_v)`, `R = 287.0531 (1 + 0.378 x_v)`,
20//!   `c = sqrt(gamma R T)`. At 0 % it is the engine's one dry value, `sqrt(1.4 · 287.0531 · T)`,
21//!   340.294 m/s at 15 °C.
22//! - **Aloft (0.50.0: one vapour model).** The governing air (the station, or the downrange
23//!   [`AtmoSock`] zone that replaces it as the base, each with its own humidity) is well mixed:
24//!   its water-vapour mole fraction `x_v` is held at every height, for all three of the lapse,
25//!   the density and the sound speed. Temperature and pressure start from the governing air's
26//!   own values and follow the ICAO layers' lapse rates in geopotential height, with the
27//!   virtual-temperature (moist) hydrostatic exponent: the dry one scaled by the moist-air
28//!   molar-mass ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`, the factor the CIPM-2007 density
29//!   applies, so moist air's pressure falls more slowly with height. The density scales the
30//!   governing air's by `(T_0 · P) / (P_0 · T)`, and the sound speed is the formula above at the
31//!   local temperature and the governing `x_v`. Held aloft, `x_v` exceeds saturation in the colder
32//!   air: at every height above a saturated station, and from about 2.2 km above a 15 °C / 50 %
33//!   station and 0.4 km above a 35 °C / 90 % one. At +3 km it is 1.35 times saturation over the
34//!   first and 2.06 times over the second, and at +10 km 34 and 29 times. Condensation is not
35//!   modelled. At 0 % every term is the dry one, bit for bit. Until 0.50.0 the sound speed held the
36//!   relative humidity instead (re-deriving `x_v` at the local temperature and pressure) and the
37//!   lapse was dry.
38//! - **Units.** [`RelativeHumidity`] stores a percent. Every Rust field and function takes a
39//!   percent (`AtmosphericConditions::humidity`, `BallisticInputs::humidity_percent`, an
40//!   [`AtmoSegment`]'s slot 2); only the SI JSON wire (`relative_humidity`) carries a fraction,
41//!   and it converts through [`RelativeHumidity::try_fraction`].
42//! - **Default.** An omitted humidity is [`DEFAULT_HUMIDITY_PERCENT`], 50 %, unless another reading
43//!   supplies it (a saved profile, the shot day for `--zero-humidity`), with two exceptions: an
44//!   `.a7p` file's absent humidity is 0 % (the format's own meaning), and the bridge's `true.*`
45//!   commands require `humidity_pct`.
46//! - **Validation.** One rule, [`RelativeHumidity::try_percent`] / [`RelativeHumidity::try_fraction`]:
47//!   a reading up to [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] (5 points) outside 0-100 % is the
48//!   saturated or dry air it measures and flies exactly as 100 % or 0 %; anything farther out,
49//!   NaN or infinite is refused. Air that cannot exist (an uncapped `x_v` of 1 or more) is
50//!   refused by [`StationAir::new`] and [`AtmoSock::validate`], the same test the
51//!   `atmosphere.density_altitude` service applies.
52//!
53//! Two gas constants appear here, one from each standard, each used the same way on every
54//! path: the CIPM-2007 density's `R / M_a = 8.314472 / 0.02896546 = 287.0478` J/(kg·K), inside
55//! its own formula, and the US Standard Atmosphere 1976 dry-air constant `R_AIR = 287.0531`,
56//! for the hydrostatic lapse (divided by `M_m / M_a` for humid air) and the sound speed.
57//!
58//! One deliberate exception: the muzzle Miller stability factor
59//! ([`crate::stability::compute_stability_coefficient`]) keeps Miller's published dry
60//! temperature and pressure correction, so it does not move with humidity.
61//!
62//! A kernel caller builds its atmosphere the way `TrajectorySolver` does (README.md shows the
63//! same code):
64//!
65//! ```
66//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
67//! use ballistics_engine::{air_at, KernelAtmosphere, RelativeHumidity, StationAir};
68//!
69//! // 15 C, 1013.25 hPa, 50 % at sea level: the same air TrajectorySolver flies.
70//! let station = StationAir::new(0.0, 15.0, 1013.25, RelativeHumidity::try_percent(50.0)?)?;
71//! let atmosphere = KernelAtmosphere::Station(station);
72//! // For TrajectoryParams::atmosphere / FastIntegrationParams::atmosphere. The air 300 m up:
73//! let aloft = air_at(&atmosphere, None, 0.0, 300.0);
74//! println!("{:.3} kg/m3, {:.3} m/s", aloft.density_kg_m3, aloft.speed_of_sound_mps);
75//! assert!(aloft.density_kg_m3 < station.density_kg_m3());
76//! assert_eq!(air_at(&atmosphere, None, 0.0, 0.0).speed_of_sound_mps, station.speed_of_sound_mps());
77//! # Ok(())
78//! # }
79//! ```
80
81use crate::gravity::Gravity;
82use std::borrow::Cow;
83use std::cmp::Ordering;
84use std::fmt;
85
86/// ICAO Standard Atmosphere layer definitions
87#[derive(Debug, Clone)]
88struct AtmosphereLayer {
89    /// Base geopotential height of this layer (m)
90    base_altitude: f64,
91    /// Base temperature at layer start (K)
92    base_temperature: f64,
93    /// Base pressure at layer start (Pa)
94    base_pressure: f64,
95    /// Temperature lapse rate (K/m)
96    lapse_rate: f64,
97}
98
99/// ICAO Standard Atmosphere constants
100// ICAO reference quantities are defined using standard Earth gravity, independently of the
101// acceleration chosen for an internal simulation.
102const G_ACCEL_MPS2: f64 = crate::constants::G_ACCEL_MPS2;
103/// Specific gas constant for dry air, J/(kg·K), the US Standard Atmosphere 1976 value. With
104/// [`GAMMA`] it is the engine's one dry-air sound-speed constant: `sqrt(GAMMA * R_AIR * T)`. It
105/// also drives the hydrostatic lapse: as is for dry air, divided by the moist-air molar-mass
106/// ratio `M_m / M_a` for humid air (the virtual-temperature lapse). The CIPM-2007 density uses
107/// its own `R / M_A` (287.0478) inside its own formula; each constant is used the same way on
108/// every path.
109pub(crate) const R_AIR: f64 = 287.0531;
110/// Heat-capacity ratio of dry air.
111pub(crate) const GAMMA: f64 = 1.4;
112const GEOPOTENTIAL_EARTH_RADIUS_M: f64 = 6_356_766.0;
113const MIN_GEOMETRIC_ALTITUDE_M: f64 = -5000.0;
114const MAX_GEOMETRIC_ALTITUDE_M: f64 = 84000.0;
115const MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M: f64 = -5000.0;
116const MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M: f64 = 84000.0;
117
118/// CIPM-2007 constants for the moist-air density, [`calculate_air_density_cimp`]. Their ratio
119/// `R / M_A` is 287.0478 J/(kg·K), CIPM's dry-air gas constant; the sound speed and the lapse
120/// use the US-1976 [`R_AIR`] instead. `M_V / M_A` also sets the moist-air molar-mass ratio
121/// (`moist_molar_mass_ratio`) that both the density and the humid lapse aloft apply.
122const R: f64 = 8.314472; // Universal gas constant
123const M_A: f64 = 28.96546e-3; // Molar mass of dry air (kg/mol)
124const M_V: f64 = 18.01528e-3; // Molar mass of water vapor (kg/mol)
125
126/// ICAO Standard Atmosphere layer data up to 84 km
127/// Pressures calculated using barometric formula between layers
128const ICAO_LAYERS: &[AtmosphereLayer] = &[
129    // Troposphere (-5 - 11 km; the sea-level base extrapolates smoothly below 0 m)
130    AtmosphereLayer {
131        base_altitude: 0.0,
132        base_temperature: 288.15, // 15°C
133        base_pressure: 101325.0,  // 1013.25 hPa
134        lapse_rate: -0.0065,      // -6.5 K/km
135    },
136    // Tropopause (11 - 20 km)
137    AtmosphereLayer {
138        base_altitude: 11000.0,
139        base_temperature: 216.65, // -56.5°C
140        base_pressure: 22632.1,   // 226.32 hPa
141        lapse_rate: 0.0,          // Isothermal
142    },
143    // Stratosphere 1 (20 - 32 km)
144    AtmosphereLayer {
145        base_altitude: 20000.0,
146        base_temperature: 216.65, // -56.5°C
147        base_pressure: 5474.89,   // 54.75 hPa
148        lapse_rate: 0.001,        // +1 K/km
149    },
150    // Stratosphere 2 (32 - 47 km)
151    AtmosphereLayer {
152        base_altitude: 32000.0,
153        base_temperature: 228.65, // -44.5°C
154        base_pressure: 868.02,    // 8.68 hPa
155        lapse_rate: 0.0028,       // +2.8 K/km
156    },
157    // Stratopause (47 - 51 km)
158    AtmosphereLayer {
159        base_altitude: 47000.0,
160        base_temperature: 270.65, // -2.5°C
161        base_pressure: 110.91,    // 1.11 hPa
162        lapse_rate: 0.0,          // Isothermal
163    },
164    // Mesosphere 1 (51 - 71 km)
165    AtmosphereLayer {
166        base_altitude: 51000.0,
167        base_temperature: 270.65, // -2.5°C
168        base_pressure: 66.94,     // 0.67 hPa
169        lapse_rate: -0.0028,      // -2.8 K/km
170    },
171    // Mesosphere 2 (71 - 84 km)
172    AtmosphereLayer {
173        base_altitude: 71000.0,
174        base_temperature: 214.65, // -58.5°C
175        base_pressure: 3.96,      // 0.04 hPa
176        lapse_rate: -0.002,       // -2.0 K/km
177    },
178];
179
180/// Calculate ICAO Standard Atmosphere conditions at any altitude.
181///
182/// This function implements the full ICAO Standard Atmosphere model with all
183/// atmospheric layers up to 84 km altitude.
184///
185/// # Arguments
186/// * `altitude_m` - Geometric altitude above mean sea level in meters (-5000 to 84000; values
187///   outside are clamped). It is converted to geopotential height before layer evaluation.
188///
189/// # Returns
190/// Tuple of (temperature_k, pressure_pa)
191pub(crate) fn calculate_icao_standard_atmosphere(altitude_m: f64) -> (f64, f64) {
192    let geometric_altitude = altitude_m.clamp(MIN_GEOMETRIC_ALTITUDE_M, MAX_GEOMETRIC_ALTITUDE_M);
193    let geopotential_height = geometric_to_geopotential_height_m(geometric_altitude).clamp(
194        MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M,
195        MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M,
196    );
197
198    // Find the appropriate atmospheric layer
199    let layer = ICAO_LAYERS
200        .iter()
201        .rev()
202        .find(|layer| geopotential_height >= layer.base_altitude)
203        .unwrap_or(&ICAO_LAYERS[0]);
204
205    let height_diff = geopotential_height - layer.base_altitude;
206    let temperature = layer.base_temperature + layer.lapse_rate * height_diff;
207
208    let pressure = if layer.lapse_rate.abs() < 1e-10 {
209        // Isothermal layer
210        layer.base_pressure * (-G_ACCEL_MPS2 * height_diff / (R_AIR * layer.base_temperature)).exp()
211    } else {
212        // Non-isothermal layer
213        let temp_ratio = temperature / layer.base_temperature;
214        layer.base_pressure * temp_ratio.powf(-G_ACCEL_MPS2 / (layer.lapse_rate * R_AIR))
215    };
216
217    (temperature, pressure)
218}
219
220/// Convert physical geometric altitude to the geopotential height used by ICAO layer tables.
221#[inline]
222fn geometric_to_geopotential_height_m(geometric_altitude_m: f64) -> f64 {
223    GEOPOTENTIAL_EARTH_RADIUS_M * geometric_altitude_m
224        / (GEOPOTENTIAL_EARTH_RADIUS_M + geometric_altitude_m)
225}
226
227/// Whether a pressure lies inside the legacy default sentinel's band, within 0.5 hPa of the
228/// 1013.25 hPa sea-level standard. [`resolve_station_pressure`] reads an unmarked value there
229/// as omitted at any altitude above 1 m.
230pub(crate) fn in_legacy_default_pressure_band(pressure_hpa: f64) -> bool {
231    const SEA_LEVEL_HPA: f64 = 1013.25;
232    (pressure_hpa - SEA_LEVEL_HPA).abs() < 0.5
233}
234
235/// Whether a temperature lies inside the legacy default sentinel's band, within 0.1 °C of the
236/// 15 °C sea-level standard. [`resolve_station_temperature`] reads an unmarked value there as
237/// omitted at any altitude above 1 m.
238pub(crate) fn in_legacy_default_temperature_band(temperature_c: f64) -> bool {
239    const SEA_LEVEL_TEMP_C: f64 = 15.0;
240    (temperature_c - SEA_LEVEL_TEMP_C).abs() < 0.1
241}
242
243/// Resolve the station-pressure override for an air-density calculation, by the legacy
244/// default-sentinel convention.
245///
246/// Presence-blind legacy convention: a bare `f64` cannot say whether it was supplied, so a
247/// sea-level default at a real altitude is read as omitted. The rule:
248/// * A pressure within 0.5 hPa of the 1013.25 hPa sea-level standard at an altitude above 1 m
249///   is read as "omitted, standard atmosphere at this altitude": `None`, so
250///   [`calculate_atmosphere`] derives the station pressure from altitude (ICAO standard)
251///   instead of flying sea-level density there.
252/// * Any other value is returned as `Some` and used as the STATION pressure, so altitude is
253///   not double-counted.
254///
255/// The ±0.5 hPa tolerance covers the `29.92 inHg ≈ 1013.21 hPa` conversion, and `>1 m` avoids
256/// triggering at sea level. A real reading inside that band (QNH 1031 hPa at 150 m reduces to
257/// 1012.86 hPa) is indistinguishable from the default here. A caller that knows presence uses
258/// [`resolve_station_conditions_with_presence`], which flies a supplied value as given.
259pub fn resolve_station_pressure(pressure_hpa: f64, altitude_m: f64) -> Option<f64> {
260    if in_legacy_default_pressure_band(pressure_hpa) && altitude_m.abs() > 1.0 {
261        None // pressure left at default + real altitude → derive station pressure from altitude
262    } else {
263        Some(pressure_hpa) // explicit station pressure is authoritative
264    }
265}
266
267/// Resolve the temperature override for an air-density calculation, by the legacy
268/// default-sentinel convention, mirroring [`resolve_station_pressure`].
269///
270/// Presence-blind legacy convention: a bare `f64` cannot say whether it was supplied, so a
271/// sea-level default at a real altitude is read as omitted.
272/// * A temperature within 0.1 °C of the 15 °C sea-level standard at an altitude above 1 m is
273///   read as "omitted, standard atmosphere at this altitude": `None`, so
274///   [`calculate_atmosphere`] applies the ICAO lapse-rate temperature for that altitude
275///   (≈ −6.5 °C/km).
276/// * Any other value is returned as `Some` and used as given.
277///
278/// Without the omitted case, `--altitude` with the default temperature held the air at 15 °C,
279/// which under-estimates density by ~2.4% at 1 km up to ~7% at 3 km versus the standard
280/// atmosphere (validated against py_ballisticcalc). The 0.1 °C tolerance matches the
281/// `59 °F = 15.0 °C` default exactly, and `>1 m` avoids triggering at sea level. A real 15 °C
282/// reading at altitude is indistinguishable from the default here; a caller that knows presence
283/// uses [`resolve_station_conditions_with_presence`].
284pub fn resolve_station_temperature(temperature_c: f64, altitude_m: f64) -> Option<f64> {
285    if in_legacy_default_temperature_band(temperature_c) && altitude_m.abs() > 1.0 {
286        None // temperature left at default + real altitude → derive ICAO lapse temperature
287    } else {
288        Some(temperature_c) // explicit temperature is authoritative
289    }
290}
291
292/// Return the station temperature and pressure that [`calculate_atmosphere`] will use after
293/// applying the default-at-altitude resolution rules.
294///
295/// A thin, byte-identical delegate to
296/// [`resolve_station_conditions_with_pressure_mode`] at [`PressureReferenceMode::Absolute`]
297/// (MBA-1397) — kept as a separate name/signature so no existing caller needs to change.
298///
299/// Presence-blind: both values go through the legacy default sentinels
300/// ([`resolve_station_temperature`], [`resolve_station_pressure`]). See
301/// [`resolve_station_conditions_with_presence`].
302pub fn resolve_station_conditions(
303    temperature_c: f64,
304    pressure_hpa: f64,
305    altitude_m: f64,
306) -> (f64, f64) {
307    resolve_station_conditions_with_pressure_mode(
308        temperature_c,
309        pressure_hpa,
310        altitude_m,
311        PressureReferenceMode::Absolute,
312    )
313}
314
315/// Whether a station-pressure input is already absolute (station) pressure, or a sea-level-
316/// corrected altimeter setting (QNH / "barometer" reading) that must be reduced to station
317/// pressure at the shooter's altitude before use (MBA-1397).
318///
319/// Kestrel, AB Mobile, Shooter, JBM, and Hornady 4DOF all let the user declare which one they
320/// are entering. Previously this engine only supported [`Absolute`](Self::Absolute) — an
321/// entered sea-level-corrected barometer/METAR value at a real altitude was silently treated
322/// as station pressure, over-stating air density and under-stating drop.
323#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
324#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
325pub enum PressureReferenceMode {
326    /// The input is already absolute station pressure — today's meaning, and the default, so
327    /// every existing caller that never sets this is byte-identical to pre-MBA-1397 behavior.
328    #[default]
329    Absolute,
330    /// The input is a sea-level-corrected altimeter setting (QNH) and must be reduced to
331    /// station pressure at the target altitude via [`reduce_qnh_to_station_pressure`].
332    Qnh,
333}
334
335/// Reduce a sea-level-corrected altimeter setting (QNH) to the station pressure at
336/// `altitude_m` (MBA-1397), using the altimeter-setting relation (MBA-1605):
337///
338/// `station = QNH * (1 + (L*h/T0) * (P0/QNH)^n)^(1/n)`, with `n = -L*R/g`
339///
340/// for the ICAO troposphere's lapse rate `L` (-0.0065 K/m), sea-level temperature `T0`
341/// (288.15 K) and sea-level pressure `P0` (1013.25 hPa), so `n` = 0.190263. This is what an
342/// altimeter setting means: an altimeter set to QNH reads field elevation on the ground, so the
343/// station pressure's ISA pressure altitude is the QNH's own pressure altitude plus `h`. Written
344/// that way it is the additive form `station = P0 * ((QNH/P0)^n + L*h/T0)^(1/n)`; the
345/// algebraically equal form above is the one evaluated, because it returns QNH bit-exactly at
346/// `h = 0`.
347///
348/// This is the altimeter-setting relation on ICAO constants with geopotential height. It has the
349/// shape of the NWS/ASOS altimeter-setting algorithm but is not that algorithm, which uses its
350/// own rounded constants (`n` = 0.190284 and `k` = 8.4228807e-5, `P0^n * 0.0065/T0` at 288 K),
351/// adds the field elevation as entered rather than its geopotential height, and subtracts a
352/// 0.3 hPa sensor offset. Even without that offset, NWS/ASOS gives a station pressure about
353/// 0.1 hPa lower than this function at 1500 m and 0.3 to 0.45 hPa lower at 4000 to 5000 m (QNH
354/// 950 to 1050 hPa).
355///
356/// Before 0.49.0 this function scaled the standard pressure ratio by QNH,
357/// `station = QNH * (1 + L*h/T0)^(1/n)`, and called that the altimeter-setting reduction. It is
358/// not: the two agree only at QNH = 1013.25 hPa or at `h = 0`, and the ratio form ran 0.49 hPa
359/// low for a QNH of 1030 hPa at 1500 m.
360///
361/// `h` is GEOPOTENTIAL height, not the geometric altitude the caller supplies — this function
362/// converts the one to the other first (`geometric_to_geopotential_height_m`), as ISA requires.
363/// Substituting geometric altitude directly into that expression reproduces the reduction only
364/// to about 0.04 hPa at 1500 m, which is why the worked values below are not what the bare
365/// formula gives.
366///
367/// Reuses the SAME troposphere layer (`ICAO_LAYERS[0]`) and physical constants
368/// (`G_ACCEL_MPS2`, `R_AIR`) that `calculate_icao_standard_atmosphere` (private to this crate)
369/// uses for its own non-isothermal-layer pressure formula, rather than re-hardcoding the
370/// lapse rate / sea-level temperature / exponent a second time. `altitude_m` is clamped and
371/// converted to geopotential height exactly like `calculate_icao_standard_atmosphere`, and
372/// `(P0/QNH)^n` is exactly 1 at QNH = 1013.25 hPa. At QNH = 1013.25 hPa the reduction therefore
373/// equals the ICAO standard station pressure to rounding, but not bit for bit at every altitude
374/// (for example 1012.0492647136854 against 1012.0492647136847 at 10 m; the two agree exactly at
375/// 150 m). Callers that must stay bit-identical for an omitted pressure keep the mode they
376/// already used for it.
377///
378/// The reduction is only physically meaningful within the troposphere (the altitude range
379/// real shooting takes place in); it is not re-derived per-layer for higher altitudes. No
380/// station pressure exists once the QNH's pressure altitude plus `h` reaches `T0/-L`
381/// (44,331 m, where the troposphere's lapse rate reaches absolute zero), nor for a non-positive
382/// QNH; there this returns NaN, which callers refuse as a non-finite pressure.
383pub fn reduce_qnh_to_station_pressure(qnh_hpa: f64, altitude_m: f64) -> f64 {
384    let geometric_altitude = altitude_m.clamp(MIN_GEOMETRIC_ALTITUDE_M, MAX_GEOMETRIC_ALTITUDE_M);
385    let geopotential_height = geometric_to_geopotential_height_m(geometric_altitude).clamp(
386        MIN_STANDARD_GEOPOTENTIAL_HEIGHT_M,
387        MAX_STANDARD_GEOPOTENTIAL_HEIGHT_M,
388    );
389    let layer = &ICAO_LAYERS[0]; // troposphere: the only layer the altimeter-setting relation covers
390    let height_term = layer.lapse_rate * geopotential_height / layer.base_temperature;
391    let exponent = -G_ACCEL_MPS2 / (layer.lapse_rate * R_AIR); // 1/n
392    let sea_level_hpa = layer.base_pressure / 100.0;
393    let setting_term = (sea_level_hpa / qnh_hpa).powf(exponent.recip()); // (P0/QNH)^n
394    qnh_hpa * (1.0 + height_term * setting_term).powf(exponent)
395}
396
397/// Mode-aware counterpart of [`resolve_station_pressure`] (MBA-1397). Does NOT change that
398/// function's signature or behavior — [`PressureReferenceMode::Absolute`] is a pure
399/// passthrough to it — so this is a new function alongside the original, not a replacement.
400///
401/// [`PressureReferenceMode::Qnh`] reduces `pressure_hpa` (interpreted as a QNH) to station
402/// pressure via [`reduce_qnh_to_station_pressure`] and returns it as `Some(..)`
403/// UNCONDITIONALLY, bypassing the default-sentinel ambiguity `resolve_station_pressure` must
404/// use to infer omission from a bare `f64`. This matters: a QNH the caller explicitly declared
405/// should never be silently re-interpreted as an omitted default merely because the REDUCED
406/// number happens to land within the sentinel's tolerance of the 1013.25 hPa sea-level
407/// constant (a real, reachable case — e.g. a high-pressure day's QNH reducing to ~1013 hPa at
408/// a few hundred meters of elevation).
409pub fn resolve_station_pressure_with_mode(
410    pressure_hpa: f64,
411    altitude_m: f64,
412    mode: PressureReferenceMode,
413) -> Option<f64> {
414    match mode {
415        PressureReferenceMode::Absolute => resolve_station_pressure(pressure_hpa, altitude_m),
416        PressureReferenceMode::Qnh => {
417            Some(reduce_qnh_to_station_pressure(pressure_hpa, altitude_m))
418        }
419    }
420}
421
422/// Mode-aware counterpart of [`resolve_station_conditions`] (MBA-1397): identical for
423/// [`PressureReferenceMode::Absolute`] (byte-identical delegate — [`resolve_station_conditions`]
424/// itself now forwards here), and reduces an explicit QNH pressure to station pressure via
425/// [`resolve_station_pressure_with_mode`] for [`PressureReferenceMode::Qnh`] before applying
426/// the same standard-atmosphere fallback used when either input is left at its sea-level
427/// default.
428///
429/// Presence-blind: this is [`resolve_station_conditions_with_presence`] with
430/// [`StationAtmospherePresence::NEITHER`], bit for bit. The temperature sentinel runs in BOTH
431/// arms, so a typed 15 °C at altitude flies the ICAO lapse temperature here even with a
432/// declared QNH; only the pressure sentinel is bypassed in the `Qnh` arm. A caller that knows
433/// which values were supplied uses [`resolve_station_conditions_with_presence`].
434pub fn resolve_station_conditions_with_pressure_mode(
435    temperature_c: f64,
436    pressure_hpa: f64,
437    altitude_m: f64,
438    pressure_mode: PressureReferenceMode,
439) -> (f64, f64) {
440    resolve_station_conditions_with_presence(
441        temperature_c,
442        pressure_hpa,
443        altitude_m,
444        pressure_mode,
445        StationAtmospherePresence::NEITHER,
446    )
447}
448
449/// Which of a station temperature / pressure pair the caller actually supplied (0.49.0).
450///
451/// A field that is not supplied is resolved by the pre-0.49.0 default-sentinel rule
452/// ([`resolve_station_temperature`] / [`resolve_station_pressure_with_mode`]): the ICAO
453/// standard at |altitude| > 1 m when the value is the sea-level default, the value itself
454/// otherwise. That makes [`Self::NEITHER`] exactly the old behaviour of every presence-blind
455/// API, which is why it is the `Default`, and makes a supplied field authoritative whatever
456/// its value: a typed 15 °C, 59 °F, 1013.25 hPa or 29.92 inHg at altitude flies as typed.
457///
458/// Pass it to [`resolve_station_conditions_with_presence`], or to one of the
459/// `*_with_station_presence` twins of the solver, zero, Monte Carlo, lead, hold-curve and
460/// truing entry points.
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
462pub struct StationAtmospherePresence {
463    /// The station temperature was a reading the caller supplied.
464    pub temperature_supplied: bool,
465    /// The station pressure (or the QNH it is reduced from) was a reading the caller supplied.
466    pub pressure_supplied: bool,
467}
468
469impl StationAtmospherePresence {
470    /// Neither value was supplied: the pre-0.49.0 default-sentinel rule, bit for bit.
471    pub const NEITHER: Self = Self::new(false, false);
472    /// Both values were supplied: both fly as given (a declared QNH after its reduction).
473    pub const BOTH: Self = Self::new(true, true);
474
475    /// Presence from two flags.
476    pub const fn new(temperature_supplied: bool, pressure_supplied: bool) -> Self {
477        Self {
478            temperature_supplied,
479            pressure_supplied,
480        }
481    }
482
483    /// Presence of a temperature reading and a pressure reading.
484    pub const fn from_readings(temperature: StationReading, pressure: StationReading) -> Self {
485        Self::new(temperature.supplied, pressure.supplied)
486    }
487}
488
489/// A station temperature or pressure on a presence-carrying request (0.49.0): the value the
490/// engine is handed and whether the caller supplied it.
491///
492/// On the wire it is a bare JSON number when supplied and ABSENT when omitted. The type's own
493/// `Deserialize` rejects a JSON `null`; the truing DTOs (`TruingModelInputsV1`,
494/// `WindTruingRequest`) read a `null` field as omitted, as the `card.*` requests do. An omitted
495/// reading carries the surface's legacy default (59 °F / 29.92 inHg on
496/// the truing DTOs, the metric CLI's 1013.25 hPa expressed in inHg, and so on), so it resolves
497/// exactly as that default did before 0.49.0. Use [`Self::omitted`] for that, never a bare
498/// `Option`: at |altitude| <= 1 m an omitted value flies as itself, so the default it carries
499/// is part of the result.
500#[derive(Debug, Clone, Copy, PartialEq)]
501pub struct StationReading {
502    /// The value handed to the engine.
503    pub value: f64,
504    /// Whether the caller supplied it. `false` means the legacy default-sentinel rule decides.
505    pub supplied: bool,
506}
507
508impl StationReading {
509    /// A reading the caller supplied: it flies as given.
510    pub const fn supplied(value: f64) -> Self {
511        Self {
512            value,
513            supplied: true,
514        }
515    }
516
517    /// No reading: `default_value` is the surface's legacy default, resolved by the
518    /// pre-0.49.0 rule (ICAO standard at a real altitude when it is the sea-level default).
519    pub const fn omitted(default_value: f64) -> Self {
520        Self {
521            value: default_value,
522            supplied: false,
523        }
524    }
525
526    /// `true` when no reading was supplied. Used as `skip_serializing_if`.
527    pub fn is_omitted(&self) -> bool {
528        !self.supplied
529    }
530}
531
532impl serde::Serialize for StationReading {
533    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
534        serializer.serialize_f64(self.value)
535    }
536}
537
538impl<'de> serde::Deserialize<'de> for StationReading {
539    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
540        <f64 as serde::Deserialize>::deserialize(deserializer).map(Self::supplied)
541    }
542}
543
544/// Resolve the station temperature and pressure a solve flies, honouring which of them the
545/// caller supplied (0.49.0). This is the presence-aware resolver every surface that knows
546/// presence goes through.
547///
548/// For each field:
549/// * supplied: returned as given; a pressure declared as QNH ([`PressureReferenceMode::Qnh`])
550///   is first reduced to station pressure with [`reduce_qnh_to_station_pressure`];
551/// * omitted: resolved exactly as before 0.49.0, through [`resolve_station_temperature`] /
552///   [`resolve_station_pressure_with_mode`], then the ICAO standard at `altitude_m` when the
553///   value is the sea-level default at a real altitude.
554///
555/// With [`StationAtmospherePresence::NEITHER`] the result is bit-identical to
556/// [`resolve_station_conditions_with_pressure_mode`] (which now delegates here). With
557/// [`StationAtmospherePresence::BOTH`] in [`PressureReferenceMode::Absolute`] it returns the
558/// pair unchanged.
559pub fn resolve_station_conditions_with_presence(
560    temperature_c: f64,
561    pressure_hpa: f64,
562    altitude_m: f64,
563    pressure_mode: PressureReferenceMode,
564    presence: StationAtmospherePresence,
565) -> (f64, f64) {
566    let temp_override = if presence.temperature_supplied {
567        Some(temperature_c)
568    } else {
569        resolve_station_temperature(temperature_c, altitude_m)
570    };
571    let press_override = if presence.pressure_supplied {
572        Some(match pressure_mode {
573            PressureReferenceMode::Absolute => pressure_hpa,
574            PressureReferenceMode::Qnh => reduce_qnh_to_station_pressure(pressure_hpa, altitude_m),
575        })
576    } else {
577        resolve_station_pressure_with_mode(pressure_hpa, altitude_m, pressure_mode)
578    };
579    if let (Some(temp_c), Some(pressure_hpa)) = (temp_override, press_override) {
580        // Value-neutral fast path: the ICAO evaluation below would be discarded.
581        return (temp_c, pressure_hpa);
582    }
583    let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
584    (
585        temp_override.unwrap_or(std_temp_k - 273.15),
586        press_override.unwrap_or(std_pressure_pa / 100.0),
587    )
588}
589
590// ---------------------------------------------------------------------------------------
591// Station-pressure plausibility
592// ---------------------------------------------------------------------------------------
593
594/// The lowest ratio of station pressure to the ICAO standard pressure at the station's
595/// altitude that [`station_pressure_plausibility`] treats as weather. See that function for
596/// where the band comes from.
597pub const STATION_PRESSURE_MIN_PLAUSIBLE_RATIO: f64 = 0.85;
598/// The highest ratio of station pressure to the ICAO standard pressure at the station's
599/// altitude that [`station_pressure_plausibility`] treats as weather.
600pub const STATION_PRESSURE_MAX_PLAUSIBLE_RATIO: f64 = 1.08;
601
602/// How an explicit absolute station pressure compares with the ICAO standard pressure at the
603/// altitude it was sent with. Returned by [`station_pressure_plausibility`].
604#[derive(Debug, Clone, Copy, PartialEq)]
605pub struct StationPressurePlausibility {
606    /// The ICAO standard pressure at the altitude, in pascals.
607    pub icao_standard_pa: f64,
608    /// The station pressure divided by `icao_standard_pa`.
609    pub ratio: f64,
610    /// Whether `ratio` lies outside [`STATION_PRESSURE_MIN_PLAUSIBLE_RATIO`] to
611    /// [`STATION_PRESSURE_MAX_PLAUSIBLE_RATIO`] (both edges inside), or is not finite.
612    pub implausible: bool,
613}
614
615/// Compare an explicit absolute station pressure, in pascals, with the ICAO standard pressure
616/// at `altitude_m`, and say whether the two can describe the same station.
617///
618/// An explicit absolute pressure is authoritative wherever the engine takes one, so a pressure
619/// that belongs to some other altitude is flown as it was sent. The two common cases are a
620/// sea-level figure sent at a real elevation: a 101325 Pa placeholder, or a weather report's
621/// altimeter setting (QNH) sent as station pressure instead of as a QNH. At Cusco's 3310.128 m
622/// a 101325 Pa placeholder is 1.503 times the standard pressure there. The reverse, a true
623/// station reading sent with the wrong altitude (omitted, or in the wrong unit), shows up as a
624/// ratio far from 1 too. Callers use this to warn; nothing here changes a pressure.
625///
626/// The band, [`STATION_PRESSURE_MIN_PLAUSIBLE_RATIO`] to
627/// [`STATION_PRESSURE_MAX_PLAUSIBLE_RATIO`], is wide enough that recorded weather never leaves
628/// it. The WMO's table of weather and climate extremes (as of 31 July 2025) lists these
629/// sea-level pressure records:
630///
631/// - 870 hPa in the eye of Typhoon Tip, 12 October 1979, the lowest (tornadoes excluded);
632/// - 1083.8 hPa at Agata, Russia, 31 December 1968, the highest at a station below 750 m;
633/// - 1089.1 hPa at Tosontsengel, Mongolia, 30 December 2004, the highest above 750 m.
634///
635/// Against the 1013.25 hPa standard those are 0.859, 1.070 and 1.075. They are sea-level
636/// figures. At a station above sea level the high extreme moves toward standard, because the
637/// record highs come from cold air: reduced to sea level through a column denser than the
638/// standard one, a station pressure nearer standard becomes the record sea-level figure. Cold
639/// air moves the low side the other way. Under a cold column an ordinary sea-level pressure
640/// puts a high station further below standard than the sea-level figure is: a 3000 m station
641/// under a 243 K column reads 0.948 times the ICAO standard there with 1013.25 hPa at sea
642/// level, and 0.917 with 980 hPa. Both stay well above 0.85.
643///
644/// The band catches gross mismatches, not every placeholder: 101325 Pa stays inside it up to
645/// about 645 m, where it is already 8% above standard.
646///
647/// This is for absolute station pressure only. A QNH is a sea-level figure by declaration, so
648/// comparing it with the standard at the station's altitude would say nothing about it.
649pub fn station_pressure_plausibility(
650    station_pressure_pa: f64,
651    altitude_m: f64,
652) -> StationPressurePlausibility {
653    let (_, icao_standard_pa) = calculate_icao_standard_atmosphere(altitude_m);
654    let ratio = station_pressure_pa / icao_standard_pa;
655    let implausible = !(STATION_PRESSURE_MIN_PLAUSIBLE_RATIO
656        ..=STATION_PRESSURE_MAX_PLAUSIBLE_RATIO)
657        .contains(&ratio);
658    StationPressurePlausibility {
659        icao_standard_pa,
660        ratio,
661        implausible,
662    }
663}
664
665// ---------------------------------------------------------------------------------------
666// MBA-1366: density altitude as a direct atmosphere input
667// ---------------------------------------------------------------------------------------
668
669/// NWS pressure-altitude and FAA-rule constants — the ONE copy.
670///
671/// Both directions of the density-altitude model now live in this module: the forward
672/// [`faa_rule_density_altitude_ft`] (the engine's reported density altitude) and its exact
673/// inverse [`resolve_atmosphere_for_density_altitude`] (MBA-1366, the DA entry mode). They
674/// used to live apart, with these constants duplicated here because the forward formula sat
675/// in `pdf_dope_card` — first in the `ballistics` binary, then (from 0.33.0's Task 10) in
676/// this library but behind `#[cfg(feature = "pdf")]`, which this unconditional module could
677/// not import across without breaking the `--no-default-features` wasm32 build CI
678/// type-checks.
679///
680/// The fix was to move the formula DOWN rather than import it UP: `atmosphere` is
681/// unconditional, so the forward function lives here and
682/// `pdf_dope_card::calculate_density_altitude` now delegates to it, bit for bit. That leaves
683/// no second copy to drift, and it is what lets the `atmosphere.density_altitude` bridge
684/// command exist in every build with the bridge — including wasm32, which has no PDF card.
685///
686/// `src/main.rs`'s `density_altitude_round_trips_through_the_dope_card_formula*` tests still
687/// pin forward and inverse together, now through a single set of constants.
688const DA_NWS_SEA_LEVEL_HPA: f64 = 1013.25;
689const DA_NWS_PRESSURE_ALT_FT: f64 = 145_366.45;
690const DA_NWS_EXPONENT: f64 = 0.190_284;
691const DA_NWS_SEA_LEVEL_TEMP_F: f64 = 59.0;
692const DA_NWS_LAPSE_F_PER_1000FT: f64 = 3.57;
693/// The FAA rule of thumb, "120 ft of density altitude per °C away from standard", expressed
694/// per °F because the NWS constants above are Fahrenheit.
695const DA_FAA_RULE_FT_PER_DEG_F: f64 = 120.0 * 5.0 / 9.0;
696const DA_FT_TO_M: f64 = 0.3048;
697
698/// NWS pressure altitude, feet, from STATION pressure in hPa.
699///
700/// The published NWS station-pressure equation
701/// (<https://www.weather.gov/media/epz/wxcalc/pressureAltitude.pdf>):
702///
703/// ```text
704/// PA_ft = 145366.45 * (1 - (P_hPa / 1013.25)^0.190284)
705/// ```
706///
707/// Station pressure, never an altimeter setting (MBA-643): a QNH already corrects to sea
708/// level and would report the pressure altitude of the sea rather than of the firing point.
709///
710/// It is the troposphere's closed form, with the NWS's rounded constants, and that is all it
711/// is anywhere: below -5 km and above 11 km it continues the troposphere's lapse, which the
712/// standard atmosphere does not have above 11 km, so there it is no longer the standard
713/// atmosphere's altitude of the pressure (standard pressure at 20 km, 5474.89 Pa, reads
714/// 18879 m), and it approaches 145366.45 ft (44308 m), where that lapse would reach 0 K, as
715/// the pressure falls to 0. [`pressure_altitude_m`] is this formula inside -5 km to 11 km and
716/// the standard atmosphere's own altitude outside it.
717pub fn nws_pressure_altitude_ft(station_pressure_hpa: f64) -> f64 {
718    DA_NWS_PRESSURE_ALT_FT
719        * (1.0 - (station_pressure_hpa / DA_NWS_SEA_LEVEL_HPA).powf(DA_NWS_EXPONENT))
720}
721
722/// The pressure altitude of a station pressure, m, wherever it lands: the NWS formula
723/// ([`nws_pressure_altitude_ft`] in metres, to the bit) inside -5 km to 11 km, where it is the
724/// published figure, and outside that band the standard atmosphere's own (geopotential)
725/// altitude of the pressure, walking the same ICAO layers [`air_at`] walks: the troposphere's
726/// lapse below -5 km, isothermal from 11 km, warming from 20 km and 32 km, isothermal again
727/// from 47 km, cooling from 51 km and 71 km, the last layer's lapse continuing above 84 km.
728/// Each layer's base pressure is chained from 101325 Pa by the layer formula, so standard
729/// pressure at any height reads that height.
730///
731/// Every pressure above 0 has a finite pressure altitude, below 178.3 km (where the last
732/// layer's lapse reaches 0 K). At the band's edges the two differ by the few metres the NWS
733/// constants and the ICAO troposphere part by: the NWS formula reads 22615.3 Pa as 11000 m and
734/// the standard atmosphere reads it as 11005 m, so the figure steps up by 5 m there as the
735/// pressure falls, and at the bottom edge (177725 Pa) it steps down by 2 m as the pressure
736/// rises. It never falls as the pressure falls. A NaN pressure gives NaN.
737///
738/// ```
739/// use ballistics_engine::atmosphere::{nws_pressure_altitude_ft, pressure_altitude_m};
740///
741/// // Inside the band, the NWS formula to the bit.
742/// assert_eq!(pressure_altitude_m(850.0).to_bits(), (nws_pressure_altitude_ft(850.0) * 0.3048).to_bits());
743/// // Standard pressure at 20 km reads 20 km.
744/// assert!((pressure_altitude_m(54.7489) - 20_000.0).abs() < 1.0);
745/// // A near vacuum still has an altitude.
746/// assert!(pressure_altitude_m(0.01).is_finite());
747/// ```
748pub fn pressure_altitude_m(station_pressure_hpa: f64) -> f64 {
749    let nws_m = nws_pressure_altitude_ft(station_pressure_hpa) * DA_FT_TO_M;
750    if nws_m.is_nan() || (LOWEST_PRESSURE_ALTITUDE_M..=TROPOSPHERE_TOP_M).contains(&nws_m) {
751        return nws_m;
752    }
753    standard_pressure_altitude_m(station_pressure_hpa * 100.0)
754}
755
756/// The standard atmosphere's geopotential altitude, m, of a pressure in pascals: the ICAO layers
757/// walked from sea level, each base pressure chained by the layer formula, the troposphere's
758/// lapse continued below sea level and the last layer's above 84 km.
759fn standard_pressure_altitude_m(pressure_pa: f64) -> f64 {
760    let sea_level = &ICAO_LAYERS[0];
761    let mut base_pressure = sea_level.base_pressure;
762    for (index, layer) in ICAO_LAYERS.iter().enumerate() {
763        let (base, base_temperature, lapse) = (
764            layer.base_altitude,
765            layer.base_temperature,
766            layer.lapse_rate,
767        );
768        let isothermal = lapse.abs() < 1e-10;
769        let scale_height = R_AIR * base_temperature / G_ACCEL_MPS2;
770        let top = ICAO_LAYERS
771            .get(index + 1)
772            .map_or(f64::INFINITY, |next| next.base_altitude);
773        let top_pressure = if top.is_infinite() {
774            0.0
775        } else if isothermal {
776            base_pressure * (-(top - base) / scale_height).exp()
777        } else {
778            base_pressure
779                * (1.0 + lapse * (top - base) / base_temperature)
780                    .powf(-G_ACCEL_MPS2 / (lapse * R_AIR))
781        };
782        if pressure_pa >= top_pressure || top.is_infinite() {
783            return if isothermal {
784                base + scale_height * (base_pressure / pressure_pa).ln()
785            } else {
786                let temperature = base_temperature
787                    * (pressure_pa / base_pressure).powf(-lapse * R_AIR / G_ACCEL_MPS2);
788                base + (temperature - base_temperature) / lapse
789            };
790        }
791        base_pressure = top_pressure;
792    }
793    unreachable!("the last layer has no top")
794}
795
796/// Density altitude by the FAA rule of thumb, feet: NWS pressure altitude plus 120 ft for
797/// every °C the station is away from ISA temperature at that pressure altitude. **Humidity is
798/// not an input.**
799///
800/// ```text
801/// DA_ft = PA_ft + (120 * 5/9) * (T_F - ISA_T_F(PA))      ISA_T_F(PA) = 59 - 3.57 * PA_ft/1000
802/// ```
803///
804/// This is the density altitude the engine has always reported —
805/// `pdf_dope_card::calculate_density_altitude` delegates to it — and the one
806/// [`resolve_atmosphere_for_density_altitude`], the density-altitude ENTRY mode, inverts
807/// exactly.
808///
809/// It stays humidity-free for compatibility, not out of necessity. Every card printed to date
810/// shows this figure, and the entry mode that inverts it has shipped since MBA-1366 taking a
811/// temperature but no humidity (the run's humidity is applied separately, afterwards). A
812/// humidity-aware forward could be inverted just as well given the run's humidity, the way
813/// temperature already is; it would change every printed card and what an entered density
814/// altitude resolves to.
815///
816/// Outside the troposphere this still starts from [`nws_pressure_altitude_ft`], not the
817/// layered [`pressure_altitude_m`] reported by the bridge. Both the NWS pressure formula and
818/// this temperature correction continue there, preserving the inverse used for density-altitude
819/// entry. They do not become the standard atmosphere's pressure or density altitude.
820///
821/// It is not the National Weather Service's density altitude either, despite the NWS pressure
822/// altitude inside it: the NWS calculator uses virtual temperature, so it includes humidity
823/// and tracks [`density_matched_altitude_m`] to within a few meters.
824///
825/// And it is an approximation. The rule is a straight line where the real dependence curves,
826/// and 120 ft/°C is slightly steeper than the exact slope at sea level (118.6 ft/°C for an
827/// ideal gas, 119.0 for the CIPM density [`density_matched_altitude_m`] uses), so
828/// it drifts from the exact figure as the temperature moves away from standard FOR THE
829/// PRESSURE ALTITUDE: about +22 m at 30 °C and 1013.25 hPa in completely dry air. See
830/// [`density_matched_altitude_m`] for the exact, humidity-inclusive figure, and why the bridge
831/// reports both.
832pub fn faa_rule_density_altitude_ft(station_pressure_hpa: f64, temperature_f: f64) -> f64 {
833    let pressure_alt = nws_pressure_altitude_ft(station_pressure_hpa);
834
835    // ISA temperature at pressure altitude (lapse rate: 3.57°F per 1000 ft)
836    let isa_temp_f = DA_NWS_SEA_LEVEL_TEMP_F - (pressure_alt / 1000.0) * DA_NWS_LAPSE_F_PER_1000FT;
837
838    pressure_alt + DA_FAA_RULE_FT_PER_DEG_F * (temperature_f - isa_temp_f)
839}
840
841/// ISA troposphere constants for [`density_matched_altitude_m`].
842const ISA_SEA_LEVEL_TEMP_K: f64 = 288.15;
843const ISA_LAPSE_K_PER_M: f64 = 0.0065;
844
845/// The reference air that [`density_matched_altitude_m`] calls sea level: ICAO standard sea
846/// level, perfectly dry, evaluated with the SAME CIPM-2007 model as the air being described.
847const DENSITY_MATCH_REFERENCE_TEMP_C: f64 = 15.0;
848const DENSITY_MATCH_REFERENCE_PRESSURE_HPA: f64 = 1013.25;
849
850/// The altitude in the ICAO Standard Atmosphere whose standard density equals the ACTUAL
851/// density of this air, humidity included — density altitude by its textbook definition.
852///
853/// ```text
854/// ratio = rho_CIPM(T, P, RH) / rho_CIPM(15 C, 1013.25 hPa, 0%)
855/// h_m   = (T0 / L) * (1 - ratio^(1/n))      T0 = 288.15 K, L = 0.0065 K/m,
856///                                            n  = g0 / (R L) - 1  (= 4.25588)
857/// ```
858///
859/// # Why this exists alongside [`faa_rule_density_altitude_ft`]
860///
861/// Two different quantities are both called "density altitude" in the field, and reporting
862/// them under one name is how an external user came to ask why the engine read 0 m where
863/// another tool read 36 m at ICAO standard with 50% humidity (2026-09). The FAA-rule figure
864/// is humidity-free for compatibility (see its docs). This one answers the question a shooter
865/// usually means — "which ISA altitude has the air density I actually have" — and so it must
866/// include humidity: water vapor (18 g/mol) is lighter than dry air (~29 g/mol), so humid air
867/// is thinner.
868///
869/// At 15 °C, 1013.25 hPa and 50% RH this reads 33.1 m where the FAA-rule figure reads 0. But
870/// the difference is NOT purely humidity, and callers must not present it that way: the FAA
871/// rule also drifts from this exact figure whenever the temperature is not standard for the
872/// pressure altitude, so the two disagree by about 22 m at 30 °C in perfectly dry air.
873///
874/// # Anchoring
875///
876/// Density comes from [`calculate_atmosphere`] — the one CIPM-2007 path every solver uses —
877/// and the ratio is taken against that SAME model's density for ICAO standard dry sea level,
878/// not against the textbook 1.225 kg/m³. The model is accurate, but it is not built to
879/// reproduce 1.225 exactly (its own anchor test allows ±0.002), and at sea level 0.002 kg/m³
880/// is roughly 17 m of altitude. Anchoring to the model makes ICAO standard dry air read
881/// exactly 0 and makes the humidity effect the model's own.
882///
883/// # Scope
884///
885/// Heights are the standard atmosphere's own (geopotential), with no correction to geometric
886/// height — the same plain-height convention as the FAA-rule figure and the DA entry mode.
887///
888/// Up to 11 km this is the closed-form troposphere above, which covers every shooting condition
889/// on Earth; below sea level it continues the troposphere's lapse, as the standard atmosphere
890/// does. Air thinner than the standard tropopause's (hot air, or a low station pressure) reads
891/// its altitude in the standard atmosphere's upper layers, the ICAO table [`air_at`] walks:
892/// isothermal from 11 km, warming from 20 km and 32 km, isothermal again from 47 km, cooling from
893/// 51 km and 71 km, the last layer's lapse continuing above 84 km. So the figure is the standard
894/// atmosphere's altitude of equal density for any finite positive density: standard air reads
895/// its own altitude in every layer, and it falls steadily as the air thins. Up to 11 km the
896/// result is the closed form above to the bit.
897///
898/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
899/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
900/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
901/// refuse what this computes.
902pub fn density_matched_altitude_m(
903    temperature_c: f64,
904    station_pressure_hpa: f64,
905    humidity_percent: f64,
906) -> f64 {
907    let (density, _) = calculate_atmosphere(
908        0.0,
909        Some(temperature_c),
910        Some(station_pressure_hpa),
911        humidity_percent,
912    );
913    let (reference, _) = calculate_atmosphere(
914        0.0,
915        Some(DENSITY_MATCH_REFERENCE_TEMP_C),
916        Some(DENSITY_MATCH_REFERENCE_PRESSURE_HPA),
917        0.0,
918    );
919    let ratio = density / reference;
920    let exponent = G_ACCEL_MPS2 / (R_AIR * ISA_LAPSE_K_PER_M) - 1.0;
921    let troposphere =
922        (ISA_SEA_LEVEL_TEMP_K / ISA_LAPSE_K_PER_M) * (1.0 - ratio.powf(1.0 / exponent));
923    // NaN, and every figure up to the tropopause, is the closed form's, to the bit.
924    if troposphere.is_nan() || troposphere <= TROPOSPHERE_TOP_M {
925        return troposphere;
926    }
927    standard_altitude_above_tropopause_m(ratio, exponent)
928}
929
930/// The standard atmosphere's altitude, m (geopotential), of the density ratio `ratio` (to ICAO
931/// sea level) thinner than the tropopause's: the ICAO layers above the troposphere walked up from
932/// 11 km, the last one's lapse continuing above 84 km, as [`air_at`] walks them.
933/// `troposphere_exponent` is the troposphere's density exponent `g0 / (R L) - 1`, which sets the
934/// tropopause's ratio, `(T(11 km) / T0)^n`. Any ratio from 0 up to the tropopause's has a finite
935/// altitude: the last layer cools to 0 K, and to no density, at 178.3 km.
936fn standard_altitude_above_tropopause_m(ratio: f64, troposphere_exponent: f64) -> f64 {
937    let sea_level = &ICAO_LAYERS[0];
938    let mut base_ratio =
939        (ICAO_LAYERS[1].base_temperature / sea_level.base_temperature).powf(troposphere_exponent);
940    for (index, layer) in ICAO_LAYERS.iter().enumerate().skip(1) {
941        let (base, base_temperature, lapse) = (
942            layer.base_altitude,
943            layer.base_temperature,
944            layer.lapse_rate,
945        );
946        // The density ratio within this layer, relative to its base: isothermal, or the power
947        // law of a lapse.
948        let isothermal = lapse.abs() < 1e-10;
949        let scale_height = R_AIR * base_temperature / G_ACCEL_MPS2;
950        let density_exponent = -G_ACCEL_MPS2 / (R_AIR * lapse) - 1.0;
951        let top = ICAO_LAYERS
952            .get(index + 1)
953            .map_or(f64::INFINITY, |next| next.base_altitude);
954        let top_ratio = if top.is_infinite() {
955            0.0
956        } else if isothermal {
957            base_ratio * (-(top - base) / scale_height).exp()
958        } else {
959            base_ratio * (1.0 + lapse * (top - base) / base_temperature).powf(density_exponent)
960        };
961        if ratio >= top_ratio || top.is_infinite() {
962            return if isothermal {
963                base + scale_height * (base_ratio / ratio).ln()
964            } else {
965                let temperature =
966                    base_temperature * (ratio / base_ratio).powf(1.0 / density_exponent);
967                base + (temperature - base_temperature) / lapse
968            };
969        }
970        base_ratio = top_ratio;
971    }
972    unreachable!("the last layer has no top")
973}
974
975/// Back-solve an ISA-equivalent station altitude/temperature/pressure from a directly-declared
976/// density altitude (MBA-1366) — the single-value atmosphere entry mode Shooter, Nosler, AB
977/// Analytics, Ballistic AE, and TRASOL all support as an alternative to altitude + pressure +
978/// temperature.
979///
980/// This is the exact algebraic inverse of the FAA-rule density-altitude model this engine
981/// already uses to REPORT density altitude ([`faa_rule_density_altitude_ft`], which
982/// `pdf_dope_card::calculate_density_altitude` delegates to):
983///
984/// ```text
985/// pressure_alt_ft = 145366.45 * (1 - (station_hpa / 1013.25)^0.190284)
986/// isa_temp_f      = 59.0 - pressure_alt_ft / 1000.0 * 3.57
987/// density_alt_ft  = pressure_alt_ft + (120*5/9) * (station_temp_f - isa_temp_f)
988/// ```
989///
990/// Solved for `station_hpa` given a target `density_alt_ft` and a station temperature `K = 120
991/// * 5/9` is the "120 ft per °C" density-altitude correction rule, expressed in ft per °F):
992///
993/// ```text
994/// pressure_alt_ft = (density_alt_ft - K*(station_temp_f - 59.0)) / (1 + K*3.57/1000.0)
995/// station_hpa     = 1013.25 * (1 - pressure_alt_ft/145366.45)^(1/0.190284)
996/// ```
997///
998/// # Temperature precedence (MBA-1366)
999/// * `explicit_temperature_c == None`: ISA-at-density-altitude is the default. Algebraically
1000///   this collapses `pressure_alt_ft` to EXACTLY `density_alt_ft`: the correction term above is
1001///   zero by construction whenever the station temperature equals the ISA temperature at that
1002///   pressure altitude, which is self-consistently true when temperature is left at ISA — i.e.
1003///   omitting an explicit temperature is equivalent to typing `--altitude <density_altitude>`
1004///   with no `--temperature`/`--pressure` override.
1005/// * `explicit_temperature_c == Some(t)`: `t` wins outright (returned unchanged as
1006///   `temperature_c`, never re-derived) and the station pressure is re-solved so the resulting
1007///   density altitude still reproduces the input exactly. The FAA-rule density altitude is
1008///   honored either way, but the DENSITY is not: the rule is a straight-line approximation, not
1009///   a curve of equal density, so the ISA-default case rebuilds different air — at 30 °C and
1010///   1013.25 hPa, a rebuilt 11.4 °C / 949 hPa, 0.3% denser, with a speed of sound 3% lower. Only
1011///   the real temperature reproduces the real air.
1012///
1013/// # Height convention
1014/// The FAA-rule formula being inverted ([`faa_rule_density_altitude_ft`]) performs no
1015/// geopotential correction — it treats its altitude as a plain height (the DOPE card, which
1016/// delegates to it, leaves its own `_altitude_ft` parameter unused for that reason). Consistent with that, the `altitude_m` this returns is GEOMETRIC altitude
1017/// — the same convention every other engine altitude input uses (`--altitude`,
1018/// [`AtmosphericConditions::altitude`](crate::cli_api::AtmosphericConditions::altitude)) —
1019/// rather than being run through `geometric_to_geopotential_height_m` a second time here; that
1020/// conversion is `calculate_icao_standard_atmosphere`'s job (both private to this crate — see
1021/// their doc comments elsewhere in this file), applied once this altitude re-enters the normal
1022/// altitude-lapse pipeline (this is what "back-solve an ISA-equivalent atmosphere" means —
1023/// unlike [`get_direct_atmosphere`], which would freeze speed of sound and bypass that pipeline
1024/// entirely).
1025///
1026/// # Interaction with [`PressureReferenceMode`] (QNH)
1027/// Density altitude supersedes pressure outright — callers must not also run a declared
1028/// `--pressure`/QNH value through [`resolve_station_pressure_with_mode`] when a density
1029/// altitude is present; see the CLI/WASM call sites, which emit a note to that effect.
1030///
1031/// # Returns
1032/// `(altitude_m, temperature_c, pressure_hpa)`, meant to be written directly into
1033/// [`crate::cli_api::AtmosphericConditions`] (and the paired `BallisticInputs` environment
1034/// fields, so powder-temperature sensitivity and the moist speed of sound both see the real
1035/// resolved temperature) via the Authoritative
1036/// (`TrajectorySolver::new_with_resolved_station_atmosphere`) constructor.
1037pub fn resolve_atmosphere_for_density_altitude(
1038    density_altitude_m: f64,
1039    explicit_temperature_c: Option<f64>,
1040) -> (f64, f64, f64) {
1041    let density_altitude_ft = density_altitude_m / DA_FT_TO_M;
1042    const K: f64 = DA_FAA_RULE_FT_PER_DEG_F;
1043
1044    let (pressure_alt_ft, temperature_c) = match explicit_temperature_c {
1045        Some(temp_c) => {
1046            let temp_f = temp_c * 9.0 / 5.0 + 32.0;
1047            let denom = 1.0 + K * DA_NWS_LAPSE_F_PER_1000FT / 1000.0;
1048            let pressure_alt_ft =
1049                (density_altitude_ft - K * (temp_f - DA_NWS_SEA_LEVEL_TEMP_F)) / denom;
1050            (pressure_alt_ft, temp_c)
1051        }
1052        None => {
1053            // ISA-at-DA default: the correction term vanishes by construction (see doc
1054            // comment above), so the pressure altitude IS the density altitude exactly.
1055            let pressure_alt_ft = density_altitude_ft;
1056            let isa_temp_f =
1057                DA_NWS_SEA_LEVEL_TEMP_F - pressure_alt_ft / 1000.0 * DA_NWS_LAPSE_F_PER_1000FT;
1058            let isa_temp_c = (isa_temp_f - 32.0) * 5.0 / 9.0;
1059            (pressure_alt_ft, isa_temp_c)
1060        }
1061    };
1062
1063    let pressure_hpa = DA_NWS_SEA_LEVEL_HPA
1064        * (1.0 - pressure_alt_ft / DA_NWS_PRESSURE_ALT_FT).powf(1.0 / DA_NWS_EXPONENT);
1065    let altitude_m = pressure_alt_ft * DA_FT_TO_M;
1066
1067    (altitude_m, temperature_c, pressure_hpa)
1068}
1069
1070/// The NWS station pressure, hPa, at a pressure altitude in feet, when it is finite and above 0:
1071/// the inverse of [`nws_pressure_altitude_ft`], as [`resolve_atmosphere_for_density_altitude`]
1072/// evaluates it. `None` at or above 145366.45 ft, where the formula's lapse reaches 0 K, and
1073/// where it overflows far below sea level.
1074fn nws_station_pressure_hpa(pressure_altitude_ft: f64) -> Option<f64> {
1075    let pressure_hpa = DA_NWS_SEA_LEVEL_HPA
1076        * (1.0 - pressure_altitude_ft / DA_NWS_PRESSURE_ALT_FT).powf(1.0 / DA_NWS_EXPONENT);
1077    (pressure_hpa.is_finite() && pressure_hpa > 0.0).then_some(pressure_hpa)
1078}
1079
1080/// The station a density altitude gives ([`resolve_atmosphere_for_density_altitude`], bit for
1081/// bit), or the refusal of a density altitude no air has: the one rule every surface that takes
1082/// a density altitude applies. A density altitude flies when it is finite and the station the
1083/// FAA rule's inverse gives for it can exist; nothing narrower. The station is checked as any
1084/// other is afterwards (its humidity, and air that cannot exist), by [`StationAir::new`].
1085///
1086/// ```
1087/// use ballistics_engine::atmosphere::station_for_density_altitude;
1088///
1089/// assert!(station_for_density_altitude(-10_000.0, None).is_ok()); // far below sea level
1090/// assert!(station_for_density_altitude(40_000.0, None).is_ok()); // far above the troposphere
1091/// assert!(station_for_density_altitude(50_000.0, None).is_err()); // below 0 K by the rule
1092/// assert!(station_for_density_altitude(50_000.0, Some(40.0)).is_ok()); // hot air that thin
1093/// ```
1094///
1095/// # Errors
1096///
1097/// - `density_altitude_m` not finite: [`AtmosphereErrorReason::NotFinite`] on
1098///   `density_altitude_m`.
1099/// - an `explicit_temperature_c` the one temperature rule refuses
1100///   ([`check_station_temperature_c`]), on `temperature_c`.
1101/// - no air at it: [`AtmosphereErrorReason::NoAirAtDensityAltitude`] on `density_altitude_m`,
1102///   whose [`AtmosphereError::altitude_m`] is its pressure altitude by the FAA rule.
1103pub fn station_for_density_altitude(
1104    density_altitude_m: f64,
1105    explicit_temperature_c: Option<f64>,
1106) -> Result<(f64, f64, f64), AtmosphereError> {
1107    const FIELD: &str = "density_altitude_m";
1108    if !density_altitude_m.is_finite() {
1109        return Err(AtmosphereError::new(
1110            FIELD,
1111            density_altitude_m,
1112            AtmosphereErrorReason::NotFinite,
1113        ));
1114    }
1115    if let Some(temperature_c) = explicit_temperature_c {
1116        check_station_temperature_c(temperature_c)?;
1117    }
1118    let (altitude_m, temperature_c, pressure_hpa) =
1119        resolve_atmosphere_for_density_altitude(density_altitude_m, explicit_temperature_c);
1120    let exists = altitude_m.is_finite()
1121        && pressure_hpa.is_finite()
1122        && pressure_hpa > 0.0
1123        && temperature_c.is_finite()
1124        && temperature_c > ABSOLUTE_ZERO_C;
1125    if !exists {
1126        return Err(AtmosphereError {
1127            altitude_m: Some(altitude_m),
1128            ..AtmosphereError::new(
1129                FIELD,
1130                density_altitude_m,
1131                AtmosphereErrorReason::NoAirAtDensityAltitude,
1132            )
1133        });
1134    }
1135    Ok((altitude_m, temperature_c, pressure_hpa))
1136}
1137
1138/// Enhanced atmospheric calculation with ICAO Standard Atmosphere.
1139///
1140/// # Arguments
1141/// * `altitude_m` - Altitude in meters
1142/// * `temp_override_c` - Temperature override in Celsius (None for standard)
1143/// * `press_override_hpa` - Pressure override in hPa (None for standard)
1144/// * `humidity_percent` - Humidity percentage (0-100)
1145///
1146/// # Returns
1147/// Tuple of (air_density_kg_m3, speed_of_sound_mps)
1148///
1149/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
1150/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
1151/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
1152/// refuse what this computes.
1153pub fn calculate_atmosphere(
1154    altitude_m: f64,
1155    temp_override_c: Option<f64>,
1156    press_override_hpa: Option<f64>,
1157    humidity_percent: f64,
1158) -> (f64, f64) {
1159    // Get standard atmosphere conditions or use overrides
1160    let combined_overrides = temp_override_c.zip(press_override_hpa);
1161    let (temp_k, pressure_pa) = if let Some((temp_c, pressure_hpa)) = combined_overrides {
1162        // Both overrides provided
1163        (temp_c + 273.15, pressure_hpa * 100.0)
1164    } else {
1165        // Get ICAO standard conditions
1166        let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
1167
1168        let final_temp_k = if let Some(temp_c) = temp_override_c {
1169            temp_c + 273.15
1170        } else {
1171            std_temp_k
1172        };
1173
1174        let final_pressure_pa = if let Some(press_hpa) = press_override_hpa {
1175            press_hpa * 100.0
1176        } else {
1177            std_pressure_pa
1178        };
1179
1180        (final_temp_k, final_pressure_pa)
1181    };
1182
1183    // Humidity clamp shared by the CIPM density and the moist speed of sound: a total-function
1184    // guard for this unvalidated public function. Validated callers (StationAir::new) pass a
1185    // RelativeHumidity, already in range, so it never moves their value. A NaN passes through
1186    // the clamp and gives NaN air (the vapour cap keeps it).
1187    let humidity_clamped = humidity_percent.clamp(0.0, 100.0);
1188    let temp_c = temp_k - 273.15;
1189
1190    // Density: CIPM-2007 is the engine's one humid-air density model. Every solver's station
1191    // density comes from this call, through StationAir::new; a downrange zone's base density
1192    // calls calculate_air_density_cimp directly in air_at. There is no second density formula.
1193    let density = calculate_air_density_cimp(temp_c, pressure_pa / 100.0, humidity_clamped);
1194
1195    // Speed of sound uses an ideal-gas moist-air mixture approximation, first order in the
1196    // water-vapor mole fraction. Extracted into `moist_speed_of_sound`, whose formula air_at
1197    // also evaluates at every step (at the station's x_v, held aloft); its vapor pressure comes
1198    // from the SAME Wagner-Pruss saturation-pressure equation (`enhanced_saturation_vapor_pressure`)
1199    // and CIPM enhancement factor that the density above uses. Only the vapor fraction is
1200    // shared; the acoustic relation remains ideal-gas.
1201    let speed_of_sound = moist_speed_of_sound(temp_k, pressure_pa, humidity_clamped);
1202
1203    (density, speed_of_sound)
1204}
1205
1206/// Speed of sound using an ideal-gas moist-air mixture approximation, first order in the
1207/// water-vapor mole fraction.
1208///
1209/// The water-vapor mole fraction is derived from the SAME Wagner-Pruss saturation vapor
1210/// pressure (`enhanced_saturation_vapor_pressure`) and CIPM-2007 enhancement factor used by
1211/// [`calculate_air_density_cimp`], so a single vapor formula feeds both density and c. Only the
1212/// vapor fraction is shared with the CIPM path; the acoustic relation itself remains ideal-gas.
1213/// The mixture applies first-order humidity corrections to the dry-air heat-capacity ratio and
1214/// gas constant, `gamma = 1.4 (1 - 0.062 x_v)` and `R = 287.0531 (1 + 0.378 x_v)`, then
1215/// evaluates `sqrt(gamma * R * T)`; at 0 % that is the dry `sqrt(1.4 · 287.0531 · T)`. It is
1216/// not Cramer's full real-gas polynomial and does not include Cramer's pressure or
1217/// carbon-dioxide terms.
1218///
1219/// It is the station's (and a downrange zone's) sound speed. Aloft, [`air_at`] evaluates the same
1220/// formula at the local temperature and the station's (or zone's) own `x_v`, held at every
1221/// height, so at the station's height the two agree to the bit.
1222///
1223/// # Arguments
1224/// * `temp_k` - Temperature in Kelvin
1225/// * `pressure_pa` - Total (station) pressure in Pa
1226/// * `humidity_percent` - Relative humidity percentage (0-100)
1227///
1228/// # Returns
1229/// Speed of sound in m/s
1230///
1231/// Its gas constant, `287.0531 (1 + 0.378 x_v)`, is first order in `x_v`: it differs from the exact
1232/// `R_AIR / (M_m / M_a)` the lapse uses by -1.1e-5 at 15 °C / 50 % and -1.3e-3 at 45 °C / 100 %
1233/// (1013.25 hPa), where the sound speed is 0.24 m/s (0.065 %) below what the lapse's gas constant
1234/// gives. The gap grows as the pressure falls: 0.50 m/s at 45 °C / 100 % and 700 hPa.
1235///
1236/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
1237/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
1238/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
1239/// refuse what this computes.
1240pub fn moist_speed_of_sound(temp_k: f64, pressure_pa: f64, humidity_percent: f64) -> f64 {
1241    // The one CIPM vapour mole fraction (`vapor_mole_fraction`, which the density uses too),
1242    // capped at the physical maximum of 1 by the one NaN-keeping cap. Its pressure floor guards
1243    // pressure_pa == 0 (a 0 hPa override would otherwise give +Inf -> NaN speed of sound).
1244    let mole_fraction_vapor = capped_vapor_mole_fraction(moist_air_vapor_mole_fraction(
1245        temp_k,
1246        pressure_pa,
1247        humidity_percent,
1248    ));
1249
1250    moist_sound_speed_at_mole_fraction(temp_k, mole_fraction_vapor)
1251}
1252
1253/// The moist-air sound speed of [`moist_speed_of_sound`] at a GIVEN water-vapour mole fraction:
1254/// `sqrt(1.4 (1 - 0.062 x_v) · 287.0531 (1 + 0.378 x_v) · T)`. The station's sound speed
1255/// evaluates it at the station's own `x_v`, and [`air_at`] at the governing air's `x_v`, held
1256/// aloft; at `x_v = 0` it is the dry `sqrt(1.4 · 287.0531 · T)` to the bit.
1257#[inline(always)]
1258fn moist_sound_speed_at_mole_fraction(temp_k: f64, mole_fraction_vapor: f64) -> f64 {
1259    // Heat-capacity ratio and gas constant for moist air (mole-fraction coefficients). 0.378 is
1260    // the dry-air molecular-weight ratio (0.6078 would belong to specific humidity, not mole
1261    // fraction).
1262    let gamma_moist = GAMMA * (1.0 - mole_fraction_vapor * 0.062);
1263    let r_moist = R_AIR * (1.0 + 0.378 * mole_fraction_vapor);
1264
1265    (gamma_moist * r_moist * temp_k).sqrt()
1266}
1267
1268/// The moist-air molar-mass ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`, where
1269/// `M_m = (1 - x_v) M_a + x_v M_v` is the molar mass of air holding a water-vapour mole fraction
1270/// `x_v`. The CIPM-2007 density ([`calculate_air_density_cimp`]) multiplies by it, and the
1271/// virtual-temperature lapse of [`air_at`] scales the dry hydrostatic exponent by it, so the lapse
1272/// and the density carry the same humidity term. Exactly 1 at `x_v = 0`.
1273///
1274/// The two gas constants still differ a little, dry air included: the lapse's ideal-gas `R_AIR /
1275/// (M_m / M_a)` and the `Z R / M_m` the CIPM-2007 density implies (its compressibility `Z`, and its
1276/// `R / M_a = 287.0478` against `R_AIR = 287.0531`) differ by 1.2e-4 to 9.0e-4 from -20 to 45 °C,
1277/// 700 to 1013.25 hPa and 0 to 100 %.
1278#[inline(always)]
1279fn moist_molar_mass_ratio(mole_fraction_vapor: f64) -> f64 {
1280    1.0 - mole_fraction_vapor * (1.0 - M_V / M_A)
1281}
1282
1283/// The water-vapour mole fraction of the GOVERNING air (the station's, or the active
1284/// [`AtmoSock`] zone's) that [`air_at`] holds at every height: the station sound speed's own
1285/// `x_v` ([`calculate_atmosphere`]'s kelvin and pascal conversions, then the one
1286/// [`vapor_mole_fraction`], capped at 1), so the air at the governing air's height is that air
1287/// to the bit. Exactly 0 at 0 %.
1288///
1289/// The one place this `x_v` is formed. It is evaluated once per base air, when a
1290/// [`StationAir`] or an [`AtmoSock`] is built (see [`GoverningAir`]), and per call only by the
1291/// legacy `get_local_atmosphere*` wrappers, whose base is a caller's raw tuple.
1292#[inline(always)]
1293fn governing_vapor_mole_fraction(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
1294    capped_vapor_mole_fraction(moist_air_vapor_mole_fraction(
1295        temp_c + 273.15,
1296        pressure_hpa * 100.0,
1297        humidity_percent,
1298    ))
1299}
1300
1301/// The water-vapour mole fraction capped at its physical maximum, 1: `x.min(1.0)` for every
1302/// number, to the bit, but a NaN stays a NaN (`f64::min` would return 1.0 for it, pure steam).
1303///
1304/// Every capped `x_v` in the engine goes through it ([`calculate_air_density_cimp`],
1305/// [`moist_speed_of_sound`], the governing air's `x_v` aloft), so a NaN humidity, or air above
1306/// water's critical point (647.096 K, where the saturation pressure is undefined), gives NaN
1307/// air everywhere instead of steam. A cap is reached only by air
1308/// that cannot exist, which every validated boundary refuses before it gets here.
1309#[inline(always)]
1310fn capped_vapor_mole_fraction(mole_fraction_vapor: f64) -> f64 {
1311    if mole_fraction_vapor > 1.0 {
1312        1.0
1313    } else {
1314        mole_fraction_vapor
1315    }
1316}
1317
1318/// Enhanced air density calculation using CIPM formula with ICAO atmosphere.
1319///
1320/// # Arguments
1321/// * `temp_c` - Temperature in Celsius
1322/// * `pressure_hpa` - Pressure in hPa
1323/// * `humidity_percent` - Humidity percentage (0-100)
1324///
1325/// # Returns
1326/// Air density in kg/m³
1327///
1328/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
1329/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
1330/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
1331/// refuse what this computes.
1332pub fn calculate_air_density_cimp(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
1333    let t_k = temp_c + 273.15;
1334
1335    // Enhanced saturation vapor pressure calculation
1336    let p_sv = enhanced_saturation_vapor_pressure(t_k);
1337
1338    let pressure_pa = pressure_hpa * 100.0;
1339
1340    // Enhanced enhancement factor with temperature dependence. CIPM constants use Pa.
1341    let f = enhanced_enhancement_factor(pressure_pa, temp_c);
1342
1343    // Floor the pressure divisor (mirrors calculate_atmosphere): a 0 hPa pressure would
1344    // otherwise make x_v = +Inf -> NaN density. No-op for all valid (>0) pressures.
1345    let p_pa = pressure_pa.max(f64::MIN_POSITIVE);
1346
1347    // Mole fraction of water vapor, capped at the physical maximum of 1 (a NaN stays NaN). The
1348    // cap is silent: air whose vapor pressure would exceed its total pressure does not exist,
1349    // and callers that must refuse it rather than compute pure steam test
1350    // `water_vapor_mole_fraction_uncapped` first (StationAir::new, AtmoSock::validate and the
1351    // bridge's `atmosphere.density_altitude`).
1352    let x_v = capped_vapor_mole_fraction(vapor_mole_fraction(p_sv, f, humidity_percent, p_pa));
1353
1354    // Enhanced compressibility factor. CIPM virial constants use Pa.
1355    let z = enhanced_compressibility_factor(p_pa, t_k, x_v);
1356
1357    // Calculate density with enhanced precision. The last factor is the moist-air molar-mass
1358    // ratio M_m / M_a, which the virtual-temperature lapse aloft scales by too.
1359    // Note: parentheses are important here for correct operator precedence
1360    ((p_pa * M_A) / (z * R * t_k)) * moist_molar_mass_ratio(x_v)
1361}
1362
1363/// CIPM-2007 mole fraction of water vapor, `x_v = RH * f * p_sv / p`, UNCAPPED: the one
1364/// formula [`calculate_air_density_cimp`] uses (it caps the result at 1). A value at or above 1
1365/// means the stated humidity would need more vapor pressure than the air has total pressure.
1366pub(crate) fn water_vapor_mole_fraction_uncapped(
1367    temp_c: f64,
1368    pressure_hpa: f64,
1369    humidity_percent: f64,
1370) -> f64 {
1371    let t_k = temp_c + 273.15;
1372    let p_sv = enhanced_saturation_vapor_pressure(t_k);
1373    let pressure_pa = pressure_hpa * 100.0;
1374    let f = enhanced_enhancement_factor(pressure_pa, temp_c);
1375    vapor_mole_fraction(
1376        p_sv,
1377        f,
1378        humidity_percent,
1379        pressure_pa.max(f64::MIN_POSITIVE),
1380    )
1381}
1382
1383/// [`water_vapor_mole_fraction_uncapped`] in the units the sound speed works in: temperature in
1384/// kelvin and total pressure in Pa. UNCAPPED; [`moist_speed_of_sound`] caps it at 1.
1385///
1386/// The enhancement factor reads `temp_k - 273.15`, which is not always the caller's Celsius
1387/// value to the last bit, so this is a separate entry rather than a call through the Celsius
1388/// one. Both reach the same [`vapor_mole_fraction`].
1389#[inline(always)]
1390fn moist_air_vapor_mole_fraction(temp_k: f64, pressure_pa: f64, humidity_percent: f64) -> f64 {
1391    let temp_c = temp_k - 273.15;
1392    let p_sv_hpa = enhanced_saturation_vapor_pressure(temp_k);
1393    let f = enhanced_enhancement_factor(pressure_pa, temp_c);
1394    vapor_mole_fraction(
1395        p_sv_hpa,
1396        f,
1397        humidity_percent,
1398        pressure_pa.max(f64::MIN_POSITIVE),
1399    )
1400}
1401
1402/// The engine's ONE water-vapour mole fraction, `x_v = (RH/100) * f * p_sv / p`, uncapped.
1403///
1404/// The CIPM-2007 density ([`calculate_air_density_cimp`]), the moist speed of sound
1405/// ([`moist_speed_of_sound`]) and the impossible-air test ([`water_vapor_mole_fraction_uncapped`],
1406/// behind [`StationAir::new`] and the density-altitude service) all evaluate it here, in this
1407/// operation order, so they cannot drift apart. `p_sv_hpa` is in hPa and `p_pa` in Pa; the
1408/// humidity is clamped into `[0, 100]` as a total-function guard for the unvalidated legacy
1409/// entry points (validated callers pass a [`RelativeHumidity`], already in range), and a NaN
1410/// humidity, or a NaN `p_sv_hpa` above water's critical point at any humidity above 0, gives a
1411/// NaN `x_v`, which [`capped_vapor_mole_fraction`] keeps.
1412///
1413/// Dry air holds no water vapour at any temperature: at 0 % `x_v` is exactly 0 whatever
1414/// `p_sv_hpa` is, so dry air above water's critical point (647.096 K, where `p_sv_hpa` is NaN)
1415/// is dry air, not air that cannot exist. Wherever `p_sv_hpa` is a number (below that point)
1416/// this is the very value the full formula gives, bit for bit: the same zero, with its sign,
1417/// and NaN for a NaN temperature or pressure (through `f`).
1418#[inline(always)]
1419pub(crate) fn vapor_mole_fraction(p_sv_hpa: f64, f: f64, humidity_percent: f64, p_pa: f64) -> f64 {
1420    let humidity_percent = humidity_percent.clamp(0.0, 100.0);
1421    if humidity_percent == 0.0 {
1422        // The full formula without its positive, finite p_sv factor (and the exact factors 100
1423        // and 1/100, which move no zero): the same signed zero, or NaN, as ever.
1424        return humidity_percent * f / p_pa;
1425    }
1426    // Vapor pressure with clamping. p_sv is in hPa (enhanced_saturation_vapor_pressure
1427    // returns hPa — its critical-pressure constant is 220640 hPa), so p_v is in hPa too.
1428    let p_v = humidity_percent / 100.0 * f * p_sv_hpa;
1429
1430    // Convert the vapor pressure to Pa BEFORE forming the mole fraction: the divisor below
1431    // is in Pa. Dividing the hPa p_v by the Pa total made x_v 100x too small, which erased
1432    // the humidity term and returned essentially dry-air density (e.g. 15 C / 1013.25 hPa /
1433    // 50% RH gave ~1.2254 instead of the CIPM-2007 moist value ~1.2216 — moist air is
1434    // LIGHTER than dry air).
1435    let p_v_pa = p_v * 100.0;
1436    p_v_pa / p_pa
1437}
1438
1439/// Saturation vapor pressure of water, hPa, over LIQUID water at every temperature (the WMO
1440/// convention for relative humidity, also below 0 °C; there is no ice branch).
1441///
1442/// The Wagner-Pruss saturation-pressure equation, the form of the IAPWS supplementary release
1443/// on the saturation properties of ordinary water substance:
1444/// `ln(p_sv / p_c) = (T_c / T) (a1 τ + a2 τ^1.5 + a3 τ^3 + a4 τ^3.5 + a5 τ^4 + a6 τ^7.5)` with
1445/// `τ = 1 - T / T_c`, `T_c = 647.096 K` and `p_c = 22.064 MPa`. (The industrial IF97
1446/// formulation's region-4 saturation equation is a different formula.)
1447#[inline(always)]
1448fn enhanced_saturation_vapor_pressure(t_k: f64) -> f64 {
1449    #[cfg(test)]
1450    air_trace::count_saturation_pressure();
1451
1452    // Wagner-Pruss coefficients a1..a6.
1453    const A: [f64; 6] = [
1454        -7.85951783,
1455        1.84408259,
1456        -11.7866497,
1457        22.6807411,
1458        -15.9618719,
1459        1.80122502,
1460    ];
1461
1462    // Ensure temperature is positive and reasonable
1463    let t_k_safe = t_k.max(173.15); // -100°C minimum
1464
1465    let tau = 1.0 - t_k_safe / 647.096; // Critical temperature of water
1466    let ln_p_ratio = (647.096 / t_k_safe)
1467        * (A[0] * tau
1468            + A[1] * tau.powf(1.5)
1469            + A[2] * tau.powf(3.0)
1470            + A[3] * tau.powf(3.5)
1471            + A[4] * tau.powf(4.0)
1472            + A[5] * tau.powf(7.5));
1473
1474    220640.0 * ln_p_ratio.exp() // Critical pressure in hPa (22.064 MPa)
1475}
1476
1477/// CIPM-2007 enhancement factor `f = alpha + beta*p + gamma*t^2` (p in Pa, t in Celsius).
1478#[inline(always)]
1479fn enhanced_enhancement_factor(p: f64, t: f64) -> f64 {
1480    const ALPHA: f64 = 1.00062;
1481    const BETA: f64 = 3.14e-8;
1482    const GAMMA: f64 = 5.6e-7;
1483
1484    ALPHA + BETA * p + GAMMA * t * t
1485}
1486
1487/// CIPM-2007 compressibility factor `Z` (virial expansion, second order in `p/T`).
1488#[inline(always)]
1489fn enhanced_compressibility_factor(p: f64, t_k: f64, x_v: f64) -> f64 {
1490    // CIPM-2007 molar virial coefficients (p in Pa, t in Celsius).
1491    const A0: f64 = 1.58123e-6;
1492    const A1: f64 = -2.9331e-8;
1493    const A2: f64 = 1.1043e-10;
1494    const B0: f64 = 5.707e-6;
1495    const B1: f64 = -2.051e-8;
1496    const C0: f64 = 1.9898e-4;
1497    const C1: f64 = -2.376e-6;
1498    const D: f64 = 1.83e-11;
1499    const E: f64 = -0.765e-8;
1500
1501    // Ensure temperature is positive
1502    let t_k_safe = t_k.max(173.15); // -100°C minimum
1503    let t = t_k_safe - 273.15;
1504    let p_t = p / t_k_safe;
1505
1506    let z_second_order =
1507        1.0 - p_t * (A0 + A1 * t + A2 * t * t + (B0 + B1 * t) * x_v + (C0 + C1 * t) * x_v * x_v);
1508
1509    let z_third_order = p_t * p_t * (D + E * x_v * x_v);
1510
1511    z_second_order + z_third_order
1512}
1513
1514/// Convert an `(x, y)` position in the shot-aligned frame to true world altitude.
1515///
1516/// The engine rotates gravity by `shooting_angle_rad`, so shot-frame X follows the inclined
1517/// line of fire and Y is perpendicular to it in the vertical plane. Atmosphere lookup needs the
1518/// world-vertical projection of that position, added to the station altitude.
1519#[inline]
1520pub(crate) fn shot_frame_altitude(
1521    base_altitude_m: f64,
1522    downrange_m: f64,
1523    shot_y_m: f64,
1524    shooting_angle_rad: f64,
1525) -> f64 {
1526    base_altitude_m + downrange_m * shooting_angle_rad.sin() + shot_y_m * shooting_angle_rad.cos()
1527}
1528
1529/// Local DRY air: [`get_local_atmosphere_humid`] at 0 % relative humidity.
1530///
1531/// Dry by contract, which is why it is deprecated: a flight's air has a humidity, and
1532/// [`air_at`] over a [`StationAir`] flies it. The replacement is
1533/// `air_at(&KernelAtmosphere::Station(StationAir::new(base_alt, base_temp_c, base_press_hpa,
1534/// humidity)?), None, 0.0, altitude_m)`; a caller that holds its own density ratio builds the
1535/// station with [`StationAir::with_density_ratio`] instead. The density is the same as every other
1536/// path's (the base ratio scaled by the lapse); the sound speed is the engine's one dry value,
1537/// `sqrt(1.4 · 287.0531 · T)`, the shared composition at [`RelativeHumidity::DRY`]. Until 0.50.0
1538/// this function used a second dry constant, `sqrt(401.874 · T)`, 4.2e-7 slower.
1539///
1540/// # Arguments
1541/// * `altitude_m` - Query geometric altitude above mean sea level in meters
1542/// * `base_alt` - Base geometric altitude above mean sea level in meters
1543/// * `base_temp_c` - Base temperature in Celsius
1544/// * `base_press_hpa` - Base pressure in hPa
1545/// * `base_ratio` - Base density ratio
1546///
1547/// # Returns
1548/// Tuple of (air_density_kg_m3, speed_of_sound_mps)
1549#[deprecated(
1550    since = "0.50.0",
1551    note = "dry air by contract; use air_at(&KernelAtmosphere::Station(StationAir::new(..)?), None, 0.0, altitude_m), or StationAir::with_density_ratio for a caller-held density ratio"
1552)]
1553pub fn get_local_atmosphere(
1554    altitude_m: f64,
1555    base_alt: f64,
1556    base_temp_c: f64,
1557    base_press_hpa: f64,
1558    base_ratio: f64,
1559) -> (f64, f64) {
1560    let air = compose_local_air(
1561        altitude_m,
1562        base_alt,
1563        &GoverningAir::new(
1564            base_temp_c,
1565            base_press_hpa,
1566            base_ratio,
1567            RelativeHumidity::DRY.percent(),
1568        ),
1569        Gravity::EARTH,
1570    );
1571    (air.density_kg_m3, air.speed_of_sound_mps)
1572}
1573
1574/// The local air, unvalidated: the same composition as [`air_at`], from a caller-held base
1575/// tuple. The base air's water-vapour mole fraction, from `base_temp_c`, `base_press_hpa` and
1576/// `humidity_percent`, is held at every height for the virtual-temperature lapse, the density
1577/// and the moist-air speed of sound at the local temperature.
1578///
1579/// A legacy entry point: it clamps an out-of-range humidity instead of refusing it (a NaN
1580/// propagates to NaN air, never to steam), and it cannot know whether `base_ratio` was built at
1581/// `humidity_percent`. In-crate code calls [`air_at`] with a [`KernelAtmosphere`] instead.
1582///
1583/// # Arguments
1584/// * `altitude_m` - Query geometric altitude above mean sea level in meters
1585/// * `base_alt` - Base (station) geometric altitude above mean sea level in meters
1586/// * `base_temp_c` - Base temperature in Celsius
1587/// * `base_press_hpa` - Base pressure in hPa
1588/// * `base_ratio` - Base density ratio (density / 1.225)
1589/// * `humidity_percent` - Relative humidity percentage (0-100)
1590///
1591/// # Returns
1592/// Tuple of (air_density_kg_m3, moist_speed_of_sound_mps)
1593pub fn get_local_atmosphere_humid(
1594    altitude_m: f64,
1595    base_alt: f64,
1596    base_temp_c: f64,
1597    base_press_hpa: f64,
1598    base_ratio: f64,
1599    humidity_percent: f64,
1600) -> (f64, f64) {
1601    get_local_atmosphere_humid_with_gravity(
1602        altitude_m,
1603        base_alt,
1604        base_temp_c,
1605        base_press_hpa,
1606        base_ratio,
1607        humidity_percent,
1608        Gravity::EARTH,
1609    )
1610}
1611
1612#[allow(clippy::too_many_arguments)]
1613pub(crate) fn get_local_atmosphere_humid_with_gravity(
1614    altitude_m: f64,
1615    base_alt: f64,
1616    base_temp_c: f64,
1617    base_press_hpa: f64,
1618    base_ratio: f64,
1619    humidity_percent: f64,
1620    gravity: Gravity,
1621) -> (f64, f64) {
1622    // The same composition `air_at` uses, without its validation: this legacy entry keeps its
1623    // internal clamp of an out-of-range humidity (a NaN gives NaN air), and can never diverge
1624    // from `air_at`. Its base is the caller's raw tuple, so it computes the base air's vapour
1625    // mole fraction on every call, through the same one formula.
1626    let air = compose_local_air(
1627        altitude_m,
1628        base_alt,
1629        &GoverningAir::new(base_temp_c, base_press_hpa, base_ratio, humidity_percent),
1630        gravity,
1631    );
1632    (air.density_kg_m3, air.speed_of_sound_mps)
1633}
1634
1635// =================================================================================================
1636// The single source of truth for humid air: a validated relative humidity, the station air built
1637// from it, the kernel atmosphere that carries it, and the one per-step air lookup.
1638// =================================================================================================
1639
1640/// The relative humidity, in percent, that an omitted humidity means: 50 %.
1641///
1642/// [`RelativeHumidity::DEFAULT`] holds the same value. `AtmosphericConditions::default` means
1643/// it, and solve v1's omitted `relative_humidity` is the same default in the SI wire's unit,
1644/// `RelativeHumidity::DEFAULT.fraction()` (exactly 0.5).
1645pub const DEFAULT_HUMIDITY_PERCENT: f64 = 50.0;
1646
1647/// How far, in percentage points, a relative-humidity READING may lie outside 0-100 % and
1648/// still be read as the saturated (100 %) or dry (0 %) air it measures: 5.
1649///
1650/// Weather is an input source, never a gate. The humidity a shooter enters is most often a
1651/// sensor's (a Kestrel, a WEATHERmeter, a phone), and relative-humidity sensors are good to
1652/// about ±2-3 %: in fog and other condensing air they read above 100 %, where free air is
1653/// supersaturated by under 1 %, and in very dry air they can read a little below 0 %. Such a
1654/// reading is sensor error around saturated or dry air, not a different atmosphere, and must
1655/// not fail a calculation. So [`RelativeHumidity::try_percent`] accepts a percent from -5 to
1656/// 105 and stores it clamped into 0..=100 (101.7 is exactly 100, -2 exactly 0), and
1657/// [`RelativeHumidity::try_fraction`] does the same with a fraction from -0.05 to 1.05. Every
1658/// surface reads humidity through those two constructors, so every surface has this band.
1659///
1660/// A value farther out is refused, as before: it is not a reading of real air but a wrong unit
1661/// (a percent sent as a fraction) or a typo. Air that cannot exist at all (a water-vapour mole
1662/// fraction of 1 or more) is a separate rule, [`StationAir::new`]'s, and the band does not
1663/// relax it.
1664pub const HUMIDITY_SENSOR_TOLERANCE_PERCENT: f64 = 5.0;
1665
1666/// The percents [`RelativeHumidity::try_percent`] accepts: the sensor band around 0..=100.
1667const HUMIDITY_PERCENT_BAND: (f64, f64) = (
1668    -HUMIDITY_SENSOR_TOLERANCE_PERCENT,
1669    100.0 + HUMIDITY_SENSOR_TOLERANCE_PERCENT,
1670);
1671
1672/// The fractions [`RelativeHumidity::try_fraction`] accepts: the same band in fraction units,
1673/// exactly -0.05 and 1.05.
1674const HUMIDITY_FRACTION_BAND: (f64, f64) = (
1675    -HUMIDITY_SENSOR_TOLERANCE_PERCENT / 100.0,
1676    1.0 + HUMIDITY_SENSOR_TOLERANCE_PERCENT / 100.0,
1677);
1678
1679/// Absolute zero in degrees Celsius; a station temperature must lie above it.
1680const ABSOLUTE_ZERO_C: f64 = -273.15;
1681/// The density ratio `density / 1.225 kg/m³` a station may carry is below this (and above 0).
1682/// It is `fast_integrate`'s ceiling for a supplied standard-mode ratio.
1683const MAX_STATION_DENSITY_RATIO: f64 = 2.0;
1684/// Uniform (direct-mode) air must have a density below this, in kg/m³, and at least 0 (a
1685/// vacuum): 0.49.0's `compute_derivatives` direct-mode detection, `density < 2`, which took a
1686/// density of exactly 0 as the way to switch drag off.
1687const MAX_UNIFORM_DENSITY_KG_M3: f64 = 2.0;
1688/// Uniform (direct-mode) air must have a speed of sound above this, in m/s. The same bound the
1689/// kernels' direct-mode detection uses today.
1690const MIN_UNIFORM_SPEED_OF_SOUND_MPS: f64 = 200.0;
1691
1692/// A validated relative humidity.
1693///
1694/// It stores a PERCENT in `[0, 100]`, and [`Self::fraction`] gives the same humidity in
1695/// `[0, 1]`. The two constructors name the unit at the call site, and there is deliberately no
1696/// `From<f64>`, so a bare number is never read in the wrong unit.
1697///
1698/// One rule, the sensor band ([`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]): a reading up to 5 points
1699/// outside the range is the saturated or dry air it measures, stored as exactly 100 or 0, so it
1700/// flies exactly as that end does. Anything farther out, or not finite, is refused with an
1701/// [`AtmosphereError`] that reports the value unchanged.
1702///
1703/// ```
1704/// use ballistics_engine::RelativeHumidity;
1705///
1706/// let from_percent = RelativeHumidity::try_percent(50.0).unwrap();
1707/// let from_fraction = RelativeHumidity::try_fraction(0.5).unwrap();
1708/// assert_eq!(from_percent, from_fraction);
1709/// assert_eq!(from_percent, RelativeHumidity::DEFAULT);
1710/// assert_eq!(from_fraction.percent(), 50.0);
1711/// assert_eq!(from_percent.fraction(), 0.5);
1712///
1713/// // A sensor reading in fog, or in very dry air, is that air.
1714/// assert_eq!(RelativeHumidity::try_percent(101.7).unwrap().percent(), 100.0);
1715/// assert_eq!(RelativeHumidity::try_percent(-2.0).unwrap(), RelativeHumidity::DRY);
1716/// assert_eq!(RelativeHumidity::try_fraction(1.03).unwrap().percent(), 100.0);
1717///
1718/// assert!(RelativeHumidity::try_percent(150.0).is_err());
1719/// assert!(RelativeHumidity::try_percent(105.0000001).is_err());
1720/// // A percent sent where a fraction belongs is refused, not read as 50 %.
1721/// assert!(RelativeHumidity::try_fraction(50.0).is_err());
1722/// ```
1723///
1724/// A bare `f64` does not convert, because it does not say whether 0.5 means 50 % or 0.5 %
1725/// (E0277: no `From<f64>`):
1726///
1727/// ```compile_fail,E0277
1728/// use ballistics_engine::RelativeHumidity;
1729///
1730/// let humidity: RelativeHumidity = 0.5.into();
1731/// ```
1732#[derive(Debug, Clone, Copy, PartialEq)]
1733pub struct RelativeHumidity(f64);
1734
1735impl RelativeHumidity {
1736    /// The default for an omitted humidity: [`DEFAULT_HUMIDITY_PERCENT`], 50 %.
1737    pub const DEFAULT: Self = Self(DEFAULT_HUMIDITY_PERCENT);
1738
1739    /// Dry air, 0 %.
1740    pub const DRY: Self = Self(0.0);
1741
1742    /// The lowest and the highest fraction [`Self::try_fraction`] accepts, both included: the
1743    /// sensor band ([`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]) in fraction units, exactly
1744    /// `(-0.05, 1.05)`.
1745    ///
1746    /// For a schema that publishes the bounds the decoder enforces (the MCP server's
1747    /// `relative_humidity`), so the band it states is derived from the one number rather than
1748    /// written out again.
1749    pub const FRACTION_BAND: (f64, f64) = HUMIDITY_FRACTION_BAND;
1750
1751    /// A relative humidity given in PERCENT.
1752    ///
1753    /// Accepts a finite `percent` from -5 to 105, both ends included (the sensor band,
1754    /// [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]). A percent in `0.0..=100.0` is stored unchanged,
1755    /// one above 100 as exactly 100 and one below 0 (or `-0.0`) as `0.0`. Anything else is
1756    /// refused, with field `humidity_percent`, the value unchanged, and reason
1757    /// [`AtmosphereErrorReason::NotFinite`] or
1758    /// [`AtmosphereErrorReason::HumidityPercentOutOfRange`].
1759    pub fn try_percent(percent: f64) -> Result<Self, AtmosphereError> {
1760        sensor_band(
1761            percent,
1762            HUMIDITY_PERCENT_BAND,
1763            100.0,
1764            "humidity_percent",
1765            AtmosphereErrorReason::HumidityPercentOutOfRange,
1766        )
1767        .map(Self)
1768    }
1769
1770    /// A relative humidity given as a FRACTION, the SI wire's `relative_humidity`.
1771    ///
1772    /// Accepts a finite `fraction` from -0.05 to 1.05, both ends included (the sensor band in
1773    /// fraction units), and stores the fraction snapped into `0.0..=1.0` times 100: an
1774    /// in-range fraction is `fraction * 100.0`, exact at 0, 0.5 and 1 and within one ulp of the
1775    /// decimal percent elsewhere, one above 1 is exactly 100, one below 0 is 0. Anything else is
1776    /// refused, with field `relative_humidity`, the value unchanged, and reason
1777    /// [`AtmosphereErrorReason::NotFinite`] or
1778    /// [`AtmosphereErrorReason::HumidityFractionOutOfRange`]; so a percent sent by mistake
1779    /// (`50.0`) is an error rather than 5000 %.
1780    pub fn try_fraction(fraction: f64) -> Result<Self, AtmosphereError> {
1781        // The very conversion solve v1 and the density-altitude service apply today, so a
1782        // caller moving onto this constructor flies the same bits.
1783        Self::snap_fraction(fraction).map(|fraction| Self(fraction * 100.0))
1784    }
1785
1786    /// The fraction [`Self::try_fraction`] accepts, snapped into `0.0..=1.0` in the fraction's
1787    /// own unit: an in-range fraction comes back with its bits unchanged (`-0.0` as `0.0`),
1788    /// one above 1 as exactly 1 and one below 0 as 0. For a wire that echoes the fraction it
1789    /// flies (solve v1's resolved `relative_humidity`); its errors are `try_fraction`'s.
1790    pub(crate) fn snap_fraction(fraction: f64) -> Result<f64, AtmosphereError> {
1791        sensor_band(
1792            fraction,
1793            HUMIDITY_FRACTION_BAND,
1794            1.0,
1795            "relative_humidity",
1796            AtmosphereErrorReason::HumidityFractionOutOfRange,
1797        )
1798    }
1799
1800    /// Whether `fraction` is a relative humidity in `0.0..=1.0` itself, not merely a sensor
1801    /// reading the band reads as one: exactly the fractions [`Self::snap_fraction`] leaves
1802    /// where it found them (`-0.0` included, NaN and the infinities not).
1803    ///
1804    /// For a caller that moves a humidity HYPOTHETICALLY rather than reading one, the
1805    /// perturbation layer's central difference: a perturbed 1.001 is not fog read by a sensor,
1806    /// and flying it as saturated air would silently halve the derivative at the end.
1807    pub(crate) fn is_physical_fraction(fraction: f64) -> bool {
1808        matches!(Self::snap_fraction(fraction), Ok(snapped) if snapped == fraction)
1809    }
1810
1811    /// The humidity in percent, `0.0..=100.0`.
1812    pub const fn percent(self) -> f64 {
1813        self.0
1814    }
1815
1816    /// The humidity as a fraction, `0.0..=1.0` (`percent / 100`).
1817    ///
1818    /// A `const fn`, so a wire default can be written as the one default in the wire's unit:
1819    /// `RelativeHumidity::DEFAULT.fraction()` is exactly `0.5`.
1820    pub const fn fraction(self) -> f64 {
1821        self.0 / 100.0
1822    }
1823}
1824
1825/// The one sensor-band rule, in a unit whose saturated air is `saturated` (100 for a percent,
1826/// 1 for a fraction): a finite `value` inside `band` comes back snapped into
1827/// `0.0..=saturated` (at or below 0, `-0.0` included, as `+0.0`; above `saturated` as exactly
1828/// `saturated`; otherwise unchanged); anything else is refused with `field` and the value
1829/// unchanged.
1830fn sensor_band(
1831    value: f64,
1832    (lowest, highest): (f64, f64),
1833    saturated: f64,
1834    field: &'static str,
1835    out_of_band: AtmosphereErrorReason,
1836) -> Result<f64, AtmosphereError> {
1837    let unit = match out_of_band {
1838        AtmosphereErrorReason::HumidityFractionOutOfRange => HumidityUnit::Fraction,
1839        _ => HumidityUnit::Percent,
1840    };
1841    if !value.is_finite() {
1842        return Err(
1843            AtmosphereError::new(field, value, AtmosphereErrorReason::NotFinite).of_humidity(unit),
1844        );
1845    }
1846    if !(lowest..=highest).contains(&value) {
1847        return Err(AtmosphereError::new(field, value, out_of_band).of_humidity(unit));
1848    }
1849    Ok(if value <= 0.0 {
1850        0.0
1851    } else if value > saturated {
1852        saturated
1853    } else {
1854        value
1855    })
1856}
1857
1858/// The range of a relative humidity PERCENT as every refusal states it, built from
1859/// [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] so the words cannot drift from the band the
1860/// constructor enforces: `percent from 0 to 100 (a sensor reading from -5 to 105 is read as 0 or
1861/// 100)`.
1862fn humidity_percent_range() -> String {
1863    format!(
1864        "percent from 0 to 100 (a sensor reading from {} to {} is read as 0 or 100)",
1865        HUMIDITY_PERCENT_BAND.0, HUMIDITY_PERCENT_BAND.1
1866    )
1867}
1868
1869/// The range of a relative humidity FRACTION (the SI wire's `relative_humidity`) as every
1870/// refusal states it, from the same constant: `fraction from 0 to 1 (0.5 = 50 %; a sensor
1871/// reading from -0.05 to 1.05 is read as 0 or 1)`.
1872fn humidity_fraction_range() -> String {
1873    format!(
1874        "fraction from 0 to 1 (0.5 = 50 %; a sensor reading from {} to {} is read as 0 or 1)",
1875        HUMIDITY_FRACTION_BAND.0, HUMIDITY_FRACTION_BAND.1
1876    )
1877}
1878
1879/// Parse a relative-humidity PERCENT typed as text (a terminal or CLI flag's value) through the
1880/// one validator, [`RelativeHumidity::try_percent`].
1881///
1882/// The error is the reason alone, for a caller that names the flag and the value itself (clap
1883/// does): `not a number; relative humidity is a percent from 0 to 100 (a sensor reading from -5
1884/// to 105 is read as 0 or 100)` for text that is no number, and
1885/// [`AtmosphereError::explanation`] for a number the band refuses.
1886///
1887/// ```
1888/// use ballistics_engine::atmosphere::parse_humidity_percent_text;
1889///
1890/// assert_eq!(parse_humidity_percent_text("101.7").unwrap().percent(), 100.0);
1891/// assert!(parse_humidity_percent_text("150")
1892///     .unwrap_err()
1893///     .starts_with("relative humidity must be a percent from 0 to 100 (a sensor reading"));
1894/// assert!(parse_humidity_percent_text("wet").unwrap_err().starts_with("not a number; "));
1895/// ```
1896pub fn parse_humidity_percent_text(raw: &str) -> Result<RelativeHumidity, String> {
1897    let value: f64 = raw.trim().parse().map_err(|_| {
1898        format!(
1899            "not a number; relative humidity is a {}",
1900            humidity_percent_range()
1901        )
1902    })?;
1903    RelativeHumidity::try_percent(value).map_err(|error| error.explanation())
1904}
1905
1906/// Parse a terminal humidity flag's value (`--humidity 37.5`, `--zero-humidity 80`) through the
1907/// one validator, [`RelativeHumidity::try_percent`]: a PERCENT, 0 to 100, and a sensor reading
1908/// up to [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] outside it is the end it reads as (`101.7` gives
1909/// `100.0`); anything farther out is refused, never clamped. The WASM terminal's hand-written
1910/// parser calls it for every humidity flag (the native CLI's clap parser goes through
1911/// [`parse_humidity_percent_text`]); its errors name the flag, for example
1912/// `"--humidity = 150: relative humidity must be a percent from 0 to 100 (a sensor reading from
1913/// -5 to 105 is read as 0 or 100)"`.
1914#[cfg(any(target_arch = "wasm32", test))]
1915pub(crate) fn parse_humidity_percent_arg(flag: &str, raw: &str) -> Result<f64, String> {
1916    match raw.trim().parse::<f64>() {
1917        Ok(value) => RelativeHumidity::try_percent(value)
1918            .map(RelativeHumidity::percent)
1919            .map_err(|error| error.at_field(flag.to_string()).to_string()),
1920        Err(_) => Err(format!(
1921            "{flag} = {raw}: {}",
1922            parse_humidity_percent_text(raw).expect_err("text that is no number")
1923        )),
1924    }
1925}
1926
1927/// Why an atmosphere value was refused. Carried by [`AtmosphereError`].
1928#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1929#[non_exhaustive]
1930pub enum AtmosphereErrorReason {
1931    /// The value is NaN or infinite.
1932    NotFinite,
1933    /// A relative humidity percent outside `[0, 100]` by more than the sensor band,
1934    /// [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`]: below -5 or above 105. It displays the band it
1935    /// enforces: "relative humidity must be a percent from 0 to 100 (a sensor reading from -5 to
1936    /// 105 is read as 0 or 100)".
1937    HumidityPercentOutOfRange,
1938    /// A relative humidity fraction outside `[0, 1]` by more than the sensor band: below -0.05
1939    /// or above 1.05. It displays the band in fraction units: "relative humidity must be a
1940    /// fraction from 0 to 1 (0.5 = 50 %; a sensor reading from -0.05 to 1.05 is read as 0 or 1)".
1941    HumidityFractionOutOfRange,
1942    /// A temperature at or below absolute zero, -273.15 °C.
1943    AtOrBelowAbsoluteZero,
1944    /// A pressure at or below zero.
1945    NonPositivePressure,
1946    /// Air that cannot exist: the stated humidity needs a water-vapour mole fraction of 1 or
1947    /// more, that is more vapour pressure than the air's total pressure; or the air is humid
1948    /// above water's critical point (647.096 K), where no saturation vapour pressure, and so no
1949    /// relative humidity, is defined; or, dry above that point, it is too hot for the CIPM-2007
1950    /// density to stay finite and positive; or its pressure is so far beyond any air's (above
1951    /// about 4e156 Pa) that the density does not either. Dry air at any lower temperature above
1952    /// absolute zero exists. The same refusal the `atmosphere.density_altitude` service makes.
1953    ImpossibleAir,
1954    /// A station density ratio (density / 1.225 kg/m³) outside `(0, 2)`.
1955    DensityRatioOutOfRange,
1956    /// A uniform (direct-mode) air density outside `[0, 2)` kg/m³ (0 is a vacuum).
1957    UniformDensityOutOfRange,
1958    /// A uniform (direct-mode) speed of sound at or below 200 m/s.
1959    UniformSpeedOfSoundOutOfRange,
1960    /// A downrange atmosphere zone whose `until_distance_m` is not above 0.
1961    NonPositiveZoneThreshold,
1962    /// Air that cannot exist aloft: from this station (or downrange zone) temperature the
1963    /// standard lapse takes the air to absolute zero, at an altitude the flight reaches. Every
1964    /// trajectory kernel refuses the flight at the step that gets there, with this reason on the
1965    /// temperature ([`AtmosphereError::field`] `temperature_c`, the governing air's temperature);
1966    /// [`AtmosphereError::altitude_m`] is where the air reaches 0 K. A flight that stays below
1967    /// that height flies.
1968    AirAloftBelowAbsoluteZero,
1969    /// A density altitude no air has by the FAA rule its entry inverts
1970    /// ([`station_for_density_altitude`]): at its pressure altitude by that rule
1971    /// ([`AtmosphereError::altitude_m`]) the NWS pressure formula gives no finite pressure above
1972    /// 0 (at or above 145366.45 ft, 44308 m), or, with no temperature given, the rule's standard
1973    /// temperature is at or below absolute zero (at or above 145286 ft, 44283 m). On the field
1974    /// `density_altitude_m`.
1975    NoAirAtDensityAltitude,
1976}
1977
1978impl fmt::Display for AtmosphereErrorReason {
1979    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1980        f.write_str(match self {
1981            Self::NotFinite => "must be finite",
1982            Self::HumidityPercentOutOfRange => {
1983                return write!(
1984                    f,
1985                    "relative humidity must be a {}",
1986                    humidity_percent_range()
1987                )
1988            }
1989            Self::HumidityFractionOutOfRange => {
1990                return write!(
1991                    f,
1992                    "relative humidity must be a {}",
1993                    humidity_fraction_range()
1994                )
1995            }
1996            Self::AtOrBelowAbsoluteZero => "temperature must be above absolute zero (-273.15 °C)",
1997            Self::NonPositivePressure => "pressure must be greater than 0",
1998            Self::ImpossibleAir => {
1999                "no such air exists: at this temperature and pressure the humidity needs a \
2000                 water-vapour mole fraction of 1 or more (more vapour pressure than the total), \
2001                 or the air is humid above water's critical point, or too hot or too dense to \
2002                 have a density"
2003            }
2004            Self::DensityRatioOutOfRange => {
2005                "density ratio (density / 1.225 kg/m^3) must be greater than 0 and less than 2"
2006            }
2007            Self::UniformDensityOutOfRange => {
2008                "air density must be at least 0 (a vacuum) and less than 2 kg/m^3"
2009            }
2010            Self::UniformSpeedOfSoundOutOfRange => "speed of sound must be greater than 200 m/s",
2011            Self::NonPositiveZoneThreshold => {
2012                "an atmosphere zone's until_distance_m must be greater than 0"
2013            }
2014            Self::AirAloftBelowAbsoluteZero => "the air aloft would fall below absolute zero",
2015            Self::NoAirAtDensityAltitude => "no air has this density altitude by the FAA rule",
2016        })
2017    }
2018}
2019
2020/// The unit a refused relative humidity was given in, so a refusal that names no range of its
2021/// own (a NaN) can still state the one the value had to lie in.
2022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2023enum HumidityUnit {
2024    Percent,
2025    Fraction,
2026}
2027
2028/// An atmosphere value refused at a boundary: which field, the value given, and why.
2029///
2030/// The constructors name their own parameters (`humidity_percent`, `relative_humidity`,
2031/// `temperature_c`, `pressure_hpa`, ...). A boundary that knows the caller's path, such as a
2032/// JSON pointer, relabels the error with [`Self::at_field`], or states the whole refusal in its
2033/// own words with [`Self::refusal_in`]. It displays as `"<field> = <value>: <explanation>"`.
2034#[derive(Debug, Clone, PartialEq)]
2035pub struct AtmosphereError {
2036    field: Cow<'static, str>,
2037    value: f64,
2038    reason: AtmosphereErrorReason,
2039    humidity_unit: Option<HumidityUnit>,
2040    /// Where air that cannot exist aloft reaches absolute zero, m above mean sea level.
2041    altitude_m: Option<f64>,
2042}
2043
2044impl AtmosphereError {
2045    /// Find a typed atmosphere refusal through a service's error chain.
2046    /// Keep the cause until the boundary can name the reading in its own units.
2047    pub fn in_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Self> {
2048        let mut current = Some(error);
2049        while let Some(error) = current {
2050            if let Some(air) = error.downcast_ref::<Self>() {
2051                return Some(air);
2052            }
2053            current = error.source();
2054        }
2055        None
2056    }
2057
2058    /// Name a refusal discovered aloft using the same temperature source as the station check.
2059    pub fn temperature_refusal(&self, field: AirField<'_>, units: AirUnits) -> AirRefusal {
2060        self.temperature_refusal_from(field, units, StationTemperatureOrigin::Reading)
2061    }
2062
2063    /// Like [`Self::temperature_refusal`], retaining a density altitude's derived temperature.
2064    pub fn temperature_refusal_from(
2065        &self,
2066        field: AirField<'_>,
2067        units: AirUnits,
2068        origin: StationTemperatureOrigin,
2069    ) -> AirRefusal {
2070        let reading = match origin {
2071            StationTemperatureOrigin::Reading => {
2072                format!("{} = {}", field.name, units.temperature.text(self.value))
2073            }
2074            StationTemperatureOrigin::DensityAltitude => format!(
2075                "{} gives a station temperature of {}",
2076                field.name,
2077                units.temperature.text(self.value)
2078            ),
2079        };
2080        AirRefusal {
2081            path: field.path.to_string(),
2082            message: format!("{reading}: {}", self.explanation_in(units.altitude)),
2083            reason: self.reason,
2084        }
2085    }
2086
2087    fn new(field: &'static str, value: f64, reason: AtmosphereErrorReason) -> Self {
2088        Self {
2089            field: Cow::Borrowed(field),
2090            value,
2091            reason,
2092            humidity_unit: None,
2093            altitude_m: None,
2094        }
2095    }
2096
2097    /// Air that cannot exist aloft: from the governing air's `temperature_c` the standard lapse
2098    /// reaches absolute zero at `altitude_m` (geometric, above mean sea level), which the flight
2099    /// reaches.
2100    fn aloft(temperature_c: f64, altitude_m: f64) -> Self {
2101        Self {
2102            altitude_m: Some(altitude_m),
2103            ..Self::new(
2104                "temperature_c",
2105                temperature_c,
2106                AtmosphereErrorReason::AirAloftBelowAbsoluteZero,
2107            )
2108        }
2109    }
2110
2111    /// The same error, about a relative humidity given in `unit`.
2112    fn of_humidity(mut self, unit: HumidityUnit) -> Self {
2113        self.humidity_unit = Some(unit);
2114        self
2115    }
2116
2117    /// Why the value was refused, in words: the reason's own text, naming the quantity and the
2118    /// range it must lie in where the reason alone would not. A relative humidity that is not
2119    /// finite is "relative humidity must be a finite percent from 0 to 100 (a sensor reading
2120    /// from -5 to 105 is read as 0 or 100)", not a bare "must be finite"; every other refusal is
2121    /// its [`AtmosphereErrorReason`]'s text.
2122    ///
2123    /// For a caller that names the field itself (a flag parser). Any altitude it quotes is in
2124    /// metres; [`Self::explanation_in`] states it in another unit.
2125    pub fn explanation(&self) -> String {
2126        self.explanation_in(AltitudeUnit::Meters)
2127    }
2128
2129    /// [`Self::explanation`] with any altitude it quotes (where air that cannot exist aloft
2130    /// reaches absolute zero) in `altitude_unit`: `"... reaches 0 K at 5049 ft above mean sea
2131    /// level ..."` in feet.
2132    pub fn explanation_in(&self, altitude_unit: AltitudeUnit) -> String {
2133        match (self.reason, self.humidity_unit) {
2134            (AtmosphereErrorReason::NotFinite, Some(HumidityUnit::Percent)) => format!(
2135                "relative humidity must be a finite {}",
2136                humidity_percent_range()
2137            ),
2138            (AtmosphereErrorReason::NotFinite, Some(HumidityUnit::Fraction)) => format!(
2139                "relative humidity must be a finite {}",
2140                humidity_fraction_range()
2141            ),
2142            (reason @ AtmosphereErrorReason::AirAloftBelowAbsoluteZero, _) => {
2143                match self.altitude_m {
2144                    Some(altitude_m) => format!(
2145                        "{reason}: from this temperature the standard lapse reaches 0 K at {} \
2146                         above mean sea level, which this flight reaches (check the temperature \
2147                         and its unit)",
2148                        altitude_unit.text(altitude_m)
2149                    ),
2150                    None => reason.to_string(),
2151                }
2152            }
2153            (AtmosphereErrorReason::NoAirAtDensityAltitude, _) => match self.altitude_m {
2154                Some(pressure_altitude_m) => {
2155                    let cause =
2156                        if nws_station_pressure_hpa(pressure_altitude_m / DA_FT_TO_M).is_some() {
2157                            "the rule's standard temperature is at or below absolute zero"
2158                        } else {
2159                            "the NWS pressure formula gives no finite pressure above 0"
2160                        };
2161                    format!(
2162                        "no air has this density altitude: at its pressure altitude by the FAA \
2163                         rule, {}, {cause} (check the density altitude and its unit)",
2164                        altitude_unit.text(pressure_altitude_m)
2165                    )
2166                }
2167                None => AtmosphereErrorReason::NoAirAtDensityAltitude.to_string(),
2168            },
2169            (reason, _) => reason.to_string(),
2170        }
2171    }
2172
2173    /// For air that cannot exist aloft ([`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]),
2174    /// the geometric altitude above mean sea level, m, at which the lapse from the refused
2175    /// temperature reaches absolute zero; `None` for every other refusal.
2176    pub fn altitude_m(&self) -> Option<f64> {
2177        self.altitude_m
2178    }
2179
2180    /// The refused field's name or path.
2181    pub fn field(&self) -> &str {
2182        &self.field
2183    }
2184
2185    /// The value that was refused, unchanged.
2186    pub fn value(&self) -> f64 {
2187        self.value
2188    }
2189
2190    /// Why it was refused.
2191    pub fn reason(&self) -> AtmosphereErrorReason {
2192        self.reason
2193    }
2194
2195    /// The same error under the caller's own name for the field, for example
2196    /// `"$.atmosphere.relative_humidity"`.
2197    pub fn at_field(mut self, field: impl Into<Cow<'static, str>>) -> Self {
2198        self.field = field.into();
2199        self
2200    }
2201}
2202
2203impl fmt::Display for AtmosphereError {
2204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2205        write!(
2206            f,
2207            "{} = {}: {}",
2208            self.field,
2209            echo_number(self.value),
2210            self.explanation()
2211        )
2212    }
2213}
2214
2215impl std::error::Error for AtmosphereError {}
2216
2217/// The bottom of the band the NWS pressure-altitude formula is read in, m: the bottom of the
2218/// ICAO table.
2219pub(crate) const LOWEST_PRESSURE_ALTITUDE_M: f64 = -5_000.0;
2220/// The top of the standard atmosphere's troposphere, m, and of the band the NWS
2221/// pressure-altitude formula is read in ([`pressure_altitude_m`]). No reading is refused for a
2222/// pressure altitude outside the band; it only decides which reading air that cannot exist is
2223/// blamed on ([`AtmosphereError::refusal_in`]), since a station pressure there is far likelier a
2224/// unit mistake (hPa sent as pascals is 25 km up) than a humidity.
2225pub(crate) const TROPOSPHERE_TOP_M: f64 = 11_000.0;
2226
2227/// The pressure altitude of a station pressure, m ([`pressure_altitude_m`]), when it lies
2228/// outside the troposphere's band.
2229pub(crate) fn pressure_altitude_outside_troposphere_m(station_pressure_hpa: f64) -> Option<f64> {
2230    let nws_m = nws_pressure_altitude_ft(station_pressure_hpa) * DA_FT_TO_M;
2231    (!(LOWEST_PRESSURE_ALTITUDE_M..=TROPOSPHERE_TOP_M).contains(&nws_m))
2232        .then(|| pressure_altitude_m(station_pressure_hpa))
2233}
2234
2235/// °C to K.
2236const KELVIN_OFFSET: f64 = 273.15;
2237
2238/// Water's critical temperature, K: above it no saturation vapour pressure (and so no relative
2239/// humidity) is defined, and only dry air exists.
2240const WATER_CRITICAL_TEMPERATURE_K: f64 = 647.096;
2241
2242/// −100 °C. The engine's saturation-vapour-pressure and CIPM compressibility formulas clamp
2243/// their temperature here: below it the humidity terms are extrapolated (evaluated at this
2244/// temperature), while the rest of the density is the air's own.
2245pub(crate) const HUMID_AIR_MODEL_MIN_K: f64 = 173.15;
2246/// 100 °C. Above the boiling point the saturation-vapour-pressure formula stops describing a
2247/// stable atmosphere, and above water's critical point (647.096 K) it is not defined at all:
2248/// there only dry air exists.
2249pub(crate) const HUMID_AIR_MODEL_MAX_K: f64 = 373.15;
2250
2251/// Whether a station temperature, K, lies outside [`HUMID_AIR_MODEL_MIN_K`] to
2252/// [`HUMID_AIR_MODEL_MAX_K`] (both edges inside), where the humid-air terms are extrapolated.
2253///
2254/// Not a refusal: no surface refuses a temperature for lying outside this range. It only
2255/// decides which reading air that cannot exist is blamed on ([`AtmosphereError::refusal_in`]):
2256/// outside the range the formulas hold for, the temperature is the likelier mistake (°F typed as
2257/// °C, °C sent as kelvin) than the humidity.
2258pub(crate) fn outside_humid_air_model_range(temperature_k: f64) -> bool {
2259    !(HUMID_AIR_MODEL_MIN_K..=HUMID_AIR_MODEL_MAX_K).contains(&temperature_k)
2260}
2261
2262/// Where the station pressure a solve flies came from, so air that cannot exist at a station
2263/// pressure outside the troposphere is blamed on the reading that put it there: the pressure
2264/// when it was a station reading, the altitude when the pressure was the altitude's.
2265///
2266/// Every surface decides it one way, through [`Self::of`] (or [`Self::resolving`], from what a
2267/// presence-aware resolution was handed), or, for a station a density altitude gave,
2268/// [`Self::DensityAltitude`].
2269#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2270pub enum StationPressureOrigin {
2271    /// A station pressure reading, or a QNH that is itself outside the troposphere (hPa sent as
2272    /// pascals): the pressure is to blame.
2273    #[default]
2274    Reading,
2275    /// No pressure was given: the station flies the ICAO standard pressure at its altitude, so
2276    /// the altitude is to blame (feet sent as metres).
2277    Standard,
2278    /// A QNH that is itself a plausible sea-level pressure, reduced to the station altitude: the
2279    /// altitude is to blame.
2280    Qnh,
2281    /// A density altitude's station ([`station_for_density_altitude`]): the density altitude is
2282    /// to blame. A surface names the derived pressure by the density altitude's field,
2283    /// so the refusal blames [`AirSpelling::pressure`] even if the altitude was overridden.
2284    DensityAltitude,
2285}
2286
2287impl StationPressureOrigin {
2288    /// The origin of a station pressure from what was given: `given_hpa` is the pressure as
2289    /// given (a QNH before its reduction), or `None` when none was given and the station flies
2290    /// the standard pressure at its altitude; `mode` says whether a given pressure is a QNH.
2291    pub fn of(given_hpa: Option<f64>, mode: PressureReferenceMode) -> Self {
2292        match (given_hpa, mode) {
2293            (None, _) => Self::Standard,
2294            (Some(qnh_hpa), PressureReferenceMode::Qnh)
2295                if pressure_altitude_outside_troposphere_m(qnh_hpa).is_none() =>
2296            {
2297                Self::Qnh
2298            }
2299            (Some(_), _) => Self::Reading,
2300        }
2301    }
2302
2303    /// The origin of the pressure [`resolve_station_conditions_with_presence`] resolves from
2304    /// these same inputs: a pressure the presence rule replaces with the ICAO standard at the
2305    /// altitude (an omitted sea-level default at a real altitude) is the standard's; any other
2306    /// is the given one, a QNH or a reading.
2307    pub fn resolving(
2308        pressure_hpa: f64,
2309        altitude_m: f64,
2310        mode: PressureReferenceMode,
2311        presence: StationAtmospherePresence,
2312    ) -> Self {
2313        let given = presence.pressure_supplied
2314            || resolve_station_pressure_with_mode(pressure_hpa, altitude_m, mode).is_some();
2315        Self::of(given.then_some(pressure_hpa), mode)
2316    }
2317}
2318
2319/// Where the station temperature a solve flies came from, so air that cannot exist, blamed on
2320/// the temperature, names the reading that carried it.
2321#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2322pub enum StationTemperatureOrigin {
2323    /// A temperature reading, or, when none was given, the ICAO standard temperature at the
2324    /// station altitude (which never leaves the range the humid-air formulas hold for, so no
2325    /// refusal blames it).
2326    #[default]
2327    Reading,
2328    /// The temperature of a density altitude's station, given no temperature
2329    /// ([`station_for_density_altitude`]): the density altitude is to blame. A surface that
2330    /// flies one names the temperature by the density altitude's field.
2331    DensityAltitude,
2332}
2333
2334/// Where a station's pressure and temperature came from, as a surface that resolved the station
2335/// itself states them to a refusal of its air
2336/// ([`crate::cli_api::AtmosphericConditions::air_refusal_from`]): the reading to blame, and the
2337/// QNH as it was given when the pressure was one, so the refusal quotes what was sent, never the
2338/// station pressure reduced from it as if it had been sent.
2339///
2340/// Build one with [`Self::of`] or [`Self::resolving`] (from the pressure as given, a QNH before
2341/// its reduction) or [`Self::density_altitude`].
2342#[derive(Debug, Clone, Copy, PartialEq, Default)]
2343pub struct StationOrigin {
2344    /// Where the station pressure came from.
2345    pub pressure: StationPressureOrigin,
2346    /// The QNH, hPa, the station pressure was reduced from, when the pressure was given as one;
2347    /// `None` for a station pressure reading, an omitted pressure and a density altitude's.
2348    pub qnh_hpa: Option<f64>,
2349    /// Where the station temperature came from.
2350    pub temperature: StationTemperatureOrigin,
2351}
2352
2353impl StationOrigin {
2354    /// [`StationPressureOrigin::of`], keeping `given_hpa` as the QNH when `mode` declares it
2355    /// one. The temperature is a reading.
2356    pub fn of(given_hpa: Option<f64>, mode: PressureReferenceMode) -> Self {
2357        Self {
2358            pressure: StationPressureOrigin::of(given_hpa, mode),
2359            qnh_hpa: given_hpa.filter(|_| mode == PressureReferenceMode::Qnh),
2360            temperature: StationTemperatureOrigin::Reading,
2361        }
2362    }
2363
2364    /// [`StationPressureOrigin::resolving`], keeping `pressure_hpa` as the QNH when `mode`
2365    /// declares it one (a QNH is always reduced, so always given). The temperature is a reading.
2366    pub fn resolving(
2367        pressure_hpa: f64,
2368        altitude_m: f64,
2369        mode: PressureReferenceMode,
2370        presence: StationAtmospherePresence,
2371    ) -> Self {
2372        let pressure = StationPressureOrigin::resolving(pressure_hpa, altitude_m, mode, presence);
2373        Self {
2374            pressure,
2375            qnh_hpa: (mode == PressureReferenceMode::Qnh
2376                && pressure != StationPressureOrigin::Standard)
2377                .then_some(pressure_hpa),
2378            temperature: StationTemperatureOrigin::Reading,
2379        }
2380    }
2381
2382    /// A density altitude's station: its pressure (and altitude) are the density altitude's, and
2383    /// so is its temperature unless one was given (`temperature_given`).
2384    pub fn density_altitude(temperature_given: bool) -> Self {
2385        Self {
2386            pressure: StationPressureOrigin::DensityAltitude,
2387            qnh_hpa: None,
2388            temperature: if temperature_given {
2389                StationTemperatureOrigin::Reading
2390            } else {
2391                StationTemperatureOrigin::DensityAltitude
2392            },
2393        }
2394    }
2395}
2396
2397/// One station reading as a surface names it: the `name` its messages use and the `path` its
2398/// machine-readable refusal points at. A CLI uses the flag for both (`--humidity`); a JSON
2399/// command uses the member's name and its path (`humidity`, `$.humidity`).
2400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2401pub struct AirField<'a> {
2402    /// The reading's name in a message.
2403    pub name: &'a str,
2404    /// Where the reading sits in the surface's input: a JSON path, a flag, a file's field.
2405    pub path: &'a str,
2406}
2407
2408impl<'a> AirField<'a> {
2409    /// A reading whose message name and path are the same text, as a CLI flag's are.
2410    pub const fn named(name: &'a str) -> Self {
2411        Self { name, path: name }
2412    }
2413}
2414
2415/// How one surface spells the station air it was given, so a refusal of that air reads in the
2416/// surface's own words: its field names, the humidity in the unit it was sent in, and the
2417/// temperature and pressure the solve resolved, in the surface's units with the unit named.
2418#[derive(Debug, Clone, PartialEq)]
2419pub struct AirSpelling<'a> {
2420    /// The relative humidity.
2421    pub humidity: AirField<'a>,
2422    /// The station temperature.
2423    pub temperature: AirField<'a>,
2424    /// The station pressure.
2425    pub pressure: AirField<'a>,
2426    /// The station altitude, or, for a station a density altitude gave, the density altitude
2427    /// (a density altitude no air has is refused at this field, in `altitude_unit`).
2428    pub altitude: AirField<'a>,
2429    /// The humidity as the surface was sent it, in its own unit (a percent, or the SI wire's
2430    /// fraction).
2431    pub humidity_sent: f64,
2432    /// The station temperature the solve flies, with its unit: `"212 °F"`, `"373.15 K"`.
2433    pub temperature_text: String,
2434    /// The unit the surface states a temperature in: the unit of `temperature_text`, in which a
2435    /// refusal of a temperature at or below absolute zero states where absolute zero is, and a
2436    /// refusal that blames the temperature states the range the humid-air formulas hold for.
2437    pub temperature_unit: TemperatureUnit,
2438    /// Where the station temperature came from: a reading, named by `temperature` as the
2439    /// reading it is (`temperature = 214 °F`), or a density altitude, named by `temperature` as
2440    /// the reading that gave it (`density_altitude gives a station temperature of ...`).
2441    pub temperature_origin: StationTemperatureOrigin,
2442    /// The station pressure the solve flies, with its unit: `"29.92 inHg"`, `"100000 Pa"`.
2443    pub pressure_text: String,
2444    /// Where that pressure came from: a reading, the standard pressure at the altitude, a QNH
2445    /// reduced there, or a density altitude. It decides whether a station pressure outside the
2446    /// troposphere is the pressure's fault, the altitude's or the density altitude's.
2447    pub pressure_origin: StationPressureOrigin,
2448    /// When the pressure was given as a QNH, the QNH as the surface was sent it, with its unit
2449    /// (`"1013.25 Pa"`, `"5 hPa"`); `None` otherwise. A refusal that names the pressure's field
2450    /// quotes this, the reading that was sent, and says it was reduced to `pressure_text`, never
2451    /// the station pressure as if it had been sent.
2452    pub qnh_text: Option<String>,
2453    /// The unit the surface states an altitude in: every altitude a refusal quotes (a pressure
2454    /// altitude, the troposphere's bounds, the station altitude, where air aloft reaches 0 K).
2455    pub altitude_unit: AltitudeUnit,
2456}
2457
2458impl AirSpelling<'_> {
2459    /// The pressure's field, said to be a QNH, quoting it as it was sent when the surface gave
2460    /// it: `"--pressure is a QNH of 5 hPa"`, or `"--pressure is a QNH"`.
2461    fn qnh_named(&self) -> String {
2462        match &self.qnh_text {
2463            Some(qnh) => format!("{} is a QNH of {qnh}", self.pressure.name),
2464            None => format!("{} is a QNH", self.pressure.name),
2465        }
2466    }
2467}
2468
2469/// The unit a surface states an altitude in, in a refusal of its air: metres (the default, and
2470/// every SI surface's), or feet (a terminal run with `--units imperial`).
2471#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2472pub enum AltitudeUnit {
2473    /// Metres: `1539 m`.
2474    #[default]
2475    Meters,
2476    /// Feet: `5049 ft`.
2477    Feet,
2478}
2479
2480impl AltitudeUnit {
2481    /// An altitude given in metres, stated in this unit to the nearest whole unit: `"1539 m"`,
2482    /// `"5049 ft"`; from 10^7 units on, in exponent form to six significant digits
2483    /// (`"-3.28813e34 m"`), never dozens of digits.
2484    pub fn text(self, altitude_m: f64) -> String {
2485        let (value, unit) = match self {
2486            Self::Meters => (altitude_m, "m"),
2487            Self::Feet => (altitude_m / 0.3048, "ft"),
2488        };
2489        if value.is_finite() && value.abs() >= EXPONENT_FROM {
2490            format!("{} {unit}", exponent_text(value))
2491        } else {
2492            format!("{value:.0} {unit}")
2493        }
2494    }
2495
2496    /// A reading of an altitude given in metres, stated in this unit as a refusal quotes a
2497    /// reading ([`reading_text`]): `"200000 ft"`, `"44500 m"`, `"NaN ft"`.
2498    pub fn reading(self, altitude_m: f64) -> String {
2499        match self {
2500            Self::Meters => reading_text(altitude_m, "m"),
2501            Self::Feet => reading_text(altitude_m / 0.3048, "ft"),
2502        }
2503    }
2504}
2505
2506/// The unit a surface states a temperature in, in a refusal of its air.
2507#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2508pub enum TemperatureUnit {
2509    /// Degrees Celsius: `15 °C`.
2510    #[default]
2511    Celsius,
2512    /// Degrees Fahrenheit: `59 °F`.
2513    Fahrenheit,
2514    /// Kelvin, as the SI wire states it: `288.15 K`.
2515    Kelvin,
2516}
2517
2518impl TemperatureUnit {
2519    /// A temperature given in °C, stated in this unit as a refusal quotes a reading
2520    /// ([`reading_text`]): `"212 °F"`, `"373.15 K"`.
2521    pub fn text(self, temperature_c: f64) -> String {
2522        match self {
2523            Self::Celsius => reading_text(temperature_c, "°C"),
2524            Self::Fahrenheit => reading_text(temperature_c * 9.0 / 5.0 + 32.0, "°F"),
2525            Self::Kelvin => reading_text(temperature_c + KELVIN_OFFSET, "K"),
2526        }
2527    }
2528
2529    /// Absolute zero in this unit: `"-273.15 °C"`, `"-459.67 °F"`, `"0 K"`.
2530    pub fn absolute_zero_text(self) -> &'static str {
2531        match self {
2532            Self::Celsius => "-273.15 °C",
2533            Self::Fahrenheit => "-459.67 °F",
2534            Self::Kelvin => "0 K",
2535        }
2536    }
2537}
2538
2539/// The unit a surface states a pressure in, in a refusal of its air.
2540#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2541pub enum PressureUnit {
2542    /// Hectopascals: `1013.25 hPa`.
2543    #[default]
2544    Hectopascals,
2545    /// Inches of mercury, `inHg × 33.8639 = hPa`: `29.92 inHg`.
2546    InchesOfMercury,
2547}
2548
2549impl PressureUnit {
2550    /// A pressure given in hPa, stated in this unit as a refusal quotes a reading
2551    /// ([`reading_text`]): `"29.92 inHg"`, `"1013.25 hPa"`, `"1e160 hPa"`. A pressure that is
2552    /// not 0 is never stated as 0: one that rounds to 0 at two decimals is written in exponent
2553    /// form, `"1e-300 hPa"`. (A pressure converts between units by a factor, never an offset,
2554    /// so a pressure that small is a reading, not rounding left over from a conversion.)
2555    pub fn text(self, pressure_hpa: f64) -> String {
2556        let (value, unit) = match self {
2557            Self::Hectopascals => (pressure_hpa, "hPa"),
2558            Self::InchesOfMercury => (pressure_hpa / 33.8639, "inHg"),
2559        };
2560        let text = reading_text(value, unit);
2561        if value != 0.0 && value.is_finite() && text == format!("0 {unit}") {
2562            format!("{} {unit}", exponent_text(value))
2563        } else {
2564            text
2565        }
2566    }
2567}
2568
2569/// The units a surface states its station readings in, in a refusal of its air: the
2570/// temperature, the pressure and every altitude the refusal quotes.
2571#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2572pub struct AirUnits {
2573    /// The temperature's unit.
2574    pub temperature: TemperatureUnit,
2575    /// The pressure's unit.
2576    pub pressure: PressureUnit,
2577    /// The altitude's unit.
2578    pub altitude: AltitudeUnit,
2579}
2580
2581impl AirUnits {
2582    /// °C, hPa and metres.
2583    pub const METRIC: Self = Self {
2584        temperature: TemperatureUnit::Celsius,
2585        pressure: PressureUnit::Hectopascals,
2586        altitude: AltitudeUnit::Meters,
2587    };
2588    /// °F, inHg and feet.
2589    pub const IMPERIAL: Self = Self {
2590        temperature: TemperatureUnit::Fahrenheit,
2591        pressure: PressureUnit::InchesOfMercury,
2592        altitude: AltitudeUnit::Feet,
2593    };
2594}
2595
2596/// A reading in a refusal message: rounded to 2 decimals with the trailing zeros dropped (so a
2597/// temperature converted to °C and back reads `212`, not `212.00000000000003`), then its unit.
2598/// From a magnitude of 10^7 on it is written in exponent form to six significant digits
2599/// (`1e160 hPa`), so an absurd reading reads in a few characters, never hundreds of digits.
2600pub fn reading_text(value: f64, unit: &str) -> String {
2601    if value.is_finite() && value.abs() >= EXPONENT_FROM {
2602        return format!("{} {unit}", exponent_text(value));
2603    }
2604    let rounded = format!("{value:.2}");
2605    let trimmed = if rounded.contains('.') {
2606        rounded.trim_end_matches('0').trim_end_matches('.')
2607    } else {
2608        rounded.as_str()
2609    };
2610    let trimmed = if trimmed == "-0" { "0" } else { trimmed };
2611    format!("{trimmed} {unit}")
2612}
2613
2614/// The magnitude from which a refusal writes a number in exponent form ([`reading_text`],
2615/// [`AltitudeUnit::text`], [`echo_number`]): `1e160`, not 161 digits.
2616const EXPONENT_FROM: f64 = 1e7;
2617
2618/// `value` in exponent form to six significant digits, trailing zeros dropped: `1e160`,
2619/// `-3.28813e34`, `1e-300`. For a figure a refusal states that is too large (or, for a
2620/// pressure, too small) to write out.
2621fn exponent_text(value: f64) -> String {
2622    let text = format!("{value:.5e}");
2623    match text.split_once('e') {
2624        Some((mantissa, exponent)) if mantissa.contains('.') => format!(
2625            "{}e{exponent}",
2626            mantissa.trim_end_matches('0').trim_end_matches('.')
2627        ),
2628        _ => text,
2629    }
2630}
2631
2632/// A number a refusal echoes as it was given: exactly, in its shortest form (`106`, `29.92`,
2633/// `-0.5`), or in exponent form when its magnitude is 10^7 or more, or below 0.001 and not 0
2634/// (`1e300`, `-1e-300`), so an absurd reading reads in a few characters, never hundreds of
2635/// digits. The SI wire's echo (`solve_v1::echo_si`) is this.
2636pub fn echo_number(value: f64) -> String {
2637    if value == 0.0 || !value.is_finite() || (1e-3..EXPONENT_FROM).contains(&value.abs()) {
2638        format!("{value}")
2639    } else {
2640        format!("{value:e}")
2641    }
2642}
2643
2644/// Station air refused in one surface's own words: the field to blame, as that surface locates
2645/// it ([`Self::path`]), and the message ([`Self::message`]).
2646///
2647/// Every surface states a refusal of the same air one way. Air that cannot exist reads
2648/// `"<humidity> = <h> at <temperature> and <pressure>: no such air exists: ..."`, naming the
2649/// three readings that together are impossible; a humidity outside the sensor band reads
2650/// `"<humidity> = <h>: relative humidity must be a percent from 0 to 100 (...)"`. Built by
2651/// [`AtmosphereError::refusal_in`].
2652#[derive(Debug, Clone, PartialEq, Eq)]
2653pub struct AirRefusal {
2654    path: String,
2655    message: String,
2656    reason: AtmosphereErrorReason,
2657}
2658
2659impl AirRefusal {
2660    /// Why the air was refused.
2661    pub fn reason(&self) -> AtmosphereErrorReason {
2662        self.reason
2663    }
2664
2665    /// Where the reading to blame sits in the surface's input, as the surface's
2666    /// [`AirSpelling`] locates it.
2667    pub fn path(&self) -> &str {
2668        &self.path
2669    }
2670
2671    /// The refusal, in the surface's words.
2672    pub fn message(&self) -> &str {
2673        &self.message
2674    }
2675}
2676
2677impl fmt::Display for AirRefusal {
2678    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2679        f.write_str(&self.message)
2680    }
2681}
2682
2683impl std::error::Error for AirRefusal {}
2684
2685impl AtmosphereError {
2686    /// This refusal of a station's air, stated in a surface's own words.
2687    ///
2688    /// `spelling` names the surface's readings and carries their values in its units;
2689    /// `station_altitude_m`, `station_temperature_c` and `station_pressure_hpa` are the station
2690    /// the solve resolved. A refusal for any reason but air that cannot exist blames the reading
2691    /// this error names, in the surface's units (a temperature at or below absolute zero states
2692    /// absolute zero in [`AirSpelling::temperature_unit`]; a density altitude no air has is the
2693    /// field [`AirSpelling::altitude`] names, since a surface that flies one names its altitude by
2694    /// it). Air that cannot exist is blamed by one rule on every surface, so every surface
2695    /// locates the same air at the same reading:
2696    ///
2697    /// 1. the temperature, when the air is humid above water's critical point (647.096 K), or
2698    ///    the temperature is outside 173.15 K to 373.15 K (-100 °C to 100 °C, where the humid-air
2699    ///    formulas hold). Such a temperature is refused by no surface on its own (the humidity
2700    ///    terms are extrapolated there); with air that cannot exist it is the likelier mistake.
2701    ///    The message names it where it came from ([`AirSpelling::temperature_origin`]): the
2702    ///    reading (`; temperature = 214 °F is outside -148 °F to 212 °F, ...: check the
2703    ///    temperature and its unit`), or the density altitude that gave it (`; density_altitude
2704    ///    gives a station temperature of ...: check the density altitude's unit`);
2705    /// 2. when the station pressure's pressure altitude is outside the troposphere, the reading
2706    ///    that put it there ([`AirSpelling::pressure_origin`]): the pressure when it was a
2707    ///    reading, because a pressure in the wrong unit (hPa sent as pascals) is far likelier
2708    ///    than a humidity of 50 % in air 25 km up, and the altitude when the pressure was the
2709    ///    standard pressure there or a plausible QNH reduced there (feet sent as metres), the
2710    ///    density altitude when a density altitude gave it. The message says which unit to
2711    ///    check, and quotes a QNH as it was sent ([`AirSpelling::qnh_text`]), with the station
2712    ///    pressure it was reduced to;
2713    /// 3. otherwise the humidity.
2714    ///
2715    /// A QNH the altimeter-setting relation leaves no station pressure for is quoted as it was
2716    /// sent too, never as the NaN it reduced to: blamed on the altitude when it is a plausible
2717    /// sea-level pressure, on the pressure otherwise.
2718    pub fn refusal_in(
2719        &self,
2720        spelling: &AirSpelling<'_>,
2721        station_altitude_m: f64,
2722        station_temperature_c: f64,
2723        station_pressure_hpa: f64,
2724    ) -> AirRefusal {
2725        let (path, message) = self.refusal_parts(
2726            spelling,
2727            station_altitude_m,
2728            station_temperature_c,
2729            station_pressure_hpa,
2730        );
2731        AirRefusal {
2732            path,
2733            message,
2734            reason: self.reason,
2735        }
2736    }
2737
2738    fn refusal_parts(
2739        &self,
2740        spelling: &AirSpelling<'_>,
2741        station_altitude_m: f64,
2742        station_temperature_c: f64,
2743        station_pressure_hpa: f64,
2744    ) -> (String, String) {
2745        let explanation = self.explanation_in(spelling.altitude_unit);
2746        let altitude = |altitude_m: f64| spelling.altitude_unit.text(altitude_m);
2747        if self.reason == AtmosphereErrorReason::ImpossibleAir {
2748            let air = format!(
2749                "{} = {} at {} and {}: {explanation}",
2750                spelling.humidity.name,
2751                echo_number(spelling.humidity_sent),
2752                spelling.temperature_text,
2753                spelling.pressure_text
2754            );
2755            // In kelvin, as `atmosphere.density_altitude` compares it. A wire `temperature_k`
2756            // between 136.6 K and 546.3 K loses nothing when 273.15 is subtracted (Sterbenz), so
2757            // adding it back restores the very float that command compared; farther out no
2758            // rounding comes near an edge. The two commands decide every edge alike.
2759            if self.field == "temperature_c"
2760                || outside_humid_air_model_range(station_temperature_c + KELVIN_OFFSET)
2761            {
2762                // Named where it came from, as every other blamed reading is. Humid air above
2763                // water's critical point, and dry air too hot to have a density, are outside
2764                // the range too.
2765                let range = format!(
2766                    "outside {} to {}, where the humid-air formulas hold",
2767                    spelling
2768                        .temperature_unit
2769                        .text(HUMID_AIR_MODEL_MIN_K - KELVIN_OFFSET),
2770                    spelling
2771                        .temperature_unit
2772                        .text(HUMID_AIR_MODEL_MAX_K - KELVIN_OFFSET)
2773                );
2774                let blame = match spelling.temperature_origin {
2775                    StationTemperatureOrigin::Reading => format!(
2776                        "{} = {} is {range}: check the temperature and its unit",
2777                        spelling.temperature.name, spelling.temperature_text
2778                    ),
2779                    StationTemperatureOrigin::DensityAltitude => format!(
2780                        "{} gives a station temperature of {}, {range}: check the density \
2781                         altitude's unit",
2782                        spelling.temperature.name, spelling.temperature_text
2783                    ),
2784                };
2785                return (
2786                    spelling.temperature.path.to_string(),
2787                    format!("{air}; {blame}"),
2788                );
2789            }
2790            if let Some(altitude_m) = pressure_altitude_outside_troposphere_m(station_pressure_hpa)
2791            {
2792                let troposphere = format!(
2793                    "a pressure altitude of {}, outside the troposphere ({} to {})",
2794                    altitude(altitude_m),
2795                    altitude(LOWEST_PRESSURE_ALTITUDE_M),
2796                    altitude(TROPOSPHERE_TOP_M)
2797                );
2798                // A QNH is quoted as it was sent, and said to be reduced, never as if the station
2799                // pressure reduced from it had been sent.
2800                let reduced = |unit: &str| {
2801                    format!(
2802                        "{air}; {}, and reduced to the station altitude of {} it is a station \
2803                         pressure of {}, {troposphere}: check the {unit}'s unit",
2804                        spelling.qnh_named(),
2805                        altitude(station_altitude_m),
2806                        spelling.pressure_text
2807                    )
2808                };
2809                return match spelling.pressure_origin {
2810                    StationPressureOrigin::Reading if spelling.qnh_text.is_some() => {
2811                        (spelling.pressure.path.to_string(), reduced("pressure"))
2812                    }
2813                    StationPressureOrigin::Reading => (
2814                        spelling.pressure.path.to_string(),
2815                        format!(
2816                            "{air}; {} = {} is {troposphere}: check the pressure's unit",
2817                            spelling.pressure.name, spelling.pressure_text
2818                        ),
2819                    ),
2820                    StationPressureOrigin::Standard => (
2821                        spelling.altitude.path.to_string(),
2822                        format!(
2823                            "{air}; no {} was given, and the standard pressure at the station \
2824                             altitude of {} is {troposphere}: check the altitude's unit",
2825                            spelling.pressure.name,
2826                            altitude(station_altitude_m)
2827                        ),
2828                    ),
2829                    StationPressureOrigin::Qnh => {
2830                        (spelling.altitude.path.to_string(), reduced("altitude"))
2831                    }
2832                    StationPressureOrigin::DensityAltitude => (
2833                        spelling.pressure.path.to_string(),
2834                        format!(
2835                            "{air}; {} gives a station pressure of {}, {troposphere}: check the \
2836                             density altitude's unit",
2837                            spelling.pressure.name, spelling.pressure_text
2838                        ),
2839                    ),
2840                };
2841            }
2842            return (spelling.humidity.path.to_string(), air);
2843        }
2844        // A QNH whose reduction to the station altitude leaves no station pressure (the
2845        // altimeter-setting relation has none that high) is quoted as it was sent, never as the
2846        // NaN it reduced to: the altitude's fault when the QNH is itself a plausible sea-level
2847        // pressure, as on the SI wire, and the pressure's when it is not.
2848        if self.field == "pressure_hpa"
2849            && matches!(
2850                self.reason,
2851                AtmosphereErrorReason::NotFinite | AtmosphereErrorReason::NonPositivePressure
2852            )
2853            && (spelling.pressure_origin == StationPressureOrigin::Qnh
2854                || spelling.qnh_text.is_some())
2855        {
2856            let (path, unit) = if spelling.pressure_origin == StationPressureOrigin::Qnh {
2857                (spelling.altitude.path, "altitude")
2858            } else {
2859                (spelling.pressure.path, "pressure")
2860            };
2861            return (
2862                path.to_string(),
2863                format!(
2864                    "{}, and reduced to the station altitude of {} it leaves no station \
2865                     pressure: the altimeter-setting relation has none that high (check the \
2866                     {unit}'s unit)",
2867                    spelling.qnh_named(),
2868                    altitude(station_altitude_m)
2869                ),
2870            );
2871        }
2872        // Absolute zero in the surface's own unit, as its reading is.
2873        let explanation = match self.reason {
2874            AtmosphereErrorReason::AtOrBelowAbsoluteZero => format!(
2875                "temperature must be above absolute zero ({})",
2876                spelling.temperature_unit.absolute_zero_text()
2877            ),
2878            _ => explanation,
2879        };
2880        let (field, value) = match &*self.field {
2881            // A temperature or a pressure a density altitude gave is named as that density
2882            // altitude's, never as if it had been sent as the reading.
2883            "temperature_c"
2884                if spelling.temperature_origin == StationTemperatureOrigin::DensityAltitude =>
2885            {
2886                return (
2887                    spelling.temperature.path.to_string(),
2888                    format!(
2889                        "{} gives a station temperature of {}: {explanation}",
2890                        spelling.temperature.name, spelling.temperature_text
2891                    ),
2892                );
2893            }
2894            "pressure_hpa"
2895                if spelling.pressure_origin == StationPressureOrigin::DensityAltitude =>
2896            {
2897                return (
2898                    spelling.pressure.path.to_string(),
2899                    format!(
2900                        "{} gives a station pressure of {}: {explanation}",
2901                        spelling.pressure.name, spelling.pressure_text
2902                    ),
2903                );
2904            }
2905            "temperature_c" => (spelling.temperature, spelling.temperature_text.clone()),
2906            "pressure_hpa" => (spelling.pressure, spelling.pressure_text.clone()),
2907            // An altitude is refused only when it is not finite, which needs no unit.
2908            "altitude_m" => (spelling.altitude, echo_number(self.value)),
2909            // A density altitude flies as the station's altitude, and a surface that flies one
2910            // names the altitude by the density altitude's field, in the surface's unit.
2911            "density_altitude_m" => (
2912                spelling.altitude,
2913                spelling.altitude_unit.reading(self.value),
2914            ),
2915            _ => (spelling.humidity, echo_number(self.value)),
2916        };
2917        (
2918            field.path.to_string(),
2919            format!("{} = {value}: {explanation}", field.name),
2920        )
2921    }
2922}
2923
2924/// The air at the shooter: station altitude, temperature, pressure and relative humidity, with
2925/// the density and speed of sound they give.
2926///
2927/// Every field is private and there is no `Default`, so a station cannot be built without its
2928/// humidity, and its density and sound speed cannot disagree about that humidity. Build one with
2929/// [`Self::new`]. [`Self::with_density_ratio`] exists only for legacy 4-tuple callers that hold
2930/// a density ratio of their own.
2931///
2932/// ```
2933/// use ballistics_engine::{RelativeHumidity, StationAir};
2934///
2935/// let station = StationAir::new(0.0, 15.0, 1013.25, RelativeHumidity::DEFAULT).unwrap();
2936/// assert!(station.density_kg_m3() < 1.225); // moist air is lighter than dry
2937/// assert!(station.speed_of_sound_mps() > 340.29); // and carries sound faster
2938///
2939/// // Air that cannot exist is refused: saturated air at 100 C needs more vapour pressure than
2940/// // the 1013.25 hPa the air has.
2941/// let saturated = RelativeHumidity::try_percent(100.0).unwrap();
2942/// assert!(StationAir::new(0.0, 100.0, 1013.25, saturated).is_err());
2943/// ```
2944#[derive(Clone, Copy, PartialEq)]
2945pub struct StationAir {
2946    altitude_m: f64,
2947    temperature_c: f64,
2948    pressure_hpa: f64,
2949    humidity: RelativeHumidity,
2950    density_ratio: f64,
2951    density_kg_m3: f64,
2952    speed_of_sound_mps: f64,
2953    /// The station's water-vapour mole fraction, which [`air_at`] holds at every height:
2954    /// [`governing_vapor_mole_fraction`] at the fields above, computed once here rather than at
2955    /// every step of every flight. A cache of the other fields, not state of
2956    /// its own, so `Debug` leaves it out.
2957    vapor_mole_fraction: f64,
2958}
2959
2960// The derive's output before the vapour mole fraction was held, field for field: it is a cache.
2961impl fmt::Debug for StationAir {
2962    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2963        f.debug_struct("StationAir")
2964            .field("altitude_m", &self.altitude_m)
2965            .field("temperature_c", &self.temperature_c)
2966            .field("pressure_hpa", &self.pressure_hpa)
2967            .field("humidity", &self.humidity)
2968            .field("density_ratio", &self.density_ratio)
2969            .field("density_kg_m3", &self.density_kg_m3)
2970            .field("speed_of_sound_mps", &self.speed_of_sound_mps)
2971            .finish()
2972    }
2973}
2974
2975impl StationAir {
2976    /// The station air at `altitude_m` (geometric, above mean sea level), `temperature_c`,
2977    /// absolute station pressure `pressure_hpa` and `humidity`.
2978    ///
2979    /// The density and sound speed are [`calculate_atmosphere`]'s at exactly these inputs, so a
2980    /// station built here matches every solver that resolves its air through that function, to
2981    /// the bit. The density ratio is `density / 1.225`.
2982    ///
2983    /// # Errors
2984    ///
2985    /// - `altitude_m`, `temperature_c` or `pressure_hpa` not finite:
2986    ///   [`AtmosphereErrorReason::NotFinite`].
2987    /// - `temperature_c <= -273.15`: [`AtmosphereErrorReason::AtOrBelowAbsoluteZero`].
2988    /// - `pressure_hpa <= 0`: [`AtmosphereErrorReason::NonPositivePressure`].
2989    /// - Impossible air, refused by exactly the `atmosphere.density_altitude` service's test
2990    ///   (an uncapped water-vapour mole fraction that is NaN or at least 1):
2991    ///   [`AtmosphereErrorReason::ImpossibleAir`], on `humidity_percent`, or on
2992    ///   `temperature_c` for humid air above water's critical point (647.096 K), and for dry air
2993    ///   there too hot for the CIPM-2007 density to stay positive (about 90,000 K at
2994    ///   1013.25 hPa); or on `pressure_hpa` for a pressure so far beyond any air's (above about
2995    ///   4e156 Pa) that the density is not finite and positive.
2996    ///
2997    /// Those are the only temperatures refused ([`check_station_temperature_c`] is the rule on
2998    /// its own): outside 173.15-373.15 K (-100 °C to 100 °C) the humidity terms are extrapolated,
2999    /// never refused. Below 173.15 K the saturation vapour pressure and the CIPM compressibility
3000    /// are evaluated at 173.15 K (they clamp their temperature there), and above 373.15 K they
3001    /// are carried past the range they are fitted to. Dry air holds no vapour at any
3002    /// temperature, so at 0 % neither term is reached. A station whose lapse takes the air to
3003    /// absolute zero aloft is accepted here and refused by the flight that reaches that height
3004    /// ([`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]).
3005    pub fn new(
3006        altitude_m: f64,
3007        temperature_c: f64,
3008        pressure_hpa: f64,
3009        humidity: RelativeHumidity,
3010    ) -> Result<Self, AtmosphereError> {
3011        check_station_state(altitude_m, temperature_c, pressure_hpa)?;
3012        refuse_impossible_air(temperature_c, pressure_hpa, humidity)?;
3013        Ok(Self::from_calculate_atmosphere(
3014            altitude_m,
3015            temperature_c,
3016            pressure_hpa,
3017            humidity,
3018        ))
3019    }
3020
3021    /// A station that keeps a caller-held `density_ratio` (density / 1.225 kg/m³) verbatim.
3022    ///
3023    /// For legacy `(altitude, temperature, pressure, ratio)` 4-tuples only, through
3024    /// [`KernelAtmosphere::from_legacy_params`]: the caller asserts that the ratio was built at
3025    /// this humidity. Everywhere else use [`Self::new`], which cannot pair a density with the
3026    /// wrong humidity. The sound speed is the station's own at `humidity`, as in `new`.
3027    ///
3028    /// # Errors
3029    ///
3030    /// Those of [`Self::new`], plus a `density_ratio` that is not finite or not in `(0, 2)`.
3031    pub fn with_density_ratio(
3032        altitude_m: f64,
3033        temperature_c: f64,
3034        pressure_hpa: f64,
3035        density_ratio: f64,
3036        humidity: RelativeHumidity,
3037    ) -> Result<Self, AtmosphereError> {
3038        const FIELD: &str = "density_ratio";
3039        check_station_state(altitude_m, temperature_c, pressure_hpa)?;
3040        if !density_ratio.is_finite() {
3041            return Err(AtmosphereError::new(
3042                FIELD,
3043                density_ratio,
3044                AtmosphereErrorReason::NotFinite,
3045            ));
3046        }
3047        if !(density_ratio > 0.0 && density_ratio < MAX_STATION_DENSITY_RATIO) {
3048            return Err(AtmosphereError::new(
3049                FIELD,
3050                density_ratio,
3051                AtmosphereErrorReason::DensityRatioOutOfRange,
3052            ));
3053        }
3054        refuse_impossible_air(temperature_c, pressure_hpa, humidity)?;
3055        Ok(Self {
3056            altitude_m,
3057            temperature_c,
3058            pressure_hpa,
3059            humidity,
3060            density_ratio,
3061            density_kg_m3: density_ratio * 1.225,
3062            // calculate_atmosphere's own sound speed: its K and Pa conversions, then the moist
3063            // formula.
3064            speed_of_sound_mps: moist_speed_of_sound(
3065                temperature_c + 273.15,
3066                pressure_hpa * 100.0,
3067                humidity.percent(),
3068            ),
3069            vapor_mole_fraction: governing_vapor_mole_fraction(
3070                temperature_c,
3071                pressure_hpa,
3072                humidity.percent(),
3073            ),
3074        })
3075    }
3076
3077    fn from_calculate_atmosphere(
3078        altitude_m: f64,
3079        temperature_c: f64,
3080        pressure_hpa: f64,
3081        humidity: RelativeHumidity,
3082    ) -> Self {
3083        let (density_kg_m3, speed_of_sound_mps) = calculate_atmosphere(
3084            altitude_m,
3085            Some(temperature_c),
3086            Some(pressure_hpa),
3087            humidity.percent(),
3088        );
3089        Self {
3090            altitude_m,
3091            temperature_c,
3092            pressure_hpa,
3093            humidity,
3094            density_ratio: density_kg_m3 / 1.225,
3095            density_kg_m3,
3096            speed_of_sound_mps,
3097            vapor_mole_fraction: governing_vapor_mole_fraction(
3098                temperature_c,
3099                pressure_hpa,
3100                humidity.percent(),
3101            ),
3102        }
3103    }
3104
3105    /// The station as the governing air of a point no downrange zone covers.
3106    #[inline(always)]
3107    fn governing_air(&self) -> GoverningAir {
3108        GoverningAir {
3109            temperature_c: self.temperature_c,
3110            pressure_hpa: self.pressure_hpa,
3111            density_ratio: self.density_ratio,
3112            vapor_mole_fraction: self.vapor_mole_fraction,
3113            #[cfg(test)]
3114            humidity_percent: self.humidity.percent(),
3115        }
3116    }
3117
3118    /// Station geometric altitude above mean sea level, m. The altitude lapse starts here.
3119    pub fn altitude_m(&self) -> f64 {
3120        self.altitude_m
3121    }
3122
3123    /// Station temperature, °C.
3124    pub fn temperature_c(&self) -> f64 {
3125        self.temperature_c
3126    }
3127
3128    /// Absolute station pressure, hPa.
3129    pub fn pressure_hpa(&self) -> f64 {
3130        self.pressure_hpa
3131    }
3132
3133    /// Station relative humidity.
3134    pub fn humidity(&self) -> RelativeHumidity {
3135        self.humidity
3136    }
3137
3138    /// Station density over 1.225 kg/m³.
3139    pub fn density_ratio(&self) -> f64 {
3140        self.density_ratio
3141    }
3142
3143    /// Station air density, kg/m³ (CIPM-2007, humid).
3144    pub fn density_kg_m3(&self) -> f64 {
3145        self.density_kg_m3
3146    }
3147
3148    /// Station speed of sound, m/s (moist air). The reference for station Mach.
3149    pub fn speed_of_sound_mps(&self) -> f64 {
3150        self.speed_of_sound_mps
3151    }
3152}
3153
3154/// The one rule a station temperature, °C, is held to on its own, on every surface: finite and
3155/// above absolute zero (-273.15 °C). Nothing narrower: outside 173.15-373.15 K (-100 °C to
3156/// 100 °C) the humidity terms are extrapolated, never refused. [`StationAir::new`] applies it,
3157/// and then the impossible-air rule, which is the only other reason a temperature is refused (in
3158/// flight too: [`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`]). A surface that checks a
3159/// reading as it is typed (a CLI flag, converted to °C) applies this same function, so a reading
3160/// is accepted or refused alike everywhere.
3161///
3162/// ```
3163/// use ballistics_engine::atmosphere::check_station_temperature_c;
3164///
3165/// assert!(check_station_temperature_c(250.0).is_ok()); // extrapolated, not refused
3166/// assert!(check_station_temperature_c(-150.0).is_ok());
3167/// assert!(check_station_temperature_c(-273.15).is_err()); // absolute zero
3168/// assert!(check_station_temperature_c(f64::NAN).is_err());
3169/// ```
3170///
3171/// # Errors
3172///
3173/// [`AtmosphereErrorReason::NotFinite`] or [`AtmosphereErrorReason::AtOrBelowAbsoluteZero`],
3174/// on `temperature_c`.
3175pub fn check_station_temperature_c(temperature_c: f64) -> Result<(), AtmosphereError> {
3176    if !temperature_c.is_finite() {
3177        return Err(AtmosphereError::new(
3178            "temperature_c",
3179            temperature_c,
3180            AtmosphereErrorReason::NotFinite,
3181        ));
3182    }
3183    if temperature_c <= ABSOLUTE_ZERO_C {
3184        return Err(AtmosphereError::new(
3185            "temperature_c",
3186            temperature_c,
3187            AtmosphereErrorReason::AtOrBelowAbsoluteZero,
3188        ));
3189    }
3190    Ok(())
3191}
3192
3193/// [`check_station_temperature_c`] for a temperature typed into a flag (`flag`, such as
3194/// `--temperature`) in °F (`fahrenheit`) or °C, refused in the flag's own words and unit:
3195/// `"--temperature -500 F is at or below absolute zero (-459.67 F)"`, `"--temperature NaN C is
3196/// not a finite number"`. The reading is converted to °C exactly as the CLI and the browser
3197/// terminal fly it, `(F - 32) · 5 / 9`, so the flag refuses precisely the readings the solve
3198/// would.
3199///
3200/// ```
3201/// use ballistics_engine::atmosphere::check_temperature_flag;
3202///
3203/// assert!(check_temperature_flag("--temperature", 482.0, true).is_ok()); // 250 °C
3204/// assert_eq!(
3205///     check_temperature_flag("--temperature", -500.0, true).unwrap_err(),
3206///     "--temperature -500 F is at or below absolute zero (-459.67 F)"
3207/// );
3208/// ```
3209///
3210/// # Errors
3211///
3212/// The refusal, in the flag's words, of a reading [`check_station_temperature_c`] refuses.
3213pub fn check_temperature_flag(flag: &str, value: f64, fahrenheit: bool) -> Result<(), String> {
3214    let (celsius, unit, absolute_zero) = if fahrenheit {
3215        ((value - 32.0) * 5.0 / 9.0, "F", "-459.67 F")
3216    } else {
3217        (value, "C", "-273.15 C")
3218    };
3219    check_station_temperature_c(celsius).map_err(|error| match error.reason() {
3220        AtmosphereErrorReason::NotFinite => {
3221            format!(
3222                "{flag} {} {unit} is not a finite number",
3223                echo_number(value)
3224            )
3225        }
3226        _ => format!(
3227            "{flag} {} {unit} is at or below absolute zero ({absolute_zero})",
3228            echo_number(value)
3229        ),
3230    })
3231}
3232
3233/// The one rule a station pressure, hPa, is held to on its own, on every surface: finite and
3234/// above 0. Nothing narrower: a near vacuum and twice sea level fly. [`StationAir::new`] applies
3235/// it, and then the impossible-air rule, which is the only other reason a pressure is refused. A
3236/// surface that checks a reading as it is typed applies this same function
3237/// ([`check_pressure_flag`]), so a reading is accepted or refused alike everywhere.
3238///
3239/// ```
3240/// use ballistics_engine::atmosphere::check_station_pressure_hpa;
3241///
3242/// assert!(check_station_pressure_hpa(0.01).is_ok()); // 1 Pa
3243/// assert!(check_station_pressure_hpa(2000.0).is_ok());
3244/// assert!(check_station_pressure_hpa(0.0).is_err());
3245/// assert!(check_station_pressure_hpa(f64::NAN).is_err());
3246/// ```
3247///
3248/// # Errors
3249///
3250/// [`AtmosphereErrorReason::NotFinite`] or [`AtmosphereErrorReason::NonPositivePressure`], on
3251/// `pressure_hpa`.
3252pub fn check_station_pressure_hpa(pressure_hpa: f64) -> Result<(), AtmosphereError> {
3253    if !pressure_hpa.is_finite() {
3254        return Err(AtmosphereError::new(
3255            "pressure_hpa",
3256            pressure_hpa,
3257            AtmosphereErrorReason::NotFinite,
3258        ));
3259    }
3260    if pressure_hpa <= 0.0 {
3261        return Err(AtmosphereError::new(
3262            "pressure_hpa",
3263            pressure_hpa,
3264            AtmosphereErrorReason::NonPositivePressure,
3265        ));
3266    }
3267    Ok(())
3268}
3269
3270/// [`check_station_pressure_hpa`] for a pressure typed into a flag (`flag`, such as
3271/// `--pressure`) in inHg (`inhg`) or hPa, refused in the flag's own words and unit:
3272/// `"--pressure -1 inHg is at or below zero"`, `"--pressure NaN hPa is not a finite number"`.
3273/// The reading is converted to hPa exactly as the CLI and the browser terminal fly it
3274/// (`inHg × 33.8639`), so the flag refuses precisely the readings the solve would.
3275///
3276/// ```
3277/// use ballistics_engine::atmosphere::check_pressure_flag;
3278///
3279/// assert!(check_pressure_flag("--pressure", 5.0, true).is_ok()); // the stratosphere
3280/// assert_eq!(
3281///     check_pressure_flag("--pressure", -1.0, true).unwrap_err(),
3282///     "--pressure -1 inHg is at or below zero"
3283/// );
3284/// ```
3285///
3286/// # Errors
3287///
3288/// The refusal, in the flag's words, of a reading [`check_station_pressure_hpa`] refuses.
3289pub fn check_pressure_flag(flag: &str, value: f64, inhg: bool) -> Result<(), String> {
3290    let (hpa, unit) = if inhg {
3291        (value * 33.8639, "inHg")
3292    } else {
3293        (value, "hPa")
3294    };
3295    check_station_pressure_hpa(hpa).map_err(|error| match error.reason() {
3296        AtmosphereErrorReason::NotFinite => {
3297            format!(
3298                "{flag} {} {unit} is not a finite number",
3299                echo_number(value)
3300            )
3301        }
3302        _ => format!("{flag} {} {unit} is at or below zero", echo_number(value)),
3303    })
3304}
3305
3306/// The one rule a station altitude or a density altitude typed into a flag (`flag`, such as
3307/// `--altitude`) is held to on its own, in feet (`feet`) or metres: a finite number, refused in
3308/// the flag's own words and unit otherwise (`"--altitude NaN ft is not a finite number"`). A
3309/// density altitude is held to the rest of its rule where its station is resolved
3310/// ([`station_for_density_altitude`]), since that depends on the temperature.
3311///
3312/// ```
3313/// use ballistics_engine::atmosphere::check_altitude_flag;
3314///
3315/// assert!(check_altitude_flag("--altitude", 300_000.0, true).is_ok());
3316/// assert_eq!(
3317///     check_altitude_flag("--altitude", f64::NAN, true).unwrap_err(),
3318///     "--altitude NaN ft is not a finite number"
3319/// );
3320/// ```
3321///
3322/// # Errors
3323///
3324/// The refusal of a value that is not a finite number once converted to metres.
3325pub fn check_altitude_flag(flag: &str, value: f64, feet: bool) -> Result<(), String> {
3326    let (metres, unit) = if feet {
3327        (value * DA_FT_TO_M, "ft")
3328    } else {
3329        (value, "m")
3330    };
3331    if metres.is_finite() {
3332        Ok(())
3333    } else {
3334        Err(format!(
3335            "{flag} {} {unit} is not a finite number",
3336            echo_number(value)
3337        ))
3338    }
3339}
3340
3341fn check_station_state(
3342    altitude_m: f64,
3343    temperature_c: f64,
3344    pressure_hpa: f64,
3345) -> Result<(), AtmosphereError> {
3346    if !altitude_m.is_finite() {
3347        return Err(AtmosphereError::new(
3348            "altitude_m",
3349            altitude_m,
3350            AtmosphereErrorReason::NotFinite,
3351        ));
3352    }
3353    check_station_temperature_c(temperature_c)?;
3354    check_station_pressure_hpa(pressure_hpa)
3355}
3356
3357/// The impossible-air rule every station and zone is held to (and the `atmosphere.density_altitude`
3358/// service through it): an uncapped vapour mole fraction that is NaN (humid air above water's
3359/// critical point) or at least 1; and, above that point, where only dry air gets this far, a
3360/// CIPM-2007 density that is not finite and positive.
3361fn refuse_impossible_air(
3362    temperature_c: f64,
3363    pressure_hpa: f64,
3364    humidity: RelativeHumidity,
3365) -> Result<(), AtmosphereError> {
3366    let x_v = water_vapor_mole_fraction_uncapped(temperature_c, pressure_hpa, humidity.percent());
3367    if x_v.is_nan() {
3368        return Err(AtmosphereError::new(
3369            "temperature_c",
3370            temperature_c,
3371            AtmosphereErrorReason::ImpossibleAir,
3372        ));
3373    }
3374    if x_v >= 1.0 {
3375        return Err(AtmosphereError::new(
3376            "humidity_percent",
3377            humidity.percent(),
3378            AtmosphereErrorReason::ImpossibleAir,
3379        ));
3380    }
3381    // Air the CIPM-2007 density cannot describe is refused. Dry air above water's critical point
3382    // holds no vapour (its mole fraction is exactly 0) and flies, but its compressibility is a
3383    // virial fit carried far past its range there, and far enough above it (about 90,000 K at
3384    // 1013.25 hPa) it gives no positive density at all: refused at its temperature. At any lower
3385    // temperature only a pressure far beyond any air's (above about 4e156 Pa, where the fit's
3386    // squared pressure term overflows and the density comes out 0, which a flight would take for
3387    // a vacuum) does that: refused at its pressure. For every other station the density is
3388    // finite and positive, and the rule is the two tests above.
3389    let density = calculate_air_density_cimp(temperature_c, pressure_hpa, humidity.percent());
3390    if !(density.is_finite() && density > 0.0) {
3391        let hot = temperature_c + KELVIN_OFFSET > WATER_CRITICAL_TEMPERATURE_K;
3392        return Err(if hot {
3393            AtmosphereError::new(
3394                "temperature_c",
3395                temperature_c,
3396                AtmosphereErrorReason::ImpossibleAir,
3397            )
3398        } else {
3399            AtmosphereError::new(
3400                "pressure_hpa",
3401                pressure_hpa,
3402                AtmosphereErrorReason::ImpossibleAir,
3403            )
3404        });
3405    }
3406    Ok(())
3407}
3408
3409/// The air at one point of a flight, from [`air_at`].
3410#[derive(Debug, Clone, Copy, PartialEq)]
3411pub struct LocalAir {
3412    /// Local air density, kg/m³.
3413    pub density_kg_m3: f64,
3414    /// Local speed of sound, m/s.
3415    pub speed_of_sound_mps: f64,
3416    /// Local temperature, K. For [`KernelAtmosphere::Uniform`] it is the dry-air temperature
3417    /// that gives the caller's sound speed, `c² / (1.4 · 287.0531)`.
3418    pub temperature_k: f64,
3419    /// Local pressure, Pa. `0.0` for [`KernelAtmosphere::Uniform`], which does not model it.
3420    pub pressure_pa: f64,
3421}
3422
3423/// The atmosphere a trajectory kernel flies.
3424///
3425/// [`Self::Station`] carries station air, humidity included, and the air varies with altitude
3426/// and downrange zones through [`air_at`]. [`Self::Uniform`] is direct mode: one density and
3427/// sound speed at every point.
3428///
3429/// Neither variant can hold unvalidated air. [`StationAir`] has private fields, and `Uniform`
3430/// can only be built by [`Self::uniform`] or [`Self::from_legacy_params`] outside this crate.
3431/// Match it with `..`:
3432///
3433/// ```
3434/// use ballistics_engine::KernelAtmosphere;
3435///
3436/// let atmosphere = KernelAtmosphere::uniform(1.1, 330.0).unwrap();
3437/// match atmosphere {
3438///     KernelAtmosphere::Uniform { density_kg_m3, speed_of_sound_mps, .. } => {
3439///         assert_eq!((density_kg_m3, speed_of_sound_mps), (1.1, 330.0));
3440///     }
3441///     KernelAtmosphere::Station(_) => unreachable!(),
3442/// }
3443/// ```
3444///
3445/// ```compile_fail,E0639
3446/// use ballistics_engine::KernelAtmosphere;
3447///
3448/// // Bypassing `uniform`'s validation does not compile (E0639: the variant is
3449/// // `#[non_exhaustive]`).
3450/// let atmosphere = KernelAtmosphere::Uniform { density_kg_m3: -1.0, speed_of_sound_mps: 0.0 };
3451/// ```
3452#[derive(Debug, Clone, Copy, PartialEq)]
3453pub enum KernelAtmosphere {
3454    /// Station-referenced air, humidity included.
3455    Station(StationAir),
3456    /// Direct mode: the caller's density and speed of sound, unchanged at every point.
3457    #[non_exhaustive]
3458    Uniform {
3459        /// Air density, kg/m³, in `[0, 2)`; exactly 0 is a vacuum, with no drag at all.
3460        density_kg_m3: f64,
3461        /// Speed of sound, m/s, above 200.
3462        speed_of_sound_mps: f64,
3463    },
3464}
3465
3466impl KernelAtmosphere {
3467    /// Direct-mode air: one density and speed of sound at every point.
3468    ///
3469    /// A density of exactly 0 is a vacuum: the flight feels gravity and nothing else, exactly as
3470    /// 0.49.0's `compute_derivatives` flew the `(0, c, 0, 0)` tuple. `-0.0`
3471    /// is the same vacuum and is stored as `0.0`.
3472    ///
3473    /// ```
3474    /// use ballistics_engine::KernelAtmosphere;
3475    ///
3476    /// assert!(KernelAtmosphere::uniform(0.0, 340.29).is_ok()); // a vacuum
3477    /// assert!(KernelAtmosphere::uniform(-1.0, 340.29).is_err());
3478    /// ```
3479    ///
3480    /// # Errors
3481    ///
3482    /// A `density_kg_m3` that is not finite or not in `[0, 2)`, or a `speed_of_sound_mps` that
3483    /// is not finite or not above 200. The upper density and lower sound-speed bounds are the
3484    /// ones 0.49.0's `compute_derivatives` used to recognise direct mode; its other kernels
3485    /// differed (`fast_integrate` required a density above 0).
3486    pub fn uniform(density_kg_m3: f64, speed_of_sound_mps: f64) -> Result<Self, AtmosphereError> {
3487        if !density_kg_m3.is_finite() {
3488            return Err(AtmosphereError::new(
3489                "density_kg_m3",
3490                density_kg_m3,
3491                AtmosphereErrorReason::NotFinite,
3492            ));
3493        }
3494        if !(0.0..MAX_UNIFORM_DENSITY_KG_M3).contains(&density_kg_m3) {
3495            return Err(AtmosphereError::new(
3496                "density_kg_m3",
3497                density_kg_m3,
3498                AtmosphereErrorReason::UniformDensityOutOfRange,
3499            ));
3500        }
3501        // -0.0 is the same vacuum as 0.0; adding 0.0 stores it as +0.0 and moves no other value.
3502        let density_kg_m3 = density_kg_m3 + 0.0;
3503        if !speed_of_sound_mps.is_finite() {
3504            return Err(AtmosphereError::new(
3505                "speed_of_sound_mps",
3506                speed_of_sound_mps,
3507                AtmosphereErrorReason::NotFinite,
3508            ));
3509        }
3510        if speed_of_sound_mps <= MIN_UNIFORM_SPEED_OF_SOUND_MPS {
3511            return Err(AtmosphereError::new(
3512                "speed_of_sound_mps",
3513                speed_of_sound_mps,
3514                AtmosphereErrorReason::UniformSpeedOfSoundOutOfRange,
3515            ));
3516        }
3517        Ok(Self::Uniform {
3518            density_kg_m3,
3519            speed_of_sound_mps,
3520        })
3521    }
3522
3523    /// The one-line migration from the legacy kernel 4-tuple, at the humidity the caller states.
3524    ///
3525    /// - `(density, speed_of_sound, 0.0, 0.0)`, the direct-mode sentinel, becomes
3526    ///   [`Self::uniform`] (which validates it; `humidity` is unused, the caller's sound speed
3527    ///   already being given).
3528    /// - `(altitude_m, temperature_c, pressure_hpa, density_ratio)`, standard mode, becomes a
3529    ///   [`StationAir::with_density_ratio`] at `humidity`. A finite ratio `<= 0` means "not
3530    ///   supplied" and becomes `1.0` (MBA-1157); a ratio at or above 2 is refused.
3531    ///
3532    /// # Errors
3533    ///
3534    /// Those of [`Self::uniform`] or [`StationAir::with_density_ratio`].
3535    pub fn from_legacy_params(
3536        params: (f64, f64, f64, f64),
3537        humidity: RelativeHumidity,
3538    ) -> Result<Self, AtmosphereError> {
3539        let (first, second, third, fourth) = params;
3540        if third == 0.0 && fourth == 0.0 {
3541            return Self::uniform(first, second);
3542        }
3543        let density_ratio = if fourth.is_finite() && fourth <= 0.0 {
3544            1.0
3545        } else {
3546            fourth
3547        };
3548        StationAir::with_density_ratio(first, second, third, density_ratio, humidity)
3549            .map(Self::Station)
3550    }
3551
3552    /// The altitude a kernel measures a point's height from: the station's own altitude, as
3553    /// `TrajectorySolver` does, so a caller's inputs cannot fly a different station; or
3554    /// `uniform_fallback` for uniform air, which does not vary with altitude.
3555    pub(crate) fn reference_altitude_m(&self, uniform_fallback: f64) -> f64 {
3556        match self {
3557            Self::Station(station) => station.altitude_m,
3558            Self::Uniform { .. } => uniform_fallback,
3559        }
3560    }
3561}
3562
3563/// The governing (base) air a point of a flight lapses from: the station's, or the active
3564/// downrange [`AtmoSock`] zone's. Everything in it is fixed for the whole flight, its
3565/// water-vapour mole fraction and density ratio included, so it is computed once, when the
3566/// station ([`StationAir`]) or the zones ([`AtmoSock::new`]) are built, and the per-step lookup
3567/// only reads it (recomputing the vapour mole fraction, and a zone's CIPM density, at every
3568/// step made `fast_integrate`, the lean Monte Carlo and `TrajectorySolver`'s RK4 and RK45
3569/// 4-10 % slower than 0.49.0, for no change in any bit).
3570#[derive(Debug, Clone, Copy)]
3571struct GoverningAir {
3572    /// Base temperature, °C.
3573    temperature_c: f64,
3574    /// Base absolute pressure, hPa.
3575    pressure_hpa: f64,
3576    /// Base density over 1.225 kg/m³.
3577    density_ratio: f64,
3578    /// [`governing_vapor_mole_fraction`] at the base temperature, pressure and humidity: the
3579    /// `x_v` held at every height.
3580    vapor_mole_fraction: f64,
3581    /// The relative humidity, percent, that `vapor_mole_fraction` came from, for the test-only
3582    /// [`air_trace`]; the composition itself reads only the mole fraction.
3583    #[cfg(test)]
3584    humidity_percent: f64,
3585}
3586
3587impl GoverningAir {
3588    /// Base air at `temperature_c`, `pressure_hpa` and `humidity_percent` (raw: clamped into
3589    /// 0-100 by the one vapour formula, a NaN kept), with the caller's `density_ratio`. Its
3590    /// vapour mole fraction goes through [`governing_vapor_mole_fraction`], the one place that
3591    /// formula lives.
3592    #[inline]
3593    fn new(
3594        temperature_c: f64,
3595        pressure_hpa: f64,
3596        density_ratio: f64,
3597        humidity_percent: f64,
3598    ) -> Self {
3599        Self {
3600            temperature_c,
3601            pressure_hpa,
3602            density_ratio,
3603            vapor_mole_fraction: governing_vapor_mole_fraction(
3604                temperature_c,
3605                pressure_hpa,
3606                humidity_percent,
3607            ),
3608            #[cfg(test)]
3609            humidity_percent,
3610        }
3611    }
3612
3613    /// A downrange zone's air: its own temperature, pressure and humidity, with the CIPM-2007
3614    /// density ratio at that humidity. Unvalidated, like the zone (see [`AtmoSock::validate`]).
3615    fn zone(&(temperature_c, pressure_hpa, humidity_percent, _): &AtmoSegment) -> Self {
3616        Self::new(
3617            temperature_c,
3618            pressure_hpa,
3619            calculate_air_density_cimp(temperature_c, pressure_hpa, humidity_percent) / 1.225,
3620            humidity_percent,
3621        )
3622    }
3623}
3624
3625/// The air at one point of a flight: the ONE per-step air computation.
3626///
3627/// `downrange_m` selects a zone of `zones`; `altitude_m` is the point's geometric altitude above
3628/// mean sea level (the world-vertical altitude, not the shot-frame y).
3629///
3630/// - [`KernelAtmosphere::Uniform`] returns the caller's density and sound speed unchanged at
3631///   every point, and ignores `zones`.
3632/// - [`KernelAtmosphere::Station`] picks a base: the zone that covers `downrange_m` when
3633///   `zones` holds any (its temperature, pressure and humidity, with a CIPM density ratio at
3634///   that humidity), otherwise the station itself. An empty zone set means the station. The
3635///   lapse always starts at the station altitude. The base air is well mixed: its water-vapour
3636///   mole fraction `x_v` (from its own temperature, pressure and humidity) is held at every
3637///   height, for all three steps:
3638///   1. temperature and pressure follow the ICAO layers in geopotential height, with the
3639///      virtual-temperature hydrostatic exponent: the dry one times the moist-air molar-mass
3640///      ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`;
3641///   2. density is the base ratio scaled by `(T_base · P) / (P_base · T)`, the base
3642///      composition;
3643///   3. the speed of sound is [`moist_speed_of_sound`]'s formula at the local temperature and
3644///      the base `x_v`.
3645///
3646///   The temperature and pressure of steps 1 and 2 are returned too. At the base air's own
3647///   height this is that air exactly (the sound speed is [`StationAir::speed_of_sound_mps`] to
3648///   the bit); at 0 % every step is the dry one, `sqrt(1.4 · 287.0531 · T)` for the sound
3649///   speed.
3650///
3651///   Held aloft, `x_v` exceeds saturation in the colder air: at every height above a saturated
3652///   station, and from about 2.2 km above a 15 °C / 50 % station and 0.4 km above a 35 °C / 90 %
3653///   one. At +3 km it is 1.35 times saturation over the first and 2.06 times over the second, and
3654///   at +10 km 34 and 29 times. Condensation is not modelled.
3655///
3656///   The base `x_v`, and a zone's density ratio, are fixed for the flight, so they are computed
3657///   once, when the station ([`StationAir::new`]) or the zones ([`AtmoSock::new`]) are built.
3658///   This lookup evaluates no saturation pressure; build the station and the zones once per
3659///   flight, not per step.
3660///
3661/// `zones` must already have passed [`AtmoSock::validate`], as every validated kernel entry
3662/// checks them once ([`crate::trajectory_integration::try_integrate_trajectory`],
3663/// `TrajectorySolver`, `fast_integrate*`). This per-step lookup does not: an unvalidated zone
3664/// humidity outside 0-100 is clamped into it, and a NaN one gives NaN air, never steam.
3665///
3666/// Where the lapse from the base temperature reaches absolute zero (183 km above 15 °C at sea
3667/// level, 1.54 km above a 10 K station) there is no air: from that height the result is not
3668/// finite. Every trajectory kernel refuses a flight that reaches it, at the step that gets
3669/// there, as [`AtmosphereErrorReason::AirAloftBelowAbsoluteZero`] on the temperature.
3670pub fn air_at(
3671    atmosphere: &KernelAtmosphere,
3672    zones: Option<&AtmoSock>,
3673    downrange_m: f64,
3674    altitude_m: f64,
3675) -> LocalAir {
3676    air_at_with_gravity(atmosphere, zones, downrange_m, altitude_m, Gravity::EARTH)
3677}
3678
3679/// [`air_at`] in a run's uniform gravity, which sets the hydrostatic lapse.
3680pub(crate) fn air_at_with_gravity(
3681    atmosphere: &KernelAtmosphere,
3682    zones: Option<&AtmoSock>,
3683    downrange_m: f64,
3684    altitude_m: f64,
3685    gravity: Gravity,
3686) -> LocalAir {
3687    match atmosphere {
3688        KernelAtmosphere::Uniform {
3689            density_kg_m3,
3690            speed_of_sound_mps,
3691        } => LocalAir {
3692            density_kg_m3: *density_kg_m3,
3693            speed_of_sound_mps: *speed_of_sound_mps,
3694            temperature_k: speed_of_sound_mps * speed_of_sound_mps / (GAMMA * R_AIR),
3695            pressure_pa: 0.0,
3696        },
3697        KernelAtmosphere::Station(station) => {
3698            #[cfg(test)]
3699            let saturation_pressures_before = air_trace::saturation_pressures();
3700            // The zone that covers this point, else the station: either way air computed when
3701            // it was built, so this step evaluates no vapour formula. An empty sock covers
3702            // nothing.
3703            let base = match zones.and_then(|sock| sock.governing_air_for_range(downrange_m)) {
3704                Some(zone) => *zone,
3705                None => station.governing_air(),
3706            };
3707            let air = compose_local_air(altitude_m, station.altitude_m, &base, gravity);
3708            #[cfg(test)]
3709            air_trace::attribute_lookup_saturation_pressures(saturation_pressures_before);
3710            air
3711        }
3712    }
3713}
3714
3715/// The geometric altitudes above mean sea level, m, between which the lapse from `base_temp_k`
3716/// at `base_alt_m` keeps the air above absolute zero: `(floor, ceiling)`, with
3717/// `-inf` / `+inf` where it never gets there.
3718///
3719/// The temperature [`air_at`] flies is piecewise linear in geopotential height, the base
3720/// temperature carried through the ICAO lapse rates exactly as [`integrate_local_atmosphere_layers`]
3721/// walks them (the last layer's lapse continuing above 84.852 km, the troposphere's below 0 m),
3722/// so each edge is where one layer's line reaches 0 K. Every realistic station has a ceiling too:
3723/// 15 °C at sea level reaches 0 K about 183 km up.
3724fn absolute_zero_altitudes_m(base_temp_k: f64, base_alt_m: f64) -> (f64, f64) {
3725    let base = geometric_to_geopotential_height_m(base_alt_m);
3726    let to_geometric = |geopotential_m: f64| {
3727        if geopotential_m >= GEOPOTENTIAL_EARTH_RADIUS_M {
3728            f64::INFINITY
3729        } else {
3730            GEOPOTENTIAL_EARTH_RADIUS_M * geopotential_m
3731                / (GEOPOTENTIAL_EARTH_RADIUS_M - geopotential_m)
3732        }
3733    };
3734
3735    // Up: at an exact boundary, ascent starts in the higher layer.
3736    let mut ceiling = f64::INFINITY;
3737    let (mut height, mut temperature) = (base, base_temp_k);
3738    let mut index = ICAO_LAYERS
3739        .iter()
3740        .rposition(|layer| height >= layer.base_altitude)
3741        .unwrap_or(0);
3742    loop {
3743        let lapse = ICAO_LAYERS[index].lapse_rate;
3744        let end = ICAO_LAYERS
3745            .get(index + 1)
3746            .map_or(f64::INFINITY, |next| next.base_altitude);
3747        if lapse < 0.0 {
3748            let zero = height + temperature / -lapse;
3749            if zero <= end {
3750                ceiling = to_geometric(zero);
3751                break;
3752            }
3753        }
3754        if end.is_infinite() {
3755            break;
3756        }
3757        temperature += lapse * (end - height);
3758        height = end;
3759        index += 1;
3760    }
3761
3762    // Down: at an exact boundary, descent starts in the lower layer. The troposphere's lapse
3763    // warms the air below its base, so only a warming layer above it (the stratosphere's) can
3764    // take a cold enough base to 0 K on the way down.
3765    let mut floor = f64::NEG_INFINITY;
3766    let (mut height, mut temperature) = (base, base_temp_k);
3767    let mut index = ICAO_LAYERS
3768        .iter()
3769        .rposition(|layer| height > layer.base_altitude)
3770        .unwrap_or(0);
3771    loop {
3772        let lapse = ICAO_LAYERS[index].lapse_rate;
3773        let end = if index == 0 {
3774            f64::NEG_INFINITY
3775        } else {
3776            ICAO_LAYERS[index].base_altitude
3777        };
3778        if lapse > 0.0 {
3779            let zero = height - temperature / lapse;
3780            if zero >= end {
3781                floor = to_geometric(zero);
3782                break;
3783            }
3784        }
3785        if index == 0 {
3786            break;
3787        }
3788        temperature -= lapse * (height - end);
3789        height = end;
3790        index -= 1;
3791    }
3792    (floor, ceiling)
3793}
3794
3795/// The refusal of a flight that went where its air cannot exist: the step that started at
3796/// `downrange_m` and `altitude_m` (the last state a kernel accepted, geometric altitude above
3797/// mean sea level) failed to a non-finite state, and the air within `reach_m` of where it started
3798/// (the farthest any stage of that step could lie from it) falls to absolute zero, where
3799/// [`air_at`] has no air at all.
3800///
3801/// The governing air is the zone that covers the step (at its start, or as far downrange as it
3802/// could reach) or the station. `None` when that air stays above 0 K within the step's reach,
3803/// so a step that failed for any other reason keeps its own error, and for uniform air, which
3804/// does not lapse. Kernels call this only once a step has failed, so a flight that stays below
3805/// the height its air reaches 0 K flies exactly as it did.
3806pub(crate) fn air_aloft_refusal(
3807    atmosphere: &KernelAtmosphere,
3808    zones: Option<&AtmoSock>,
3809    downrange_m: f64,
3810    altitude_m: f64,
3811    reach_m: f64,
3812) -> Option<AtmosphereError> {
3813    let KernelAtmosphere::Station(station) = atmosphere else {
3814        return None;
3815    };
3816    if !(downrange_m.is_finite() && altitude_m.is_finite() && reach_m.is_finite()) {
3817        return None;
3818    }
3819    let reach_m = reach_m.abs();
3820    [downrange_m, downrange_m + reach_m]
3821        .into_iter()
3822        .find_map(|downrange_m| {
3823            let temperature_c = zones
3824                .and_then(|sock| sock.governing_air_for_range(downrange_m))
3825                .map_or(station.temperature_c, |zone| zone.temperature_c);
3826            let (floor, ceiling) =
3827                absolute_zero_altitudes_m(temperature_c + KELVIN_OFFSET, station.altitude_m);
3828            if altitude_m + reach_m >= ceiling {
3829                Some(AtmosphereError::aloft(temperature_c, ceiling))
3830            } else if altitude_m - reach_m <= floor {
3831                Some(AtmosphereError::aloft(temperature_c, floor))
3832            } else {
3833                None
3834            }
3835        })
3836}
3837
3838/// The composition behind [`air_at`] and the legacy `get_local_atmosphere*` wrappers,
3839/// unvalidated. The only place the aloft vapour model lives.
3840///
3841/// The governing (base) air is well mixed: its water-vapour mole fraction `x_v`, from its own
3842/// temperature, pressure and humidity, is held at every height, for all three of
3843/// - the lapse: the ICAO lapse rates with the virtual-temperature hydrostatic exponent, the dry
3844///   one scaled by the moist-air molar-mass ratio `M_m / M_a = 1 - x_v (1 - M_v / M_a)`;
3845/// - the density: the base ratio scaled by `(T_0 · P) / (P_0 · T)`, the base composition;
3846/// - the sound speed: [`moist_sound_speed_at_mole_fraction`] at the local temperature and that
3847///   same `x_v`.
3848///
3849/// `base` carries that `x_v`, computed once per base air (see [`GoverningAir`]), so the
3850/// composition evaluates no saturation pressure. At 0 % `x_v` is 0 and every term is the dry
3851/// one to the bit.
3852#[inline]
3853fn compose_local_air(
3854    altitude_m: f64,
3855    base_alt: f64,
3856    base: &GoverningAir,
3857    gravity: Gravity,
3858) -> LocalAir {
3859    let (temperature_k, pressure_pa, density_kg_m3) = local_temp_pressure_density_with_gravity(
3860        altitude_m,
3861        base_alt,
3862        base.temperature_c,
3863        base.pressure_hpa,
3864        base.density_ratio,
3865        base.vapor_mole_fraction,
3866        gravity,
3867    );
3868    let air = LocalAir {
3869        density_kg_m3,
3870        speed_of_sound_mps: moist_sound_speed_at_mole_fraction(
3871            temperature_k,
3872            base.vapor_mole_fraction,
3873        ),
3874        temperature_k,
3875        pressure_pa,
3876    };
3877    #[cfg(test)]
3878    air_trace::record(air_trace::AirTraceEntry {
3879        altitude_m,
3880        base_alt_m: base_alt,
3881        base_temp_c: base.temperature_c,
3882        base_press_hpa: base.pressure_hpa,
3883        base_ratio: base.density_ratio,
3884        humidity_percent: base.humidity_percent,
3885        gravity_mps2: gravity.magnitude(),
3886        air,
3887        lookup_saturation_pressures: None,
3888        consumed: None,
3889        consumptions: 0,
3890    });
3891    air
3892}
3893
3894/// Test-only record of every per-step air composition, for the humidity class tests: which base
3895/// (station or zone) a path composed from, the base humidity whose water-vapour mole fraction it
3896/// held at every height for the lapse, the density and the sound speed, and the air it got.
3897/// Compiled out of every non-test build.
3898#[cfg(test)]
3899pub(crate) mod air_trace {
3900    use super::LocalAir;
3901    use std::cell::{Cell, RefCell};
3902
3903    /// One call of the composition behind [`super::air_at`]: its inputs and its result.
3904    #[derive(Debug, Clone, Copy)]
3905    pub(crate) struct AirTraceEntry {
3906        /// The point's geometric altitude, m.
3907        pub altitude_m: f64,
3908        /// Where the lapse started, m.
3909        pub base_alt_m: f64,
3910        /// The base temperature, °C: the station's, or the active zone's.
3911        pub base_temp_c: f64,
3912        /// The base pressure, hPa.
3913        pub base_press_hpa: f64,
3914        /// The base density ratio (density / 1.225).
3915        pub base_ratio: f64,
3916        /// The base relative humidity, percent: the one whose vapour mole fraction the
3917        /// composition held aloft for the lapse, the density and the sound speed.
3918        pub humidity_percent: f64,
3919        /// The gravity the lapse used, m/s².
3920        pub gravity_mps2: f64,
3921        /// What the composition returned.
3922        pub air: LocalAir,
3923        /// How many Wagner-Pruss saturation pressures the per-step lookup ([`super::air_at`])
3924        /// evaluated for this point, from choosing its base to returning its air: every
3925        /// humid-air formula (a vapour mole fraction, a CIPM density) goes through one. `None`
3926        /// for a composition made outside that lookup (the legacy `get_local_atmosphere*`
3927        /// wrappers, which compose from a caller's raw base once per call).
3928        pub lookup_saturation_pressures: Option<u64>,
3929        /// What the drag computation that followed took from this air ([`record_consumed`]):
3930        /// the last one, if any did.
3931        pub consumed: Option<ConsumedAir>,
3932        /// How many drag computations took this air: 1 for every per-step lookup.
3933        pub consumptions: u32,
3934    }
3935
3936    /// What a per-step drag computation (`TrajectorySolver::calculate_acceleration`,
3937    /// `compute_derivatives`, the `fast_integrate` substep) took from the air it had just
3938    /// composed: the density its drag force used, and the airspeed and Mach its drag
3939    /// coefficient was looked up at. The trace's composition records what `air_at` gave; this
3940    /// records what the kernel flew, so a kernel that calls `air_at` and then flies something
3941    /// else cannot pass the class tests.
3942    #[derive(Debug, Clone, Copy)]
3943    pub(crate) struct ConsumedAir {
3944        /// The air density in the drag force, kg/m³.
3945        pub density_kg_m3: f64,
3946        /// The airspeed the Mach divides, m/s.
3947        pub airspeed_mps: f64,
3948        /// The Mach the drag coefficient was looked up at.
3949        pub mach: f64,
3950    }
3951
3952    thread_local! {
3953        static TRACE: RefCell<Option<Vec<AirTraceEntry>>> = const { RefCell::new(None) };
3954        static SATURATION_PRESSURES: Cell<u64> = const { Cell::new(0) };
3955    }
3956
3957    /// Count one Wagner-Pruss saturation-pressure evaluation on this thread.
3958    #[inline(always)]
3959    pub(super) fn count_saturation_pressure() {
3960        SATURATION_PRESSURES.with(|count| count.set(count.get() + 1));
3961    }
3962
3963    /// The Wagner-Pruss saturation pressures evaluated on this thread so far, traced or not.
3964    pub(crate) fn saturation_pressures() -> u64 {
3965        SATURATION_PRESSURES.with(Cell::get)
3966    }
3967
3968    /// Credit the per-step lookup that started when the count stood at `before` with what it
3969    /// evaluated, on the composition it just recorded (the trace's last entry), if tracing.
3970    pub(super) fn attribute_lookup_saturation_pressures(before: u64) {
3971        let evaluated = saturation_pressures() - before;
3972        TRACE.with(|trace| {
3973            if let Some(last) = trace
3974                .borrow_mut()
3975                .as_mut()
3976                .and_then(|entries| entries.last_mut())
3977            {
3978                last.lookup_saturation_pressures = Some(evaluated);
3979            }
3980        });
3981    }
3982
3983    /// Credit the composition this thread just recorded (the trace's last entry) with a drag
3984    /// computation that took `density_kg_m3` and looked its drag coefficient up at `mach` for
3985    /// `airspeed_mps`, if tracing. Called at each per-step drag site, from the values it flies.
3986    pub(crate) fn record_consumed(density_kg_m3: f64, airspeed_mps: f64, mach: f64) {
3987        TRACE.with(|trace| {
3988            if let Some(last) = trace
3989                .borrow_mut()
3990                .as_mut()
3991                .and_then(|entries| entries.last_mut())
3992            {
3993                last.consumed = Some(ConsumedAir {
3994                    density_kg_m3,
3995                    airspeed_mps,
3996                    mach,
3997                });
3998                last.consumptions += 1;
3999            }
4000        });
4001    }
4002
4003    pub(super) fn record(entry: AirTraceEntry) {
4004        TRACE.with(|trace| {
4005            if let Some(entries) = trace.borrow_mut().as_mut() {
4006                entries.push(entry);
4007            }
4008        });
4009    }
4010
4011    /// Restores the trace that was active before [`traced`], even if the traced code panics.
4012    struct Restore(Option<Vec<AirTraceEntry>>);
4013
4014    impl Drop for Restore {
4015        fn drop(&mut self) {
4016            let previous = self.0.take();
4017            TRACE.with(|trace| *trace.borrow_mut() = previous);
4018        }
4019    }
4020
4021    /// Run `run` and return its result with every air composition it made on this thread, in
4022    /// call order.
4023    pub(crate) fn traced<R>(run: impl FnOnce() -> R) -> (R, Vec<AirTraceEntry>) {
4024        let restore = Restore(TRACE.with(|trace| trace.borrow_mut().replace(Vec::new())));
4025        let result = run();
4026        let entries = TRACE
4027            .with(|trace| trace.borrow_mut().take())
4028            .unwrap_or_default();
4029        drop(restore);
4030        (result, entries)
4031    }
4032}
4033
4034/// The lapse and density of [`compose_local_air`] in Earth gravity, for the tests, for DRY base
4035/// air (`x_v = 0`, the dry hydrostatic lapse). Returns
4036/// `(local_temp_k, local_pressure_pa, density_kg_m3)`.
4037#[cfg(test)]
4038fn local_temp_pressure_density(
4039    altitude_m: f64,
4040    base_alt: f64,
4041    base_temp_c: f64,
4042    base_press_hpa: f64,
4043    base_ratio: f64,
4044) -> (f64, f64, f64) {
4045    local_temp_pressure_density_with_gravity(
4046        altitude_m,
4047        base_alt,
4048        base_temp_c,
4049        base_press_hpa,
4050        base_ratio,
4051        0.0,
4052        Gravity::EARTH,
4053    )
4054}
4055
4056/// The lapse and density of [`compose_local_air`]: temperature and pressure through the ICAO
4057/// layers from the base, with the virtual-temperature hydrostatic exponent for base air holding
4058/// the water-vapour mole fraction `vapor_mole_fraction` (its moist gas constant
4059/// `R_AIR / (M_m / M_a)`, exactly `R_AIR` at 0), and the density from the base ratio. Returns
4060/// `(local_temp_k, local_pressure_pa, density_kg_m3)`.
4061fn local_temp_pressure_density_with_gravity(
4062    altitude_m: f64,
4063    base_alt: f64,
4064    base_temp_c: f64,
4065    base_press_hpa: f64,
4066    base_ratio: f64,
4067    vapor_mole_fraction: f64,
4068    gravity: Gravity,
4069) -> (f64, f64, f64) {
4070    let base_temp_k = base_temp_c + 273.15;
4071
4072    // A non-finite endpoint would make the boundary walk fail to advance. The
4073    // previous single-column formula also produced non-finite outputs here.
4074    if !altitude_m.is_finite() || !base_alt.is_finite() {
4075        return (f64::NAN, f64::NAN, f64::NAN);
4076    }
4077
4078    // The virtual-temperature lapse: R_m T = R_AIR T_v with T_v = T / (M_m / M_a). At x_v = 0
4079    // the ratio is exactly 1 and this is R_AIR to the bit.
4080    let gas_constant = R_AIR / moist_molar_mass_ratio(vapor_mole_fraction);
4081    let base_geopotential_m = geometric_to_geopotential_height_m(base_alt);
4082    let target_geopotential_m = geometric_to_geopotential_height_m(altitude_m);
4083    let (temp_k, pressure_hpa) = integrate_local_atmosphere_layers(
4084        base_geopotential_m,
4085        target_geopotential_m,
4086        base_temp_k,
4087        base_press_hpa,
4088        gas_constant,
4089        gravity,
4090    );
4091
4092    // Enhanced density calculation
4093    let density_ratio = base_ratio * (base_temp_k * pressure_hpa) / (base_press_hpa * temp_k);
4094    let density = density_ratio * 1.225;
4095
4096    (temp_k, pressure_hpa * 100.0, density)
4097}
4098
4099/// Carry arbitrary station temperature and pressure through each crossed ICAO
4100/// layer in geopotential-height coordinates. The layer table supplies lapse rates and boundaries
4101/// only; station deviations from the standard atmosphere remain anchored at the converted base.
4102/// `gas_constant` (J/(kg·K)) sets the hydrostatic exponent: [`R_AIR`] for dry air, the moist
4103/// `R_AIR / (M_m / M_a)` for humid air (the virtual-temperature lapse).
4104fn integrate_local_atmosphere_layers(
4105    base_geopotential_m: f64,
4106    target_geopotential_m: f64,
4107    mut temp_k: f64,
4108    mut pressure_hpa: f64,
4109    gas_constant: f64,
4110    gravity: Gravity,
4111) -> (f64, f64) {
4112    let mut current_alt = base_geopotential_m;
4113
4114    if target_geopotential_m > current_alt {
4115        while current_alt < target_geopotential_m {
4116            // At an exact boundary, ascent starts in the higher layer.
4117            let layer_index = ICAO_LAYERS
4118                .iter()
4119                .rposition(|layer| current_alt >= layer.base_altitude)
4120                .unwrap_or(0);
4121            let segment_end = ICAO_LAYERS
4122                .get(layer_index + 1)
4123                .map_or(target_geopotential_m, |next| {
4124                    target_geopotential_m.min(next.base_altitude)
4125                });
4126            (temp_k, pressure_hpa) = integrate_local_atmosphere_segment(
4127                temp_k,
4128                pressure_hpa,
4129                segment_end - current_alt,
4130                ICAO_LAYERS[layer_index].lapse_rate,
4131                gas_constant,
4132                gravity,
4133            );
4134            current_alt = segment_end;
4135        }
4136    } else {
4137        while current_alt > target_geopotential_m {
4138            // At an exact boundary, descent starts in the lower layer. The
4139            // strict comparison is what makes a cross-layer round trip reversible.
4140            let layer_index = ICAO_LAYERS
4141                .iter()
4142                .rposition(|layer| current_alt > layer.base_altitude)
4143                .unwrap_or(0);
4144            let segment_end = if layer_index == 0 {
4145                target_geopotential_m
4146            } else {
4147                target_geopotential_m.max(ICAO_LAYERS[layer_index].base_altitude)
4148            };
4149            (temp_k, pressure_hpa) = integrate_local_atmosphere_segment(
4150                temp_k,
4151                pressure_hpa,
4152                segment_end - current_alt,
4153                ICAO_LAYERS[layer_index].lapse_rate,
4154                gas_constant,
4155                gravity,
4156            );
4157            current_alt = segment_end;
4158        }
4159    }
4160
4161    (temp_k, pressure_hpa)
4162}
4163
4164/// One layer of the hydrostatic lapse, at the gas constant `gas_constant` (see
4165/// [`integrate_local_atmosphere_layers`]).
4166#[inline]
4167fn integrate_local_atmosphere_segment(
4168    base_temp_k: f64,
4169    base_pressure_hpa: f64,
4170    height_diff: f64,
4171    lapse_rate: f64,
4172    gas_constant: f64,
4173    gravity: Gravity,
4174) -> (f64, f64) {
4175    let temp_k = base_temp_k + lapse_rate * height_diff;
4176    let pressure_hpa = if lapse_rate.abs() < 1e-10 {
4177        base_pressure_hpa
4178            * (-gravity.magnitude() * height_diff / (gas_constant * base_temp_k)).exp()
4179    } else {
4180        let temp_ratio = temp_k / base_temp_k;
4181        base_pressure_hpa * temp_ratio.powf(-gravity.magnitude() / (lapse_rate * gas_constant))
4182    };
4183
4184    (temp_k, pressure_hpa)
4185}
4186
4187#[cfg(test)]
4188mod uniform_gravity_tests {
4189    use super::*;
4190
4191    #[test]
4192    fn uniform_gravity_controls_hydrostatic_pressure_without_moving_the_station_anchor() {
4193        for magnitude in [0.0, 1.62, 9.80665, 20.0] {
4194            let gravity = Gravity::new(magnitude).unwrap();
4195            let (temperature, pressure) =
4196                integrate_local_atmosphere_segment(280.0, 900.0, 100.0, 0.0, R_AIR, gravity);
4197            assert_eq!(temperature, 280.0);
4198            assert!(
4199                (pressure / 900.0 - (-magnitude * 100.0 / (R_AIR * 280.0)).exp()).abs() < 1e-14
4200            );
4201            let station = local_temp_pressure_density_with_gravity(
4202                300.0, 300.0, 20.0, 900.0, 0.9, 0.0, gravity,
4203            );
4204            assert_eq!(
4205                station,
4206                local_temp_pressure_density(300.0, 300.0, 20.0, 900.0, 0.9)
4207            );
4208        }
4209        // Exercise both the lapse and isothermal branches while crossing layer boundaries.
4210        let (_, pressure, _) = local_temp_pressure_density_with_gravity(
4211            25_000.0,
4212            0.0,
4213            20.0,
4214            900.0,
4215            0.9,
4216            0.0,
4217            Gravity::new(0.0).unwrap(),
4218        );
4219        assert_eq!(pressure, 90_000.0);
4220    }
4221}
4222
4223/// Determine local lapse rate based on altitude and atmospheric layer.
4224#[cfg(test)]
4225#[inline(always)]
4226fn determine_local_lapse_rate(altitude_m: f64) -> f64 {
4227    // Find the current atmospheric layer to get appropriate lapse rate
4228    let layer = ICAO_LAYERS
4229        .iter()
4230        .rev()
4231        .find(|layer| altitude_m >= layer.base_altitude)
4232        .unwrap_or(&ICAO_LAYERS[0]);
4233
4234    layer.lapse_rate
4235}
4236
4237/// Direct atmosphere calculation for simple cases.
4238///
4239/// # Arguments
4240/// * `density` - Pre-computed air density
4241/// * `speed_of_sound` - Pre-computed speed of sound
4242///
4243/// # Returns
4244/// Tuple of (air_density, speed_of_sound) - just passes through the values
4245#[inline(always)]
4246pub fn get_direct_atmosphere(density: f64, speed_of_sound: f64) -> (f64, f64) {
4247    (density, speed_of_sound)
4248}
4249
4250/// Legacy function name for backwards compatibility: [`calculate_air_density_cimp`].
4251///
4252/// A raw primitive: `humidity_percent` is not validated. A number outside 0-100 is clamped
4253/// into it, and a NaN propagates to a NaN result, never to pure steam. Validate a reading with
4254/// [`RelativeHumidity::try_percent`] and build the station with [`StationAir::new`], which
4255/// refuse what this computes.
4256pub fn calculate_air_density_cipm(temp_c: f64, pressure_hpa: f64, humidity_percent: f64) -> f64 {
4257    calculate_air_density_cimp(temp_c, pressure_hpa, humidity_percent)
4258}
4259
4260/// A single downrange-referenced atmosphere zone:
4261/// `(temp_c, pressure_hpa, humidity_percent, until_distance_m)`.
4262///
4263/// The T/P/H are the STATION-REFERENCED conditions (defined at the shooter base altitude) that
4264/// apply from the previous segment's threshold out to `until_distance_m`. This mirrors
4265/// [`crate::wind::WindSegment`]'s `(speed, angle, until_distance)` shape so the two segmented
4266/// models compose the same way (wind by X, atmosphere by X, altitude lapse by Y).
4267pub type AtmoSegment = (f64, f64, f64, f64);
4268
4269/// Downrange-segmented atmosphere handler (MBA-1137), the density analogue of
4270/// [`crate::wind::WindSock`].
4271///
4272/// Holds a set of station-referenced atmosphere zones ordered by their `until_distance_m`
4273/// threshold and answers a stateless downrange lookup ([`AtmoSock::atmo_for_range`]).
4274///
4275/// The zone T/P/H are the base (shooter-altitude) conditions for that stretch of range; the
4276/// solver swaps them into the same local-atmosphere altitude-lapse pipeline that a single-station
4277/// solve uses, so the downrange (X) zone and the vertical (Y) altitude lapse compose orthogonally
4278/// without double-counting (the zone sets the base tuple, the lapse multiplies on top of it).
4279#[derive(Clone)]
4280pub struct AtmoSock {
4281    /// Zones sorted ascending by `until_distance_m` (segment slot 3).
4282    segments: Vec<AtmoSegment>,
4283    /// Each zone's governing air (its density ratio and water-vapour mole fraction), in
4284    /// `segments`' order, computed once in [`Self::new`] rather than at every step. A cache of
4285    /// `segments`, so `Debug` leaves it out.
4286    governing: Vec<GoverningAir>,
4287}
4288
4289// The derive's output before the zones' governing air was held: it is a cache of the zones.
4290impl fmt::Debug for AtmoSock {
4291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4292        f.debug_struct("AtmoSock")
4293            .field("segments", &self.segments)
4294            .finish()
4295    }
4296}
4297
4298impl AtmoSock {
4299    /// Create a new `AtmoSock` from station-referenced atmosphere zones.
4300    ///
4301    /// Each segment is `(temp_c, pressure_hpa, humidity_percent, until_distance_m)`. Segments are
4302    /// sorted by `until_distance_m`, with NaN thresholds ordered last. Each zone's density ratio
4303    /// and water-vapour mole fraction, fixed for any flight, are computed here once.
4304    pub fn new(mut segments: Vec<AtmoSegment>) -> Self {
4305        segments.sort_by(|a, b| match (a.3.is_nan(), b.3.is_nan()) {
4306            (true, true) => Ordering::Equal,
4307            (true, false) => Ordering::Greater,
4308            (false, true) => Ordering::Less,
4309            (false, false) => a.3.partial_cmp(&b.3).unwrap(),
4310        });
4311        let governing = segments.iter().map(GoverningAir::zone).collect();
4312        AtmoSock {
4313            segments,
4314            governing,
4315        }
4316    }
4317
4318    /// True when this sock carries no zones. [`air_at`] treats an empty sock as no sock: the
4319    /// station's own air.
4320    pub fn is_empty(&self) -> bool {
4321        self.segments.is_empty()
4322    }
4323
4324    /// Check every zone the way [`StationAir::new`] checks a station, plus its threshold.
4325    ///
4326    /// A zone needs a finite temperature above -273.15 °C, a finite pressure above 0, a
4327    /// relative humidity that [`RelativeHumidity::try_percent`] accepts (finite, 0 to 100, or a
4328    /// sensor reading within [`HUMIDITY_SENSOR_TOLERANCE_PERCENT`] of it, which the zone flies
4329    /// as the end it reads as), air that can exist (the same impossible-air test), and an
4330    /// `until_distance_m` above 0 (`+inf` is allowed, `NaN` is not). An empty sock is valid: it
4331    /// means the station.
4332    ///
4333    /// [`AtmoSock::new`] stays infallible; the checked kernel entries
4334    /// (`try_integrate_trajectory`, `fast_integrate*`) call this before integrating.
4335    ///
4336    /// # Errors
4337    ///
4338    /// The first bad zone's [`AtmosphereError`], its field named
4339    /// `atmo_sock.zones[i].<field>` with `i` the zone's index in threshold order (the order
4340    /// [`AtmoSock::new`] sorted them into).
4341    pub fn validate(&self) -> Result<(), AtmosphereError> {
4342        for (index, &(temperature_c, pressure_hpa, humidity_percent, until_m)) in
4343            self.segments.iter().enumerate()
4344        {
4345            let at = |error: AtmosphereError| {
4346                let field = format!("atmo_sock.zones[{index}].{}", error.field());
4347                error.at_field(field)
4348            };
4349            check_station_state(0.0, temperature_c, pressure_hpa).map_err(at)?;
4350            let humidity = RelativeHumidity::try_percent(humidity_percent).map_err(at)?;
4351            refuse_impossible_air(temperature_c, pressure_hpa, humidity).map_err(at)?;
4352            if until_m.is_nan() || until_m <= 0.0 {
4353                return Err(at(AtmosphereError::new(
4354                    "until_distance_m",
4355                    until_m,
4356                    AtmosphereErrorReason::NonPositiveZoneThreshold,
4357                )));
4358            }
4359        }
4360        Ok(())
4361    }
4362
4363    /// Stateless downrange lookup of the active zone's `(temp_c, pressure_hpa, humidity_percent)`.
4364    ///
4365    /// Selection matches [`crate::wind::WindSock::vector_for_range_stateless`]: the first segment
4366    /// whose `until_distance_m` STRICTLY exceeds `downrange_m` wins (thresholds are upper-exclusive).
4367    /// Unlike wind — which returns zero past the last threshold — the LAST zone is used for any
4368    /// distance at or beyond the final threshold (there is no "zero atmosphere"). An empty sock
4369    /// returns the sea-level ISA reference at the engine's default humidity,
4370    /// `(15 C, 1013.25 hPa, DEFAULT_HUMIDITY_PERCENT)`; [`air_at`] never asks it, treating an
4371    /// empty sock as the station.
4372    ///
4373    /// This is stateless and safe for numerical integration (the same X may be queried repeatedly
4374    /// or out of order across RK substeps).
4375    pub fn atmo_for_range(&self, downrange_m: f64) -> (f64, f64, f64) {
4376        match self.zone_index(downrange_m) {
4377            Some(index) => {
4378                let (temp_c, pressure_hpa, humidity_percent, _) = self.segments[index];
4379                (temp_c, pressure_hpa, humidity_percent)
4380            }
4381            // Sea-level ISA at the one default humidity.
4382            None => (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT),
4383        }
4384    }
4385
4386    /// The governing air of the zone [`Self::atmo_for_range`] selects at `downrange_m`, as
4387    /// [`Self::new`] computed it; `None` for an empty sock, which [`air_at`] reads as the
4388    /// station.
4389    #[inline]
4390    fn governing_air_for_range(&self, downrange_m: f64) -> Option<&GoverningAir> {
4391        self.zone_index(downrange_m)
4392            .map(|index| &self.governing[index])
4393    }
4394
4395    /// The one zone selection behind [`Self::atmo_for_range`] and the per-step lookup: the first
4396    /// zone whose `until_distance_m` STRICTLY exceeds `downrange_m`, the last zone at or beyond
4397    /// the final threshold (there is no zeroing), and the first (nearest) zone for a NaN
4398    /// distance, which cannot be ordered. `None` for an empty sock.
4399    #[inline]
4400    fn zone_index(&self, downrange_m: f64) -> Option<usize> {
4401        let last = self.segments.len().checked_sub(1)?;
4402        if downrange_m.is_nan() {
4403            return Some(0);
4404        }
4405        Some(
4406            self.segments
4407                .iter()
4408                .position(|segment| downrange_m < segment.3)
4409                .unwrap_or(last),
4410        )
4411    }
4412}
4413
4414#[cfg(test)]
4415mod humidity_model_tests;
4416
4417#[cfg(test)]
4418mod aloft_vapour_tests;
4419
4420#[cfg(test)]
4421mod nan_humidity_tests;
4422
4423#[cfg(test)]
4424mod held_vapour_tests;
4425
4426#[cfg(test)]
4427mod temperature_rule_tests;
4428
4429#[cfg(test)]
4430mod tests {
4431    use super::*;
4432
4433    #[test]
4434    fn inclined_shot_frame_position_maps_to_world_altitude() {
4435        let base_altitude = 100.0;
4436        let downrange = 1_000.0;
4437        let shot_y = 10.0;
4438        let angle = std::f64::consts::FRAC_PI_6;
4439        let expected = base_altitude + downrange * angle.sin() + shot_y * angle.cos();
4440
4441        let actual = shot_frame_altitude(base_altitude, downrange, shot_y, angle);
4442        assert!(
4443            (actual - expected).abs() < 1e-12,
4444            "30-degree shot at x=1000/y=10 should be at {expected} m, got {actual} m"
4445        );
4446        assert_eq!(
4447            shot_frame_altitude(base_altitude, downrange, shot_y, 0.0),
4448            base_altitude + shot_y,
4449            "flat-fire altitude must remain byte-identical"
4450        );
4451        let downhill = shot_frame_altitude(base_altitude, downrange, shot_y, -angle);
4452        let expected_downhill = base_altitude - downrange * angle.sin() + shot_y * angle.cos();
4453        assert!((downhill - expected_downhill).abs() < 1e-12);
4454    }
4455
4456    // ---- MBA-1136: CIPM-2007 as the single canonical humid-air density ----
4457
4458    /// Gate 1: dry sea-level (15 C, 1013.25 hPa, 0% RH) must stay at the ISA reference — density
4459    /// 1.225 +- 0.002 kg/m^3 and speed of sound 340.3 +- 0.6 m/s. CIPM-2007 at 0% RH reduces to
4460    /// dry-air ideal gas to within rounding, so this is essentially unchanged from the pre-CIPM
4461    /// baseline (baseline was 1.225012 / 340.294; now 1.225521 / 340.294 — the tiny density bump
4462    /// is CIPM compressibility + exact molar mass, the speed of sound is bit-identical).
4463    #[test]
4464    fn test_mba1136_dry_sea_level_reference() {
4465        let (density, sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
4466        assert!(
4467            (density - 1.225).abs() < 0.002,
4468            "dry sea-level density {density} not within 1.225 +- 0.002"
4469        );
4470        assert!(
4471            (sos - 340.3).abs() < 0.6,
4472            "dry sea-level speed of sound {sos} not within 340.3 +- 0.6"
4473        );
4474    }
4475
4476    /// Gate 2: humid air (15 C, 1013.25 hPa, 50% RH) is the CIPM-2007 value (~1.2211 +- 0.002),
4477    /// STRICTLY lighter than dry air at the same T/P, with a speed of sound slightly ABOVE dry.
4478    #[test]
4479    fn test_mba1136_humid_lighter_than_dry() {
4480        let (dry_rho, dry_sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
4481        let (moist_rho, moist_sos) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 50.0);
4482
4483        assert!(
4484            (moist_rho - 1.2211).abs() < 0.002,
4485            "50% RH density {moist_rho} not within CIPM 1.2211 +- 0.002"
4486        );
4487        assert!(
4488            moist_rho < dry_rho,
4489            "moist air ({moist_rho}) must be lighter than dry ({dry_rho})"
4490        );
4491        assert!(
4492            moist_sos > dry_sos,
4493            "moist speed of sound ({moist_sos}) must exceed dry ({dry_sos})"
4494        );
4495    }
4496
4497    /// Gate 3: density is monotone-decreasing in humidity (100% RH < 50% RH < 0% RH).
4498    #[test]
4499    fn test_mba1136_density_monotone_in_humidity() {
4500        let (rho_0, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 0.0);
4501        let (rho_50, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 50.0);
4502        let (rho_100, _) = calculate_atmosphere(0.0, Some(15.0), Some(1013.25), 100.0);
4503        assert!(
4504            rho_100 < rho_50 && rho_50 < rho_0,
4505            "humidity monotonicity violated: 100%={rho_100}, 50%={rho_50}, 0%={rho_0}"
4506        );
4507    }
4508
4509    /// rank 28: `calculate_atmosphere`'s density is exactly `calculate_air_density_cimp` — there
4510    /// is a single canonical humid-air density path (no separate Arden-Buck ideal-gas density).
4511    #[test]
4512    fn test_mba1136_atmosphere_density_is_cipm() {
4513        for (t, p, h) in [
4514            (15.0, 1013.25, 0.0),
4515            (15.0, 1013.25, 50.0),
4516            (30.0, 1000.0, 80.0),
4517            (-10.0, 1020.0, 20.0),
4518        ] {
4519            let (density, _) = calculate_atmosphere(0.0, Some(t), Some(p), h);
4520            let cipm = calculate_air_density_cimp(t, p, h);
4521            assert_eq!(
4522                density, cipm,
4523                "calculate_atmosphere density must equal CIPM at {t}C/{p}hPa/{h}%"
4524            );
4525        }
4526    }
4527
4528    /// rank 9: the extracted `moist_speed_of_sound` is exactly what `calculate_atmosphere`
4529    /// returns (behavior-identical extraction), across dry and humid conditions.
4530    #[test]
4531    fn test_mba1136_moist_speed_of_sound_extraction() {
4532        for (t, p, h) in [
4533            (15.0, 1013.25, 0.0),
4534            (15.0, 1013.25, 50.0),
4535            (25.0, 900.0, 100.0),
4536        ] {
4537            let (_, sos) = calculate_atmosphere(0.0, Some(t), Some(p), h);
4538            let extracted = moist_speed_of_sound(t + 273.15, p * 100.0, h);
4539            assert_eq!(
4540                sos, extracted,
4541                "extracted moist_speed_of_sound must match calculate_atmosphere at {t}C/{p}hPa/{h}%"
4542            );
4543        }
4544    }
4545
4546    /// rank 9: local-atmosphere reference values (base: 500 m, 10 C, 950 hPa, ratio 1.05).
4547    /// The 1500 m values include the geometric-to-geopotential height conversion.
4548    ///
4549    /// Re-baselined in 0.50.0: the dry sound speed is the engine's one dry
4550    /// constant, sqrt(1.4 * 287.0531 * T), the moist formula at 0 % RH, instead of a second
4551    /// sqrt(401.874 * T). That moves c by +4.23e-7 relative (+1.43e-4 m/s here); the density and
4552    /// the tolerance are unchanged.
4553    #[test]
4554    #[allow(deprecated)] // the dry legacy lookup is what is under test
4555    fn test_mba1136_get_local_atmosphere_reference() {
4556        let (d0, c0) = get_local_atmosphere(500.0, 500.0, 10.0, 950.0, 1.05);
4557        assert!(
4558            (d0 - 1.286250000000).abs() < 1e-9,
4559            "local density@500m drifted: {d0}"
4560        );
4561        assert!(
4562            (c0 - 337.328800091246).abs() < 1e-9,
4563            "local sos@500m drifted: {c0}"
4564        );
4565        let (d1, c1) = get_local_atmosphere(1500.0, 500.0, 10.0, 950.0, 1.05);
4566        assert!(
4567            (d1 - 1.165238292559).abs() < 1e-9,
4568            "local density@1500m drifted: {d1}"
4569        );
4570        assert!(
4571            (c1 - 333.435687667240).abs() < 1e-9,
4572            "local sos@1500m drifted: {c1}"
4573        );
4574    }
4575
4576    #[test]
4577    #[allow(deprecated)] // the dry legacy lookup is what is under test
4578    fn fractional_station_altitude_is_not_quantized() {
4579        let station_altitude_m = 500.25;
4580        let station_temp_c = 10.0;
4581        let station_pressure_hpa = 950.0;
4582        let station_density_ratio = 1.05;
4583
4584        let (density, speed_of_sound) = get_local_atmosphere(
4585            station_altitude_m,
4586            station_altitude_m,
4587            station_temp_c,
4588            station_pressure_hpa,
4589            station_density_ratio,
4590        );
4591
4592        let expected_density = station_density_ratio * 1.225;
4593        // The engine's one dry constant (0.50.0; was a second one, 401.874).
4594        let expected_speed_of_sound = (GAMMA * R_AIR * (station_temp_c + 273.15)).sqrt();
4595        assert!((density - expected_density).abs() < 1e-12);
4596        assert!((speed_of_sound - expected_speed_of_sound).abs() < 1e-12);
4597    }
4598
4599    /// rank 9: `get_local_atmosphere_humid` returns the SAME density as `get_local_atmosphere`,
4600    /// and at 0% RH its speed of sound IS the dry value, to the bit: since 0.50.0 there is one
4601    /// dry constant (the old 401.874 differed from gamma*R by 4.2e-7, which this test used to
4602    /// absorb with a 1e-3 tolerance). At real humidity the speed of sound exceeds the dry value.
4603    #[test]
4604    #[allow(deprecated)] // the dry legacy lookup is what is under test
4605    fn test_mba1136_get_local_atmosphere_humid() {
4606        let (d_dry, c_dry) = get_local_atmosphere(1500.0, 500.0, 10.0, 950.0, 1.05);
4607        let (d_h0, c_h0) = get_local_atmosphere_humid(1500.0, 500.0, 10.0, 950.0, 1.05, 0.0);
4608        assert_eq!(d_dry, d_h0, "humid variant must not change density");
4609        assert_eq!(
4610            c_h0.to_bits(),
4611            c_dry.to_bits(),
4612            "0% RH humid sos {c_h0} must be the dry sos {c_dry}"
4613        );
4614        let (_, c_h80) = get_local_atmosphere_humid(1500.0, 500.0, 10.0, 950.0, 1.05, 80.0);
4615        assert!(c_h80 > c_dry, "humid sos {c_h80} should exceed dry {c_dry}");
4616    }
4617
4618    #[test]
4619    fn test_icao_standard_atmosphere() {
4620        // Test sea level
4621        let (temp, press) = calculate_icao_standard_atmosphere(0.0);
4622        assert!((temp - 288.15).abs() < 0.01);
4623        assert!((press - 101325.0).abs() < 1.0);
4624
4625        // The table's 11 km tropopause base is geopotential height; convert it back to the
4626        // geometric altitude accepted by the public atmosphere contract.
4627        let geometric_tropopause_m =
4628            GEOPOTENTIAL_EARTH_RADIUS_M * 11000.0 / (GEOPOTENTIAL_EARTH_RADIUS_M - 11000.0);
4629        let (temp_11km, press_11km) = calculate_icao_standard_atmosphere(geometric_tropopause_m);
4630        assert!((temp_11km - 216.65).abs() < 0.01);
4631        assert!((press_11km - 22632.1).abs() < 1.0);
4632
4633        // Test stratosphere
4634        let (temp_25km, _) = calculate_icao_standard_atmosphere(25000.0);
4635        assert!(temp_25km > 216.65); // Temperature increases in stratosphere
4636    }
4637
4638    #[test]
4639    fn standard_atmosphere_extends_below_sea_level() {
4640        let altitude_m = -430.0;
4641        let (temp_k, pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
4642
4643        assert!((temp_k - 290.945_189_079_054).abs() < 1e-9);
4644        assert!((pressure_pa - 106_598.763_552_437).abs() < 0.1);
4645
4646        let (station_temp_c, station_pressure_hpa) =
4647            resolve_station_conditions(15.0, 1013.25, altitude_m);
4648        assert!((station_temp_c - 17.795_189_079_054).abs() < 1e-9);
4649        assert!((station_pressure_hpa - 1_065.987_635_524).abs() < 1e-6);
4650
4651        let (sea_density, _) = calculate_atmosphere(0.0, None, None, 0.0);
4652        let (below_sea_density, _) = calculate_atmosphere(altitude_m, None, None, 0.0);
4653        assert!((below_sea_density - 1.276_908_642_79).abs() < 1e-6);
4654        assert!(below_sea_density > sea_density * 1.04);
4655
4656        assert_eq!(
4657            calculate_icao_standard_atmosphere(-6000.0),
4658            calculate_icao_standard_atmosphere(MIN_GEOMETRIC_ALTITUDE_M)
4659        );
4660    }
4661
4662    #[test]
4663    fn standard_atmosphere_converts_geometric_to_geopotential_height() {
4664        let cases: [(f64, f64, f64); 3] = [
4665            (10_000.0, 223.252_092_647_979, 26_499.901_600_244),
4666            (30_000.0, 226.509_083_611_330, 1_197.032_108_466),
4667            (84_000.0, 190.841_043_736_102, 0.531_525_514_935),
4668        ];
4669        for (geometric_m, expected_temp_k, expected_pressure_pa) in cases {
4670            let (temp_k, pressure_pa) = calculate_icao_standard_atmosphere(geometric_m);
4671            let pressure_tolerance = expected_pressure_pa.max(1.0_f64) * 1e-6;
4672
4673            assert!((temp_k - expected_temp_k).abs() < 1e-9);
4674            assert!((pressure_pa - expected_pressure_pa).abs() < pressure_tolerance);
4675        }
4676    }
4677
4678    #[test]
4679    #[allow(deprecated)] // the dry legacy lookup is one of the paths under test
4680    fn local_atmosphere_walks_icao_layers_continuously() {
4681        for altitude_m in [
4682            10999.0, 11000.0, 11001.0, 11050.0, 19999.0, 20000.0, 20001.0, 25000.0,
4683        ] {
4684            let (local_temp_k, local_pressure_pa, _) =
4685                local_temp_pressure_density(altitude_m, 0.0, 15.0, 1013.25, 1.0);
4686            let (standard_temp_k, standard_pressure_pa) =
4687                calculate_icao_standard_atmosphere(altitude_m);
4688
4689            assert!(
4690                (local_temp_k - standard_temp_k).abs() < 1e-9,
4691                "local temperature diverged from ICAO at {altitude_m} m: local={local_temp_k}, standard={standard_temp_k}"
4692            );
4693            assert!(
4694                ((local_pressure_pa - standard_pressure_pa) / standard_pressure_pa).abs() < 5e-5,
4695                "local pressure diverged from ICAO at {altitude_m} m: local={local_pressure_pa}, standard={standard_pressure_pa}"
4696            );
4697        }
4698
4699        let (density_below, sound_below) = get_local_atmosphere(10999.0, 0.0, 15.0, 1013.25, 1.0);
4700        let (density_above, sound_above) = get_local_atmosphere(11001.0, 0.0, 15.0, 1013.25, 1.0);
4701        assert!(
4702            (density_below - density_above).abs() < 0.001,
4703            "density jumped across 11 km: below={density_below}, above={density_above}"
4704        );
4705        assert!(
4706            (sound_below - sound_above).abs() < 0.1,
4707            "speed of sound jumped across 11 km: below={sound_below}, above={sound_above}"
4708        );
4709    }
4710
4711    #[test]
4712    fn local_atmosphere_preserves_nonstandard_station_offset_and_round_trips() {
4713        let base_alt = 7500.0;
4714        let base_temp_c = 5.0;
4715        let base_pressure_hpa = 410.0;
4716        let base_ratio = 0.72;
4717
4718        let (high_temp_k, high_pressure_pa, high_density) = local_temp_pressure_density(
4719            25000.0,
4720            base_alt,
4721            base_temp_c,
4722            base_pressure_hpa,
4723            base_ratio,
4724        );
4725        assert!((high_temp_k - 260.244_615_053_376).abs() < 1e-9);
4726        assert!((high_pressure_pa / 100.0 - 40.964_358_485_456).abs() < 1e-9);
4727        assert!((high_density - 0.094_186_400_274).abs() < 1e-9);
4728
4729        let (back_temp_k, back_pressure_pa, back_density) = local_temp_pressure_density(
4730            base_alt,
4731            25000.0,
4732            high_temp_k - 273.15,
4733            high_pressure_pa / 100.0,
4734            high_density / 1.225,
4735        );
4736        assert!((back_temp_k - (base_temp_c + 273.15)).abs() < 1e-9);
4737        assert!((back_pressure_pa / 100.0 - base_pressure_hpa).abs() < 1e-8);
4738        assert!((back_density - base_ratio * 1.225).abs() < 1e-9);
4739    }
4740
4741    #[test]
4742    fn test_enhanced_atmosphere_sea_level() {
4743        let (density, speed) = calculate_atmosphere(0.0, None, None, 0.0);
4744        assert!((density - 1.225).abs() < 0.01);
4745        assert!((speed - 340.0).abs() < 1.0);
4746    }
4747
4748    /// The band's edges are inside it, in both directions. At sea level the ICAO standard is
4749    /// exactly 101325 Pa, and 1.08 and 0.85 times it are exact in binary, so the division
4750    /// lands on the constants themselves rather than next to them.
4751    #[test]
4752    fn station_pressure_plausibility_band_edges_are_inside_the_band() {
4753        let at_sea_level = |pa| station_pressure_plausibility(pa, 0.0);
4754        assert_eq!(at_sea_level(101_325.0).icao_standard_pa, 101_325.0);
4755
4756        let high_edge = at_sea_level(109_431.0);
4757        assert_eq!(high_edge.ratio, STATION_PRESSURE_MAX_PLAUSIBLE_RATIO);
4758        assert!(!high_edge.implausible, "{high_edge:?}");
4759        assert!(at_sea_level(109_432.0).implausible);
4760
4761        let low_edge = at_sea_level(86_126.25);
4762        assert_eq!(low_edge.ratio, STATION_PRESSURE_MIN_PLAUSIBLE_RATIO);
4763        assert!(!low_edge.implausible, "{low_edge:?}");
4764        assert!(at_sea_level(86_126.0).implausible);
4765
4766        // Away from sea level the edges hold to a part in a billion either side.
4767        for altitude_m in [-400.0, 1500.0, 3310.128] {
4768            let (_, icao_pa) = calculate_icao_standard_atmosphere(altitude_m);
4769            for (ratio, implausible) in [
4770                (STATION_PRESSURE_MAX_PLAUSIBLE_RATIO * (1.0 - 1e-9), false),
4771                (STATION_PRESSURE_MAX_PLAUSIBLE_RATIO * (1.0 + 1e-9), true),
4772                (STATION_PRESSURE_MIN_PLAUSIBLE_RATIO * (1.0 + 1e-9), false),
4773                (STATION_PRESSURE_MIN_PLAUSIBLE_RATIO * (1.0 - 1e-9), true),
4774            ] {
4775                let p = station_pressure_plausibility(ratio * icao_pa, altitude_m);
4776                assert_eq!(p.icao_standard_pa, icao_pa);
4777                assert_eq!(
4778                    p.implausible, implausible,
4779                    "{altitude_m} m, ratio {ratio}: {p:?}"
4780                );
4781            }
4782        }
4783
4784        assert!(station_pressure_plausibility(f64::NAN, 0.0).implausible);
4785    }
4786
4787    /// The record sea-level pressures the band is justified by stay inside it, and the reported
4788    /// placeholder at Cusco does not.
4789    #[test]
4790    fn station_pressure_plausibility_passes_record_weather_and_flags_a_placeholder() {
4791        for record_hpa in [870.0, 1083.8, 1089.1] {
4792            let p = station_pressure_plausibility(record_hpa * 100.0, 0.0);
4793            assert!(!p.implausible, "{record_hpa} hPa: {p:?}");
4794        }
4795
4796        let placeholder = station_pressure_plausibility(101_325.0, 3310.128);
4797        assert!(placeholder.implausible, "{placeholder:?}");
4798        assert!((placeholder.ratio - 1.503).abs() < 5e-4, "{placeholder:?}");
4799        // A real Cusco station reading is close to standard.
4800        assert!(!station_pressure_plausibility(68_830.0, 3310.128).implausible);
4801        // The same reading at an omitted (0 m) altitude is far below standard.
4802        assert!(station_pressure_plausibility(68_830.0, 0.0).implausible);
4803        // 101325 Pa leaves the band between 640 m and 650 m.
4804        assert!(!station_pressure_plausibility(101_325.0, 640.0).implausible);
4805        assert!(station_pressure_plausibility(101_325.0, 650.0).implausible);
4806    }
4807
4808    #[test]
4809    fn test_resolve_station_pressure_contract() {
4810        // Default sea-level pressure + real altitude => derive from altitude (None).
4811        assert_eq!(resolve_station_pressure(1013.25, 2000.0), None);
4812        // 29.92 inHg ≈ 1013.21 hPa is also treated as the default (within tolerance).
4813        assert_eq!(resolve_station_pressure(1013.21, 2000.0), None);
4814        // An explicit, non-default station pressure is authoritative (Some, used directly).
4815        assert_eq!(resolve_station_pressure(850.0, 2000.0), Some(850.0));
4816        // At/near sea level the default is used directly (no derivation needed).
4817        assert_eq!(resolve_station_pressure(1013.25, 0.0), Some(1013.25));
4818    }
4819
4820    #[test]
4821    fn qnh_reduction_matches_hand_computed_value_at_nonzero_altitude() {
4822        // Hand-computed (Python, double precision) from the altimeter-setting relation.
4823        // NOTE the geopotential step — 1500 m geometric is 1499.646 m geopotential, and it is
4824        // the geopotential height that enters the formula:
4825        //   h_geo   = 6356766*1500/(6356766+1500)                    = 1499.6461... m
4826        //   n       = 1/5.255875601466713                            = 0.19026325503612...
4827        //   station = 1030.0 * (1 - (0.0065*h_geo/288.15)*(1013.25/1030.0)^n)^(1/n)
4828        //           = 860.0681114332783 hPa
4829        // The ratio form this replaced, 1030.0 * (1 - 0.0065*h_geo/288.15)^5.2558756, gave
4830        // 859.5753123926447 hPa: 0.49 hPa low, because it scales the standard pressure ratio
4831        // by QNH instead of adding the station height to the QNH's pressure altitude.
4832        let reduced = reduce_qnh_to_station_pressure(1030.0, 1500.0);
4833        assert!(
4834            (reduced - 860.068_111_433_278_3).abs() < 1e-9,
4835            "reduced={reduced}"
4836        );
4837        // The reduction must strictly lower the pressure versus the raw QNH input.
4838        assert!(reduced < 1030.0);
4839    }
4840
4841    #[test]
4842    fn qnh_reduction_is_identity_at_sea_level() {
4843        // At h=0 the geopotential height is 0, so the ratio is exactly 1.0 and QNH passes
4844        // through unchanged (bit-exact: 1.0f64.powf(x) == 1.0).
4845        assert_eq!(reduce_qnh_to_station_pressure(1030.0, 0.0), 1030.0);
4846        assert_eq!(reduce_qnh_to_station_pressure(950.5, 0.0), 950.5);
4847    }
4848
4849    #[test]
4850    fn qnh_sea_level_standard_matches_icao_standard_atmosphere_at_every_altitude() {
4851        // A QNH of exactly 1013.25 hPa (the sea-level standard) must reduce to precisely the
4852        // ICAO standard station pressure at any altitude -- this is what keeps the omitted-
4853        // pressure default byte-identical whether the caller declares Absolute or Qnh.
4854        for altitude_m in [0.0, 500.0, 2000.0, 4500.0] {
4855            let (_, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
4856            let reduced = reduce_qnh_to_station_pressure(1013.25, altitude_m);
4857            assert!(
4858                (reduced - std_pressure_pa / 100.0).abs() < 1e-9,
4859                "altitude={altitude_m} reduced={reduced} std={}",
4860                std_pressure_pa / 100.0
4861            );
4862        }
4863    }
4864
4865    /// The doc comment's comparison with the NWS/ASOS altimeter-setting algorithm, checked:
4866    /// with that algorithm's constants (n = 0.190284, k = 8.4228807e-5, the field elevation as
4867    /// entered) and without its 0.3 hPa sensor offset, its station pressure is about 0.1 hPa
4868    /// below this function's at 1500 m and 0.3 to 0.45 hPa below at 4000 to 5000 m, over QNH
4869    /// 950 to 1050 hPa.
4870    #[test]
4871    fn qnh_reduction_differs_from_nws_asos_by_the_documented_amounts() {
4872        let nws_station_hpa = |qnh_hpa: f64, elevation_m: f64| {
4873            (qnh_hpa.powf(0.190284) - 8.4228807e-5 * elevation_m).powf(1.0 / 0.190284)
4874        };
4875        for (altitude_m, low, high) in [
4876            (1500.0, 0.09, 0.11),
4877            (4000.0, 0.3, 0.45),
4878            (5000.0, 0.3, 0.45),
4879        ] {
4880            for qnh_hpa in [950.0, 980.0, 1013.25, 1030.0, 1050.0] {
4881                let gap = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m)
4882                    - nws_station_hpa(qnh_hpa, altitude_m);
4883                assert!(
4884                    (low..=high).contains(&gap),
4885                    "QNH {qnh_hpa} at {altitude_m} m: this function is {gap} hPa above NWS/ASOS"
4886                );
4887            }
4888        }
4889    }
4890
4891    #[test]
4892    fn qnh_reduction_adds_the_station_height_to_the_qnhs_pressure_altitude() {
4893        // What an altimeter setting means: an altimeter set to QNH reads field elevation on
4894        // the ground, so the station pressure's ISA pressure altitude is the QNH's own pressure
4895        // altitude plus the station's (geopotential) height. The troposphere's pressure
4896        // altitude is H(p) = (T0/-L) * (1 - (p/P0)^n), n = -L*R/g.
4897        let layer = &ICAO_LAYERS[0];
4898        let n = -layer.lapse_rate * R_AIR / G_ACCEL_MPS2;
4899        let p0_hpa = layer.base_pressure / 100.0;
4900        let pressure_altitude_m = |pressure_hpa: f64| {
4901            layer.base_temperature / -layer.lapse_rate * (1.0 - (pressure_hpa / p0_hpa).powf(n))
4902        };
4903        // The unit-test pin, Cusco (SPZO), La Paz (SLLP), low and high settings, a standard
4904        // setting, and a station below sea level.
4905        for (qnh_hpa, altitude_m) in [
4906            (1030.0, 1500.0),
4907            (1033.0, 3310.0),
4908            (1038.0, 4061.0),
4909            (1000.0, 2000.0),
4910            (980.0, 1500.0),
4911            (1040.0, 4500.0),
4912            (1013.25, 3000.0),
4913            (1030.0, -400.0),
4914        ] {
4915            let station_hpa = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
4916            let added_m = pressure_altitude_m(station_hpa) - pressure_altitude_m(qnh_hpa);
4917            let height_m = geometric_to_geopotential_height_m(altitude_m);
4918            assert!(
4919                (added_m - height_m).abs() < 1e-6,
4920                "QNH {qnh_hpa} hPa at {altitude_m} m: station {station_hpa} hPa adds \
4921                 {added_m} m of pressure altitude, expected {height_m} m"
4922            );
4923        }
4924    }
4925
4926    #[test]
4927    fn qnh_reduction_is_nan_where_no_station_pressure_exists() {
4928        // A station pressure exists only while the QNH's pressure altitude plus the station
4929        // height stays below T0/-L (44,331 m, where the troposphere's lapse rate reaches
4930        // absolute zero). Past that the result is NaN, which every caller's finite-pressure
4931        // check refuses, rather than a near-vacuum number that would be flown as real air.
4932        assert!(reduce_qnh_to_station_pressure(500.0, 40_000.0).is_nan());
4933        assert!(reduce_qnh_to_station_pressure(-1030.0, 1500.0).is_nan());
4934        // Everywhere real shooting happens the reduction is finite and positive, lowers the
4935        // pressure above sea level and raises it below.
4936        for qnh_step in 0..=24 {
4937            let qnh_hpa = 850.0 + 10.0 * f64::from(qnh_step);
4938            for altitude_step in 0..=20 {
4939                let altitude_m = -1000.0 + 500.0 * f64::from(altitude_step);
4940                let station_hpa = reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
4941                assert!(
4942                    station_hpa.is_finite() && station_hpa > 0.0,
4943                    "QNH {qnh_hpa} hPa at {altitude_m} m gave {station_hpa} hPa"
4944                );
4945                assert_eq!(
4946                    station_hpa.partial_cmp(&qnh_hpa),
4947                    0.0.partial_cmp(&altitude_m),
4948                    "QNH {qnh_hpa} hPa at {altitude_m} m gave {station_hpa} hPa"
4949                );
4950            }
4951        }
4952    }
4953
4954    #[test]
4955    fn resolve_station_pressure_with_mode_absolute_matches_resolve_station_pressure() {
4956        // PressureReferenceMode::Absolute must be byte-identical to resolve_station_pressure
4957        // for every case that function's own contract test exercises.
4958        for (pressure_hpa, altitude_m) in [
4959            (1013.25, 2000.0),
4960            (1013.21, 2000.0),
4961            (850.0, 2000.0),
4962            (1013.25, 0.0),
4963        ] {
4964            assert_eq!(
4965                resolve_station_pressure_with_mode(
4966                    pressure_hpa,
4967                    altitude_m,
4968                    PressureReferenceMode::Absolute
4969                ),
4970                resolve_station_pressure(pressure_hpa, altitude_m)
4971            );
4972        }
4973    }
4974
4975    #[test]
4976    fn resolve_station_pressure_with_mode_qnh_bypasses_the_default_sentinel() {
4977        // Constructed so the REDUCED value coincidentally lands within the absolute-mode
4978        // sentinel's +/-0.5 hPa tolerance of 1013.25 hPa at a real (>1 m) altitude -- exactly
4979        // the case that would silently discard an explicit reading under the old,
4980        // mode-blind resolve_station_pressure.
4981        let qnh = 1030.0;
4982        let altitude_m = 138.078_300_203_223_02;
4983        let reduced = reduce_qnh_to_station_pressure(qnh, altitude_m);
4984        assert!(
4985            (reduced - 1013.25).abs() < 0.5,
4986            "test fixture must land inside the sentinel band; reduced={reduced}"
4987        );
4988
4989        // Qnh mode must still return Some(reduced) -- never None -- regardless of the
4990        // coincidence, and must equal the reduction, not a derived-from-altitude value.
4991        assert_eq!(
4992            resolve_station_pressure_with_mode(qnh, altitude_m, PressureReferenceMode::Qnh),
4993            Some(reduced)
4994        );
4995
4996        // Sanity: the OLD absolute-mode function, given that same reduced number directly,
4997        // WOULD have discarded it (returned None, deriving ICAO-standard pressure instead) --
4998        // demonstrating why Qnh mode must never be routed back through the plain sentinel
4999        // check on its output.
5000        assert_eq!(resolve_station_pressure(reduced, altitude_m), None);
5001        let (_, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
5002        assert!(
5003            (std_pressure_pa / 100.0 - reduced).abs() > 10.0,
5004            "fixture must show the sentinel misfire actually changes the answer materially"
5005        );
5006    }
5007
5008    #[test]
5009    fn resolve_station_conditions_with_pressure_mode_absolute_matches_resolve_station_conditions() {
5010        for (temp_c, pressure_hpa, altitude_m) in [
5011            (15.0, 1013.25, 2000.0),
5012            (-5.0, 850.0, 2000.0),
5013            (15.0, 1013.25, 0.0),
5014        ] {
5015            assert_eq!(
5016                resolve_station_conditions_with_pressure_mode(
5017                    temp_c,
5018                    pressure_hpa,
5019                    altitude_m,
5020                    PressureReferenceMode::Absolute
5021                ),
5022                resolve_station_conditions(temp_c, pressure_hpa, altitude_m)
5023            );
5024        }
5025    }
5026
5027    #[test]
5028    fn resolve_station_conditions_with_pressure_mode_qnh_reduces_pressure_only() {
5029        // -5.0 C is not the sea-level default sentinel (15.0 C), so it stays authoritative --
5030        // isolating that only the pressure resolution differs between the two modes.
5031        let (temp_c, pressure_hpa) = resolve_station_conditions_with_pressure_mode(
5032            -5.0,
5033            1030.0,
5034            1500.0,
5035            PressureReferenceMode::Qnh,
5036        );
5037        // Temperature resolution is untouched by pressure mode: an explicit, non-default
5038        // temperature stays authoritative exactly as resolve_station_conditions would give.
5039        assert_eq!(temp_c, -5.0);
5040        assert!((pressure_hpa - 860.068_111_433_278_3).abs() < 1e-9);
5041    }
5042
5043    #[test]
5044    fn test_altitude_affects_density_with_default_pressure() {
5045        // Regression: with the default pressure, altitude MUST lower density (previously the
5046        // air-density path ignored altitude whenever pressure was the sea-level default).
5047        let press = resolve_station_pressure(1013.25, 0.0);
5048        let (rho_sea, _) = calculate_atmosphere(0.0, Some(15.0), press, 50.0);
5049        let press_alt = resolve_station_pressure(1013.25, 2000.0);
5050        let (rho_2km, _) = calculate_atmosphere(2000.0, Some(15.0), press_alt, 50.0);
5051        assert!(
5052            rho_2km < rho_sea * 0.9,
5053            "density at 2000 m ({rho_2km}) should be well below sea level ({rho_sea})"
5054        );
5055
5056        // But an explicit station pressure stays authoritative (no altitude double-count):
5057        // density with an explicit pressure is independent of the altitude field.
5058        let p = resolve_station_pressure(900.0, 2000.0);
5059        let (rho_a, _) = calculate_atmosphere(2000.0, Some(15.0), p, 50.0);
5060        let (rho_b, _) = calculate_atmosphere(0.0, Some(15.0), p, 50.0);
5061        assert!(
5062            (rho_a - rho_b).abs() < 1e-9,
5063            "explicit pressure must ignore altitude"
5064        );
5065    }
5066
5067    #[test]
5068    fn test_resolve_station_temperature_contract() {
5069        // Default 15 C + real altitude => derive ICAO lapse temperature (None).
5070        assert_eq!(resolve_station_temperature(15.0, 2000.0), None);
5071        // An explicit, non-default temperature is authoritative (Some, used directly).
5072        assert_eq!(resolve_station_temperature(-5.0, 2000.0), Some(-5.0));
5073        assert_eq!(resolve_station_temperature(30.0, 2000.0), Some(30.0));
5074        // At/near sea level the default is used directly (no derivation needed).
5075        assert_eq!(resolve_station_temperature(15.0, 0.0), Some(15.0));
5076    }
5077
5078    #[test]
5079    fn test_altitude_only_default_matches_full_icao_standard() {
5080        // Regression: resolving BOTH temperature and pressure for an altitude-only query (defaults
5081        // left in place) must equal the fully-standard atmosphere at that altitude — i.e. altitude
5082        // now drives temperature (ICAO lapse) AND pressure, not just pressure. Validated against
5083        // py_ballisticcalc to ~0.04%. Previously the air held 15 C, leaving density ~7% too thin
5084        // (warm) at 3 km.
5085        for alt in [1000.0, 2000.0, 2500.0, 3000.0] {
5086            let t = resolve_station_temperature(15.0, alt);
5087            let p = resolve_station_pressure(1013.25, alt);
5088            let (rho_resolved, _) = calculate_atmosphere(alt, t, p, 0.0);
5089            let (rho_std, _) = calculate_atmosphere(alt, None, None, 0.0);
5090            assert!(
5091                (rho_resolved - rho_std).abs() < 1e-9,
5092                "alt {alt}: altitude-only default density {rho_resolved} should equal the full \
5093                 ICAO standard {rho_std}"
5094            );
5095            // And it must be denser than the old temperature-held-at-15C behavior (colder = denser).
5096            let (rho_warm, _) = calculate_atmosphere(alt, Some(15.0), p, 0.0);
5097            assert!(
5098                rho_resolved > rho_warm,
5099                "alt {alt}: lapse-temperature density {rho_resolved} should exceed 15 C-held {rho_warm}"
5100            );
5101        }
5102    }
5103
5104    #[test]
5105    fn test_enhanced_atmosphere_with_humidity() {
5106        let (density_dry, speed_dry) = calculate_atmosphere(0.0, None, None, 0.0);
5107        let (density_humid, speed_humid) = calculate_atmosphere(0.0, None, None, 80.0);
5108
5109        // Humid air should be less dense
5110        assert!(density_humid < density_dry);
5111        // Humid air should have slightly higher speed of sound
5112        assert!(speed_humid > speed_dry);
5113    }
5114
5115    #[test]
5116    fn test_enhanced_atmosphere_stratosphere() {
5117        // Test in stratosphere where temperature increases
5118        let (density_20km, speed_20km) = calculate_atmosphere(20000.0, None, None, 0.0);
5119        let (density_30km, speed_30km) = calculate_atmosphere(30000.0, None, None, 0.0);
5120
5121        // Density should decrease with altitude
5122        assert!(density_30km < density_20km);
5123        // Speed of sound should increase due to temperature increase
5124        assert!(speed_30km > speed_20km);
5125    }
5126
5127    #[test]
5128    fn test_enhanced_cimp_density() {
5129        let density = calculate_air_density_cimp(15.0, 1013.25, 0.0);
5130        assert!((density - 1.225).abs() < 0.01);
5131
5132        // Test with humidity
5133        let density_humid = calculate_air_density_cimp(15.0, 1013.25, 50.0);
5134        assert!(density_humid < density);
5135    }
5136
5137    #[test]
5138    fn test_cipm_moist_air_matches_python_reference() {
5139        // Regression for the hPa/Pa mole-fraction slip: p_v (hPa) was divided by the total
5140        // pressure in Pa, making x_v 100x too small and erasing the humidity effect entirely.
5141        // Reference values computed with the validated Python implementation
5142        // (ballistics.physics.atmosphere_icao.calculate_air_density_cipm_icao), same cases as
5143        // the Flask suite's tests/test_atmosphere.py::TestCalculateAirDensityCIPM. Tolerance
5144        // 0.1% (matches that suite's Rust-vs-Python assertion).
5145        let cases = [
5146            (15.0, 1013.25, 50.0, 1.221125867723075),
5147            (30.0, 1000.0, 80.0, 1.1344071877123691),
5148            (-10.0, 1020.0, 20.0, 1.3500610713710515),
5149        ];
5150        for (temp_c, pressure_hpa, humidity_pct, expected) in cases {
5151            let density = calculate_air_density_cipm(temp_c, pressure_hpa, humidity_pct);
5152            let rel_err = ((density - expected) / expected).abs();
5153            assert!(
5154                rel_err < 1e-3,
5155                "CIPM density at {temp_c} C / {pressure_hpa} hPa / {humidity_pct}% RH: \
5156                 got {density}, expected {expected} (rel err {rel_err:.2e} >= 1e-3)"
5157            );
5158        }
5159
5160        // Moist air must be materially lighter than dry air at the same temp/pressure
5161        // (the broken version returned a difference of only ~4e-5 kg/m^3).
5162        let dry = calculate_air_density_cipm(15.0, 1013.25, 0.0);
5163        let moist = calculate_air_density_cipm(15.0, 1013.25, 50.0);
5164        assert!(
5165            dry - moist > 3e-3,
5166            "humidity effect too small: dry {dry} vs 50% RH {moist}"
5167        );
5168    }
5169
5170    #[test]
5171    fn test_variable_lapse_rates() {
5172        // Test that lapse rates change appropriately with altitude
5173        let lapse_tropo = determine_local_lapse_rate(5000.0);
5174        let lapse_strato = determine_local_lapse_rate(25000.0);
5175
5176        assert!((lapse_tropo - (-0.0065)).abs() < 0.0001);
5177        assert!(lapse_strato > 0.0); // Positive lapse rate in stratosphere
5178    }
5179
5180    // ---- MBA-1137: AtmoSock stateless downrange lookup (mirrors the WindSock tests) ----
5181
5182    #[test]
5183    fn test_atmo_sock_empty_falls_back_to_isa() {
5184        let sock = AtmoSock::new(vec![]);
5185        assert!(sock.is_empty());
5186        // Empty sock returns the sea-level ISA reference regardless of distance, at the engine's
5187        // one default humidity (50 %, not a 0 % of its own). air_at never asks: to it an empty
5188        // sock is the station.
5189        assert_eq!(
5190            sock.atmo_for_range(0.0),
5191            (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT)
5192        );
5193        assert_eq!(
5194            sock.atmo_for_range(500.0),
5195            (15.0, 1013.25, DEFAULT_HUMIDITY_PERCENT)
5196        );
5197    }
5198
5199    #[test]
5200    fn test_atmo_sock_single_segment_holds_beyond_last() {
5201        // One zone until 100 m; it must apply BOTH before and beyond the threshold (unlike wind,
5202        // which zeroes past the last segment — atmosphere holds the last zone).
5203        let sock = AtmoSock::new(vec![(25.0, 1000.0, 30.0, 100.0)]);
5204        assert_eq!(sock.atmo_for_range(50.0), (25.0, 1000.0, 30.0));
5205        assert_eq!(sock.atmo_for_range(100.0), (25.0, 1000.0, 30.0)); // beyond last -> hold
5206        assert_eq!(sock.atmo_for_range(5000.0), (25.0, 1000.0, 30.0));
5207    }
5208
5209    #[test]
5210    fn test_atmo_sock_boundary_is_upper_exclusive() {
5211        // A zone's until_distance_m is exclusive: a query exactly at the boundary rolls to the
5212        // next zone (mirrors WindSock::test_wind_sock_boundary_is_upper_exclusive).
5213        let sock = AtmoSock::new(vec![
5214            (30.0, 1010.0, 80.0, 100.0), // hot/humid near zone
5215            (-5.0, 900.0, 10.0, 200.0),  // cold/thin far zone
5216        ]);
5217        // Just below 100 m -> first zone.
5218        assert_eq!(sock.atmo_for_range(99.999), (30.0, 1010.0, 80.0));
5219        // Exactly 100 m -> second zone.
5220        assert_eq!(sock.atmo_for_range(100.0), (-5.0, 900.0, 10.0));
5221        // Beyond the last boundary -> hold the last zone (NOT zeroed).
5222        assert_eq!(sock.atmo_for_range(200.0), (-5.0, 900.0, 10.0));
5223        assert_eq!(sock.atmo_for_range(1e6), (-5.0, 900.0, 10.0));
5224    }
5225
5226    #[test]
5227    fn test_atmo_sock_sorts_unordered_segments() {
5228        // Segments supplied out of order are sorted by until_distance so the lookup is monotone.
5229        let sock = AtmoSock::new(vec![
5230            (-5.0, 900.0, 10.0, 200.0),
5231            (30.0, 1010.0, 80.0, 100.0),
5232        ]);
5233        assert_eq!(sock.atmo_for_range(50.0), (30.0, 1010.0, 80.0));
5234        assert_eq!(sock.atmo_for_range(150.0), (-5.0, 900.0, 10.0));
5235    }
5236
5237    #[test]
5238    fn test_atmo_sock_orders_nan_thresholds_last() {
5239        let positive_nan = f64::from_bits(0x7ff8_0000_0000_0001);
5240        let negative_nan = f64::from_bits(0xfff8_0000_0000_0002);
5241        let sock = AtmoSock::new(vec![
5242            (97.0, 997.0, 97.0, positive_nan),
5243            (30.0, 1030.0, 30.0, 300.0),
5244            (98.0, 998.0, 98.0, negative_nan),
5245            (10.0, 1010.0, 10.0, 100.0),
5246            (99.0, 999.0, 99.0, f64::NAN),
5247            (20.0, 1020.0, 20.0, 200.0),
5248        ]);
5249
5250        let thresholds: Vec<_> = sock.segments.iter().map(|segment| segment.3).collect();
5251        assert_eq!(&thresholds[..3], &[100.0, 200.0, 300.0]);
5252        assert!(thresholds[3..].iter().all(|threshold| threshold.is_nan()));
5253        assert_eq!(sock.atmo_for_range(f64::NAN), (10.0, 1010.0, 10.0));
5254        assert_eq!(sock.atmo_for_range(350.0), (99.0, 999.0, 99.0));
5255    }
5256
5257    #[test]
5258    fn test_atmo_sock_nan_uses_first_zone() {
5259        let sock = AtmoSock::new(vec![
5260            (30.0, 1010.0, 80.0, 100.0),
5261            (-5.0, 900.0, 10.0, 200.0),
5262        ]);
5263        // NaN can't be ordered; deterministically use the nearest (first) zone rather than panic.
5264        assert_eq!(sock.atmo_for_range(f64::NAN), (30.0, 1010.0, 80.0));
5265    }
5266
5267    // ---- MBA-1366: density altitude as a direct atmosphere input ----
5268
5269    /// With no explicit temperature, the resolved altitude must equal the input density
5270    /// altitude EXACTLY (this is the algebraic identity documented on
5271    /// `resolve_atmosphere_for_density_altitude`: the correction term vanishes when station
5272    /// temperature is left at ISA).
5273    #[test]
5274    fn density_altitude_default_temp_pressure_alt_equals_density_alt() {
5275        for da_ft in [0.0_f64, 1000.0, 3000.0, 7500.0, -500.0] {
5276            let da_m = da_ft * DA_FT_TO_M;
5277            let (altitude_m, temp_c, pressure_hpa) =
5278                resolve_atmosphere_for_density_altitude(da_m, None);
5279            assert!(
5280                (altitude_m - da_m).abs() < 1e-6,
5281                "da_ft={da_ft}: altitude_m {altitude_m} should equal da_m {da_m}"
5282            );
5283            // Sanity: pressure must be a plausible station pressure (strictly decreasing with DA).
5284            assert!(pressure_hpa > 0.0 && pressure_hpa < 1100.0);
5285            assert!(temp_c.is_finite());
5286        }
5287        // At DA=0 the result must be exactly the sea-level ISA reference.
5288        let (alt0, temp0, press0) = resolve_atmosphere_for_density_altitude(0.0, None);
5289        assert!(alt0.abs() < 1e-9);
5290        assert!((temp0 - 15.0).abs() < 1e-6);
5291        assert!((press0 - 1013.25).abs() < 1e-6);
5292    }
5293
5294    /// Higher density altitude at the ISA default must yield a lower station pressure (thinner
5295    /// air), matching the physical meaning of density altitude.
5296    #[test]
5297    fn density_altitude_pressure_decreases_monotonically() {
5298        let (_, _, p0) = resolve_atmosphere_for_density_altitude(0.0, None);
5299        let (_, _, p1) = resolve_atmosphere_for_density_altitude(1000.0, None);
5300        let (_, _, p2) = resolve_atmosphere_for_density_altitude(3000.0, None);
5301        assert!(p1 < p0);
5302        assert!(p2 < p1);
5303    }
5304
5305    /// An explicit temperature must be honored EXACTLY (never re-derived), while the implied
5306    /// pressure altitude (and therefore the resolved altitude/pressure) differs from the
5307    /// ISA-default case -- proving density is still honored (a different pressure/altitude
5308    /// combination that reproduces the SAME density altitude at the warmer/colder temperature).
5309    #[test]
5310    fn density_altitude_explicit_temperature_overrides_isa_default_but_honors_density() {
5311        let da_m = 1000.0 * DA_FT_TO_M;
5312        let (default_alt_m, default_temp_c, default_pressure_hpa) =
5313            resolve_atmosphere_for_density_altitude(da_m, None);
5314
5315        // A HOTTER-than-ISA explicit station temperature at the same density altitude implies a
5316        // LOWER pressure altitude: hot (less dense) air already accounts for some of the
5317        // "thinness" that defines the density altitude, so less physical elevation is needed to
5318        // reach the rest of it (equivalently: the correction term subtracts from DA before the
5319        // pressure inversion, since a warmer station reads MORE dense-feeling per unit of actual
5320        // elevation than ISA does).
5321        let hot_temp_c = default_temp_c + 20.0;
5322        let (hot_alt_m, hot_temp_out, hot_pressure_hpa) =
5323            resolve_atmosphere_for_density_altitude(da_m, Some(hot_temp_c));
5324        assert_eq!(
5325            hot_temp_out, hot_temp_c,
5326            "explicit temperature must be honored exactly"
5327        );
5328        assert!(
5329            hot_alt_m < default_alt_m,
5330            "hotter station temp at same DA should imply a lower pressure altitude: \
5331             hot={hot_alt_m} default={default_alt_m}"
5332        );
5333        assert!(hot_pressure_hpa > default_pressure_hpa);
5334
5335        // A COLDER-than-ISA explicit temperature implies a HIGHER pressure altitude.
5336        let cold_temp_c = default_temp_c - 20.0;
5337        let (cold_alt_m, cold_temp_out, cold_pressure_hpa) =
5338            resolve_atmosphere_for_density_altitude(da_m, Some(cold_temp_c));
5339        assert_eq!(cold_temp_out, cold_temp_c);
5340        assert!(cold_alt_m > default_alt_m);
5341        assert!(cold_pressure_hpa < default_pressure_hpa);
5342    }
5343
5344    /// Round trip using ONLY this crate's own math (the forward NWS pressure-altitude formula,
5345    /// re-derived independently in the test rather than reusing the production function) -- an
5346    /// implementation-independent algebraic sanity check. The REAL cross-crate round trip
5347    /// against the production `pdf_dope_card::calculate_density_altitude` forward function
5348    /// lives in `src/main.rs` (that function is CLI-binary-only and unreachable from this
5349    /// library crate).
5350    #[test]
5351    fn density_altitude_round_trips_through_hand_derived_forward_formula() {
5352        fn forward_density_altitude_ft(pressure_hpa: f64, temp_c: f64) -> f64 {
5353            let pressure_alt_ft = 145_366.45 * (1.0 - (pressure_hpa / 1013.25).powf(0.190_284));
5354            let isa_temp_f = 59.0 - (pressure_alt_ft / 1000.0) * 3.57;
5355            let temp_f = temp_c * 9.0 / 5.0 + 32.0;
5356            pressure_alt_ft + (120.0 * 5.0 / 9.0) * (temp_f - isa_temp_f)
5357        }
5358
5359        for da_ft in [0.0_f64, 500.0, 2500.0, 6000.0] {
5360            let da_m = da_ft * DA_FT_TO_M;
5361            // Default (ISA-at-DA) branch.
5362            let (_, temp_c, pressure_hpa) = resolve_atmosphere_for_density_altitude(da_m, None);
5363            let round_tripped_ft = forward_density_altitude_ft(pressure_hpa, temp_c);
5364            assert!(
5365                (round_tripped_ft - da_ft).abs() < 1e-6,
5366                "da_ft={da_ft}: round-tripped {round_tripped_ft} (temp_c={temp_c}, pressure_hpa={pressure_hpa})"
5367            );
5368
5369            // Explicit-temperature branch.
5370            let explicit_temp_c = 25.0;
5371            let (_, temp_out, pressure_hpa_explicit) =
5372                resolve_atmosphere_for_density_altitude(da_m, Some(explicit_temp_c));
5373            assert_eq!(temp_out, explicit_temp_c);
5374            let round_tripped_explicit_ft =
5375                forward_density_altitude_ft(pressure_hpa_explicit, temp_out);
5376            assert!(
5377                (round_tripped_explicit_ft - da_ft).abs() < 1e-6,
5378                "da_ft={da_ft} (explicit {explicit_temp_c}C): round-tripped {round_tripped_explicit_ft}"
5379            );
5380        }
5381    }
5382}
5383
5384/// Station-presence resolution (0.49.0): a supplied station reading is never read as omitted.
5385#[cfg(test)]
5386mod station_presence_tests {
5387    use super::*;
5388
5389    /// The body of `resolve_station_conditions_with_pressure_mode` exactly as it stood at
5390    /// ab4eb0c, before presence existed. It calls only the primitives this change leaves
5391    /// alone, so comparing against it cannot pass by comparing the new code with itself.
5392    fn legacy_resolve_ab4eb0c(
5393        temperature_c: f64,
5394        pressure_hpa: f64,
5395        altitude_m: f64,
5396        pressure_mode: PressureReferenceMode,
5397    ) -> (f64, f64) {
5398        let temp_override = resolve_station_temperature(temperature_c, altitude_m);
5399        let press_override =
5400            resolve_station_pressure_with_mode(pressure_hpa, altitude_m, pressure_mode);
5401        let (std_temp_k, std_pressure_pa) = calculate_icao_standard_atmosphere(altitude_m);
5402        let temp_c = temp_override.unwrap_or(std_temp_k - 273.15);
5403        let pressure_hpa = press_override.unwrap_or(std_pressure_pa / 100.0);
5404        (temp_c, pressure_hpa)
5405    }
5406
5407    const TEMPERATURES_C: [f64; 10] = [
5408        -40.0, 14.89, 14.9, 14.95, 15.0, 15.05, 15.0999, 15.1, 15.2, 30.0,
5409    ];
5410    const PRESSURES_HPA: [f64; 11] = [
5411        1012.7,
5412        1012.75,
5413        1012.8562053925472,
5414        1013.0,
5415        1013.2079,
5416        1013.25,
5417        1013.5,
5418        1013.75,
5419        1014.0,
5420        850.0,
5421        1031.0,
5422    ];
5423    const ALTITUDES_M: [f64; 13] = [
5424        -2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 1.0000001, 3.0, 10.0, 150.0, 1500.0, 1524.0, 5000.0,
5425    ];
5426    const MODES: [PressureReferenceMode; 2] =
5427        [PressureReferenceMode::Absolute, PressureReferenceMode::Qnh];
5428
5429    fn assert_bits(actual: (f64, f64), expected: (f64, f64), context: &str) {
5430        assert_eq!(
5431            actual.0.to_bits(),
5432            expected.0.to_bits(),
5433            "temperature {context}: {actual:?} vs {expected:?}"
5434        );
5435        assert_eq!(
5436            actual.1.to_bits(),
5437            expected.1.to_bits(),
5438            "pressure {context}: {actual:?} vs {expected:?}"
5439        );
5440    }
5441
5442    #[test]
5443    fn neither_is_bit_identical_to_ab4eb0c() {
5444        for t in TEMPERATURES_C {
5445            for p in PRESSURES_HPA {
5446                for alt in ALTITUDES_M {
5447                    for mode in MODES {
5448                        let expected = legacy_resolve_ab4eb0c(t, p, alt, mode);
5449                        let context = format!("({t}, {p}, {alt}, {mode:?})");
5450                        assert_bits(
5451                            resolve_station_conditions_with_presence(
5452                                t,
5453                                p,
5454                                alt,
5455                                mode,
5456                                StationAtmospherePresence::NEITHER,
5457                            ),
5458                            expected,
5459                            &context,
5460                        );
5461                        assert_bits(
5462                            resolve_station_conditions_with_pressure_mode(t, p, alt, mode),
5463                            expected,
5464                            &context,
5465                        );
5466                    }
5467                }
5468            }
5469        }
5470
5471        // Six points captured at ab4eb0c, so a change to a shared primitive cannot pass
5472        // unseen through the verbatim copy above.
5473        let pinned = [
5474            (
5475                (15.05, 1013.0, 150.0, PressureReferenceMode::Absolute),
5476                // captured at ab4eb0c
5477                (
5478                    f64::from_bits(0x402c0ccfd0c49b20),
5479                    f64::from_bits(0x408f1ae13f434f1f),
5480                ),
5481            ),
5482            (
5483                (15.0, 1013.25, 1500.0, PressureReferenceMode::Absolute),
5484                // captured at ab4eb0c
5485                (
5486                    f64::from_bits(0x4015025af8d136c0),
5487                    f64::from_bits(0x408a6cc6358cefbd),
5488                ),
5489            ),
5490            (
5491                (15.0, 1013.25, 10.0, PressureReferenceMode::Qnh),
5492                // captured at ab4eb0c
5493                (
5494                    f64::from_bits(0x402ddeb85559de00),
5495                    f64::from_bits(0x408fa064e4e5f101),
5496                ),
5497            ),
5498            (
5499                (15.0, 1013.2079, 1524.0, PressureReferenceMode::Qnh),
5500                // captured at ab4eb0c
5501                (
5502                    f64::from_bits(0x401462aff47e8bc0),
5503                    f64::from_bits(0x408a58982cf0204f),
5504                ),
5505            ),
5506            (
5507                (
5508                    14.95,
5509                    1012.8562053925472,
5510                    1.0000001,
5511                    PressureReferenceMode::Absolute,
5512                ),
5513                // captured at ab4eb0c
5514                (
5515                    f64::from_bits(0x402dfcac08345a20),
5516                    f64::from_bits(0x408fa909fb979713),
5517                ),
5518            ),
5519            (
5520                (15.0, 1013.25, 3.0, PressureReferenceMode::Absolute),
5521                // captured at ab4eb0c
5522                (
5523                    f64::from_bits(0x402df60418e281e0),
5524                    f64::from_bits(0x408fa71e04fe2409),
5525                ),
5526            ),
5527        ];
5528        for ((t, p, alt, mode), expected) in pinned {
5529            let context = format!("pinned ({t}, {p}, {alt}, {mode:?})");
5530            assert_bits(
5531                resolve_station_conditions_with_presence(
5532                    t,
5533                    p,
5534                    alt,
5535                    mode,
5536                    StationAtmospherePresence::NEITHER,
5537                ),
5538                expected,
5539                &context,
5540            );
5541            assert_bits(
5542                resolve_station_conditions_with_pressure_mode(t, p, alt, mode),
5543                expected,
5544                &context,
5545            );
5546        }
5547    }
5548
5549    #[test]
5550    fn both_returns_the_supplied_pair() {
5551        for t in TEMPERATURES_C {
5552            for p in PRESSURES_HPA {
5553                for alt in ALTITUDES_M {
5554                    let context = format!("({t}, {p}, {alt})");
5555                    assert_bits(
5556                        resolve_station_conditions_with_presence(
5557                            t,
5558                            p,
5559                            alt,
5560                            PressureReferenceMode::Absolute,
5561                            StationAtmospherePresence::BOTH,
5562                        ),
5563                        (t, p),
5564                        &context,
5565                    );
5566                    assert_bits(
5567                        resolve_station_conditions_with_presence(
5568                            t,
5569                            p,
5570                            alt,
5571                            PressureReferenceMode::Qnh,
5572                            StationAtmospherePresence::BOTH,
5573                        ),
5574                        (t, reduce_qnh_to_station_pressure(p, alt)),
5575                        &context,
5576                    );
5577                }
5578            }
5579        }
5580        // The headline repro: QNH 1031 hPa at 150 m reduces into the band and still flies.
5581        let (_, p) = resolve_station_conditions_with_presence(
5582            20.0,
5583            1031.0,
5584            150.0,
5585            PressureReferenceMode::Qnh,
5586            StationAtmospherePresence::BOTH,
5587        );
5588        assert_eq!(p.to_bits(), 1012.8562053925472_f64.to_bits(), "{p:?}");
5589    }
5590
5591    #[test]
5592    fn presence_is_per_field() {
5593        let (icao_t_k, icao_p_pa) = calculate_icao_standard_atmosphere(1500.0);
5594        let temperature_only = resolve_station_conditions_with_presence(
5595            15.0,
5596            1013.25,
5597            1500.0,
5598            PressureReferenceMode::Absolute,
5599            StationAtmospherePresence::new(true, false),
5600        );
5601        assert_bits(temperature_only, (15.0, icao_p_pa / 100.0), "(true, false)");
5602        let pressure_only = resolve_station_conditions_with_presence(
5603            15.0,
5604            1013.0,
5605            1500.0,
5606            PressureReferenceMode::Absolute,
5607            StationAtmospherePresence::new(false, true),
5608        );
5609        assert_bits(pressure_only, (icao_t_k - 273.15, 1013.0), "(false, true)");
5610    }
5611
5612    #[test]
5613    fn presence_constructors_agree() {
5614        assert_eq!(
5615            StationAtmospherePresence::default(),
5616            StationAtmospherePresence::NEITHER
5617        );
5618        assert_eq!(
5619            StationAtmospherePresence::NEITHER,
5620            StationAtmospherePresence::new(false, false)
5621        );
5622        assert_eq!(
5623            StationAtmospherePresence::BOTH,
5624            StationAtmospherePresence::new(true, true)
5625        );
5626        assert_eq!(
5627            StationAtmospherePresence::from_readings(
5628                StationReading::supplied(15.0),
5629                StationReading::omitted(1013.25)
5630            ),
5631            StationAtmospherePresence::new(true, false)
5632        );
5633        assert_eq!(
5634            StationAtmospherePresence::from_readings(
5635                StationReading::omitted(59.0),
5636                StationReading::supplied(29.92)
5637            ),
5638            StationAtmospherePresence::new(false, true)
5639        );
5640        assert!(StationReading::omitted(29.92).is_omitted());
5641        assert!(!StationReading::supplied(29.92).is_omitted());
5642        assert_eq!(
5643            StationReading::omitted(29.92).value.to_bits(),
5644            29.92_f64.to_bits()
5645        );
5646    }
5647
5648    #[derive(Debug, serde::Serialize, serde::Deserialize)]
5649    #[serde(deny_unknown_fields)]
5650    struct Probe {
5651        #[serde(
5652            default = "probe_default",
5653            skip_serializing_if = "StationReading::is_omitted"
5654        )]
5655        pressure_inhg: StationReading,
5656    }
5657
5658    fn probe_default() -> StationReading {
5659        StationReading::omitted(29.92)
5660    }
5661
5662    #[test]
5663    fn station_reading_serde() {
5664        let absent: Probe = serde_json::from_str("{}").unwrap();
5665        assert!(!absent.pressure_inhg.supplied);
5666        assert_eq!(absent.pressure_inhg.value.to_bits(), 29.92_f64.to_bits());
5667
5668        let present: Probe = serde_json::from_str(r#"{"pressure_inhg": 29.92}"#).unwrap();
5669        assert!(present.pressure_inhg.supplied);
5670        assert_eq!(present.pressure_inhg.value.to_bits(), 29.92_f64.to_bits());
5671
5672        assert_eq!(serde_json::to_string(&absent).unwrap(), "{}");
5673        assert_eq!(
5674            serde_json::to_string(&present).unwrap(),
5675            r#"{"pressure_inhg":29.92}"#
5676        );
5677
5678        assert!(serde_json::from_str::<Probe>(r#"{"pressure_inhg": null}"#).is_err());
5679        assert!(serde_json::from_str::<Probe>(r#"{"pressure_inhg": "29.92"}"#).is_err());
5680    }
5681}