ballistics_engine/
solve_v1.rs

1//! Transport-free implementation of the solve-json v1 trajectory service.
2//!
3//! This module owns the semantic boundary between the stable, explicit-SI v1 data-transfer
4//! objects and the engine's legacy internal input types.  It deliberately performs no JSON I/O,
5//! filesystem access, network access, profile lookup, or terminal output.
6
7use crate::solve_json::{
8    AtmosphereV1, DragModelV1, DragTableKindV1, DragTableV1, EffectsV1, PressureReferenceV1,
9    ProjectileV1, ResolvedAtmosphereV1, ResolvedConstantWindV1, ResolvedEffectsV1,
10    ResolvedProjectileV1, ResolvedRifleV1, ResolvedSamplingV1, ResolvedSegmentedWindV1,
11    ResolvedShotV1, ResolvedSolveRequestV1, ResolvedSolverV1, ResolvedWindSegmentV1,
12    ResolvedWindV1, RifleV1, SampleFlagV1, SamplingV1, SchemaVersionV1, ShotV1, SolveErrorCodeV1,
13    SolveErrorEnvelopeV1, SolveErrorV1, SolveNoticeV1, SolveRequestV1, SolveSuccessV1,
14    SolveSummaryV1, SolverMethodV1, SolverV1, SuccessStatusV1, TerminationReasonV1,
15    TrajectorySampleV1, TwistDirectionV1, WindReferenceV1, WindShearModelV1, WindV1,
16    MAX_SOLVE_JSON_SAMPLES_V1,
17};
18use crate::trajectory_observation::{
19    bracket_param, Bracket, TrajectoryObservation, TrajectoryObservationError,
20    TrajectoryObservationFlag, TrajectoryTermination,
21};
22use crate::wind::WindSegment;
23use crate::{
24    AtmosphericConditions, BallisticInputs, BallisticsError, DragModel, RelativeHumidity,
25    TrajectorySolver, WindConditions,
26};
27
28const DEFAULT_SIGHT_HEIGHT_M: f64 = 0.05;
29const DEFAULT_MUZZLE_HEIGHT_M: f64 = 0.0;
30const DEFAULT_TWIST_RATE_M_PER_TURN: f64 = 0.3048;
31const DEFAULT_ALTITUDE_M: f64 = 0.0;
32/// An omitted `$.atmosphere.relative_humidity`: the one default, `RelativeHumidity::DEFAULT`
33/// (`DEFAULT_HUMIDITY_PERCENT`), as the wire's fraction, exactly 0.5.
34const DEFAULT_RELATIVE_HUMIDITY: f64 = RelativeHumidity::DEFAULT.fraction();
35const DEFAULT_TIME_STEP_S: f64 = 0.001;
36const DEFAULT_SAMPLE_INTERVAL_M: f64 = 10.0;
37const DEFAULT_GROUND_THRESHOLD_M: f64 = -100.0;
38
39const METERS_PER_INCH: f64 = 0.0254;
40const KILOMETRES_PER_METRE: f64 = 0.001;
41const SECONDS_PER_HOUR: f64 = 3_600.0;
42pub(crate) const PASCALS_PER_HECTOPASCAL: f64 = 100.0;
43pub(crate) const KELVIN_OFFSET_C: f64 = 273.15;
44const KG_PER_GRAIN: f64 = 0.000_064_798_91;
45
46/// Stable assumption code emitted for a literal protocol default.
47pub const ASSUMPTION_DEFAULT_APPLIED: &str = "default_applied";
48/// Stable assumption code emitted when station temperature is resolved from ICAO atmosphere.
49pub const ASSUMPTION_ICAO_STANDARD_TEMPERATURE: &str = "icao_standard_temperature";
50/// Stable assumption code emitted when station pressure is resolved from ICAO atmosphere.
51pub const ASSUMPTION_ICAO_STANDARD_PRESSURE: &str = "icao_standard_pressure";
52/// Stable assumption code emitted when an explicit `pressure_reference: "qnh"` pressure is
53/// reduced to station pressure (MBA-1397).
54pub const ASSUMPTION_QNH_REDUCED_TO_STATION_PRESSURE: &str = "qnh_reduced_to_station_pressure";
55/// Stable assumption code emitted when projectile length is inferred from mass and diameter.
56pub const ASSUMPTION_ESTIMATED_PROJECTILE_LENGTH: &str = "estimated_projectile_length";
57
58/// Stable warning code for segmented wind that becomes calm before the requested maximum range.
59pub const WARNING_PARTIAL_WIND_COVERAGE: &str = "partial_wind_coverage";
60/// Stable warning code emitted for each opt-in experimental physical effect.
61pub const WARNING_EXPERIMENTAL_EFFECT: &str = "experimental_effect";
62/// Stable warning code for an explicitly supplied fixed step that adaptive RK45 ignores.
63pub const WARNING_RK45_TIME_STEP_IGNORED: &str = "rk45_time_step_ignored";
64/// Stable warning code for a request that supplies both `zero_distance_m` and
65/// `muzzle_angle_rad` (0.33.0 decision-support Task 2): the explicit angle is used directly
66/// and the elevation search does not run. `zero_distance_m` is retained in `resolved_request`
67/// and is not otherwise inert -- see the warning message for what it still affects.
68pub const WARNING_ZERO_DISTANCE_ELEVATION_NOT_RESOLVED: &str =
69    "zero_distance_elevation_not_resolved";
70/// Stable warning code emitted when a `corrections.bc5d_table_path` request names a drag
71/// model outside the table's G1/G7 planes and the lookup is typed as G1 (the same coercion
72/// the CLI's `--bc-table-dir` path performs, surfaced instead of silent).
73pub const WARNING_BC5D_DRAG_MODEL_COERCED: &str = "bc5d_drag_model_coerced";
74/// Stable warning code emitted when an accepted `effects.wind_shear_model` has no profile on
75/// this solve path and therefore leaves the wind unchanged (0.36.0). Only `"ekman_spiral"`
76/// reaches it today: the boundary-layer evaluator behind `TrajectorySolver` implements the
77/// logarithmic and power-law profiles, and returns the operative wind for anything else. The
78/// model is still echoed in `resolved_request`, so this warning is what distinguishes "applied
79/// and it moved the numbers" from "applied and it could not".
80pub const WARNING_WIND_SHEAR_MODEL_NOT_MODELED: &str = "wind_shear_model_not_modeled";
81
82/// `effects.aerodynamic_jump` was enabled while the request left the geometry the estimator
83/// reads to a default (MBA-959).
84///
85/// The jump scales with gyroscopic stability and bullet length, so it reads
86/// `rifle.twist_rate_m_per_turn` and `projectile.length_m`. Omitting either does NOT disable
87/// the correction and does not zero it — the solve proceeds against the assumed 1:12 barrel
88/// and the mass/diameter length estimate, and produces a confident number computed for a
89/// rifle the caller does not own. Measured on a .308 175 gr at 800 m in a 10 mph full-value
90/// crosswind, an omitted twist moves the jump from 10.79 cm to 9.08 cm — a 16% error that is
91/// invisible in the response, because the jump is folded into every drop rather than reported
92/// as its own column.
93///
94/// The two assumption notices for the defaults themselves are still emitted; this one exists
95/// because those say "a default was applied" without saying that anything now depends on it.
96///
97/// Aerodynamic jump is not the only effect that reads the barrel: `effects.magnus` and
98/// `effects.enhanced_spin_drift` do too, under the separate
99/// [`WARNING_SPIN_EFFECT_ASSUMED_TWIST_RATE`], and `summary.stability_factor` on every solve,
100/// under [`WARNING_STABILITY_FACTOR_ASSUMED_TWIST_RATE`]. The codes are distinct so that each
101/// one names the model it belongs to — they are NOT mutually exclusive, and a single omitted
102/// `rifle.twist_rate_m_per_turn` routinely raises several of them at once. A request enabling
103/// both `aerodynamic_jump` and `magnus` without a stated twist gets all three: one per
104/// consumer, each at its own path. Callers must match on the code they care about rather than
105/// assume at most one assumed-barrel warning is present.
106pub const WARNING_AERODYNAMIC_JUMP_ASSUMED_GEOMETRY: &str = "aerodynamic_jump_assumed_geometry";
107
108/// A spin-driven effect (`effects.magnus` or `effects.enhanced_spin_drift`) was enabled while
109/// the request left `rifle.twist_rate_m_per_turn` to its default (MBA-1484).
110///
111/// Both models are functions of the spin the rifling imparts, so both read the twist rate —
112/// enhanced spin drift through the muzzle gyroscopic stability factor that scales the Litz
113/// drift, Magnus through the spin rate that sets its side force and yaw of repose. Omitting
114/// the field does NOT disable either one and does not zero it: `resolve_rifle` substitutes
115/// `DEFAULT_TWIST_RATE_M_PER_TURN` (0.3048 m, exactly 1:12 inches) and the solve runs against
116/// that barrel, producing a confident number for a rifle the caller does not own. The early
117/// return in `TrajectorySolver::apply_spin_drift` for a non-positive twist is real but is
118/// unreachable from here, because the default is applied long before the solver sees the
119/// field.
120///
121/// Measured on a .308 175 gr at 800 m: `enhanced_spin_drift` reports
122/// `summary.spin_drift_m` = 0.1832 m with the twist omitted and the identical 0.1832 m with
123/// 1:12 stated — the omission is not a distinguishable request — while a stated 1:8 gives
124/// 0.3163 m, 73% more. Magnus's contribution is far smaller in absolute terms (it moved the
125/// 800 m drop by 0.19 mm at the assumed 1:12) but is no less twist-bound: at a stated 1:6 the
126/// same contribution is 0.75 mm, four times as large. In neither case is the dependence
127/// visible in the response, because both models are folded into the trajectory columns rather
128/// than reported separately — `summary.spin_drift_m` is the one exception, and it reports the
129/// number, not the barrel it came from.
130///
131/// The assumption notice for the default itself is still emitted; this one exists because it
132/// says "a default was applied" without saying that anything now depends on it.
133///
134/// This code covers the two opt-in models only. The twist is read on EVERY solve by
135/// `summary.stability_factor`, which has its own
136/// [`WARNING_STABILITY_FACTOR_ASSUMED_TWIST_RATE`]; both fire together when a spin effect is
137/// enabled without a stated twist.
138pub const WARNING_SPIN_EFFECT_ASSUMED_TWIST_RATE: &str = "spin_effect_assumed_twist_rate";
139
140/// `summary.stability_factor` was computed from the default twist because the request left
141/// `rifle.twist_rate_m_per_turn` out (MBA-1484).
142///
143/// Unlike every other assumed-barrel warning this module emits, this one is not gated on an
144/// opt-in flag, because Sg is not opt-in: `effective_sg_from_inputs` runs on every solve and
145/// the muzzle gyroscopic stability factor is a direct function of the twist. An omitted field
146/// therefore does not leave Sg alone — it reports the Sg of a 1:12 barrel, under a field name
147/// that says nothing about which barrel it describes.
148///
149/// Measured on a .308 175 gr with NO effects enabled at all: `summary.stability_factor` is
150/// 1.6650154161603787 with the twist omitted, bit-identically 1.6650154161603787 with 1:12
151/// stated, and 3.7462846863608514 with 1:8 stated — 2.25x, across the marginal/comfortable
152/// line a shooter reads Sg to decide. `drop_m` and `windage_m` are bit-identical in all three,
153/// so the trajectory really is twist-independent when no spin effect is enabled; the summary
154/// is not, and that distinction is the whole reason this code exists separately from
155/// [`WARNING_SPIN_EFFECT_ASSUMED_TWIST_RATE`].
156///
157/// Emitted at `$.rifle.twist_rate_m_per_turn` — the omitted field itself — because there is no
158/// flag to hang it on, and only when Sg is actually reported: when
159/// `summary.stability_factor` is absent nothing misleading was published and there is nothing
160/// to warn about. It fires on any request that omits the twist and gets an Sg, which is most
161/// of them; that breadth is the finding, not a reason to suppress it. The `default_applied`
162/// assumption at the same path stays, and says a default was applied without saying that a
163/// reported number now depends on it.
164pub const WARNING_STABILITY_FACTOR_ASSUMED_TWIST_RATE: &str = "stability_factor_assumed_twist_rate";
165
166/// An explicit absolute `atmosphere.pressure_pa` is outside the band of ratios to the ICAO
167/// standard pressure at `altitude_m` that weather produces (0.85 to 1.08; see
168/// [`crate::atmosphere::station_pressure_plausibility`] for where the band comes from).
169///
170/// The pressure is authoritative, so the solve flies it as sent, and the response would
171/// otherwise give no sign that it belongs to another altitude. Two habits produce it. A client
172/// sends a sea-level figure at a real elevation: a 101325 Pa placeholder, or a weather report's
173/// altimeter setting (QNH) without `pressure_reference: "qnh"`. At Cusco's 3310.128 m the
174/// placeholder is 1.503 times the standard pressure there and the solve flies sea-level air
175/// through it. Or the pressure is a true station reading and `altitude_m` is wrong: omitted, so
176/// 0 m, or in feet. The message names the likely causes for the side of the band the pressure
177/// is on.
178///
179/// Emitted at `$.atmosphere.pressure_pa` only when `pressure_pa` is present and the reference
180/// is absolute, sent or by default. An omitted pressure resolves to the standard itself, and a
181/// `"qnh"` pressure is a sea-level figure by declaration, so neither is checked. Purely a
182/// notice: no resolved value or sample changes.
183pub const WARNING_STATION_PRESSURE_IMPLAUSIBLE_FOR_ALTITUDE: &str =
184    "station_pressure_implausible_for_altitude";
185
186/// Whether the raw request supplied the geometry fields the twist-reading effects need, as
187/// opposed to letting `resolve_rifle`/`resolve_projectile` substitute a default.
188///
189/// `twist_rate` is read by aerodynamic jump, Magnus and enhanced spin drift;
190/// `projectile_length` by aerodynamic jump. Carried rather than re-derived because
191/// `resolve_effects` only sees `EffectsV1`, and the distinction is about the RAW request: by
192/// the time the rifle and projectile are resolved, an assumed 1:12 twist is
193/// indistinguishable from a stated one.
194#[derive(Debug, Clone, Copy)]
195struct SuppliedGeometry {
196    twist_rate: bool,
197    projectile_length: bool,
198}
199
200#[derive(Debug)]
201pub(crate) struct PreparedSolveV1 {
202    pub(crate) resolved_request: ResolvedSolveRequestV1,
203    assumptions: Vec<SolveNoticeV1>,
204    warnings: Vec<SolveNoticeV1>,
205    pub(crate) inputs: BallisticInputs,
206    pub(crate) wind: WindConditions,
207    pub(crate) wind_segments: Vec<WindSegment>,
208    pub(crate) atmosphere: AtmosphericConditions,
209}
210
211/// Execute one semantically validated solve-json v1 request.
212///
213/// The function is transport-free: callers are responsible for decoding and encoding the DTOs.
214/// All dimensional request values are SI.  Valid requests produce a fully resolved success DTO;
215/// invalid requests and engine failures produce the stable v1 error envelope.
216pub fn solve_v1(request: SolveRequestV1) -> Result<SolveSuccessV1, SolveErrorEnvelopeV1> {
217    let mut prepared = prepare_request(&request)?;
218    let max_range_m = prepared.resolved_request.shot.max_range_m;
219    let time_step_s = prepared.resolved_request.solver.time_step_s;
220    let sample_interval_m = prepared.resolved_request.sampling.interval_m;
221    let zero_distance_m = prepared.resolved_request.shot.zero_distance_m;
222    let target_height_m = prepared.resolved_request.shot.target_height_m;
223    let enhanced_spin_drift = prepared.resolved_request.effects.enhanced_spin_drift;
224
225    // Retain the exact mapped inputs for summary diagnostics. TrajectorySolver owns its copy and
226    // may update the private effective muzzle angle during zeroing.
227    let summary_inputs = prepared.inputs.clone();
228    let station_temperature_c = prepared.atmosphere.temperature;
229    let station_pressure_hpa = prepared.atmosphere.pressure;
230
231    let (solver, effective_angle) = build_zeroed_solver(
232        prepared.inputs,
233        prepared.wind,
234        prepared.atmosphere,
235        prepared.wind_segments,
236        max_range_m,
237        time_step_s,
238        zero_distance_m,
239        target_height_m,
240        request.shot.muzzle_angle_rad,
241    )?;
242    // 0.33.0 decision-support Task 2: an explicitly supplied muzzle_angle_rad always wins over
243    // zero_distance_m for ELEVATION (resolve_shot's match already resolved it that way; see
244    // build_zeroed_solver's doc comment for the full zero-handling rationale, including the
245    // windage-zero bias). Persist the searched angle -- bit-identical, not just numerically
246    // re-converged, on a later round-trip -- only when the elevation search actually ran.
247    if let Some(angle) = effective_angle {
248        prepared.resolved_request.shot.muzzle_angle_rad = angle;
249    }
250
251    let result = solver.solve().map_err(solve_failed)?;
252    let observations = result
253        .sample_observations(sample_interval_m, MAX_SOLVE_JSON_SAMPLES_V1)
254        .map_err(map_observation_error)?;
255
256    // MBA-1403 target-plane drops reference: this solve path samples drop via
257    // TrajectoryResult::sample_observations (LOS-perpendicular by construction), so the
258    // 1/cos(shooting_angle) reference transform is applied exactly once here, at the wire
259    // boundary. `"los"`/omitted divides by cos(0) == 1.0 exactly — byte-identical.
260    // validate_for_solve has already rejected target mode at |shooting_angle| >= 90 deg.
261    let drops_scale_denominator = match request.shot.drops_reference.unwrap_or_default() {
262        crate::solve_json::DropsReferenceV1::Los => 1.0,
263        crate::solve_json::DropsReferenceV1::Target => {
264            prepared.resolved_request.shot.shooting_angle_rad.cos()
265        }
266    };
267    let samples = observations
268        .iter()
269        .cloned()
270        .map(|mut observation| {
271            observation.drop_m /= drops_scale_denominator;
272            observation_to_wire(observation)
273        })
274        .collect::<Vec<_>>();
275    let terminal = observations.last().ok_or_else(|| {
276        internal_error("trajectory observation sampling returned no terminal observation")
277    })?;
278
279    let maximum_height_m =
280        maximum_world_height_m(&result, prepared.resolved_request.shot.shooting_angle_rad)?;
281
282    let stability = crate::spin_drift::effective_sg_from_inputs(
283        &summary_inputs,
284        station_temperature_c,
285        station_pressure_hpa,
286    );
287    let stability_factor = if stability.is_finite() && stability >= 0.0 {
288        Some(stability)
289    } else {
290        None
291    };
292
293    // MBA-1484. Sg is a direct function of the twist and is computed on every solve, so an
294    // omitted `rifle.twist_rate_m_per_turn` does not leave it alone: it publishes the Sg of the
295    // assumed 1:12 barrel (1.665 on the .308 175 gr fixture, against 3.746 at a stated 1:8)
296    // under a field name that says nothing about which barrel it describes. Warned here rather
297    // than in `resolve_effects` because this is the one assumed-barrel consumer that is not
298    // gated on a flag -- there is nothing in `EffectsV1` to key off, and the gate is whether Sg
299    // was reported at all, which is not known until it has been computed.
300    //
301    // This does fire on nearly every twist-omitting request, including ones written before the
302    // warning existed. That breadth is the finding rather than an argument against it: those
303    // requests were always being handed a barrel-dependent Sg they never described. Warning on
304    // Magnus, whose whole contribution is 0.19 mm of drop at 800 m, while staying silent about
305    // a 2.25x swing in a reported stability number is not a line that can be defended.
306    if request.rifle.twist_rate_m_per_turn.is_none() && stability_factor.is_some() {
307        prepared.warnings.push(notice(
308            WARNING_STABILITY_FACTOR_ASSUMED_TWIST_RATE,
309            "summary.stability_factor is computed from the twist on every solve, but \
310             rifle.twist_rate_m_per_turn was not supplied. The reported Sg is the Sg of the \
311             assumed 1:12 barrel, not of a barrel this request specified. The trajectory \
312             itself is unaffected unless a spin-driven effect is also enabled.",
313            "$.rifle.twist_rate_m_per_turn",
314        ));
315    }
316    let spin_drift_m = if enhanced_spin_drift {
317        stability_factor
318            .map(|sg| {
319                crate::spin_drift::litz_drift_meters(
320                    sg,
321                    terminal.time_s,
322                    summary_inputs.is_twist_right,
323                )
324            })
325            .filter(|drift| drift.is_finite())
326    } else {
327        None
328    };
329
330    if enhanced_spin_drift && stability_factor.is_some() && spin_drift_m.is_none() {
331        return Err(internal_error(
332            "enhanced spin-drift summary calculation produced a non-finite value",
333        ));
334    }
335
336    // MBA-1395: equivalent horizontal range (BDC shoot-to) — computed only for an
337    // inclined shot fired against a solved zero; None (field absent) otherwise, keeping
338    // every flat/pre-existing response byte-identical. The solver still holds the
339    // inclined, zeroed state here, so the angular-match inversion runs against the same
340    // zero the response describes.
341    let equivalent_horizontal_range_m = match (
342        zero_distance_m,
343        prepared.resolved_request.shot.shooting_angle_rad != 0.0,
344    ) {
345        (Some(zero_m), true) => solver.equivalent_horizontal_range(terminal.distance_m, zero_m),
346        _ => None,
347    };
348
349    // MBA-959: the jump the solver actually applied, read off its own components rather than
350    // recomputed here -- a second spelling of the Litz regression is a second answer. `None`
351    // when the flag is off or the solver declined the effect; `Some(0.0)` when it ran against
352    // no muzzle crosswind, which is a different fact and worth being able to tell apart.
353    let aerodynamic_jump_moa = result
354        .aerodynamic_jump
355        .as_ref()
356        .map(|components| components.vertical_jump_moa)
357        .filter(|moa| moa.is_finite());
358
359    let summary = SolveSummaryV1 {
360        actual_range_m: terminal.distance_m,
361        maximum_height_m,
362        time_of_flight_s: terminal.time_s,
363        terminal_speed_mps: terminal.speed_mps,
364        terminal_energy_j: terminal.energy_j,
365        stability_factor,
366        spin_drift_m,
367        equivalent_horizontal_range_m,
368        aerodynamic_jump_moa,
369        termination: termination_to_wire(result.termination),
370    };
371
372    // MBA-1361: a pure post-processing read of the samples above — it cannot change the
373    // trajectory, and `None` (no `reticle` block) keeps the response byte-identical.
374    let reticle_hold = match request.reticle.as_ref() {
375        Some(reticle) => Some(resolve_reticle_hold(reticle, &samples)?),
376        None => None,
377    };
378
379    let success = SolveSuccessV1 {
380        schema_version: SchemaVersionV1,
381        engine_version: env!("CARGO_PKG_VERSION").to_owned(),
382        status: SuccessStatusV1::Ok,
383        resolved_request: prepared.resolved_request,
384        assumptions: prepared.assumptions,
385        warnings: prepared.warnings,
386        summary,
387        samples,
388        reticle_hold,
389    };
390    success.validate_for_serialization()?;
391    Ok(success)
392}
393
394/// Build a `TrajectorySolver` from prepared inputs, configure it, and apply `solve_v1`'s own
395/// zero handling -- shared by `solve_v1` above and by the perturbation kernel's `evaluate`
396/// (`src/perturbation/mod.rs`, 0.33.0 decision-support Task 6, I3 review fix), which reads
397/// observations directly off the resulting solver's `TrajectoryResult` without going through
398/// the wire success DTO, and without a second, independent implementation of this zero handling
399/// that could silently drift from this one.
400///
401/// Returns the configured solver (not yet solved -- callers run `TrajectorySolver::solve`
402/// themselves, since `solve_v1` needs the solver alive afterward too, for
403/// `equivalent_horizontal_range`) alongside the elevation search's effective angle when it ran
404/// (`Some`), so a caller that wants to persist it -- as `solve_v1` does, onto
405/// `resolved_request.shot.muzzle_angle_rad` -- can; `None` when it did not run at all (no
406/// `zero_distance_m`), or ran only for windage (`zero_distance_m` present alongside an explicit
407/// `explicit_angle`, which needs no persisting since it was already supplied).
408///
409/// `explicit_angle` is the ORIGINAL (unresolved) request's `shot.muzzle_angle_rad`: an
410/// explicitly supplied angle always wins over `zero_distance_m` for ELEVATION (`resolve_shot`'s
411/// match already resolved it that way). `calculate_and_set_zero_angle` also applies a SEPARATE
412/// windage-zero convergence bias (offset-mounted sights / MBA-1396, deliberate horizontal POI /
413/// MBA-1359) to azimuth, gated only on `zero_distance_m` -- not on whether the elevation was
414/// searched for or supplied directly -- so when both fields are present, this still applies just
415/// the windage term on its own rather than skipping the whole call. That bias is deliberately
416/// never returned/persisted (unlike the elevation): `zero_distance_m` being present no longer
417/// implies "the search ran", so folding the bias into a persisted, echoed field would
418/// double-apply it on a second-generation round-trip (the same trap avoided for
419/// `atmosphere.pressure_reference` / `wind.wind_reference` in `request_roundtrip.rs`).
420#[allow(clippy::too_many_arguments)]
421pub(crate) fn build_zeroed_solver(
422    prepared_inputs: BallisticInputs,
423    wind: WindConditions,
424    atmosphere: AtmosphericConditions,
425    wind_segments: Vec<WindSegment>,
426    max_range_m: f64,
427    time_step_s: f64,
428    zero_distance_m: Option<f64>,
429    target_height_m: f64,
430    explicit_angle: Option<f64>,
431) -> Result<(TrajectorySolver, Option<f64>), SolveErrorEnvelopeV1> {
432    let mut solver =
433        TrajectorySolver::new_with_resolved_station_atmosphere(prepared_inputs, wind, atmosphere);
434    solver.set_max_range(max_range_m);
435    solver.set_time_step(time_step_s);
436    if !wind_segments.is_empty() {
437        solver.set_wind_segments(wind_segments);
438    }
439
440    let mut effective_angle = None;
441    match (zero_distance_m, explicit_angle) {
442        (Some(distance_m), None) => {
443            let angle = solver
444                .calculate_and_set_zero_angle(
445                    distance_m,
446                    target_height_m,
447                    crate::cli_api::ZeroTargetFrame::WorldVertical,
448                )
449                .map_err(solve_failed)?;
450            if !angle.is_finite() {
451                return Err(solve_failed_message(
452                    "zero-angle calculation returned a non-finite effective muzzle angle",
453                ));
454            }
455            effective_angle = Some(angle);
456        }
457        (Some(distance_m), Some(_)) => solver.apply_windage_zero_bias(distance_m),
458        (None, _) => {}
459    }
460
461    Ok((solver, effective_angle))
462}
463
464// `pub(crate)` (0.33.0 decision-support Task 6): the perturbation kernel's `evaluate` needs the
465// same request resolution `solve_v1` above starts from, to read observations off the raw
466// `TrajectoryResult` without going through the wire success DTO. Zero handling itself is shared
467// via `build_zeroed_solver` above (I3 review fix: an earlier revision hand-duplicated that match
468// in `perturbation/mod.rs` instead, verified consistent only by an outboard cross-check test --
469// a structural share removes that ongoing "keep two copies in sync" risk instead of relying on a
470// test to keep catching it).
471pub(crate) fn prepare_request(
472    request: &SolveRequestV1,
473) -> Result<PreparedSolveV1, SolveErrorEnvelopeV1> {
474    let mut assumptions = Vec::new();
475    let mut warnings = Vec::new();
476
477    let (projectile, bullet_length_m) = resolve_projectile(&request.projectile, &mut assumptions)?;
478    let rifle = resolve_rifle(&request.rifle, &mut assumptions)?;
479    let shot = resolve_shot(&request.shot, &rifle, &mut assumptions, &mut warnings)?;
480    let atmosphere = resolve_atmosphere(&request.atmosphere, &mut assumptions)?;
481    // Air that cannot exist is refused here, before any flight, as `invalid_value` at the field
482    // to blame: the refusal `atmosphere.density_altitude` gives for the same air, rather
483    // than a `solve_failed` with no path from deep inside the zero search.
484    resolved_station_air(&request.atmosphere, &atmosphere)?;
485    // Here rather than in `resolve_atmosphere`, which `atmosphere.density_altitude` shares and
486    // whose response has no `warnings` array.
487    warnings.extend(station_pressure_warning(&request.atmosphere, &atmosphere));
488    let wind_coverage_distance_m = shot.zero_distance_m.unwrap_or(0.0).max(shot.max_range_m);
489    let (resolved_wind, wind, wind_segments) = resolve_wind(
490        &request.wind,
491        wind_coverage_distance_m,
492        // MBA-1368: the RAW request option, not the resolved default — compass mode
493        // must reject an omitted shot azimuth, never silently re-reference against
494        // the 0.0 default.
495        request.shot.shot_azimuth_rad,
496        &mut assumptions,
497        &mut warnings,
498    )?;
499    let solver = resolve_solver(&request.solver, &mut assumptions, &mut warnings)?;
500    let effects = resolve_effects(
501        &request.effects,
502        atmosphere.latitude_rad,
503        SuppliedGeometry {
504            twist_rate: request.rifle.twist_rate_m_per_turn.is_some(),
505            projectile_length: request.projectile.length_m.is_some(),
506        },
507        &mut assumptions,
508        &mut warnings,
509    )?;
510    let sampling = resolve_sampling(&request.sampling, &mut assumptions)?;
511
512    // Downrange segments and altitude shear are not a defined combination, and the solver does
513    // not treat them as one: `TrajectorySolver::calculate_acceleration` takes the segmented
514    // wind sock in preference to the shear branch, so a request asking for both would get its
515    // shear dropped on the floor while `resolved_request` still claimed a model was applied.
516    // The CLI (`--wind-segment` + `--enable-wind-shear`) and the WASM front end already refuse
517    // this pairing; refuse it here too rather than inventing the third front end that solves it
518    // silently.
519    if matches!(resolved_wind, ResolvedWindV1::Segmented(_))
520        && effects
521            .wind_shear_model
522            .is_some_and(WindShearModelV1::is_enabled)
523    {
524        return Err(conflicting_fields(
525            "$.effects.wind_shear_model",
526            "wind.segments cannot be combined with effects.wind_shear_model (downrange \
527             segments plus altitude shear is not yet a defined model)",
528        ));
529    }
530
531    // A BC5D table corrects a G1/G7 ballistic coefficient along the flight; a drag table
532    // replaces the G-curve that BC is measured against, so the pair has no meaning. Refused
533    // before the table path is ever opened.
534    if projectile.drag_table.is_some()
535        && request
536            .corrections
537            .as_ref()
538            .is_some_and(|corrections| corrections.bc5d_table_path.is_some())
539    {
540        return Err(conflicting_fields(
541            "$.corrections.bc5d_table_path",
542            "corrections.bc5d_table_path cannot be combined with projectile.drag_table (BC5D \
543             corrects a G1/G7 ballistic coefficient; a drag table replaces the G-curve)",
544        ));
545    }
546
547    // MBA-1598: a BC ladder's band BCs are measured against a reference curve: drag_model's,
548    // or a `reference`-kind drag table's, which replaces it and is flown as Cd_ref / BC with
549    // the band BC exactly as a built-in model is (install_drag_table). A `projectile`-kind
550    // table is the projectile's own Cd, divided by sectional density, so it has no BC for the
551    // bands to change, and that pair is refused. The correction table builds its own ladder
552    // from ballistic_coefficient, so a caller ladder beside it is two answers to one question.
553    // Both refusals happen here, before the correction table path is ever opened.
554    if projectile.bc_segments.is_some()
555        && projectile
556            .drag_table
557            .as_ref()
558            .is_some_and(|table| table.kind == DragTableKindV1::Projectile)
559    {
560        return Err(conflicting_fields(
561            "$.projectile.bc_segments",
562            "projectile.bc_segments cannot be combined with a projectile.drag_table of kind \
563             \"projectile\": that curve is the projectile's own Cd and has no BC for the bands \
564             to change",
565        ));
566    }
567    if projectile.bc_segments.is_some()
568        && request
569            .corrections
570            .as_ref()
571            .is_some_and(|corrections| corrections.bc5d_table_path.is_some())
572    {
573        return Err(conflicting_fields(
574            "$.projectile.bc_segments",
575            "projectile.bc_segments cannot be combined with corrections.bc5d_table_path: the \
576             correction table builds its own BC ladder from ballistic_coefficient",
577        ));
578    }
579
580    let resolved_request = ResolvedSolveRequestV1 {
581        schema_version: SchemaVersionV1,
582        projectile,
583        rifle,
584        shot,
585        atmosphere,
586        wind: resolved_wind,
587        solver,
588        effects,
589        sampling,
590        // MBA-1361: pure pass-through echo (Task 1 of the 0.33.0 decision-support train) — no
591        // defaulting, no unit conversion. The reticle hold itself is computed later in
592        // solve_v1 straight from `request.reticle`, unaffected by this echo.
593        reticle: request.reticle.clone(),
594        // Pure pass-through echo, same contract as `reticle` above: segments are always
595        // regenerated from the PUBLISHED ballistic_coefficient, so re-solving a resolved
596        // request re-applies the same correction rather than compounding it.
597        corrections: request.corrections.clone(),
598    };
599
600    let temperature_c = checked_conversion(
601        resolved_request.atmosphere.temperature_k - KELVIN_OFFSET_C,
602        "$.atmosphere.temperature_k",
603        "temperature conversion to Celsius overflowed",
604    )?;
605    let pressure_hpa = checked_conversion(
606        resolved_request.atmosphere.pressure_pa / PASCALS_PER_HECTOPASCAL,
607        "$.atmosphere.pressure_pa",
608        "pressure conversion to hectopascals overflowed",
609    )?;
610    // The wire's fraction (already resolved into [0, 1]) as the one percent both engine
611    // structs carry.
612    let humidity_percent =
613        RelativeHumidity::try_fraction(resolved_request.atmosphere.relative_humidity)
614            .map_err(|error| invalid_value("$.atmosphere.relative_humidity", error.to_string()))?
615            .percent();
616    let twist_rate_inches = checked_conversion(
617        resolved_request.rifle.twist_rate_m_per_turn / METERS_PER_INCH,
618        "$.rifle.twist_rate_m_per_turn",
619        "twist-rate conversion to inches per turn overflowed",
620    )?;
621    let caliber_inches = checked_conversion(
622        resolved_request.projectile.diameter_m / METERS_PER_INCH,
623        "$.projectile.diameter_m",
624        "diameter conversion to inches overflowed",
625    )?;
626    let weight_grains = checked_conversion(
627        resolved_request.projectile.mass_kg / KG_PER_GRAIN,
628        "$.projectile.mass_kg",
629        "mass conversion to grains overflowed",
630    )?;
631    let latitude_degrees = resolved_request
632        .atmosphere
633        .latitude_rad
634        .map(f64::to_degrees)
635        .map(|value| {
636            checked_conversion(
637                value,
638                "$.atmosphere.latitude_rad",
639                "latitude conversion to degrees overflowed",
640            )
641        })
642        .transpose()?;
643
644    let (wind_speed, wind_direction) = match &resolved_request.wind {
645        ResolvedWindV1::Constant(constant) => (constant.speed_mps, constant.direction_from_rad),
646        ResolvedWindV1::Segmented(_) => (0.0, 0.0),
647    };
648
649    let mut inputs = BallisticInputs {
650        bc_value: resolved_request.projectile.ballistic_coefficient,
651        bc_type: drag_model_to_engine(resolved_request.projectile.drag_model),
652        // solve-json v1 (docs/SOLVE_JSON_V1.md) has no BC-reference-standard field yet;
653        // every published BC in that contract is treated as ICAO-referenced (MBA-1365
654        // is a CLI/WASM/FFI/profile feature, not a v1 JSON schema change).
655        bc_reference_standard: crate::cli_api::BcReferenceStandard::Icao,
656        bullet_mass: resolved_request.projectile.mass_kg,
657        muzzle_velocity: resolved_request.rifle.muzzle_velocity_mps,
658        bullet_diameter: resolved_request.projectile.diameter_m,
659        bullet_length: bullet_length_m,
660        muzzle_angle: resolved_request.shot.muzzle_angle_rad,
661        target_distance: resolved_request.shot.max_range_m,
662        azimuth_angle: resolved_request.shot.aim_azimuth_rad,
663        shot_azimuth: resolved_request.shot.shot_azimuth_rad,
664        shooting_angle: resolved_request.shot.shooting_angle_rad,
665        cant_angle: resolved_request.shot.cant_angle_rad,
666        sight_height: resolved_request.rifle.sight_height_m,
667        // MBA-1396: consumed straight from the request (validated in resolve_rifle) for the
668        // engine inputs here. Separately echoed at ResolvedRifleV1::sight_offset_lateral_m
669        // when supplied (0.33.0 decision-support Task 1) — same contract as the zero-POI
670        // fields below.
671        sight_offset_lateral_m: request.rifle.sight_offset_lateral_m.unwrap_or(0.0),
672        muzzle_height: resolved_request.rifle.muzzle_height_m,
673        target_height: resolved_request.shot.target_height_m,
674        // MBA-1359: consumed straight from the request (validated in resolve_shot) for the
675        // engine inputs here. Separately echoed at ResolvedShotV1::zero_poi_up_m /
676        // zero_poi_right_m when supplied (0.33.0 decision-support Task 1) — see
677        // resolve_shot's comment. The zero solve in solve_v1 runs on THIS solver, so both
678        // the vertical and azimuth biases apply there.
679        zero_poi_vertical_m: request.shot.zero_poi_up_m.unwrap_or(0.0),
680        zero_poi_horizontal_m: request.shot.zero_poi_right_m.unwrap_or(0.0),
681        ground_threshold: resolved_request.shot.ground_threshold_m,
682        altitude: resolved_request.atmosphere.altitude_m,
683        temperature: temperature_c,
684        pressure: pressure_hpa,
685        humidity_percent,
686        latitude: latitude_degrees,
687        wind_speed,
688        wind_angle: wind_direction,
689        twist_rate: twist_rate_inches,
690        is_twist_right: resolved_request.rifle.twist_direction == TwistDirectionV1::Right,
691        caliber_inches,
692        weight_grains,
693        manufacturer: None,
694        bullet_model: None,
695        bullet_id: None,
696        bullet_cluster: None,
697        use_rk4: resolved_request.solver.method != SolverMethodV1::Euler,
698        use_adaptive_rk45: resolved_request.solver.method == SolverMethodV1::Rk45,
699        enable_advanced_effects: resolved_request.effects.magnus
700            || resolved_request.effects.coriolis,
701        enable_magnus: resolved_request.effects.magnus,
702        enable_coriolis: resolved_request.effects.coriolis,
703        use_powder_sensitivity: false,
704        powder_temp_sensitivity: 0.0,
705        powder_temp: temperature_c,
706        powder_temp_curve: None,
707        powder_curve_temp_c: None,
708        tipoff_yaw: 0.0,
709        cd_delta2: 7.5,
710        tipoff_decay_distance: 50.0,
711        use_bc_segments: false,
712        bc_segments: None,
713        bc_segments_data: None,
714        use_enhanced_spin_drift: resolved_request.effects.enhanced_spin_drift,
715        use_form_factor: false,
716        // Altitude-dependent wind shear (0.36.0). `enable_wind_shear` is derived from the
717        // model rather than carried as its own request flag, so a request cannot express an
718        // "enabled, model none" pair: `cli_api`'s shear branch once ran power-law shear for
719        // it, and still maps any name it does not recognize to the power law.
720        //
721        // No shooter altitude is passed, and none exists to pass: this solve path runs on
722        // `TrajectorySolver`, whose `get_wind_at_altitude` keys the boundary-layer profile off
723        // height above the GROUND (the shot-frame y above y = 0, which is the ground
724        // `rifle.muzzle_height_m` is measured from, or the bore taken as 1.5 m up when that is
725        // left at 0), and `wind_shear::get_wind_at_position`, which does take a
726        // `shooter_altitude_m`, discards it for the same reason. Shear is relative to
727        // the local ground; `atmosphere.altitude_m` is height above SEA LEVEL, so feeding it in
728        // would treat a shooter standing at 1500 m MSL as a bullet flying 1500 m above the
729        // ground and inflate the ratio by an order of magnitude. `atmosphere.altitude_m`
730        // continues to reach the solve exactly where it belongs, through `inputs.altitude`
731        // above, as air density.
732        enable_wind_shear: resolved_request
733            .effects
734            .wind_shear_model
735            .is_some_and(WindShearModelV1::is_enabled),
736        wind_shear_model: resolved_request
737            .effects
738            .wind_shear_model
739            .unwrap_or_default()
740            .as_engine_str()
741            .to_owned(),
742        enable_trajectory_sampling: false,
743        sample_interval: resolved_request.sampling.interval_m,
744        // MBA-1403: consumed straight from the request for the engine inputs here.
745        // Separately echoed at ResolvedShotV1::drops_reference when supplied (0.33.0
746        // decision-support Task 1), matching the zero-POI fields above. The engine-side
747        // field is set for validation (target mode
748        // rejects |shooting_angle| >= 90 deg inside validate_for_solve); the actual wire
749        // transform is applied where observations map to samples in solve_v1, because this
750        // solve path samples via TrajectoryResult::sample_observations, not the
751        // trajectory-sampling module.
752        drops_reference: match request.shot.drops_reference.unwrap_or_default() {
753            crate::solve_json::DropsReferenceV1::Los => crate::cli_api::DropsReference::Los,
754            crate::solve_json::DropsReferenceV1::Target => crate::cli_api::DropsReference::Target,
755        },
756        enable_pitch_damping: false,
757        enable_precession_nutation: false,
758        // MBA-959 / Alfredo Mendiola Loyola's change request: the JSON bridge's own switch,
759        // where this used to be hardcoded false with no way for a caller to reach it.
760        enable_aerodynamic_jump: resolved_request.effects.aerodynamic_jump.unwrap_or(false),
761        use_cluster_bc: false,
762        // MBA-1597: `projectile.drag_table` is installed just below, once these inputs exist —
763        // the reference kind's scale reads their own sectional density, and a reference table
764        // flown beside a BC ladder sets `custom_drag_reference` there instead.
765        custom_drag_table: None,
766        cd_scale: 1.0,
767        custom_drag_reference: false,
768        bc_type_str: None,
769    };
770
771    if let Some(drag_table) = &resolved_request.projectile.drag_table {
772        install_drag_table(
773            drag_table,
774            resolved_request.projectile.ballistic_coefficient,
775            resolved_request.projectile.bc_segments.is_some(),
776            &mut inputs,
777        )?;
778    }
779
780    apply_bc5d_correction(request, &resolved_request, &mut inputs, &mut warnings)?;
781    apply_bc_segments(&resolved_request, &mut inputs)?;
782
783    let atmosphere = AtmosphericConditions {
784        temperature: temperature_c,
785        pressure: pressure_hpa,
786        humidity: humidity_percent,
787        altitude: resolved_request.atmosphere.altitude_m,
788    };
789
790    Ok(PreparedSolveV1 {
791        resolved_request,
792        assumptions,
793        warnings,
794        inputs,
795        wind,
796        wind_segments,
797        atmosphere,
798    })
799}
800
801/// Install `projectile.drag_table` on the prepared engine inputs (MBA-1597).
802///
803/// The engine flies a custom table as the projectile's OWN drag coefficient divided by its
804/// sectional density ([`BallisticInputs::custom_drag_denominator`]): the `projectile` kind, BC
805/// unused, exactly as the CLI's `--drag-table`. A `reference` curve is instead a standard the
806/// BC was measured against, which a built-in model flies as `Cd_ref / BC`. It is installed in
807/// one of two ways, which fly that same quotient:
808///
809/// * Without a BC ladder, as the own-curve path with `cd_scale = SD / BC`. Since BC = SD / i,
810///   `Cd_ref * SD / BC` is the projectile's own Cd, and the SD it is divided by is the very one
811///   the scale was built from — no second retardation formula. This is the original MBA-1597
812///   installation, kept unchanged so a request without a ladder solves byte-identically.
813/// * With a BC ladder (`has_bc_ladder`), with [`BallisticInputs::custom_drag_reference`] set
814///   and `cd_scale = 1.0`. The drag sites then divide the curve by the BC they resolve at each
815///   speed, so the band BCs, the scalar in an interior gap and the smoothstep blending at the
816///   band edges reach the table exactly as they reach a built-in model. One whole-curve scale
817///   cannot carry a BC that changes from band to band.
818///
819/// Either installation is rebuilt from the request's BC on every prepare, so a kernel that
820/// perturbs `ballistic_coefficient` and re-solves moves a reference-kind trajectory as it
821/// moves a built-in one.
822fn install_drag_table(
823    drag_table: &DragTableV1,
824    ballistic_coefficient: f64,
825    has_bc_ladder: bool,
826    inputs: &mut BallisticInputs,
827) -> Result<(), SolveErrorEnvelopeV1> {
828    let (mach, cd): (Vec<f64>, Vec<f64>) = drag_table
829        .points
830        .iter()
831        .map(|point| (point.mach, point.cd))
832        .unzip();
833    // `resolve_projectile` has already applied the same rules with exact paths; this is the
834    // engine's own gate, kept so a rule added there can never be skipped here.
835    let table = crate::drag::DragTable::try_new(mach, cd)
836        .map_err(|message| invalid_value("$.projectile.drag_table.points", message))?;
837    inputs.cd_scale = match drag_table.kind {
838        DragTableKindV1::Projectile => 1.0,
839        // A ladder's band BC must reach the denominator at every speed, which the whole-curve
840        // SD / BC scale below cannot carry, so the curve is flown as a built-in model is:
841        // unscaled, over the BC each drag site resolves. Without a ladder the SD / BC arm
842        // below is kept exactly as it was, so those solves stay byte-identical.
843        DragTableKindV1::Reference if has_bc_ladder => {
844            inputs.custom_drag_reference = true;
845            1.0
846        }
847        DragTableKindV1::Reference => {
848            let sectional_density = inputs.sectional_density_lb_in2().ok_or_else(|| {
849                internal_error("projectile mass and diameter gave no sectional density")
850            })?;
851            sectional_density / ballistic_coefficient
852        }
853    };
854    inputs.custom_drag_table = Some(table);
855    Ok(())
856}
857
858/// Apply an optional BC5D offline correction (`$.corrections.bc5d_table_path`) to the
859/// prepared engine inputs, mirroring the CLI's `--bc-table-dir` semantics exactly:
860/// CRC-verified load, the same velocity-keyed segment ladder
861/// ([`crate::bc_table_5d::Bc5dTable::generate_segments`], grains + fps axes), the
862/// table's muzzle correction folded into the scalar `bc_value` as the interior-gap
863/// fallback, and a G1 coercion warning for drag models outside the table's G1/G7
864/// planes. Because `prepare_request` feeds both [`solve_v1`]'s zero search and the
865/// trajectory (and the perturbation kernel), the zero is always solved with the SAME
866/// schedule the flight uses — the 0.22.11 auto-zero lesson.
867///
868/// On wasm32 there is no filesystem: supplying the field is a structured
869/// `invalid_value` error, never a silent no-op (WASM callers load table BYTES via
870/// `loadBc5dTable` instead).
871fn apply_bc5d_correction(
872    request: &SolveRequestV1,
873    resolved_request: &ResolvedSolveRequestV1,
874    inputs: &mut BallisticInputs,
875    warnings: &mut Vec<SolveNoticeV1>,
876) -> Result<(), SolveErrorEnvelopeV1> {
877    let Some(table_path) = request
878        .corrections
879        .as_ref()
880        .and_then(|corrections| corrections.bc5d_table_path.as_deref())
881    else {
882        return Ok(());
883    };
884
885    #[cfg(target_arch = "wasm32")]
886    {
887        let _ = (table_path, resolved_request, inputs, warnings);
888        Err(invalid_value(
889            "$.corrections.bc5d_table_path",
890            "bc5d_table_path is not supported on this build (no filesystem access); \
891             load table bytes through the WASM loadBc5dTable API instead",
892        ))
893    }
894
895    #[cfg(not(target_arch = "wasm32"))]
896    {
897        use crate::bc_table_5d::{path_cache, Bc5dError};
898
899        // Identity, not just integrity: the table's header caliber must be this shot's
900        // caliber. A wrong-caliber table is worse than no table, because every lookup
901        // still succeeds (edge-bin clamping) and silently biases every row — so it is
902        // refused as an invalid_value at the field that named it, never applied and
903        // never downgraded to a silent uncorrected solve. See
904        // `Bc5dTable::ensure_caliber_matches`.
905        let shot_caliber_in = resolved_request.projectile.diameter_m / 0.0254;
906        let table = path_cache::load_verified_for_caliber(
907            std::path::Path::new(table_path),
908            shot_caliber_in,
909        )
910        .map_err(|error| {
911            let code = match error {
912                Bc5dError::IoError(_) => SolveErrorCodeV1::IoError,
913                _ => SolveErrorCodeV1::InvalidValue,
914            };
915            SolveErrorEnvelopeV1::new(
916                SolveErrorV1::new(code, format!("bc5d_table_path: {error}"))
917                    .at_path("$.corrections.bc5d_table_path"),
918            )
919        })?;
920
921        // The v2 BC5D tables carry only G1/G7 planes; every other reference model is
922        // typed as G1, with the same warning surface as the CLI/WASM aux paths.
923        let drag_type = match resolved_request.projectile.drag_model {
924            DragModelV1::G7 => "G7",
925            DragModelV1::G1 => "G1",
926            other => {
927                warnings.push(SolveNoticeV1 {
928                    code: WARNING_BC5D_DRAG_MODEL_COERCED.to_owned(),
929                    message: format!(
930                        "BC5D correction tables support G1/G7 only; treating drag model \
931                         {other:?} as G1 for the table lookup"
932                    ),
933                    path: Some("$.corrections.bc5d_table_path".to_owned()),
934                });
935                "G1"
936            }
937        };
938
939        // Table axes are grains and fps; the prepared inputs already carry both
940        // conversions (the same checked ones the summary diagnostics use).
941        let base_bc = resolved_request.projectile.ballistic_coefficient;
942        let weight_grains = inputs.weight_grains;
943        let muzzle_fps = resolved_request.rifle.muzzle_velocity_mps / 0.3048;
944
945        if let Some(segments) =
946            table.generate_segments(base_bc, drag_type, weight_grains, Some(muzzle_fps))
947        {
948            // CLI parity (main.rs `--bc-table-dir`): the scalar BC becomes the
949            // muzzle-corrected fallback for interior coverage gaps.
950            inputs.bc_value =
951                table.get_effective_bc(weight_grains, base_bc, muzzle_fps, muzzle_fps, drag_type);
952            inputs.use_bc_segments = true;
953            inputs.bc_segments_data = Some(segments);
954        }
955        // A neutral table (no meaningful correction for this load) leaves the
956        // published constant BC in place, exactly like the CLI.
957        Ok(())
958    }
959}
960
961/// Install a `projectile.bc_segments` ladder (MBA-1598) on the prepared inputs, converting its
962/// m/s band edges to the fps the engine's `BCSegmentData` is keyed in. Without a ladder this
963/// is a no-op.
964///
965/// The scalar `bc_value` is left untouched, exactly as the CLI's `--bc-segment` and `card.*`
966/// leave it; the correction path above, by contrast, rewrites `bc_value`. The engine flies the
967/// scalar only in an interior gap between two bands, and blended into the bands within up to
968/// 25 fps either side of a gap edge. Below the lowest band, or at or above the highest, the
969/// nearest edge band applies, so under a gapless ladder the scalar never flies.
970/// Band BCs are referenced to `drag_model`'s curve, or to the drag table's curve when the table
971/// is `reference`-kind, bands are selected by airspeed (speed relative to the air mass), and
972/// every interior band edge and gap edge is smoothstep-blended (`velocity_segment_bc` in
973/// `src/bc_estimation.rs`). The lookup does not depend on the array
974/// order; the fastest-first order is only a validation rule.
975fn apply_bc_segments(
976    resolved_request: &ResolvedSolveRequestV1,
977    inputs: &mut BallisticInputs,
978) -> Result<(), SolveErrorEnvelopeV1> {
979    let Some(bc_segments) = &resolved_request.projectile.bc_segments else {
980        return Ok(());
981    };
982
983    let segments: Vec<crate::BCSegmentData> = bc_segments
984        .iter()
985        .map(|seg| crate::BCSegmentData {
986            velocity_min: seg.velocity_min_mps / 0.3048,
987            velocity_max: seg.velocity_max_mps / 0.3048,
988            bc_value: seg.ballistic_coefficient,
989        })
990        .collect();
991
992    inputs.use_bc_segments = true;
993    inputs.bc_segments_data = Some(segments);
994    Ok(())
995}
996
997fn resolve_projectile(
998    projectile: &ProjectileV1,
999    assumptions: &mut Vec<SolveNoticeV1>,
1000) -> Result<(ResolvedProjectileV1, f64), SolveErrorEnvelopeV1> {
1001    require_positive("$.projectile.mass_kg", projectile.mass_kg)?;
1002    require_positive("$.projectile.diameter_m", projectile.diameter_m)?;
1003    require_positive(
1004        "$.projectile.ballistic_coefficient",
1005        projectile.ballistic_coefficient,
1006    )?;
1007    if let Some(length_m) = projectile.length_m {
1008        require_positive("$.projectile.length_m", length_m)?;
1009    }
1010    if let Some(drag_table) = &projectile.drag_table {
1011        crate::solve_json::validate_drag_table_v1(drag_table)?;
1012    }
1013    if let Some(bc_segments) = &projectile.bc_segments {
1014        crate::solve_json::validate_bc_segments_v1(bc_segments, projectile.ballistic_coefficient)?;
1015    }
1016
1017    let bullet_length_m = match projectile.length_m {
1018        Some(length_m) => length_m,
1019        None => {
1020            let estimated = crate::stability::estimate_bullet_length_m(
1021                projectile.diameter_m,
1022                projectile.mass_kg,
1023            );
1024            if !estimated.is_finite() || estimated <= 0.0 {
1025                return Err(invalid_value(
1026                    "$.projectile",
1027                    "projectile mass and diameter could not produce a finite positive length estimate",
1028                ));
1029            }
1030            assumptions.push(notice(
1031                ASSUMPTION_ESTIMATED_PROJECTILE_LENGTH,
1032                format!(
1033                    "Projectile length was omitted; the engine estimated {estimated:.12} m from mass and diameter."
1034                ),
1035                "$.projectile.length_m",
1036            ));
1037            estimated
1038        }
1039    };
1040
1041    Ok((
1042        ResolvedProjectileV1 {
1043            mass_kg: projectile.mass_kg,
1044            diameter_m: projectile.diameter_m,
1045            length_m: projectile.length_m,
1046            drag_model: projectile.drag_model,
1047            ballistic_coefficient: projectile.ballistic_coefficient,
1048            drag_table: projectile.drag_table.clone(),
1049            bc_segments: projectile.bc_segments.clone(),
1050        },
1051        bullet_length_m,
1052    ))
1053}
1054
1055fn resolve_rifle(
1056    rifle: &RifleV1,
1057    assumptions: &mut Vec<SolveNoticeV1>,
1058) -> Result<ResolvedRifleV1, SolveErrorEnvelopeV1> {
1059    require_positive("$.rifle.muzzle_velocity_mps", rifle.muzzle_velocity_mps)?;
1060    if let Some(value) = rifle.sight_height_m {
1061        require_non_negative("$.rifle.sight_height_m", value)?;
1062    }
1063    if let Some(value) = rifle.muzzle_height_m {
1064        require_finite("$.rifle.muzzle_height_m", value)?;
1065    }
1066    if let Some(value) = rifle.twist_rate_m_per_turn {
1067        require_positive("$.rifle.twist_rate_m_per_turn", value)?;
1068    }
1069    // MBA-1396: validated here but NOT resolved through `literal_default` — an absence
1070    // notice would change the response bytes of every request that predates the field.
1071    // Consumed directly into the engine inputs, and separately echoed on the resolved
1072    // DTO at ResolvedRifleV1::sight_offset_lateral_m when supplied (0.33.0
1073    // decision-support Task 1); omitting it still stays byte-identical to requests that
1074    // predate the field.
1075    if let Some(value) = rifle.sight_offset_lateral_m {
1076        require_finite("$.rifle.sight_offset_lateral_m", value)?;
1077        if value.abs() >= 0.5 {
1078            return Err(invalid_value(
1079                "$.rifle.sight_offset_lateral_m",
1080                "lateral sight offset must be smaller than 0.5 m in magnitude (the \
1081                 sight-to-bore mount offset, in meters)",
1082            ));
1083        }
1084    }
1085
1086    let sight_height_m = literal_default(
1087        rifle.sight_height_m,
1088        DEFAULT_SIGHT_HEIGHT_M,
1089        "$.rifle.sight_height_m",
1090        "Sight height defaulted to 0.05 m.",
1091        assumptions,
1092    );
1093    let muzzle_height_m = literal_default(
1094        rifle.muzzle_height_m,
1095        DEFAULT_MUZZLE_HEIGHT_M,
1096        "$.rifle.muzzle_height_m",
1097        "Muzzle height defaulted to 0 m.",
1098        assumptions,
1099    );
1100    let twist_rate_m_per_turn = literal_default(
1101        rifle.twist_rate_m_per_turn,
1102        DEFAULT_TWIST_RATE_M_PER_TURN,
1103        "$.rifle.twist_rate_m_per_turn",
1104        "Twist rate defaulted to 0.3048 m per turn.",
1105        assumptions,
1106    );
1107    let twist_direction = match rifle.twist_direction {
1108        Some(direction) => direction,
1109        None => {
1110            assumptions.push(notice(
1111                ASSUMPTION_DEFAULT_APPLIED,
1112                "Twist direction defaulted to right-hand.",
1113                "$.rifle.twist_direction",
1114            ));
1115            TwistDirectionV1::Right
1116        }
1117    };
1118
1119    Ok(ResolvedRifleV1 {
1120        muzzle_velocity_mps: rifle.muzzle_velocity_mps,
1121        sight_height_m,
1122        muzzle_height_m,
1123        twist_rate_m_per_turn,
1124        twist_direction,
1125        // MBA-1396: pure pass-through echo (Task 1 of the 0.33.0 decision-support train) — no
1126        // defaulting, no unit conversion. Validated above.
1127        sight_offset_lateral_m: rifle.sight_offset_lateral_m,
1128    })
1129}
1130
1131fn resolve_shot(
1132    shot: &ShotV1,
1133    rifle: &ResolvedRifleV1,
1134    assumptions: &mut Vec<SolveNoticeV1>,
1135    warnings: &mut Vec<SolveNoticeV1>,
1136) -> Result<ResolvedShotV1, SolveErrorEnvelopeV1> {
1137    let muzzle_height_m = rifle.muzzle_height_m;
1138    require_positive("$.shot.max_range_m", shot.max_range_m)?;
1139    if let Some(value) = shot.zero_distance_m {
1140        require_positive("$.shot.zero_distance_m", value)?;
1141        if !(value * 2.0).is_finite() {
1142            return Err(invalid_value(
1143                "$.shot.zero_distance_m",
1144                "zero distance is too large to construct a finite trial trajectory range",
1145            ));
1146        }
1147    }
1148    if let Some(value) = shot.muzzle_angle_rad {
1149        require_finite("$.shot.muzzle_angle_rad", value)?;
1150    }
1151    // 0.33.0 decision-support Task 2: both fields may be supplied together. This used to be
1152    // a conflicting_fields error, but `From<&ResolvedSolveRequestV1> for SolveRequestV1`
1153    // (request_roundtrip.rs) always carries both when the original request solved a zero --
1154    // zero_distance_m as caller intent, muzzle_angle_rad as the effective angle already
1155    // found -- so a rebuilt request can reuse that exact angle without re-running the
1156    // elevation search. The match below already gives muzzle_angle_rad priority whenever it
1157    // is present, with or without zero_distance_m alongside it; solve_v1 mirrors that
1158    // priority by skipping the elevation search whenever an explicit angle was supplied.
1159    // zero_distance_m no longer re-derives the elevation in that case, but it is not
1160    // otherwise inert: solve_v1 still applies the separate windage-zero convergence bias
1161    // (sight_offset_lateral_m / zero_poi_right_m) gated on it, it still widens the required
1162    // wind coverage below, it is still validated above, and it still feeds
1163    // summary.equivalent_horizontal_range_m. A warning names this explicitly (below).
1164
1165    for (path, value) in [
1166        ("$.shot.aim_azimuth_rad", shot.aim_azimuth_rad),
1167        ("$.shot.shot_azimuth_rad", shot.shot_azimuth_rad),
1168        ("$.shot.shooting_angle_rad", shot.shooting_angle_rad),
1169        ("$.shot.cant_angle_rad", shot.cant_angle_rad),
1170        ("$.shot.target_height_m", shot.target_height_m),
1171        ("$.shot.ground_threshold_m", shot.ground_threshold_m),
1172    ] {
1173        if let Some(value) = value {
1174            require_finite(path, value)?;
1175        }
1176    }
1177
1178    // MBA-1359: deliberate POI offset at the zero range (Kestrel ZH/ZO). Validated here but
1179    // NOT resolved through `literal_default`: emitting an absence notice would change the
1180    // response bytes of every request that predates these fields. They are consumed
1181    // directly into the engine inputs, and separately echoed on the resolved DTO at
1182    // ResolvedShotV1::zero_poi_up_m / zero_poi_right_m when supplied (0.33.0
1183    // decision-support Task 1); omitting them still stays byte-identical to requests that
1184    // predate these fields.
1185    for (path, value) in [
1186        ("$.shot.zero_poi_up_m", shot.zero_poi_up_m),
1187        ("$.shot.zero_poi_right_m", shot.zero_poi_right_m),
1188    ] {
1189        if let Some(value) = value {
1190            require_finite(path, value)?;
1191            if value.abs() >= 1.0 {
1192                return Err(invalid_value(
1193                    path,
1194                    "zero POI offset must be smaller than 1.0 m in magnitude (a linear \
1195                     point-of-impact offset at the zero range, in meters)",
1196                ));
1197            }
1198        }
1199    }
1200
1201    // MBA-1537: exactly the condition under which `build_zeroed_solver` runs the elevation
1202    // search, named once so the zero-frame default below cannot drift out of step with the
1203    // match that decides it.
1204    let elevation_search_runs = shot.zero_distance_m.is_some() && shot.muzzle_angle_rad.is_none();
1205
1206    let muzzle_angle_rad = match (shot.zero_distance_m, shot.muzzle_angle_rad) {
1207        // An explicit angle always wins over zero_distance_m for elevation (0.33.0
1208        // decision-support Task 2). When both are supplied, note that the elevation search
1209        // did not run -- zero_distance_m is still retained and still has other effects (see
1210        // the warning message), but a caller relying on a stale muzzle_angle_rad while
1211        // setting a new zero_distance_m should not mistake the echo for confirmation that a
1212        // zero was actually solved.
1213        (Some(_), Some(angle)) => {
1214            warnings.push(notice(
1215                WARNING_ZERO_DISTANCE_ELEVATION_NOT_RESOLVED,
1216                "muzzle_angle_rad was supplied together with zero_distance_m: the elevation \
1217                 was used directly and the elevation search did not run. zero_distance_m is \
1218                 retained in resolved_request and still affects the windage-convergence bias \
1219                 (sight_offset_lateral_m / zero_poi_right_m), summary.equivalent_horizontal_range_m, \
1220                 and downrange wind-coverage validation.",
1221                "$.shot.zero_distance_m",
1222            ));
1223            angle
1224        }
1225        (None, Some(angle)) => angle,
1226        (Some(_), None) => 0.0, // Replaced with the calculated effective angle before solving.
1227        (None, None) => {
1228            assumptions.push(notice(
1229                ASSUMPTION_DEFAULT_APPLIED,
1230                "Muzzle angle defaulted to 0 rad.",
1231                "$.shot.muzzle_angle_rad",
1232            ));
1233            0.0
1234        }
1235    };
1236    let aim_azimuth_rad = literal_default(
1237        shot.aim_azimuth_rad,
1238        0.0,
1239        "$.shot.aim_azimuth_rad",
1240        "Aim azimuth defaulted to 0 rad.",
1241        assumptions,
1242    );
1243    let shot_azimuth_rad = literal_default(
1244        shot.shot_azimuth_rad,
1245        0.0,
1246        "$.shot.shot_azimuth_rad",
1247        "Shot azimuth defaulted to 0 rad (north).",
1248        assumptions,
1249    );
1250    let shooting_angle_rad = literal_default(
1251        shot.shooting_angle_rad,
1252        0.0,
1253        "$.shot.shooting_angle_rad",
1254        "Shooting angle defaulted to 0 rad.",
1255        assumptions,
1256    );
1257    let cant_angle_rad = literal_default(
1258        shot.cant_angle_rad,
1259        0.0,
1260        "$.shot.cant_angle_rad",
1261        "Cant angle defaulted to 0 rad.",
1262        assumptions,
1263    );
1264    // MBA-1537: when the elevation search runs and no target height was supplied, the height
1265    // the search converges on is the LINE OF SIGHT, not the ground datum.
1266    //
1267    // `target_height_m` is a world-vertical height above the local ground datum, and the line
1268    // of sight of a level rifle sits `muzzle_height_m + sight_height_m` above that datum -- the
1269    // same sum `TrajectoryResult::line_of_sight_height_m` reports and the same sum the sampler
1270    // uses as its LOS datum. Defaulting to a flat `0` aimed the search at the ground instead,
1271    // which put the bullet a full line-of-sight height LOW at the caller's stated zero: it
1272    // never crossed the line of sight at all. It also made `sight_height_m` inert -- the solved
1273    // angle was identical for every sight height -- and made the answer a function of
1274    // `muzzle_height_m`, which it physically is not: heights above the ground cancel once the
1275    // target tracks the line of sight. A raised muzzle stopped converging altogether once it
1276    // cleared the bullet's own drop over the zero distance (measured for a .308 at 100 yd:
1277    // 0.07 m still converges, 0.08 m does not; the drop over 91.44 m is 0.0661 m),
1278    // because the ground datum it was aiming at then sits below the muzzle.
1279    //
1280    // This is the height the `ZeroTargetFrame::SightLine` surfaces already use. `cli_api`'s
1281    // `calculate_zero_angle_with_conditions` solves against whatever target height its caller
1282    // hands it; the CLI hands it bore + sight (main.rs:8263), which is this sum. `ffi.rs`'s
1283    // `ballistics_calculate_zero_angle`
1284    // both solve against the sight height (the same sum, for their `muzzle_height` of 0).
1285    // Moving the default here is what makes them agree.
1286    //
1287    // Gated on the search actually running rather than on `zero_distance_m` alone: a request
1288    // that supplies `muzzle_angle_rad` uses that angle directly, so there is no zero to frame,
1289    // and such a request stays byte-identical -- assumption text, resolved echo and all.
1290    // Without a zero search `target_height_m` feeds only the `drops_reference: "target"`
1291    // sampler datum, which has its own distance reference (the target sits at `max_range_m`,
1292    // not at `zero_distance_m`); keeping the historical `0` there leaves that mode untouched.
1293    //
1294    // This is the LEVEL line of sight, and deliberately not projected by `shooting_angle_rad`
1295    // into the inclined sight line. Two reasons: the same field is the target-drops sampler's
1296    // LOS datum, where it is referenced to `max_range_m` rather than to `zero_distance_m`, so a
1297    // default computed at the zero distance would silently slope that datum over the wrong
1298    // span; and at `shooting_angle_rad == 0` the level form equals `sight_position_m` bit for
1299    // bit, which is what keeps that mode untouched here. An inclined zero therefore still has
1300    // to state its own target height -- `docs/SOLVE_JSON_V1.md` gives the projection, and
1301    // `tests/zero_sight_line_default.rs` pins both halves of that.
1302    let target_height_m = if elevation_search_runs {
1303        match shot.target_height_m {
1304            Some(value) => value,
1305            None => {
1306                let line_of_sight_m = muzzle_height_m + rifle.sight_height_m;
1307                assumptions.push(notice(
1308                    ASSUMPTION_DEFAULT_APPLIED,
1309                    format!(
1310                        "Target height defaulted to the line of sight, {line_of_sight_m} m above \
1311                         the local ground datum (muzzle_height_m + sight_height_m), so the solved \
1312                         elevation crosses the line of sight at zero_distance_m. Supply \
1313                         target_height_m explicitly -- 0 included -- to zero against the ground \
1314                         datum instead."
1315                    ),
1316                    "$.shot.target_height_m",
1317                ));
1318                line_of_sight_m
1319            }
1320        }
1321    } else {
1322        literal_default(
1323            shot.target_height_m,
1324            0.0,
1325            "$.shot.target_height_m",
1326            "Target height defaulted to 0 m above the local ground datum.",
1327            assumptions,
1328        )
1329    };
1330    let ground_threshold_m = literal_default(
1331        shot.ground_threshold_m,
1332        DEFAULT_GROUND_THRESHOLD_M,
1333        "$.shot.ground_threshold_m",
1334        "Ground threshold defaulted to -100 m.",
1335        assumptions,
1336    );
1337    if ground_threshold_m >= muzzle_height_m {
1338        return Err(invalid_value(
1339            "$.shot.ground_threshold_m",
1340            "ground threshold must be below the resolved muzzle height",
1341        ));
1342    }
1343
1344    Ok(ResolvedShotV1 {
1345        max_range_m: shot.max_range_m,
1346        zero_distance_m: shot.zero_distance_m,
1347        muzzle_angle_rad,
1348        aim_azimuth_rad,
1349        shot_azimuth_rad,
1350        shooting_angle_rad,
1351        cant_angle_rad,
1352        target_height_m,
1353        ground_threshold_m,
1354        // MBA-1359/MBA-1403: pure pass-through echoes (Task 1 of the 0.33.0 decision-support
1355        // train) — no defaulting, no unit conversion. Validated above.
1356        zero_poi_up_m: shot.zero_poi_up_m,
1357        zero_poi_right_m: shot.zero_poi_right_m,
1358        drops_reference: shot.drops_reference,
1359    })
1360}
1361
1362/// Resolve a solve-json v1 atmosphere exactly as a solve does: validate with `$.atmosphere.*`
1363/// paths, default what was omitted (announcing each default in `assumptions`), and reduce a
1364/// QNH to station pressure. Shared with `atmosphere.density_altitude` so that command
1365/// describes precisely the air a solve with the same `atmosphere` object would fly through.
1366pub(crate) fn resolve_atmosphere(
1367    atmosphere: &AtmosphereV1,
1368    assumptions: &mut Vec<SolveNoticeV1>,
1369) -> Result<ResolvedAtmosphereV1, SolveErrorEnvelopeV1> {
1370    // A station altitude is held to one rule on every surface: a finite number. The standard
1371    // atmosphere an omitted temperature or pressure defaults to is clamped at -5 km and 84 km,
1372    // the ends of the ICAO table, beyond which its standard air is that edge's.
1373    if let Some(value) = atmosphere.altitude_m {
1374        require_finite("$.atmosphere.altitude_m", value)?;
1375    }
1376    if let Some(value) = atmosphere.temperature_k {
1377        require_positive("$.atmosphere.temperature_k", value)?;
1378    }
1379    if let Some(value) = atmosphere.pressure_pa {
1380        require_positive("$.atmosphere.pressure_pa", value)?;
1381    }
1382    // The sensor band (`HUMIDITY_SENSOR_TOLERANCE_PERCENT`): a fraction up to 0.05
1383    // outside [0, 1] is a reading of saturated or dry air (an app's Kestrel or phone sensor in
1384    // fog), and resolves to the end it reads as, so the resolved request echoes, and every
1385    // consumer of it flies, that end. An in-range fraction keeps its bits. Beyond the band it is
1386    // refused exactly as before: the same path and code.
1387    // The message is the one fraction refusal every SI surface gives, with the band it
1388    // enforces: "relative_humidity = 1.06: relative humidity must be a fraction from 0 to 1
1389    // (0.5 = 50 %; a sensor reading from -0.05 to 1.05 is read as 0 or 1)".
1390    let relative_humidity_sent =
1391        match atmosphere.relative_humidity {
1392            Some(value) => Some(RelativeHumidity::snap_fraction(value).map_err(|error| {
1393                invalid_value("$.atmosphere.relative_humidity", error.to_string())
1394            })?),
1395            None => None,
1396        };
1397    if let Some(value) = atmosphere.latitude_rad {
1398        require_range(
1399            "$.atmosphere.latitude_rad",
1400            value,
1401            -std::f64::consts::FRAC_PI_2,
1402            std::f64::consts::FRAC_PI_2,
1403        )?;
1404    }
1405
1406    let altitude_m = match atmosphere.altitude_m {
1407        Some(value) => value,
1408        None => {
1409            assumptions.push(notice(
1410                ASSUMPTION_DEFAULT_APPLIED,
1411                "Station altitude defaulted to 0 m.",
1412                "$.atmosphere.altitude_m",
1413            ));
1414            DEFAULT_ALTITUDE_M
1415        }
1416    };
1417    let (standard_temperature_k, standard_pressure_pa) =
1418        crate::atmosphere::calculate_icao_standard_atmosphere(altitude_m);
1419    let temperature_k = match atmosphere.temperature_k {
1420        Some(value) => value,
1421        None => {
1422            assumptions.push(notice(
1423                ASSUMPTION_ICAO_STANDARD_TEMPERATURE,
1424                format!(
1425                    "Station temperature was omitted; ICAO standard temperature at {altitude_m:.6} m is {standard_temperature_k:.12} K."
1426                ),
1427                "$.atmosphere.temperature_k",
1428            ));
1429            standard_temperature_k
1430        }
1431    };
1432    let pressure_pa = match atmosphere.pressure_pa {
1433        // MBA-1397: an explicit pressure declared as a QNH (sea-level-corrected altimeter
1434        // setting) is reduced to station pressure at `altitude_m` before use. `Absolute`
1435        // (including the omitted-field default) is a pure passthrough -- byte-identical to
1436        // pre-MBA-1397 behavior for every request that never sets `pressure_reference`.
1437        Some(value) if atmosphere.pressure_reference == Some(PressureReferenceV1::Qnh) => {
1438            let qnh_hpa = value / PASCALS_PER_HECTOPASCAL;
1439            let station_hpa =
1440                crate::atmosphere::reduce_qnh_to_station_pressure(qnh_hpa, altitude_m);
1441            let station_pa = station_hpa * PASCALS_PER_HECTOPASCAL;
1442            // MBA-1605: the altimeter-setting relation has no pressure once the QNH's pressure
1443            // altitude plus the station's height reaches 44,331 m. Refused here, where both
1444            // commands that read this atmosphere resolve it, so `solve` and
1445            // `atmosphere.density_altitude` refuse it alike, before either's other checks, at
1446            // the reading the one rule blames: the altitude for a QNH that is itself a
1447            // plausible sea-level pressure (feet sent as metres), the pressure otherwise.
1448            if !(station_pa.is_finite() && station_pa > 0.0) {
1449                // The SI wire takes no density altitude, so its pressure is never one's.
1450                let path = match station_pressure_origin(atmosphere) {
1451                    crate::atmosphere::StationPressureOrigin::Reading => "$.atmosphere.pressure_pa",
1452                    crate::atmosphere::StationPressureOrigin::Standard
1453                    | crate::atmosphere::StationPressureOrigin::Qnh
1454                    | crate::atmosphere::StationPressureOrigin::DensityAltitude => {
1455                        "$.atmosphere.altitude_m"
1456                    }
1457                };
1458                return Err(invalid_value(
1459                    path,
1460                    format!(
1461                        "a QNH of {} Pa leaves no station pressure at {} m: the QNH's pressure \
1462                         altitude plus the station's height reaches the top of the \
1463                         altimeter-setting relation. pressure_pa is pascals (hPa × 100) and \
1464                         altitude_m is meters",
1465                        echo_si(value),
1466                        echo_si(altitude_m)
1467                    ),
1468                ));
1469            }
1470            assumptions.push(notice(
1471                ASSUMPTION_QNH_REDUCED_TO_STATION_PRESSURE,
1472                format!(
1473                    "Station pressure was declared as a QNH (sea-level-corrected altimeter \
1474                     setting) of {value:.6} Pa; reduced to station pressure {station_pa:.12} Pa \
1475                     at {altitude_m:.6} m with the altimeter-setting relation (the station's \
1476                     ISA pressure altitude is the QNH's plus the station's geopotential height)."
1477                ),
1478                "$.atmosphere.pressure_pa",
1479            ));
1480            station_pa
1481        }
1482        Some(value) => value,
1483        None => {
1484            assumptions.push(notice(
1485                ASSUMPTION_ICAO_STANDARD_PRESSURE,
1486                format!(
1487                    "Station pressure was omitted; ICAO standard pressure at {altitude_m:.6} m is {standard_pressure_pa:.12} Pa."
1488                ),
1489                "$.atmosphere.pressure_pa",
1490            ));
1491            standard_pressure_pa
1492        }
1493    };
1494    let relative_humidity = literal_default(
1495        relative_humidity_sent,
1496        DEFAULT_RELATIVE_HUMIDITY,
1497        "$.atmosphere.relative_humidity",
1498        // The fraction the wire carries, with the percent it means: a bare 0.5 is
1499        // the very number a reader cannot tell from 0.5 %.
1500        format!(
1501            "Relative humidity defaulted to {DEFAULT_RELATIVE_HUMIDITY} ({}%).",
1502            RelativeHumidity::DEFAULT.percent()
1503        ),
1504        assumptions,
1505    );
1506
1507    Ok(ResolvedAtmosphereV1 {
1508        altitude_m,
1509        temperature_k,
1510        pressure_pa,
1511        relative_humidity,
1512        latitude_rad: atmosphere.latitude_rad,
1513        // MBA-1397: pure pass-through echo (Task 1 of the 0.33.0 decision-support train) — the
1514        // mode itself is not resolved to a literal default; only its effect on `pressure_pa`
1515        // above is (see the QNH-reduction branch).
1516        pressure_reference: atmosphere.pressure_reference,
1517    })
1518}
1519
1520/// Where the station pressure of a solve-json v1 `atmosphere` came from, as `sent`: the
1521/// standard pressure at `altitude_m` when `pressure_pa` was omitted, a QNH when it was declared
1522/// one and is itself a plausible sea-level pressure, a reading otherwise
1523/// ([`crate::atmosphere::StationPressureOrigin::of`]). [`resolved_station_air`] locates its
1524/// impossible-air refusal by it, for `solve` and `atmosphere.density_altitude` alike, so the two
1525/// blame one reading for one station.
1526pub(crate) fn station_pressure_origin(
1527    sent: &AtmosphereV1,
1528) -> crate::atmosphere::StationPressureOrigin {
1529    let mode = match sent.pressure_reference {
1530        Some(PressureReferenceV1::Qnh) => crate::atmosphere::PressureReferenceMode::Qnh,
1531        _ => crate::atmosphere::PressureReferenceMode::Absolute,
1532    };
1533    crate::atmosphere::StationPressureOrigin::of(
1534        sent.pressure_pa.map(|pa| pa / PASCALS_PER_HECTOPASCAL),
1535        mode,
1536    )
1537}
1538
1539/// The station air a solve of `resolved` (the `sent` atmosphere after
1540/// [`resolve_atmosphere`]) flies, or the refusal of air that cannot exist: `invalid_value` at
1541/// the reading to blame, stated in the wire's own units.
1542///
1543/// One function for both commands that read a solve-json v1 `atmosphere`: the solve calls it
1544/// before any flight, and `atmosphere.density_altitude` before it computes anything, with no
1545/// check of its own, so whatever atmosphere the solve refuses, that command refuses with the
1546/// same code, path and message. A
1547/// temperature at or below absolute zero is blamed at `$.atmosphere.temperature_k`, and so is
1548/// air that cannot exist when it is humid above water's critical point or its temperature is
1549/// outside 173.15-373.15 K (where the humid-air formulas are extrapolated, a temperature is the
1550/// likelier mistake). Otherwise impossible air at a station pressure outside the troposphere is
1551/// blamed at `$.atmosphere.pressure_pa` for a pressure sent as a station reading (hPa sent as
1552/// pascals) and at `$.atmosphere.altitude_m` for one omitted or sent as a plausible QNH
1553/// ([`station_pressure_origin`]), each with a hint to check that unit and a QNH quoted as it was
1554/// sent (`pressure_pa is a QNH of 1013.25 Pa, and reduced to the station altitude of 1500 m it
1555/// is a station pressure of ...`); and any other at `$.atmosphere.relative_humidity`. A
1556/// refusal blamed on the temperature names it (`; temperature_k = 400 K is outside 173.15 K to
1557/// 373.15 K, ...`). Where both commands reach this function the message is the
1558/// same word for word: `"relative_humidity = 1 at 373.15 K and 100000 Pa: no such air exists:
1559/// ..."`. The station is built exactly as the solve's `TrajectorySolver`
1560/// builds it ([`AtmosphericConditions::station_air`] with both readings supplied, as the
1561/// resolved request carries them).
1562pub(crate) fn resolved_station_air(
1563    sent: &AtmosphereV1,
1564    resolved: &ResolvedAtmosphereV1,
1565) -> Result<crate::atmosphere::StationAir, SolveErrorEnvelopeV1> {
1566    use crate::atmosphere::{AirField, AirSpelling, StationAtmospherePresence};
1567    let humidity = RelativeHumidity::try_fraction(resolved.relative_humidity)
1568        .map_err(|error| invalid_value("$.atmosphere.relative_humidity", error.to_string()))?;
1569    let conditions = AtmosphericConditions {
1570        temperature: resolved.temperature_k - KELVIN_OFFSET_C,
1571        pressure: resolved.pressure_pa / PASCALS_PER_HECTOPASCAL,
1572        humidity: humidity.percent(),
1573        altitude: resolved.altitude_m,
1574    };
1575    conditions
1576        .station_air(StationAtmospherePresence::BOTH)
1577        .map_err(|error| {
1578            let spelling = AirSpelling {
1579                humidity: AirField {
1580                    name: "relative_humidity",
1581                    path: "$.atmosphere.relative_humidity",
1582                },
1583                temperature: AirField {
1584                    name: "temperature_k",
1585                    path: "$.atmosphere.temperature_k",
1586                },
1587                pressure: AirField {
1588                    name: "pressure_pa",
1589                    path: "$.atmosphere.pressure_pa",
1590                },
1591                altitude: AirField {
1592                    name: "altitude_m",
1593                    path: "$.atmosphere.altitude_m",
1594                },
1595                humidity_sent: resolved.relative_humidity,
1596                temperature_text: format!("{} K", echo_si(resolved.temperature_k)),
1597                temperature_unit: crate::atmosphere::TemperatureUnit::Kelvin,
1598                // The SI wire takes no density altitude: its temperature is a reading.
1599                temperature_origin: crate::atmosphere::StationTemperatureOrigin::Reading,
1600                pressure_text: format!("{} Pa", echo_si(resolved.pressure_pa)),
1601                pressure_origin: station_pressure_origin(sent),
1602                // A QNH as it was sent, never the station pressure reduced from it.
1603                qnh_text: sent
1604                    .pressure_pa
1605                    .filter(|_| sent.pressure_reference == Some(PressureReferenceV1::Qnh))
1606                    .map(|qnh_pa| format!("{} Pa", echo_si(qnh_pa))),
1607                altitude_unit: crate::atmosphere::AltitudeUnit::Meters,
1608            };
1609            let refusal = error.refusal_in(
1610                &spelling,
1611                conditions.altitude,
1612                conditions.temperature,
1613                conditions.pressure,
1614            );
1615            invalid_value(refusal.path().to_string(), refusal.message().to_string())
1616        })
1617}
1618
1619/// A caller's SI number as a refusal quotes it: plain for ordinary magnitudes, and in exponent
1620/// form for the absurd ones, which `{}` would otherwise print as 300 digits.
1621pub(crate) fn echo_si(value: f64) -> String {
1622    crate::atmosphere::echo_number(value)
1623}
1624
1625/// The [`WARNING_STATION_PRESSURE_IMPLAUSIBLE_FOR_ALTITUDE`] notice for a sent absolute
1626/// pressure that cannot be a station reading at the resolved altitude, or `None`.
1627///
1628/// `sent` is the raw request atmosphere, which says whether `pressure_pa` and `altitude_m` were
1629/// present; `resolved` carries the altitude actually used, which is 0 m when it was omitted.
1630fn station_pressure_warning(
1631    sent: &AtmosphereV1,
1632    resolved: &ResolvedAtmosphereV1,
1633) -> Option<SolveNoticeV1> {
1634    let pressure_pa = sent.pressure_pa?;
1635    if sent.pressure_reference == Some(PressureReferenceV1::Qnh) {
1636        return None;
1637    }
1638    let altitude_m = resolved.altitude_m;
1639    let check = crate::atmosphere::station_pressure_plausibility(pressure_pa, altitude_m);
1640    if !check.implausible {
1641        return None;
1642    }
1643    let ratio = check.ratio;
1644    let icao_pa = check.icao_standard_pa;
1645    let defaulted = if sent.altitude_m.is_none() {
1646        "; altitude_m was omitted and defaulted to 0 m"
1647    } else {
1648        ""
1649    };
1650    let min = crate::atmosphere::STATION_PRESSURE_MIN_PLAUSIBLE_RATIO;
1651    let max = crate::atmosphere::STATION_PRESSURE_MAX_PLAUSIBLE_RATIO;
1652    let measured = format!(
1653        "pressure_pa {pressure_pa} Pa, sent as absolute station pressure, is {ratio:.3} times \
1654         the ICAO standard pressure at altitude_m {altitude_m} m ({icao_pa:.2} Pa{defaulted})"
1655    );
1656    // A sea-level figure sent at a real elevation can only read high, so the low side names
1657    // the altitude and the unit alone.
1658    let causes = if ratio > max {
1659        format!(
1660            "above the {min} to {max} band that recorded weather stays within. Likely causes: \
1661             a sea-level placeholder such as 101325 Pa, or a weather-report altimeter setting \
1662             (QNH) sent as station pressure, which belongs in the request with \
1663             \"pressure_reference\": \"qnh\" and the real altitude_m; or altitude_m is not the \
1664             station elevation, or is not in meters."
1665        )
1666    } else {
1667        format!(
1668            "below the {min} to {max} band that recorded weather stays within. Likely causes: \
1669             altitude_m is not the station elevation (send the real one, in meters), or \
1670             pressure_pa is not in pascals."
1671        )
1672    };
1673    Some(notice(
1674        WARNING_STATION_PRESSURE_IMPLAUSIBLE_FOR_ALTITUDE,
1675        format!("{measured}, {causes} The solve used pressure_pa as sent."),
1676        "$.atmosphere.pressure_pa",
1677    ))
1678}
1679
1680fn resolve_wind(
1681    wind: &WindV1,
1682    coverage_distance_m: f64,
1683    request_shot_azimuth_rad: Option<f64>,
1684    assumptions: &mut Vec<SolveNoticeV1>,
1685    warnings: &mut Vec<SolveNoticeV1>,
1686) -> Result<(ResolvedWindV1, WindConditions, Vec<WindSegment>), SolveErrorEnvelopeV1> {
1687    // MBA-1368: resolve the entry frame ONCE, before any direction is consumed.
1688    // Omitted == shooter, byte-identical with no assumption notice (the Batch A
1689    // additive-field precedent: a notice would change every pre-existing response).
1690    // In compass mode every direction below passes through `to_relative` BEFORE the
1691    // resolved echo and the engine structures are built, so downstream physics (and
1692    // the response) only ever see shooter-relative wind-FROM radians — the QNH
1693    // fold-into-the-resolved-value precedent.
1694    let compass_azimuth_rad = match wind.wind_reference.unwrap_or_default() {
1695        WindReferenceV1::Shooter => None,
1696        WindReferenceV1::Compass => match request_shot_azimuth_rad {
1697            Some(azimuth) => Some(azimuth),
1698            None => {
1699                return Err(conflicting_fields(
1700                    "$.wind.wind_reference",
1701                    "wind_reference \"compass\" requires shot.shot_azimuth_rad (earth-fixed \
1702                     bearings are re-referenced against the shot azimuth; omitting it would \
1703                     silently treat bearings as shooter-relative)",
1704                ))
1705            }
1706        },
1707    };
1708    let to_relative = |bearing_rad: f64| -> f64 {
1709        match compass_azimuth_rad {
1710            Some(azimuth) => {
1711                crate::wind::compass_bearing_to_shooter_relative_rad(bearing_rad, azimuth)
1712            }
1713            None => bearing_rad,
1714        }
1715    };
1716
1717    if let Some(segments) = &wind.segments {
1718        if wind.speed_mps.is_some()
1719            || wind.direction_from_rad.is_some()
1720            || wind.vertical_speed_mps.is_some()
1721        {
1722            return Err(conflicting_fields(
1723                "$.wind",
1724                "segments cannot be combined with constant-wind fields",
1725            ));
1726        }
1727        if segments.is_empty() {
1728            return Err(invalid_value(
1729                "$.wind.segments",
1730                "segmented wind must contain at least one segment",
1731            ));
1732        }
1733
1734        let mut resolved_segments = Vec::with_capacity(segments.len());
1735        let mut engine_segments = Vec::with_capacity(segments.len());
1736        let mut previous_until_m = 0.0;
1737        for (index, segment) in segments.iter().enumerate() {
1738            let base = format!("$.wind.segments[{index}]");
1739            require_positive(
1740                &format!("{base}.until_distance_m"),
1741                segment.until_distance_m,
1742            )?;
1743            require_non_negative(&format!("{base}.speed_mps"), segment.speed_mps)?;
1744            require_finite(
1745                &format!("{base}.direction_from_rad"),
1746                segment.direction_from_rad,
1747            )?;
1748            if let Some(value) = segment.vertical_speed_mps {
1749                require_finite(&format!("{base}.vertical_speed_mps"), value)?;
1750            }
1751            if index > 0 && segment.until_distance_m <= previous_until_m {
1752                return Err(invalid_value(
1753                    format!("{base}.until_distance_m"),
1754                    "wind-segment boundaries must be strictly increasing",
1755                ));
1756            }
1757            previous_until_m = segment.until_distance_m;
1758
1759            let vertical_speed_mps = match segment.vertical_speed_mps {
1760                Some(value) => value,
1761                None => {
1762                    assumptions.push(notice(
1763                        ASSUMPTION_DEFAULT_APPLIED,
1764                        "Segment vertical wind speed defaulted to 0 m/s.",
1765                        format!("{base}.vertical_speed_mps"),
1766                    ));
1767                    0.0
1768                }
1769            };
1770            let speed_kmh = checked_conversion(
1771                segment.speed_mps * SECONDS_PER_HOUR * KILOMETRES_PER_METRE,
1772                &format!("{base}.speed_mps"),
1773                "wind speed conversion to kilometres per hour overflowed",
1774            )?;
1775            // MBA-1368: compass bearings become shooter-relative HERE, so both the
1776            // resolved echo and the engine segment carry the converted direction.
1777            let direction_from_rad = to_relative(segment.direction_from_rad);
1778            let angle_deg = checked_conversion(
1779                direction_from_rad.to_degrees(),
1780                &format!("{base}.direction_from_rad"),
1781                "wind direction conversion to degrees overflowed",
1782            )?;
1783
1784            resolved_segments.push(ResolvedWindSegmentV1 {
1785                until_distance_m: segment.until_distance_m,
1786                speed_mps: segment.speed_mps,
1787                direction_from_rad,
1788                vertical_speed_mps,
1789            });
1790            engine_segments.push(WindSegment {
1791                speed_kmh,
1792                angle_deg,
1793                until_m: segment.until_distance_m,
1794                vertical_mps: vertical_speed_mps,
1795            });
1796        }
1797
1798        let final_until_m = resolved_segments
1799            .last()
1800            .expect("non-empty segmented wind was checked")
1801            .until_distance_m;
1802        if final_until_m < coverage_distance_m {
1803            warnings.push(notice(
1804                WARNING_PARTIAL_WIND_COVERAGE,
1805                format!(
1806                    "Segmented wind ends at {final_until_m:.12} m; wind is calm from that boundary through the required {coverage_distance_m:.12} m solve/zero range."
1807                ),
1808                "$.wind.segments",
1809            ));
1810        }
1811
1812        Ok((
1813            ResolvedWindV1::Segmented(ResolvedSegmentedWindV1 {
1814                segments: resolved_segments,
1815                // MBA-1368: pure pass-through echo (Task 1 of the 0.33.0 decision-support
1816                // train) — the mode itself is not resolved to a literal default; only its
1817                // effect on each segment's `direction_from_rad` above is (see `to_relative`).
1818                wind_reference: wind.wind_reference,
1819            }),
1820            WindConditions::default(),
1821            engine_segments,
1822        ))
1823    } else {
1824        match (wind.speed_mps, wind.direction_from_rad) {
1825            (Some(_), None) | (None, Some(_)) => {
1826                return Err(conflicting_fields(
1827                    "$.wind",
1828                    "speed_mps and direction_from_rad must be supplied together",
1829                ));
1830            }
1831            (None, None) if wind.vertical_speed_mps.is_some() => {
1832                return Err(conflicting_fields(
1833                    "$.wind",
1834                    "vertical_speed_mps requires speed_mps and direction_from_rad",
1835                ));
1836            }
1837            _ => {}
1838        }
1839
1840        if let Some(value) = wind.speed_mps {
1841            require_non_negative("$.wind.speed_mps", value)?;
1842        }
1843        if let Some(value) = wind.direction_from_rad {
1844            require_finite("$.wind.direction_from_rad", value)?;
1845        }
1846        if let Some(value) = wind.vertical_speed_mps {
1847            require_finite("$.wind.vertical_speed_mps", value)?;
1848        }
1849
1850        let (speed_mps, direction_from_rad, vertical_speed_mps) =
1851            if let (Some(speed), Some(direction)) = (wind.speed_mps, wind.direction_from_rad) {
1852                let vertical = match wind.vertical_speed_mps {
1853                    Some(value) => value,
1854                    None => {
1855                        assumptions.push(notice(
1856                            ASSUMPTION_DEFAULT_APPLIED,
1857                            "Constant vertical wind speed defaulted to 0 m/s.",
1858                            "$.wind.vertical_speed_mps",
1859                        ));
1860                        0.0
1861                    }
1862                };
1863                (speed, to_relative(direction), vertical)
1864            } else {
1865                assumptions.push(notice(
1866                    ASSUMPTION_DEFAULT_APPLIED,
1867                    "Wind defaulted to still air.",
1868                    "$.wind",
1869                ));
1870                (0.0, 0.0, 0.0)
1871            };
1872
1873        Ok((
1874            ResolvedWindV1::Constant(ResolvedConstantWindV1 {
1875                speed_mps,
1876                direction_from_rad,
1877                vertical_speed_mps,
1878                // MBA-1368: pure pass-through echo (Task 1 of the 0.33.0 decision-support
1879                // train) — the mode itself is not resolved to a literal default; only its
1880                // effect on `direction_from_rad` above is (see `to_relative`).
1881                wind_reference: wind.wind_reference,
1882            }),
1883            WindConditions {
1884                speed: speed_mps,
1885                direction: direction_from_rad,
1886                vertical_speed: vertical_speed_mps,
1887            },
1888            Vec::new(),
1889        ))
1890    }
1891}
1892
1893fn resolve_solver(
1894    solver: &SolverV1,
1895    assumptions: &mut Vec<SolveNoticeV1>,
1896    warnings: &mut Vec<SolveNoticeV1>,
1897) -> Result<ResolvedSolverV1, SolveErrorEnvelopeV1> {
1898    if let Some(value) = solver.time_step_s {
1899        require_positive("$.solver.time_step_s", value)?;
1900    }
1901    let method = match solver.method {
1902        Some(method) => method,
1903        None => {
1904            assumptions.push(notice(
1905                ASSUMPTION_DEFAULT_APPLIED,
1906                "Solver method defaulted to adaptive RK45.",
1907                "$.solver.method",
1908            ));
1909            SolverMethodV1::Rk45
1910        }
1911    };
1912    let time_step_s = literal_default(
1913        solver.time_step_s,
1914        DEFAULT_TIME_STEP_S,
1915        "$.solver.time_step_s",
1916        "Solver time step defaulted to 0.001 s.",
1917        assumptions,
1918    );
1919    if method == SolverMethodV1::Rk45 && solver.time_step_s.is_some() {
1920        warnings.push(notice(
1921            WARNING_RK45_TIME_STEP_IGNORED,
1922            "Adaptive RK45 owns its time step; the explicitly supplied fixed time step is retained in resolved_request but ignored by integration.",
1923            "$.solver.time_step_s",
1924        ));
1925    }
1926
1927    Ok(ResolvedSolverV1 {
1928        method,
1929        time_step_s,
1930    })
1931}
1932
1933fn resolve_effects(
1934    effects: &EffectsV1,
1935    latitude_rad: Option<f64>,
1936    geometry: SuppliedGeometry,
1937    assumptions: &mut Vec<SolveNoticeV1>,
1938    warnings: &mut Vec<SolveNoticeV1>,
1939) -> Result<ResolvedEffectsV1, SolveErrorEnvelopeV1> {
1940    let magnus = bool_default(
1941        effects.magnus,
1942        "$.effects.magnus",
1943        "Magnus effect defaulted to disabled.",
1944        assumptions,
1945    );
1946    let coriolis = bool_default(
1947        effects.coriolis,
1948        "$.effects.coriolis",
1949        "Coriolis effect defaulted to disabled.",
1950        assumptions,
1951    );
1952    let enhanced_spin_drift = bool_default(
1953        effects.enhanced_spin_drift,
1954        "$.effects.enhanced_spin_drift",
1955        "Enhanced spin drift defaulted to disabled.",
1956        assumptions,
1957    );
1958
1959    if magnus && enhanced_spin_drift {
1960        return Err(conflicting_fields(
1961            "$.effects",
1962            "magnus and enhanced_spin_drift cannot both be enabled",
1963        ));
1964    }
1965    if coriolis && latitude_rad.is_none() {
1966        return Err(invalid_value(
1967            "$.atmosphere.latitude_rad",
1968            "latitude_rad is required when the Coriolis effect is enabled",
1969        ));
1970    }
1971
1972    // Aerodynamic jump (MBA-959). Like `wind_shear_model` and unlike the three booleans
1973    // above, this is NOT run through `bool_default`: an omitted field pushes no assumption
1974    // notice and leaves the echo absent, so every request written before the field existed
1975    // still serializes byte-identically. `enabled_aerodynamic_jump` is what the solver acts
1976    // on; `aerodynamic_jump` is what the echo carries, and they differ precisely when the
1977    // caller said `false` out loud.
1978    let aerodynamic_jump = effects.aerodynamic_jump;
1979    let enabled_aerodynamic_jump = aerodynamic_jump.unwrap_or(false);
1980
1981    for (enabled, path, name) in [
1982        (magnus, "$.effects.magnus", "Magnus"),
1983        (
1984            enhanced_spin_drift,
1985            "$.effects.enhanced_spin_drift",
1986            "enhanced spin drift",
1987        ),
1988        (
1989            enabled_aerodynamic_jump,
1990            "$.effects.aerodynamic_jump",
1991            "aerodynamic jump",
1992        ),
1993    ] {
1994        if enabled {
1995            warnings.push(notice(
1996                WARNING_EXPERIMENTAL_EFFECT,
1997                format!("The {name} effect is an opt-in experimental v1 model."),
1998                path,
1999            ));
2000        }
2001    }
2002
2003    // MBA-1484. Magnus and enhanced spin drift are both functions of the spin the rifling
2004    // imparts, so an omitted twist does not leave either of them alone -- it solves them
2005    // against the assumed 1:12 barrel with the same confidence as a stated one. Emitted at the
2006    // flag that made the twist load-bearing, the way the aerodynamic-jump warning below is.
2007    //
2008    // The two flags are mutually exclusive here (the `conflicting_fields` check above returns
2009    // before this point), so the loop pushes at most one notice; it is written as a loop
2010    // anyway so that a future third spin-driven flag cannot quietly go unwarned.
2011    //
2012    // `summary.stability_factor` also reads the twist, on every solve rather than on a flag,
2013    // so it cannot be covered from here -- it is warned separately in `solve_v1` under
2014    // WARNING_STABILITY_FACTOR_ASSUMED_TWIST_RATE, gated on Sg having actually been reported.
2015    // The two codes both fire when a spin effect is enabled without a stated twist; they are
2016    // distinct so each names its own consumer, not because they are mutually exclusive.
2017    for (enabled, path, name) in [
2018        (magnus, "$.effects.magnus", "Magnus"),
2019        (
2020            enhanced_spin_drift,
2021            "$.effects.enhanced_spin_drift",
2022            "Enhanced spin drift",
2023        ),
2024    ] {
2025        if enabled && !geometry.twist_rate {
2026            warnings.push(notice(
2027                WARNING_SPIN_EFFECT_ASSUMED_TWIST_RATE,
2028                format!(
2029                    "{name} is computed from the spin the rifling imparts, but \
2030                     rifle.twist_rate_m_per_turn was not supplied. The effect is still \
2031                     applied, computed from the assumed 1:12 twist rather than disabled, so \
2032                     the result is for a barrel this request did not specify."
2033                ),
2034                path,
2035            ));
2036        }
2037    }
2038
2039    // Wind shear (0.36.0). Deliberately NOT run through `bool_default`/`literal_default`: an
2040    // omitted field pushes no assumption notice and leaves the echo absent, so every request
2041    // written before this field existed still serializes byte-identically -- the same
2042    // additive-echo contract as `atmosphere.pressure_reference` and `wind.wind_reference`.
2043    //
2044    // The name reaching the engine is always the canonical one, so an `"ekman"` request and
2045    // an `"ekman_spiral"` request resolve to a single spelling in the echo. Unknown names
2046    // never arrive here: `decode_solve_request_v1` refuses them at
2047    // `$.effects.wind_shear_model`, and the typed enum makes them unrepresentable for a
2048    // caller that builds the DTO in Rust.
2049    let wind_shear_model = effects.wind_shear_model;
2050    if wind_shear_model == Some(WindShearModelV1::EkmanSpiral) {
2051        // Not silence: `cli_api`'s boundary-layer evaluator scales the operative wind by a
2052        // height ratio, and it has no near-ground closed form for the Ekman spiral, so the
2053        // ratio is 1.0 and the solve matches an unsheared one. Say so in the response
2054        // instead of letting a caller read "ekman_spiral applied" off the echo and believe
2055        // the numbers moved.
2056        warnings.push(notice(
2057            WARNING_WIND_SHEAR_MODEL_NOT_MODELED,
2058            "The ekman_spiral wind shear model has no near-ground profile on this solve path; \
2059             the wind is left at the operative value, so the result matches an unsheared solve.",
2060            "$.effects.wind_shear_model",
2061        ));
2062    }
2063
2064    // The jump is a function of stability and bullet length, so a defaulted barrel does not
2065    // leave it alone -- it computes a different answer with the same confidence. Say so at the
2066    // flag that made the geometry load-bearing, naming whichever field is missing.
2067    if enabled_aerodynamic_jump && !(geometry.twist_rate && geometry.projectile_length) {
2068        let missing = match (geometry.twist_rate, geometry.projectile_length) {
2069            (false, false) => "rifle.twist_rate_m_per_turn and projectile.length_m were",
2070            (false, true) => "rifle.twist_rate_m_per_turn was",
2071            (true, false) => "projectile.length_m was",
2072            (true, true) => unreachable!("guarded by the condition above"),
2073        };
2074        warnings.push(notice(
2075            WARNING_AERODYNAMIC_JUMP_ASSUMED_GEOMETRY,
2076            format!(
2077                "Aerodynamic jump scales with gyroscopic stability and bullet length, but \
2078                 {missing} not supplied. The correction is still applied, computed from the \
2079                 assumed geometry rather than disabled, so the jump reported in \
2080                 summary.aerodynamic_jump_moa is for a barrel this request did not specify."
2081            ),
2082            "$.effects.aerodynamic_jump",
2083        ));
2084    }
2085
2086    Ok(ResolvedEffectsV1 {
2087        magnus,
2088        coriolis,
2089        enhanced_spin_drift,
2090        wind_shear_model,
2091        aerodynamic_jump,
2092    })
2093}
2094
2095fn resolve_sampling(
2096    sampling: &SamplingV1,
2097    assumptions: &mut Vec<SolveNoticeV1>,
2098) -> Result<ResolvedSamplingV1, SolveErrorEnvelopeV1> {
2099    if let Some(value) = sampling.interval_m {
2100        require_positive("$.sampling.interval_m", value)?;
2101    }
2102    let interval_m = literal_default(
2103        sampling.interval_m,
2104        DEFAULT_SAMPLE_INTERVAL_M,
2105        "$.sampling.interval_m",
2106        "Sampling interval defaulted to 10 m.",
2107        assumptions,
2108    );
2109    Ok(ResolvedSamplingV1 { interval_m })
2110}
2111
2112fn maximum_world_height_m(
2113    result: &crate::TrajectoryResult,
2114    shooting_angle_rad: f64,
2115) -> Result<f64, SolveErrorEnvelopeV1> {
2116    let mut maximum = f64::NEG_INFINITY;
2117    for point in &result.points {
2118        let height = crate::atmosphere::shot_frame_altitude(
2119            0.0,
2120            point.position.x,
2121            point.position.y,
2122            shooting_angle_rad,
2123        );
2124        if !height.is_finite() {
2125            return Err(internal_error(
2126                "world-vertical maximum-height projection produced a non-finite value",
2127            ));
2128        }
2129        maximum = maximum.max(height);
2130    }
2131    if maximum.is_finite() {
2132        Ok(maximum)
2133    } else {
2134        Err(internal_error(
2135            "trajectory contained no finite points for maximum-height calculation",
2136        ))
2137    }
2138}
2139
2140fn observation_to_wire(observation: TrajectoryObservation) -> TrajectorySampleV1 {
2141    TrajectorySampleV1 {
2142        distance_m: observation.distance_m,
2143        time_s: observation.time_s,
2144        speed_mps: observation.speed_mps,
2145        energy_j: observation.energy_j,
2146        drop_m: observation.drop_m,
2147        windage_m: observation.windage_m,
2148        mach: observation.mach,
2149        flags: observation
2150            .flags
2151            .into_iter()
2152            .map(observation_flag_to_wire)
2153            .collect(),
2154    }
2155}
2156
2157fn observation_flag_to_wire(flag: TrajectoryObservationFlag) -> SampleFlagV1 {
2158    match flag {
2159        TrajectoryObservationFlag::Transonic => SampleFlagV1::Transonic,
2160        TrajectoryObservationFlag::Subsonic => SampleFlagV1::Subsonic,
2161        TrajectoryObservationFlag::Terminal => SampleFlagV1::Terminal,
2162        TrajectoryObservationFlag::GroundThreshold => SampleFlagV1::GroundThreshold,
2163    }
2164}
2165
2166fn termination_to_wire(termination: TrajectoryTermination) -> TerminationReasonV1 {
2167    match termination {
2168        TrajectoryTermination::MaxRange => TerminationReasonV1::MaxRange,
2169        TrajectoryTermination::GroundThreshold => TerminationReasonV1::GroundThreshold,
2170        TrajectoryTermination::TimeLimit => TerminationReasonV1::TimeLimit,
2171        TrajectoryTermination::VelocityFloor => TerminationReasonV1::VelocityFloor,
2172    }
2173}
2174
2175fn drag_model_to_engine(model: DragModelV1) -> DragModel {
2176    match model {
2177        DragModelV1::G1 => DragModel::G1,
2178        DragModelV1::G2 => DragModel::G2,
2179        DragModelV1::G5 => DragModel::G5,
2180        DragModelV1::G6 => DragModel::G6,
2181        DragModelV1::G7 => DragModel::G7,
2182        DragModelV1::G8 => DragModel::G8,
2183        DragModelV1::GI => DragModel::GI,
2184        DragModelV1::GS => DragModel::GS,
2185        DragModelV1::RA4 => DragModel::RA4,
2186    }
2187}
2188
2189fn map_observation_error(error: TrajectoryObservationError) -> SolveErrorEnvelopeV1 {
2190    let message = error.to_string();
2191    match error {
2192        TrajectoryObservationError::SampleLimitExceeded { .. }
2193        | TrajectoryObservationError::AllocationFailed { .. } => error_at(
2194            SolveErrorCodeV1::ResourceLimit,
2195            message,
2196            "$.sampling.interval_m",
2197        ),
2198        TrajectoryObservationError::InvalidInterval { .. }
2199        | TrajectoryObservationError::UnrepresentableGrid { .. } => error_at(
2200            SolveErrorCodeV1::InvalidValue,
2201            message,
2202            "$.sampling.interval_m",
2203        ),
2204        // MBA-1599: a trajectory that really moves back toward the muzzle (a headwind carrying a
2205        // stalled projectile back, a launch past vertical, or an explicit-Euler/RK4 step too
2206        // coarse for the drag) cannot be reported against downrange distance. That is a failed
2207        // solve, the code the engine already returns when such a reversal lasts until
2208        // termination. Equal distances stay internal_error below: the engine collapses a
2209        // downrange stall, so a repeated distance would be a broken engine invariant.
2210        TrajectoryObservationError::NonMonotonicTrajectory {
2211            previous_distance_m,
2212            distance_m,
2213            ..
2214        } if distance_m < previous_distance_m => solve_failed_message(format!(
2215            "the projectile moved back toward the muzzle ({previous_distance_m} m then \
2216             {distance_m} m downrange) before reaching a termination boundary, so the \
2217             trajectory cannot be reported against downrange distance"
2218        )),
2219        TrajectoryObservationError::EmptyTrajectory
2220        | TrajectoryObservationError::NonFiniteQuery { .. }
2221        | TrajectoryObservationError::OutOfRange { .. }
2222        | TrajectoryObservationError::NonMonotonicTrajectory { .. }
2223        | TrajectoryObservationError::NonFiniteState { .. }
2224        | TrajectoryObservationError::InvalidState { .. }
2225        | TrajectoryObservationError::InvalidMetadata { .. }
2226        | TrajectoryObservationError::NonFiniteObservation { .. } => internal_error(message),
2227    }
2228}
2229
2230/// Evaluate a request's reticle hold against the already-sampled trajectory (MBA-1361).
2231///
2232/// The angular drop/windage come from the SAME samples the response reports, linearly
2233/// interpolated at `range_m`, so the hold and the sample rows can never describe different
2234/// trajectories. Angles use the milliradian small-angle definition (1 mil subtends 1/1000
2235/// of the range) — the same conversion every other surface uses.
2236///
2237/// A range outside the sampled span is a structured [`SolveErrorCodeV1::InvalidValue`], not
2238/// a clamp or an extrapolation: a hold read off a trajectory that never got there is a
2239/// fabricated number.
2240fn resolve_reticle_hold(
2241    request: &crate::solve_json::ReticleRequestV1,
2242    samples: &[TrajectorySampleV1],
2243) -> Result<crate::solve_json::ReticleHoldV1, SolveErrorEnvelopeV1> {
2244    use crate::reticle::hold_point_in_reticle;
2245
2246    let path = "$.reticle.range_m";
2247    let range_m = request.range_m;
2248    if !range_m.is_finite() || range_m <= 0.0 {
2249        return Err(invalid_value(
2250            path,
2251            "reticle.range_m must be finite and greater than zero",
2252        ));
2253    }
2254
2255    let (lo, t) = match bracket_param(samples.len(), |i| samples[i].distance_m, range_m) {
2256        Bracket::Inside { lo, t } => (lo, t),
2257        Bracket::Degenerate => {
2258            return Err(internal_error(
2259                "trajectory sampling produced no points to read a reticle hold from",
2260            ));
2261        }
2262        Bracket::Below | Bracket::Above => {
2263            // `Degenerate` (len < 2) was already handled above, so at least two samples exist.
2264            let first = &samples[0];
2265            let last = &samples[samples.len() - 1];
2266            return Err(invalid_value(
2267                path,
2268                format!(
2269                    "reticle.range_m {range_m} is outside the sampled trajectory ({} to {} m)",
2270                    first.distance_m, last.distance_m
2271                ),
2272            ));
2273        }
2274    };
2275    let hi = lo + 1;
2276    let lerp = |a: f64, b: f64| a + (b - a) * t;
2277    let drop_mil = lerp(samples[lo].drop_m, samples[hi].drop_m) / range_m * 1000.0;
2278    let wind_mil = lerp(samples[lo].windage_m, samples[hi].windage_m) / range_m * 1000.0;
2279
2280    let hold = hold_point_in_reticle(
2281        drop_mil,
2282        wind_mil,
2283        request.magnification,
2284        &request.description,
2285    )
2286    .map_err(|e| invalid_value("$.reticle", e.to_string()))?;
2287
2288    let nearest = hold
2289        .nearest_mark
2290        .and_then(|index| request.description.marks.get(index));
2291    Ok(crate::solve_json::ReticleHoldV1 {
2292        range_m,
2293        magnification: request.magnification,
2294        down_mil: hold.down_mil,
2295        right_mil: hold.right_mil,
2296        mark_scale: hold.mark_scale,
2297        nearest_mark_index: hold.nearest_mark,
2298        nearest_mark_label: nearest.and_then(|mark| mark.label.clone()),
2299        nearest_mark_distance_mil: hold.nearest_mark_distance_mil,
2300        off_reticle: hold.off_reticle,
2301    })
2302}
2303
2304// `pub(crate)` (0.33.0 decision-support Task 6, I3 review fix): the perturbation kernel's
2305// `evaluate` calls `TrajectorySolver::solve` itself (see `build_zeroed_solver` above) and needs
2306// the identical `BallisticsError` -> `SolveErrorEnvelopeV1` conversion `solve_v1` uses for the
2307// same call, so both report a solve failure in the same shape.
2308pub(crate) fn solve_failed(error: BallisticsError) -> SolveErrorEnvelopeV1 {
2309    // Air that cannot exist aloft is a refusal of the station temperature that only the flight
2310    // can find (the lapse from it reaches absolute zero at a height the flight gets to): the wire
2311    // locates it at the temperature, in kelvin, as it does every other refusal of the air.
2312    if let Some(refusal) = error.atmosphere_error().filter(|refusal| {
2313        refusal.reason() == crate::atmosphere::AtmosphereErrorReason::AirAloftBelowAbsoluteZero
2314    }) {
2315        return invalid_value(
2316            "$.atmosphere.temperature_k",
2317            format!(
2318                "temperature_k = {}: {}",
2319                crate::atmosphere::reading_text(refusal.value() + KELVIN_OFFSET_C, "K"),
2320                refusal.explanation()
2321            ),
2322        );
2323    }
2324    solve_failed_message(error.to_string())
2325}
2326
2327fn solve_failed_message(message: impl Into<String>) -> SolveErrorEnvelopeV1 {
2328    SolveErrorEnvelopeV1::new(SolveErrorV1::new(SolveErrorCodeV1::SolveFailed, message))
2329}
2330
2331fn internal_error(message: impl Into<String>) -> SolveErrorEnvelopeV1 {
2332    SolveErrorEnvelopeV1::new(SolveErrorV1::new(SolveErrorCodeV1::InternalError, message))
2333}
2334
2335fn invalid_value(path: impl Into<String>, message: impl Into<String>) -> SolveErrorEnvelopeV1 {
2336    error_at(SolveErrorCodeV1::InvalidValue, message, path)
2337}
2338
2339fn conflicting_fields(path: impl Into<String>, message: impl Into<String>) -> SolveErrorEnvelopeV1 {
2340    error_at(SolveErrorCodeV1::ConflictingFields, message, path)
2341}
2342
2343fn error_at(
2344    code: SolveErrorCodeV1,
2345    message: impl Into<String>,
2346    path: impl Into<String>,
2347) -> SolveErrorEnvelopeV1 {
2348    SolveErrorEnvelopeV1::new(SolveErrorV1::new(code, message).at_path(path))
2349}
2350
2351fn notice(
2352    code: impl Into<String>,
2353    message: impl Into<String>,
2354    path: impl Into<String>,
2355) -> SolveNoticeV1 {
2356    SolveNoticeV1 {
2357        code: code.into(),
2358        message: message.into(),
2359        path: Some(path.into()),
2360    }
2361}
2362
2363fn literal_default(
2364    value: Option<f64>,
2365    default: f64,
2366    path: &'static str,
2367    message: impl Into<String>,
2368    assumptions: &mut Vec<SolveNoticeV1>,
2369) -> f64 {
2370    match value {
2371        Some(value) => value,
2372        None => {
2373            assumptions.push(notice(ASSUMPTION_DEFAULT_APPLIED, message, path));
2374            default
2375        }
2376    }
2377}
2378
2379fn bool_default(
2380    value: Option<bool>,
2381    path: &'static str,
2382    message: &'static str,
2383    assumptions: &mut Vec<SolveNoticeV1>,
2384) -> bool {
2385    match value {
2386        Some(value) => value,
2387        None => {
2388            assumptions.push(notice(ASSUMPTION_DEFAULT_APPLIED, message, path));
2389            false
2390        }
2391    }
2392}
2393
2394fn checked_conversion(value: f64, path: &str, message: &str) -> Result<f64, SolveErrorEnvelopeV1> {
2395    if value.is_finite() {
2396        Ok(value)
2397    } else {
2398        Err(invalid_value(path, message))
2399    }
2400}
2401
2402fn require_finite(path: &str, value: f64) -> Result<(), SolveErrorEnvelopeV1> {
2403    if value.is_finite() {
2404        Ok(())
2405    } else {
2406        Err(invalid_value(path, "value must be finite"))
2407    }
2408}
2409
2410fn require_positive(path: &str, value: f64) -> Result<(), SolveErrorEnvelopeV1> {
2411    if value.is_finite() && value > 0.0 {
2412        Ok(())
2413    } else {
2414        Err(invalid_value(
2415            path,
2416            "value must be finite and greater than zero",
2417        ))
2418    }
2419}
2420
2421fn require_non_negative(path: &str, value: f64) -> Result<(), SolveErrorEnvelopeV1> {
2422    if value.is_finite() && value >= 0.0 {
2423        Ok(())
2424    } else {
2425        Err(invalid_value(path, "value must be finite and non-negative"))
2426    }
2427}
2428
2429fn require_range(
2430    path: &str,
2431    value: f64,
2432    minimum: f64,
2433    maximum: f64,
2434) -> Result<(), SolveErrorEnvelopeV1> {
2435    if value.is_finite() && (minimum..=maximum).contains(&value) {
2436        Ok(())
2437    } else {
2438        Err(invalid_value(
2439            path,
2440            format!("value must be finite and in the inclusive range [{minimum}, {maximum}]"),
2441        ))
2442    }
2443}
2444
2445#[cfg(test)]
2446mod tests {
2447    use super::*;
2448
2449    fn minimal_request() -> SolveRequestV1 {
2450        SolveRequestV1 {
2451            schema_version: SchemaVersionV1,
2452            projectile: ProjectileV1 {
2453                mass_kg: 0.01134,
2454                diameter_m: 0.00782,
2455                length_m: None,
2456                drag_model: DragModelV1::G7,
2457                ballistic_coefficient: 0.243,
2458                drag_table: None,
2459                bc_segments: None,
2460            },
2461            rifle: RifleV1 {
2462                muzzle_velocity_mps: 823.0,
2463                sight_height_m: None,
2464                muzzle_height_m: None,
2465                twist_rate_m_per_turn: None,
2466                twist_direction: None,
2467                sight_offset_lateral_m: None,
2468            },
2469            shot: ShotV1 {
2470                max_range_m: 1_000.0,
2471                zero_distance_m: None,
2472                muzzle_angle_rad: None,
2473                aim_azimuth_rad: None,
2474                shot_azimuth_rad: None,
2475                shooting_angle_rad: None,
2476                cant_angle_rad: None,
2477                target_height_m: None,
2478                ground_threshold_m: None,
2479                zero_poi_up_m: None,
2480                zero_poi_right_m: None,
2481                drops_reference: None,
2482            },
2483            atmosphere: AtmosphereV1::default(),
2484            wind: WindV1::default(),
2485            solver: SolverV1::default(),
2486            effects: EffectsV1::default(),
2487            sampling: SamplingV1::default(),
2488            reticle: None,
2489            corrections: None,
2490        }
2491    }
2492
2493    #[test]
2494    fn defaults_are_resolved_in_deterministic_request_field_order() {
2495        let request = minimal_request();
2496        let prepared = prepare_request(&request).expect("valid request");
2497        let code_paths = prepared
2498            .assumptions
2499            .iter()
2500            .map(|notice| (notice.code.as_str(), notice.path.as_deref().unwrap()))
2501            .collect::<Vec<_>>();
2502
2503        assert_eq!(
2504            code_paths,
2505            vec![
2506                (
2507                    ASSUMPTION_ESTIMATED_PROJECTILE_LENGTH,
2508                    "$.projectile.length_m"
2509                ),
2510                (ASSUMPTION_DEFAULT_APPLIED, "$.rifle.sight_height_m"),
2511                (ASSUMPTION_DEFAULT_APPLIED, "$.rifle.muzzle_height_m"),
2512                (ASSUMPTION_DEFAULT_APPLIED, "$.rifle.twist_rate_m_per_turn"),
2513                (ASSUMPTION_DEFAULT_APPLIED, "$.rifle.twist_direction"),
2514                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.muzzle_angle_rad"),
2515                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.aim_azimuth_rad"),
2516                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.shot_azimuth_rad"),
2517                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.shooting_angle_rad"),
2518                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.cant_angle_rad"),
2519                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.target_height_m"),
2520                (ASSUMPTION_DEFAULT_APPLIED, "$.shot.ground_threshold_m"),
2521                (ASSUMPTION_DEFAULT_APPLIED, "$.atmosphere.altitude_m"),
2522                (
2523                    ASSUMPTION_ICAO_STANDARD_TEMPERATURE,
2524                    "$.atmosphere.temperature_k"
2525                ),
2526                (
2527                    ASSUMPTION_ICAO_STANDARD_PRESSURE,
2528                    "$.atmosphere.pressure_pa"
2529                ),
2530                (ASSUMPTION_DEFAULT_APPLIED, "$.atmosphere.relative_humidity"),
2531                (ASSUMPTION_DEFAULT_APPLIED, "$.wind"),
2532                (ASSUMPTION_DEFAULT_APPLIED, "$.solver.method"),
2533                (ASSUMPTION_DEFAULT_APPLIED, "$.solver.time_step_s"),
2534                (ASSUMPTION_DEFAULT_APPLIED, "$.effects.magnus"),
2535                (ASSUMPTION_DEFAULT_APPLIED, "$.effects.coriolis"),
2536                (ASSUMPTION_DEFAULT_APPLIED, "$.effects.enhanced_spin_drift"),
2537                (ASSUMPTION_DEFAULT_APPLIED, "$.sampling.interval_m"),
2538            ]
2539        );
2540        assert_eq!(
2541            prepared.resolved_request.rifle.twist_rate_m_per_turn,
2542            0.3048
2543        );
2544        assert!((prepared.inputs.twist_rate - 12.0).abs() < 1.0e-12);
2545        assert_eq!(prepared.atmosphere.humidity, 50.0);
2546        assert_eq!(prepared.inputs.humidity_percent, 50.0);
2547    }
2548
2549    /// An omitted `$.atmosphere.relative_humidity` is the one default,
2550    /// `RelativeHumidity::DEFAULT`, in the wire's unit; the resolved echo, the percent that flies
2551    /// and the notice all state that value. The notice names the unit too, the fraction with its
2552    /// percent, because a bare 0.5 is exactly the number a reader cannot tell from 0.5 %. Its code
2553    /// and path keep their 0.49.0 bytes (the apps key on the path).
2554    #[test]
2555    fn an_omitted_relative_humidity_is_the_one_default_and_its_notice_says_so() {
2556        let prepared = prepare_request(&minimal_request()).expect("valid request");
2557        let resolved = prepared.resolved_request.atmosphere.relative_humidity;
2558        assert_eq!(
2559            resolved.to_bits(),
2560            RelativeHumidity::DEFAULT.fraction().to_bits()
2561        );
2562        assert_eq!(resolved.to_bits(), 0.5_f64.to_bits());
2563        assert_eq!(
2564            prepared.atmosphere.humidity.to_bits(),
2565            crate::atmosphere::DEFAULT_HUMIDITY_PERCENT.to_bits()
2566        );
2567        assert_eq!(
2568            prepared.inputs.humidity_percent.to_bits(),
2569            crate::atmosphere::DEFAULT_HUMIDITY_PERCENT.to_bits()
2570        );
2571        let notices = prepared
2572            .assumptions
2573            .iter()
2574            .filter(|notice| notice.path.as_deref() == Some("$.atmosphere.relative_humidity"))
2575            .collect::<Vec<_>>();
2576        assert_eq!(notices.len(), 1, "{notices:?}");
2577        assert_eq!(notices[0].code, ASSUMPTION_DEFAULT_APPLIED);
2578        assert_eq!(
2579            notices[0].message,
2580            "Relative humidity defaulted to 0.5 (50%)."
2581        );
2582        assert_eq!(
2583            notices[0].message,
2584            format!(
2585                "Relative humidity defaulted to {} ({}%).",
2586                RelativeHumidity::DEFAULT.fraction(),
2587                RelativeHumidity::DEFAULT.percent()
2588            )
2589        );
2590    }
2591
2592    #[test]
2593    fn explicit_standard_station_values_at_altitude_remain_authoritative() {
2594        let mut request = minimal_request();
2595        request.atmosphere.altitude_m = Some(1_500.0);
2596        request.atmosphere.temperature_k = Some(288.15);
2597        request.atmosphere.pressure_pa = Some(101_325.0);
2598
2599        let prepared = prepare_request(&request).expect("valid explicit station conditions");
2600        assert_eq!(prepared.atmosphere.temperature, 15.0);
2601        assert_eq!(prepared.atmosphere.pressure, 1013.25);
2602        assert_eq!(prepared.resolved_request.atmosphere.temperature_k, 288.15);
2603        assert_eq!(prepared.resolved_request.atmosphere.pressure_pa, 101_325.0);
2604        assert!(!prepared
2605            .assumptions
2606            .iter()
2607            .any(|notice| notice.code == ASSUMPTION_ICAO_STANDARD_TEMPERATURE
2608                || notice.code == ASSUMPTION_ICAO_STANDARD_PRESSURE));
2609    }
2610
2611    /// MBA-1397: `pressure_reference: "qnh"` reduces an explicit pressure to station pressure
2612    /// and records the reduction as an assumption instead of treating it as authoritative
2613    /// as-is.
2614    #[test]
2615    fn qnh_pressure_reference_reduces_to_station_pressure_and_is_noted() {
2616        let mut request = minimal_request();
2617        request.atmosphere.altitude_m = Some(1_500.0);
2618        request.atmosphere.pressure_pa = Some(103_000.0); // 1030.0 hPa QNH
2619        request.atmosphere.pressure_reference = Some(PressureReferenceV1::Qnh);
2620
2621        let prepared = prepare_request(&request).expect("valid QNH request");
2622        let expected_station_hpa =
2623            crate::atmosphere::reduce_qnh_to_station_pressure(1030.0, 1_500.0);
2624        assert!((prepared.atmosphere.pressure - expected_station_hpa).abs() < 1e-9);
2625        assert!(
2626            (prepared.resolved_request.atmosphere.pressure_pa - expected_station_hpa * 100.0).abs()
2627                < 1e-6
2628        );
2629        // Strictly lower than the raw QNH -- proves the reduction actually happened.
2630        assert!(prepared.resolved_request.atmosphere.pressure_pa < 103_000.0);
2631
2632        assert!(prepared.assumptions.iter().any(|notice| notice.code
2633            == ASSUMPTION_QNH_REDUCED_TO_STATION_PRESSURE
2634            && notice.path.as_deref() == Some("$.atmosphere.pressure_pa")));
2635        // Must NOT also emit the omitted-pressure notice: this is a present, explicit value.
2636        assert!(!prepared
2637            .assumptions
2638            .iter()
2639            .any(|notice| notice.code == ASSUMPTION_ICAO_STANDARD_PRESSURE));
2640    }
2641
2642    /// MBA-1605: the QNH notice names the reduction the engine actually runs. Before 0.49.0 it
2643    /// said "the ICAO inverse-barometric formula", the ratio form MBA-1605 replaced.
2644    #[test]
2645    fn qnh_notice_names_the_altimeter_setting_relation() {
2646        let mut request = minimal_request();
2647        request.atmosphere.altitude_m = Some(1_500.0);
2648        request.atmosphere.pressure_pa = Some(103_000.0);
2649        request.atmosphere.pressure_reference = Some(PressureReferenceV1::Qnh);
2650
2651        let prepared = prepare_request(&request).expect("valid QNH request");
2652        let notice = prepared
2653            .assumptions
2654            .iter()
2655            .find(|notice| notice.code == ASSUMPTION_QNH_REDUCED_TO_STATION_PRESSURE)
2656            .expect("QNH notice");
2657        assert!(
2658            notice.message.contains("altimeter-setting relation"),
2659            "{}",
2660            notice.message
2661        );
2662        assert!(
2663            !notice.message.contains("inverse-barometric"),
2664            "{}",
2665            notice.message
2666        );
2667    }
2668
2669    /// MBA-1605: a QNH with no station pressure at the requested altitude (the altimeter-setting
2670    /// relation goes NaN once the setting's pressure altitude plus the station height reaches
2671    /// 44,331 m) is refused as an invalid value, never flown as near-vacuum air. A 500 hPa QNH is
2672    /// itself a pressure inside the troposphere, so the one rule blames the altitude it was
2673    /// reduced to (`atmosphere.density_altitude` always did, and the solve blamed
2674    /// `pressure_pa`); one that is not (hPa sent as pascals) is the pressure's fault. Both
2675    /// commands refuse it identically, code, path and message.
2676    #[test]
2677    fn qnh_with_no_station_pressure_at_altitude_is_refused() {
2678        for (qnh_pa, path) in [
2679            (50_000.0, "$.atmosphere.altitude_m"), // 500 hPa QNH at 40 km
2680            (1e-300, "$.atmosphere.pressure_pa"),  // no plausible QNH at all
2681        ] {
2682            let mut request = minimal_request();
2683            request.atmosphere.altitude_m = Some(40_000.0);
2684            request.atmosphere.pressure_pa = Some(qnh_pa);
2685            request.atmosphere.pressure_reference = Some(PressureReferenceV1::Qnh);
2686
2687            let error = prepare_request(&request).expect_err("no station pressure exists");
2688            assert_eq!(error.error.code, SolveErrorCodeV1::InvalidValue);
2689            assert_eq!(error.error.path(), Some(path), "{}", error.error.message);
2690            assert!(
2691                error
2692                    .error
2693                    .message
2694                    .contains("leaves no station pressure at 40000 m"),
2695                "{}",
2696                error.error.message
2697            );
2698            let density_altitude = crate::atmosphere_service::density_altitude_v1(
2699                &crate::atmosphere_service::DensityAltitudeRequestV1 {
2700                    atmosphere: request.atmosphere.clone(),
2701                },
2702            )
2703            .expect_err("no station pressure exists");
2704            assert_eq!(density_altitude.error, error.error);
2705        }
2706    }
2707
2708    /// `pressure_reference: "qnh"` with `pressure_pa` OMITTED must be byte-identical to the
2709    /// absolute default: an omitted pressure always resolves to the ICAO standard station
2710    /// pressure regardless of the declared reference (mathematically the same result as
2711    /// reducing a QNH of exactly the ICAO sea-level standard).
2712    #[test]
2713    fn qnh_pressure_reference_with_omitted_pressure_matches_absolute_default() {
2714        let mut request = minimal_request();
2715        request.atmosphere.altitude_m = Some(1_500.0);
2716        request.atmosphere.pressure_reference = Some(PressureReferenceV1::Qnh);
2717
2718        let prepared = prepare_request(&request).expect("valid request");
2719
2720        let mut absolute_request = minimal_request();
2721        absolute_request.atmosphere.altitude_m = Some(1_500.0);
2722        let absolute_prepared = prepare_request(&absolute_request).expect("valid request");
2723
2724        assert_eq!(
2725            prepared.resolved_request.atmosphere.pressure_pa,
2726            absolute_prepared.resolved_request.atmosphere.pressure_pa
2727        );
2728        assert!(prepared
2729            .assumptions
2730            .iter()
2731            .any(|notice| notice.code == ASSUMPTION_ICAO_STANDARD_PRESSURE));
2732        assert!(!prepared
2733            .assumptions
2734            .iter()
2735            .any(|notice| notice.code == ASSUMPTION_QNH_REDUCED_TO_STATION_PRESSURE));
2736    }
2737
2738    /// `pressure_reference` absent entirely (every request before MBA-1397) must be
2739    /// byte-identical to `Some(Absolute)` -- the default variant is a pure passthrough.
2740    #[test]
2741    fn absent_pressure_reference_matches_explicit_absolute() {
2742        let mut request = minimal_request();
2743        request.atmosphere.altitude_m = Some(1_500.0);
2744        request.atmosphere.pressure_pa = Some(90_000.0);
2745
2746        let mut explicit_absolute = request.clone();
2747        explicit_absolute.atmosphere.pressure_reference = Some(PressureReferenceV1::Absolute);
2748
2749        let prepared = prepare_request(&request).expect("valid request");
2750        let prepared_explicit = prepare_request(&explicit_absolute).expect("valid request");
2751        assert_eq!(
2752            prepared.resolved_request.atmosphere.pressure_pa,
2753            prepared_explicit.resolved_request.atmosphere.pressure_pa
2754        );
2755        assert_eq!(prepared.resolved_request.atmosphere.pressure_pa, 90_000.0);
2756    }
2757
2758    #[test]
2759    fn partial_segmented_wind_maps_units_and_warns_without_extending_coverage() {
2760        let mut request = minimal_request();
2761        request.wind.segments = Some(vec![crate::solve_json::WindSegmentV1 {
2762            until_distance_m: 300.0,
2763            speed_mps: 5.0,
2764            direction_from_rad: std::f64::consts::FRAC_PI_2,
2765            vertical_speed_mps: None,
2766        }]);
2767
2768        let prepared = prepare_request(&request).expect("partial wind is valid");
2769        assert_eq!(prepared.wind_segments.len(), 1);
2770        assert_eq!(prepared.wind_segments[0].speed_kmh, 18.0);
2771        assert_eq!(prepared.wind_segments[0].angle_deg, 90.0);
2772        assert_eq!(prepared.wind_segments[0].until_m, 300.0);
2773        assert_eq!(prepared.wind_segments[0].vertical_mps, 0.0);
2774        assert!(prepared.warnings.iter().any(|notice| {
2775            notice.code == WARNING_PARTIAL_WIND_COVERAGE
2776                && notice.path.as_deref() == Some("$.wind.segments")
2777        }));
2778        assert!(matches!(
2779            prepared.resolved_request.wind,
2780            ResolvedWindV1::Segmented(_)
2781        ));
2782    }
2783
2784    #[test]
2785    fn partial_wind_coverage_includes_a_zero_beyond_the_output_range() {
2786        let mut request = minimal_request();
2787        request.shot.max_range_m = 200.0;
2788        request.shot.zero_distance_m = Some(500.0);
2789        request.wind.segments = Some(vec![crate::solve_json::WindSegmentV1 {
2790            until_distance_m: 300.0,
2791            speed_mps: 5.0,
2792            direction_from_rad: 0.0,
2793            vertical_speed_mps: Some(0.0),
2794        }]);
2795
2796        let prepared = prepare_request(&request).expect("partial zero wind is valid");
2797        assert!(prepared.warnings.iter().any(|notice| {
2798            notice.code == WARNING_PARTIAL_WIND_COVERAGE
2799                && notice.path.as_deref() == Some("$.wind.segments")
2800                && notice.message.contains("500.000000000000 m")
2801        }));
2802    }
2803
2804    /// 0.33.0 decision-support Task 2: supplying both no longer conflicts. An explicit
2805    /// muzzle_angle_rad always wins (no zero search runs to derive it), while
2806    /// zero_distance_m is retained purely as the caller's original zeroing intent. This is
2807    /// exactly what `From<&ResolvedSolveRequestV1> for SolveRequestV1`
2808    /// (request_roundtrip.rs) produces for a zeroed solve, so a request rebuilt from a
2809    /// resolved request can reuse the exact original angle instead of silently re-zeroing.
2810    #[test]
2811    fn explicit_muzzle_angle_wins_over_zero_distance_when_both_are_supplied() {
2812        let mut request = minimal_request();
2813        request.shot.zero_distance_m = Some(100.0);
2814        request.shot.muzzle_angle_rad = Some(0.01);
2815        let prepared =
2816            prepare_request(&request).expect("both fields together are no longer a conflict");
2817        assert_eq!(prepared.resolved_request.shot.muzzle_angle_rad, 0.01);
2818        assert_eq!(prepared.resolved_request.shot.zero_distance_m, Some(100.0));
2819        // S5 (0.33.0 final-review fix wave): the elevation search did not run -- a caller must
2820        // be told so, not left to assume the echoed zero_distance_m confirms a zero was
2821        // actually solved for it.
2822        assert!(
2823            prepared.warnings.iter().any(|notice| {
2824                notice.code == WARNING_ZERO_DISTANCE_ELEVATION_NOT_RESOLVED
2825                    && notice.path.as_deref() == Some("$.shot.zero_distance_m")
2826            }),
2827            "expected a {WARNING_ZERO_DISTANCE_ELEVATION_NOT_RESOLVED} warning naming \
2828             $.shot.zero_distance_m; got {:?}",
2829            prepared.warnings
2830        );
2831    }
2832
2833    #[test]
2834    fn semantic_conflicts_and_invalid_values_keep_exact_paths() {
2835        // The sensor band (owner decision 2026-11-01): 1.01 is a sensor reading of saturated air,
2836        // within 0.05 of the range, so it resolves to exactly 1 and flies as 100 %.
2837        let mut request = minimal_request();
2838        request.atmosphere.relative_humidity = Some(1.01);
2839        let prepared = prepare_request(&request).expect("a reading within 0.05 of one");
2840        assert_eq!(
2841            prepared
2842                .resolved_request
2843                .atmosphere
2844                .relative_humidity
2845                .to_bits(),
2846            1.0_f64.to_bits()
2847        );
2848        assert_eq!(
2849            prepared.inputs.humidity_percent.to_bits(),
2850            100.0_f64.to_bits()
2851        );
2852        // Beyond the band it is refused, with the same path and code as before.
2853        let mut request = minimal_request();
2854        request.atmosphere.relative_humidity = Some(1.06);
2855        let error = prepare_request(&request).expect_err("humidity above the band");
2856        assert_eq!(error.error.code, SolveErrorCodeV1::InvalidValue);
2857        assert_eq!(error.error.path(), Some("$.atmosphere.relative_humidity"));
2858
2859        let mut request = minimal_request();
2860        request.effects.coriolis = Some(true);
2861        let error = prepare_request(&request).expect_err("Coriolis needs latitude");
2862        assert_eq!(error.error.code, SolveErrorCodeV1::InvalidValue);
2863        assert_eq!(error.error.path(), Some("$.atmosphere.latitude_rad"));
2864
2865        let mut request = minimal_request();
2866        request.shot.zero_distance_m = Some(f64::MAX);
2867        let error = prepare_request(&request).expect_err("zero trial range must remain finite");
2868        assert_eq!(error.error.code, SolveErrorCodeV1::InvalidValue);
2869        assert_eq!(error.error.path(), Some("$.shot.zero_distance_m"));
2870    }
2871
2872    /// Zero and fly a prepared request as `solve_v1` does when no explicit muzzle angle was
2873    /// supplied, returning its samples.
2874    fn fly(prepared: PreparedSolveV1) -> Vec<TrajectoryObservation> {
2875        let max_range_m = prepared.resolved_request.shot.max_range_m;
2876        let time_step_s = prepared.resolved_request.solver.time_step_s;
2877        let zero_distance_m = prepared.resolved_request.shot.zero_distance_m;
2878        let target_height_m = prepared.resolved_request.shot.target_height_m;
2879        let (solver, _) = build_zeroed_solver(
2880            prepared.inputs,
2881            prepared.wind,
2882            prepared.atmosphere,
2883            prepared.wind_segments,
2884            max_range_m,
2885            time_step_s,
2886            zero_distance_m,
2887            target_height_m,
2888            None,
2889        )
2890        .expect("zeroed solver");
2891        solver
2892            .solve()
2893            .expect("solve")
2894            .sample_observations(25.0, MAX_SOLVE_JSON_SAMPLES_V1)
2895            .expect("samples")
2896    }
2897
2898    /// `minimal_request` zeroed at 100 m, with a ladder written straight into the engine inputs.
2899    fn fly_with_engine_ladder(segments: Vec<crate::BCSegmentData>) -> Vec<TrajectoryObservation> {
2900        let mut request = minimal_request();
2901        request.shot.zero_distance_m = Some(100.0);
2902        let mut prepared = prepare_request(&request).expect("valid request");
2903        prepared.inputs.use_bc_segments = true;
2904        prepared.inputs.bc_segments_data = Some(segments);
2905        fly(prepared)
2906    }
2907
2908    /// MBA-1598: a wire ladder's m/s band edges reach the engine as the fps `BCSegmentData`
2909    /// the CLI's `--bc-segment` builds. The ladder arrives as JSON text through
2910    /// `decode_solve_request_v1`, so the wire spelling is covered too, and is pinned against a
2911    /// solve whose ladder is written directly in fps, with every edge on a round fps number.
2912    /// The .308 slows from 2700 fps through a band, an interior gap, a touching edge and a
2913    /// third band, so a missing or wrong conversion would key every edge off the wrong speed.
2914    #[test]
2915    fn bc_segment_edges_reach_the_engine_in_fps() {
2916        use crate::solve_json::{decode_solve_request_v1, BcSegmentV1};
2917        use crate::BCSegmentData;
2918
2919        // fps: 2200-3000 at 0.250, a 2000-2200 gap flying the scalar 0.243, then 1500-2000 at
2920        // 0.235 touching 0-1500 at 0.225.
2921        let fps_ladder = [
2922            (2_200.0, 3_000.0, 0.250),
2923            (1_500.0, 2_000.0, 0.235),
2924            (0.0, 1_500.0, 0.225),
2925        ];
2926        let mut base = minimal_request();
2927        base.shot.zero_distance_m = Some(100.0);
2928        let mut wire = serde_json::to_value(&base).expect("serialize the base request");
2929        wire["projectile"]["bc_segments"] = serde_json::json!([
2930            {"velocity_min_mps": 670.56, "velocity_max_mps": 914.4, "ballistic_coefficient": 0.250},
2931            {"velocity_min_mps": 457.2, "velocity_max_mps": 609.6, "ballistic_coefficient": 0.235},
2932            {"velocity_min_mps": 0.0, "velocity_max_mps": 457.2, "ballistic_coefficient": 0.225}
2933        ]);
2934        let request = decode_solve_request_v1(&wire.to_string()).expect("decodable ladder");
2935        assert_eq!(
2936            request.projectile.bc_segments.as_deref(),
2937            Some(
2938                &[
2939                    (670.56, 914.4, 0.250),
2940                    (457.2, 609.6, 0.235),
2941                    (0.0, 457.2, 0.225),
2942                ]
2943                .map(|(min, max, bc)| BcSegmentV1 {
2944                    velocity_min_mps: min,
2945                    velocity_max_mps: max,
2946                    ballistic_coefficient: bc,
2947                })[..]
2948            ),
2949            "the wire names decode onto the struct fields"
2950        );
2951        assert_eq!(
2952            SolveRequestV1 {
2953                projectile: ProjectileV1 {
2954                    bc_segments: None,
2955                    ..request.projectile.clone()
2956                },
2957                ..request.clone()
2958            },
2959            base,
2960            "only the ladder differs from the base request"
2961        );
2962
2963        let prepared = prepare_request(&request).expect("valid ladder");
2964        assert!(prepared.inputs.use_bc_segments);
2965        assert_eq!(
2966            prepared.inputs.bc_value, 0.243,
2967            "the scalar BC is left alone"
2968        );
2969        let installed = prepared
2970            .inputs
2971            .bc_segments_data
2972            .clone()
2973            .expect("ladder installed");
2974        assert_eq!(installed.len(), fps_ladder.len());
2975        for (band, (min_fps, max_fps, bc)) in installed.iter().zip(fps_ladder) {
2976            assert!((band.velocity_min - min_fps).abs() < 1e-9, "{band:?}");
2977            assert!((band.velocity_max - max_fps).abs() < 1e-9, "{band:?}");
2978            assert_eq!(band.bc_value, bc);
2979        }
2980
2981        let from_wire = fly(prepared);
2982        let engine_ladder = |scale: f64| {
2983            fps_ladder
2984                .iter()
2985                .map(|&(min, max, bc)| BCSegmentData {
2986                    velocity_min: min * scale,
2987                    velocity_max: max * scale,
2988                    bc_value: bc,
2989                })
2990                .collect::<Vec<_>>()
2991        };
2992        let direct = fly_with_engine_ladder(engine_ladder(1.0));
2993        assert_eq!(from_wire.len(), direct.len());
2994        for (wire, engine) in from_wire.iter().zip(&direct) {
2995            assert!((wire.distance_m - engine.distance_m).abs() < 1e-9);
2996            assert!(
2997                (wire.drop_m - engine.drop_m).abs() < 1e-9,
2998                "{wire:?} vs {engine:?}"
2999            );
3000            assert!(
3001                (wire.speed_mps - engine.speed_mps).abs() < 1e-9,
3002                "{wire:?} vs {engine:?}"
3003            );
3004            assert!(
3005                (wire.time_s - engine.time_s).abs() < 1e-12,
3006                "{wire:?} vs {engine:?}"
3007            );
3008        }
3009
3010        // The pin is not vacuous: edges left in m/s, or the scalar alone, fly differently.
3011        let terminal_drop = |samples: &[TrajectoryObservation]| samples.last().unwrap().drop_m;
3012        let unconverted = fly_with_engine_ladder(engine_ladder(0.3048));
3013        let mut scalar_only = minimal_request();
3014        scalar_only.shot.zero_distance_m = Some(100.0);
3015        let scalar_only = fly(prepare_request(&scalar_only).unwrap());
3016        for other in [&unconverted, &scalar_only] {
3017            assert!(
3018                (terminal_drop(&from_wire) - terminal_drop(other)).abs() > 1e-3,
3019                "{} vs {}",
3020                terminal_drop(&from_wire),
3021                terminal_drop(other)
3022            );
3023        }
3024    }
3025
3026    /// How `install_drag_table` installs each kind, with and without a BC ladder. Only a
3027    /// reference table beside a ladder takes the reference-curve path (`custom_drag_reference`
3028    /// set, `cd_scale` 1.0). A reference table alone keeps the original `cd_scale = SD / BC`
3029    /// installation, so every request accepted before ladders could sit beside a reference
3030    /// table solves byte-identically, and a projectile table beside a ladder is refused.
3031    #[test]
3032    fn install_drag_table_takes_the_reference_curve_path_only_beside_a_ladder() {
3033        let prepare = |kind: DragTableKindV1, with_ladder: bool| {
3034            let mut request = minimal_request();
3035            request.projectile.drag_table = Some(DragTableV1 {
3036                kind,
3037                name: None,
3038                points: vec![
3039                    crate::solve_json::DragPointV1 { mach: 0.0, cd: 0.2 },
3040                    crate::solve_json::DragPointV1 { mach: 2.0, cd: 0.3 },
3041                ],
3042            });
3043            if with_ladder {
3044                request.projectile.bc_segments = Some(vec![
3045                    crate::solve_json::BcSegmentV1 {
3046                        velocity_min_mps: 600.0,
3047                        velocity_max_mps: 999.0,
3048                        ballistic_coefficient: 0.260,
3049                    },
3050                    crate::solve_json::BcSegmentV1 {
3051                        velocity_min_mps: 0.0,
3052                        velocity_max_mps: 600.0,
3053                        ballistic_coefficient: 0.220,
3054                    },
3055                ]);
3056            }
3057            prepare_request(&request)
3058        };
3059
3060        let alone = prepare(DragTableKindV1::Reference, false).unwrap().inputs;
3061        let sd = alone.sectional_density_lb_in2().expect("SD");
3062        assert!(!alone.custom_drag_reference);
3063        assert_eq!(alone.cd_scale, sd / 0.243);
3064
3065        let laddered = prepare(DragTableKindV1::Reference, true).unwrap().inputs;
3066        assert!(laddered.custom_drag_reference);
3067        assert_eq!(laddered.cd_scale, 1.0);
3068        assert!(laddered.custom_drag_table.is_some());
3069        assert!(laddered.use_bc_segments && laddered.bc_segments_data.is_some());
3070        assert_eq!(laddered.bc_value, 0.243, "the scalar still flies in a gap");
3071
3072        let own = prepare(DragTableKindV1::Projectile, false).unwrap().inputs;
3073        assert!(!own.custom_drag_reference);
3074        assert_eq!(own.cd_scale, 1.0);
3075
3076        let refused = prepare(DragTableKindV1::Projectile, true)
3077            .expect_err("a ladder beside a projectile table is refused");
3078        assert_eq!(refused.error.code, SolveErrorCodeV1::ConflictingFields);
3079        assert_eq!(refused.error.path(), Some("$.projectile.bc_segments"));
3080    }
3081
3082    #[test]
3083    fn enum_mappers_cover_every_engine_metadata_variant() {
3084        assert_eq!(drag_model_to_engine(DragModelV1::G1), DragModel::G1);
3085        assert_eq!(drag_model_to_engine(DragModelV1::G2), DragModel::G2);
3086        assert_eq!(drag_model_to_engine(DragModelV1::G5), DragModel::G5);
3087        assert_eq!(drag_model_to_engine(DragModelV1::G6), DragModel::G6);
3088        assert_eq!(drag_model_to_engine(DragModelV1::G7), DragModel::G7);
3089        assert_eq!(drag_model_to_engine(DragModelV1::G8), DragModel::G8);
3090        assert_eq!(drag_model_to_engine(DragModelV1::GI), DragModel::GI);
3091        assert_eq!(drag_model_to_engine(DragModelV1::GS), DragModel::GS);
3092        assert_eq!(drag_model_to_engine(DragModelV1::RA4), DragModel::RA4);
3093
3094        for (engine, wire) in [
3095            (
3096                TrajectoryTermination::MaxRange,
3097                TerminationReasonV1::MaxRange,
3098            ),
3099            (
3100                TrajectoryTermination::GroundThreshold,
3101                TerminationReasonV1::GroundThreshold,
3102            ),
3103            (
3104                TrajectoryTermination::TimeLimit,
3105                TerminationReasonV1::TimeLimit,
3106            ),
3107            (
3108                TrajectoryTermination::VelocityFloor,
3109                TerminationReasonV1::VelocityFloor,
3110            ),
3111        ] {
3112            assert_eq!(termination_to_wire(engine), wire);
3113        }
3114    }
3115}