ballistics_engine/profile.rs
1//! Saved ballistic profile data model.
2//!
3//! `ProfileData` is the schema of `~/.ballistics/profiles/<name>.json` — the CLI's saved
4//! profiles — and, since the bridge grew `profile.validate`/`profile.normalize`/
5//! `profile.import_a7p`, also the profile document the JSON command bridge exchanges with
6//! embedding apps. It lived in `main.rs` from its introduction; it moved here VERBATIM so
7//! the bridge and the CLI share one definition. The serde wire shape is a compatibility
8//! contract: every stored profile on disk and every fixture in the test suite must keep
9//! loading, so field names, defaults, `skip_serializing_if` decisions, and the ABSENCE of
10//! `deny_unknown_fields` (unknown keys are tolerated and dropped, the documented
11//! forward-compat behavior) are all deliberately unchanged. See the round-trip test at the
12//! bottom of this file before touching any attribute.
13//!
14//! fs-free by design: this module must compile for wasm32, so file persistence
15//! (`save_profile`/`load_profile`) and unit conversion of loaded profiles (`converted_to`,
16//! which rides on the CLI's `UnitConverter`) stay in `main.rs`.
17
18use serde::{Deserialize, Serialize};
19
20use crate::adjustment::parse_click_value;
21use crate::cli_api::UnitSystem;
22use crate::optic::{HoldBounds, OpticProfile, TravelLimits, TurretState};
23use crate::reticle::ReticleDescription;
24use crate::truing_dsf::DsfPoint;
25
26/// Saved ballistic profile for quick recall
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct ProfileData {
29 pub name: String,
30 pub velocity: f64,
31 pub bc: f64,
32 pub mass: f64,
33 pub diameter: f64,
34 pub drag_model: String,
35 #[serde(default)]
36 pub twist_rate: Option<f64>,
37 #[serde(default)]
38 pub sight_height: Option<f64>,
39 #[serde(default)]
40 pub zero_distance: Option<f64>,
41 #[serde(default = "default_unit_system")]
42 pub units: String,
43 #[serde(default = "default_temperature")]
44 pub temperature: f64,
45 #[serde(default = "default_pressure")]
46 pub pressure: f64,
47 /// True when the stored temperature was a supplied reading (0.49.0+). Absent/false = unknown:
48 /// files written before 0.49.0 cannot tell a typed 59 °F from the default, so they keep the
49 /// legacy rule (59 °F / 15 °C at a real altitude flies the ICAO standard temperature).
50 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
51 pub temperature_supplied: bool,
52 /// True when the stored pressure was a supplied reading (0.49.0+). Absent/false = unknown:
53 /// files written before 0.49.0 cannot tell a typed 29.92 inHg from the default, so they keep
54 /// the legacy rule (29.92 inHg / 1013.25 hPa at a real altitude flies ICAO standard pressure).
55 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
56 pub pressure_supplied: bool,
57 /// Relative humidity, PERCENT, 0 to 100 (50 = 50 %), whatever `units` says. Absent means
58 /// [`crate::atmosphere::DEFAULT_HUMIDITY_PERCENT`]. A stored sensor reading within
59 /// [`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`] of 0 to 100 is kept as stored and flies as
60 /// the end it reads as; a value beyond that is refused on load
61 /// ([`Self::validate_humidity`]), never clamped.
62 #[serde(default = "default_humidity")]
63 pub humidity: f64,
64 #[serde(default)]
65 pub altitude: f64,
66 #[serde(default)]
67 pub bullet_name: Option<String>,
68 #[serde(default)]
69 pub created: Option<String>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub wind_speed: Option<f64>,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub wind_direction: Option<f64>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub shooting_angle: Option<f64>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub auto_zero: Option<f64>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub twist_right: Option<bool>,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub use_bc_segments: Option<bool>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub bullet_length: Option<f64>,
84 /// Turret elevation click graduation for `--adjustment-unit clicks` (MBA-1355), e.g. "0.1mil" or
85 /// "0.25moa" — parsed by `parse_click_value` at both save-time (validation) and
86 /// resolve-time (`resolve_click_values`). Unit-invariant (an angular graduation, not a
87 /// linear measurement), so `converted_to` leaves it untouched — see the `bc_segments`/
88 /// `drag_curve` comment below for why.
89 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub elevation_click: Option<String>,
91 /// Turret windage click graduation for `--adjustment-unit clicks` (MBA-1355). Falls back to the
92 /// resolved elevation graduation when unset — see `resolve_click_values`.
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub windage_click: Option<String>,
95 /// Velocity-banded BC breakpoints (MBA-1323 Phase 2: multi-row `.a7p` G1/G7 import).
96 /// `velocity_mps` in each entry is ALWAYS meters/second regardless of this profile's
97 /// `units` field — see [`ProfileBcSegment`]. The scalar `bc` field above is retained as
98 /// the highest-velocity row for tools that only understand a single BC; this list is the
99 /// authoritative full schedule once present. `None` (the pre-Phase-2 shape) means "no
100 /// velocity-banded schedule was captured" and callers fall back to the scalar `bc`.
101 ///
102 /// FORWARD-COMPAT WARNING (one-way): `#[serde(default)]` means this field round-trips
103 /// safely through readers that predate Phase 2, but "safely" only means *deserialization*
104 /// doesn't error — a pre-Phase-2 (or otherwise un-updated, e.g. stale WASM/bindings) reader
105 /// silently drops this key and solves with only the scalar `bc` above. That is a materially
106 /// different, unwarned answer whenever the schedule's non-fastest bands matter (empirically
107 /// confirmed: ~639 m/s vs. ~411 m/s impact velocity for the same imported profile — see
108 /// CLI_USAGE.md's "Multi-BC and CUSTOM drag curves" section). There is no sentinel trick
109 /// available here the way there is for `drag_curve`/CUSTOM below (a real, plausible-looking
110 /// `bc` value is unavoidable for back-compat with single-BC tools), so this direction of
111 /// version skew degrades silently by design and must stay documented rather than "fixed".
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub bc_segments: Option<Vec<ProfileBcSegment>>,
114 /// Full Mach/Cd drag curve (MBA-1323 Phase 2: `.a7p` `bc_type == CUSTOM` import). When
115 /// present, the scalar `bc`/`drag_model` fields are not physically meaningful for the
116 /// solve (`drag_model` reads "CUSTOM"; see `map_a7p_to_profile`'s CUSTOM handling for why
117 /// `bc` is an inert `0.0` sentinel rather than a real coefficient).
118 ///
119 /// FORWARD-COMPAT NOTE: unlike `bc_segments` above, a reader that predates Phase 2 (or
120 /// otherwise doesn't consume this field) is safe by construction, not just by omission: it
121 /// still sees `bc == 0.0` and `drag_model == "CUSTOM"`, so `BallisticInputs::validate_for_solve`
122 /// rejects the solve loudly ("bc_value must be finite and greater than zero") instead of
123 /// silently running physics under a fabricated coefficient.
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub drag_curve: Option<Vec<ProfileDragPoint>>,
126 /// Mach-keyed drop-scale-factor table (MBA-1357), accumulated one point at a time by
127 /// the `dsf` verb. `None` for every profile with no DSF calibration yet — including
128 /// every profile saved before this field existed, which loads clean and solves
129 /// untrued (same `#[serde(default)]` forward-compat pattern as `bc_segments`/
130 /// `drag_curve` above: an old reader that predates this field silently drops it on
131 /// re-save, degrading to untrued drop with no error).
132 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub dsf_points: Option<Vec<DsfPoint>>,
134 /// Which standard atmosphere `bc`/`bc_segments` are referenced to (MBA-1365): `None`
135 /// (the omitted-field default, and every profile saved before this field existed) or
136 /// `"icao"` mean ICAO; `"army-standard-metro"` declares the older Army Standard Metro
137 /// reference some vendor-published BCs use instead. Parsed by
138 /// `parse_bc_reference_profile_field`, written by `bc_reference_profile_field` (which
139 /// never writes `"icao"` — it stays the omitted default so an untouched profile
140 /// round-trips with no new key). Unit-invariant, like `bc_segments`/`drag_curve` above,
141 /// so `converted_to` leaves it untouched.
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub bc_reference: Option<String>,
144 /// Whether `pressure` is absolute station pressure or a sea-level-corrected altimeter
145 /// setting (QNH), mirroring `bc_reference` (MBA-1397): `None` (the omitted-field default,
146 /// and every profile saved before this field existed) or `"absolute"` mean absolute;
147 /// `"qnh"` declares a QNH pressure that must be reduced to station pressure before use.
148 /// Parsed by `parse_pressure_reference_profile_field`, written by
149 /// `pressure_reference_profile_field` (which never writes `"absolute"` -- it stays the
150 /// omitted default so an untouched profile round-trips with no new key).
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub pressure_reference: Option<String>,
153 /// Density altitude (MBA-1366), feet imperial / meters metric per `units` (same convention
154 /// as `altitude`). `None` (the omitted-field default, and every profile saved before this
155 /// field existed) means no density-altitude override is stored; a saved value supersedes
156 /// `altitude`/`pressure` when the profile is loaded (see `trajectory`'s
157 /// `--density-altitude` for the full precedence rule). `converted_to` rescales it exactly
158 /// like `altitude` since it shares the same feet/meters convention.
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub density_altitude: Option<f64>,
161 /// Deliberate vertical POI offset AT the zero range (MBA-1359, Kestrel "zero height"):
162 /// positive = the rifle is deliberately zeroed to impact HIGH by this much at the zero
163 /// distance. ALWAYS meters regardless of this profile's `units` field (same unit-fixed
164 /// convention as [`ProfileBcSegment::velocity_mps`]), so `converted_to` leaves it
165 /// untouched. `None` (the omitted-field default, and every profile saved before this
166 /// field existed) means no offset; an old reader silently drops it on re-save (the
167 /// `bc_segments` forward-compat pattern).
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub zero_poi_up_m: Option<f64>,
170 /// Deliberate horizontal POI offset AT the zero range (MBA-1359, Kestrel "zero
171 /// offset"): positive = impacts RIGHT. ALWAYS meters, like `zero_poi_up_m` above.
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub zero_poi_right_m: Option<f64>,
174 /// Lateral sight-to-bore mount offset (MBA-1396, offset-mounted optics): positive =
175 /// sight RIGHT of bore. ALWAYS meters (unit-fixed like the zero POI fields above), so
176 /// `converted_to` leaves it untouched; same `#[serde(default)]` forward-compat
177 /// pattern (an old reader silently drops it on re-save).
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub sight_offset_lateral_m: Option<f64>,
180 /// Elevation-axis scope tracking correction factor from a tall-target test
181 /// (MBA-1358, Litz), stored as the published ratio `actual measured travel /
182 /// dialed travel` (0.95 = the scope under-tracks by 5%). Elevation dial-unit
183 /// outputs (mil/MOA/SMOA/IPHY/clicks) are DIVIDED by this factor — an
184 /// under-tracking scope needs more dial — and dialed truing observations are
185 /// MULTIPLIED by it (scope-dial -> true angular); raw drop inches never scale.
186 /// NOTE on conventions: Kestrel's "Scope Cal" MULTIPLIES its factor into the
187 /// solution because it stores the reciprocal (dialed/actual); we divide because we
188 /// store the published actual/dialed — same physics, opposite bookkeeping.
189 /// Dimensionless, so `converted_to` leaves it untouched. Validated on load: must
190 /// be strictly between 0.5 and 1.5 (a factor outside that band means the
191 /// tall-target test went wrong, not that the scope does). `None` = 1.0 = no
192 /// correction. Derive with `ballistics tall-target`; overridden by
193 /// `--elevation-cf`.
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub elevation_cf: Option<f64>,
196 /// Windage-axis scope tracking correction factor (MBA-1358), same contract and
197 /// direction as `elevation_cf`: windage-axis dial-unit outputs (including mover
198 /// lead/ring) are divided by it; overridden by `--windage-cf`.
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub windage_cf: Option<f64>,
201 /// Named zero sets (MBA-1360): alternate zero distances and per-load dial
202 /// corrections (Lapua Sight-In POI / ATrag zero zones / Strelok multi-zero class).
203 /// Managed by `profile zero-set add|remove|list`; selected at solve time with
204 /// `--zero-set NAME`. Nothing here applies unless a set is explicitly selected —
205 /// the profile's own `zero_distance`/`auto_zero` remain the master zero.
206 ///
207 /// FORWARD-COMPAT (the `bc_segments` pattern, deliberately): `#[serde(default)]`
208 /// means a reader that predates this field loads the profile cleanly and solves
209 /// with the master zero — which is exactly what a CURRENT reader does when no
210 /// `--zero-set` is selected, so an old reader can never silently produce a
211 /// different default answer. Requesting an alternate set on an old binary fails
212 /// loudly at the flag (`--zero-set` is an unknown argument there). The one-way
213 /// skew is re-SAVING: an old reader that rewrites the profile silently drops this
214 /// key (documented, like `bc_segments`; there is no sentinel trick available that
215 /// wouldn't corrupt the master-zero fields old readers rely on).
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub zero_sets: Option<Vec<ProfileZeroSet>>,
218 /// The optic's reticle (MBA-1361), so `reticle hold --profile NAME` can place a
219 /// firing solution without being handed a description every time. Set with
220 /// `profile save --reticle-json <file>`; carried forward untouched by a re-save.
221 ///
222 /// Angular data only (milliradians from the optical center), so
223 /// `ProfileData::converted_to` (in `main.rs`) leaves it alone for the same reason it leaves
224 /// `elevation_click` alone — a subtension is not a linear measurement.
225 ///
226 /// FORWARD-COMPAT (the `bc_segments` pattern): `#[serde(default)]` means a reader that
227 /// predates this field loads the profile cleanly. Nothing about a trajectory depends
228 /// on it — it is a display/hold aid consumed only by the `reticle` command — so an old
229 /// reader cannot produce a different ballistic answer because of it; it simply has no
230 /// `reticle` verb. The one-way skew is re-SAVING, which drops the key, exactly as
231 /// documented for `bc_segments` and `zero_sets`.
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub reticle: Option<ReticleDescription>,
234 /// Turret mechanics and reticle hold bounds (MBA-1348): twelve fields (this one
235 /// through `hold_bound_right_mil` below) assembled by `ProfileData::optic_profile`
236 /// into a `ballistics_engine::optic::OpticProfile` for the dial/hold/hybrid
237 /// correction planner. Every one is independently `Option` and, like
238 /// `elevation_click`/`windage_click` above, ALWAYS stored in mil (or its own natural
239 /// type for `clicks_per_revolution`/`zero_stop`) regardless of this profile's `units`
240 /// field — angular turret/reticle geometry, not a linear measurement — so
241 /// `converted_to` leaves all twelve untouched. Set with `profile save
242 /// --clicks-per-rev/--zero-stop/--travel-up/--travel-down/--windage-travel-left/
243 /// --windage-travel-right/--turret-elev/--turret-wind/--hold-up/--hold-down/
244 /// --hold-left/--hold-right`; validated at save time via `optic_profile()` +
245 /// `OpticProfile::validate()` (a profile can never be saved with, say, a dialed
246 /// turret state outside its own declared travel, or a non-positive click size).
247 ///
248 /// FORWARD-COMPAT (the `bc_segments` pattern, deliberately): `#[serde(default)]`
249 /// means a reader that predates these fields loads the profile cleanly with every one
250 /// of them absent — identical to what a CURRENT reader does for a profile that never
251 /// set them, so an old reader can never silently produce a different ballistic
252 /// answer because of them (nothing about a trajectory solve reads them; only a later
253 /// dial/hold planner does). The one-way skew is re-SAVING on an old binary, which
254 /// silently drops all twelve keys, exactly as documented for `bc_segments`/
255 /// `zero_sets`/`reticle` above.
256 ///
257 /// This field specifically: click detents per full turret revolution, for turrets
258 /// whose cap marks revolutions at all (many hunting turrets do not). `None` means
259 /// unknown/not applicable, never a specific count.
260 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub clicks_per_revolution: Option<u32>,
262 /// Whether the elevation turret hard-stops at its lowest travel so it cannot be
263 /// dialed below zero (MBA-1348) — purely descriptive metadata, never read by
264 /// `plan_corrections` (see `OpticProfile::zero_stop`'s own doc comment for why).
265 /// `None` (the omitted-field default) means not recorded; `optic_profile()` treats
266 /// that the same as `Some(false)`.
267 #[serde(default, skip_serializing_if = "Option::is_none")]
268 pub zero_stop: Option<bool>,
269 /// Elevation travel remaining UP from the current zero (not the turret's mechanical
270 /// bottom), DIAL-space mil (MBA-1348). Required together with
271 /// `elevation_travel_down_mil` — `optic_profile()` returns a named-field `Err` if
272 /// only one of the pair is set, rather than silently treating the unset half as zero
273 /// travel (a specific, likely-false physical claim, not an honest "unknown").
274 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub elevation_travel_up_mil: Option<f64>,
276 /// Elevation travel remaining DOWN from the current zero, DIAL-space mil (MBA-1348).
277 /// See `elevation_travel_up_mil`.
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub elevation_travel_down_mil: Option<f64>,
280 /// Windage travel remaining LEFT from the current zero, DIAL-space mil (MBA-1348) —
281 /// `TravelLimits::down_mil` on the windage axis (see that type's doc comment for the
282 /// left/down convention). Required together with `windage_travel_right_mil`, like
283 /// `elevation_travel_up_mil`/`_down_mil` above.
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub windage_travel_left_mil: Option<f64>,
286 /// Windage travel remaining RIGHT from the current zero, DIAL-space mil (MBA-1348) —
287 /// `TravelLimits::up_mil` on the windage axis. See `windage_travel_left_mil`.
288 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub windage_travel_right_mil: Option<f64>,
290 /// The elevation turret's current dialed offset from zero, DIAL-space mil, signed:
291 /// positive is dialed UP (MBA-1348). Required together with
292 /// `turret_windage_dialed_mil` — `optic_profile()` returns a named-field `Err` if
293 /// only one axis of the pair is set, rather than silently assuming the other reads
294 /// zero.
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub turret_elevation_dialed_mil: Option<f64>,
297 /// The windage turret's current dialed offset from zero, DIAL-space mil, signed:
298 /// positive is dialed RIGHT (MBA-1348). See `turret_elevation_dialed_mil`.
299 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub turret_windage_dialed_mil: Option<f64>,
301 /// The reticle's usable hold extent ABOVE center, TRUE angular mil (MBA-1348) — see
302 /// `HoldBounds`, an explicit spec input (manufacturer spec sheet or bench
303 /// measurement), never derived from this profile's own `reticle` field. Required
304 /// together with `hold_bound_down_mil`/`hold_bound_left_mil`/`hold_bound_right_mil`
305 /// — all four or none.
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub hold_bound_up_mil: Option<f64>,
308 /// The reticle's usable hold extent BELOW center, TRUE angular mil (MBA-1348). See
309 /// `hold_bound_up_mil`.
310 #[serde(default, skip_serializing_if = "Option::is_none")]
311 pub hold_bound_down_mil: Option<f64>,
312 /// The reticle's usable hold extent LEFT of center, TRUE angular mil (MBA-1348). See
313 /// `hold_bound_up_mil`.
314 #[serde(default, skip_serializing_if = "Option::is_none")]
315 pub hold_bound_left_mil: Option<f64>,
316 /// The reticle's usable hold extent RIGHT of center, TRUE angular mil (MBA-1348). See
317 /// `hold_bound_up_mil`.
318 #[serde(default, skip_serializing_if = "Option::is_none")]
319 pub hold_bound_right_mil: Option<f64>,
320}
321
322/// One named zero condition / per-load dial correction (MBA-1360).
323///
324/// `zero_distance` uses the SAME display-unit convention as [`ProfileData::zero_distance`]
325/// (yards imperial / meters metric per the profile's `units` field), and
326/// `ProfileData::converted_to` (in `main.rs`) rescales it identically. `poi_up_mil`/`poi_right_mil`
327/// are constant ANGULAR dial corrections in MILs (unit-invariant, untouched by
328/// `converted_to`), ADDED to the dial outputs (elevation/windage adjustments) when the
329/// set is selected — positive = dial UP/RIGHT more; a load that impacts high/right
330/// relative to the master zero therefore stores negative values. This is deliberately
331/// dial-side (a constant angular correction per the ticket), unlike the MBA-1359
332/// linear-at-zero-range POI offsets, which bias the solved zero itself; the two compose.
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
334pub struct ProfileZeroSet {
335 pub name: String,
336 #[serde(default, skip_serializing_if = "Option::is_none")]
337 pub zero_distance: Option<f64>,
338 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub poi_up_mil: Option<f64>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub poi_right_mil: Option<f64>,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub notes: Option<String>,
344}
345
346/// One velocity-banded BC breakpoint (profile schema v2, MBA-1323 Phase 2). Stored as a raw
347/// breakpoint, NOT a pre-computed `velocity_min`/`velocity_max` band — banding into the
348/// engine's [`crate::BCSegmentData`] shape happens at solve time (`bc_segments_from_profile`), so the
349/// stored JSON stays a simple, order-independent list that round-trips cleanly.
350///
351/// `velocity_mps` is ALWAYS meters/second, independent of [`ProfileData::units`]. This is
352/// intentional (matches the engine's internal BC-segment plumbing, which is also always in
353/// engine units) and is why `ProfileData::converted_to` (in `main.rs`) leaves this field untouched — see
354/// the comment there.
355#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
356pub struct ProfileBcSegment {
357 pub bc: f64,
358 pub velocity_mps: f64,
359}
360
361/// One Mach/Cd point of a saved custom drag curve (profile schema v2, MBA-1323 Phase 2).
362/// Both fields are unit-invariant (Mach is dimensionless; Cd is dimensionless), so
363/// `ProfileData::converted_to` (in `main.rs`) leaves `drag_curve` untouched too.
364#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
365pub struct ProfileDragPoint {
366 pub mach: f64,
367 pub cd: f64,
368}
369
370fn default_unit_system() -> String {
371 "imperial".to_string()
372}
373fn default_temperature() -> f64 {
374 59.0
375}
376fn default_pressure() -> f64 {
377 29.92
378}
379fn default_humidity() -> f64 {
380 crate::atmosphere::DEFAULT_HUMIDITY_PERCENT
381}
382
383/// Assembles an all-or-nothing pair of angular profile fields — `OpticProfile`'s
384/// `TravelLimits`/`TurretState` axes — from two independently-`Option` values (MBA-1348).
385/// `None` only when NEITHER is set; `Some` only when BOTH are; a named-field `Err` when
386/// exactly one is. A silently-defaulted `0.0` for the missing half would assert a
387/// specific, likely-false physical fact (e.g. "zero down travel from zero") rather than
388/// "not recorded" — exactly the silent fabrication `OpticProfile`'s own doc comments
389/// warn against — so an incomplete pair is rejected by name instead of guessed at.
390///
391/// `a_flag`/`b_flag` name the CLI FLAGS (e.g. `"--travel-up"`), not the internal
392/// `ProfileData` struct fields (MBA-1348 review fix I2): the field↔flag mapping is not
393/// mechanical (`--travel-up` drops the axis prefix `elevation_travel_up_mil` carries;
394/// `--turret-elev` abbreviates `turret_elevation_dialed_mil`), and a user who typed
395/// `--travel-up` has no reason to recognize `elevation_travel_up_mil` in an error. This
396/// matches the convention two call sites above already use
397/// (`"--elevation-click '{v}' is invalid"`).
398pub fn require_angular_pair(
399 a_flag: &'static str,
400 a: Option<f64>,
401 b_flag: &'static str,
402 b: Option<f64>,
403) -> Result<Option<(f64, f64)>, String> {
404 match (a, b) {
405 (None, None) => Ok(None),
406 (Some(a), Some(b)) => Ok(Some((a, b))),
407 (Some(_), None) => Err(format!(
408 "{a_flag} is set but {b_flag} is not — both are required together (or neither)"
409 )),
410 (None, Some(_)) => Err(format!(
411 "{b_flag} is set but {a_flag} is not — both are required together (or neither)"
412 )),
413 }
414}
415
416/// The `require_angular_pair` all-or-nothing rule extended to `HoldBounds`' four fields
417/// (MBA-1348): all four or none, any other combination is a named-field `Err` (same
418/// no-silent-fabrication rationale — see `require_angular_pair`). Names the four CLI
419/// FLAGS in any error, not the internal struct fields (MBA-1348 review fix I2) — see
420/// `require_angular_pair`'s own doc comment for why that distinction matters.
421pub fn require_hold_bounds(
422 up: Option<f64>,
423 down: Option<f64>,
424 left: Option<f64>,
425 right: Option<f64>,
426) -> Result<Option<HoldBounds>, String> {
427 let flags = [
428 ("--hold-up", up),
429 ("--hold-down", down),
430 ("--hold-left", left),
431 ("--hold-right", right),
432 ];
433 let set_count = flags.iter().filter(|(_, v)| v.is_some()).count();
434 if set_count == 0 {
435 return Ok(None);
436 }
437 if set_count < 4 {
438 let missing: Vec<&str> = flags
439 .iter()
440 .filter(|(_, v)| v.is_none())
441 .map(|(name, _)| *name)
442 .collect();
443 return Err(format!(
444 "reticle hold bounds are incomplete — missing {} (all four of --hold-up/\
445 --hold-down/--hold-left/--hold-right are required together, or none)",
446 missing.join(", ")
447 ));
448 }
449 Ok(Some(HoldBounds {
450 up_mil: up.unwrap(),
451 down_mil: down.unwrap(),
452 left_mil: left.unwrap(),
453 right_mil: right.unwrap(),
454 }))
455}
456
457/// MBA-1358: a scope tracking correction factor must be strictly between 0.5 and 1.5.
458/// Values outside that band mean the tall-target test (or a hand edit) went wrong — a
459/// real scope does not mistrack by 50% — so they are a hard error naming the offending
460/// field/flag rather than a silently applied scale. The band itself lives in the shared
461/// `crate::adjustment::tracking_cf_in_range` so the WASM terminal enforces
462/// the identical bound.
463pub fn validate_tracking_cf(value: f64, source: &str) -> Result<(), String> {
464 if crate::adjustment::tracking_cf_in_range(value) {
465 Ok(())
466 } else {
467 Err(format!(
468 "{source} must be a tracking correction factor strictly between 0.5 and 1.5 \
469 (got {value}); derive it from a tall-target test with `ballistics tall-target`"
470 ))
471 }
472}
473
474impl ProfileData {
475 /// Assembles this profile's `OpticProfile` (MBA-1348) from `elevation_click`/
476 /// `windage_click` (parsed via `parse_click_value`, windage falling back to the
477 /// resolved elevation graduation — the same precedence `resolve_click_values` uses)
478 /// plus the twelve turret/hold fields declared alongside `reticle` above.
479 ///
480 /// Returns `Ok(None)` only when NONE of the twelve fields are set: the profile has
481 /// never been given any turret model at all. Every other combination either succeeds
482 /// (`Ok(Some(..))`) or is a named-field `Err` — including `elevation_click` itself
483 /// being unset while ANY of the other eleven fields IS set, since those eleven are
484 /// meaningless without a click graduation (`OpticProfile` cannot be constructed
485 /// without one, structurally) and silently ignoring them would let a save persist
486 /// turret/hold data no downstream code could ever use.
487 ///
488 /// Does NOT call `OpticProfile::validate()` itself — callers that need a
489 /// pre-validated profile (`profile save`) call it explicitly, so a validation
490 /// failure is attributed to the operation asking for it rather than to assembly.
491 pub fn optic_profile(&self) -> Result<Option<OpticProfile>, String> {
492 // Shape/pairing checks run FIRST and UNCONDITIONALLY -- before the elevation_click
493 // gate below -- so an incomplete travel/turret-state/hold-bound pair is rejected by
494 // name even on a profile that never set elevation_click at all (MBA-1348 review
495 // fix: a save with, e.g., only --travel-up and no --elevation-click previously
496 // skipped every one of these checks via the early `Ok(None)` return, silently
497 // persisting an incomplete pair no downstream code could ever have used anyway).
498 let elevation_travel = require_angular_pair(
499 "--travel-up",
500 self.elevation_travel_up_mil,
501 "--travel-down",
502 self.elevation_travel_down_mil,
503 )?
504 .map(|(up, down)| TravelLimits {
505 up_mil: up,
506 down_mil: down,
507 });
508
509 let windage_travel = require_angular_pair(
510 "--windage-travel-left",
511 self.windage_travel_left_mil,
512 "--windage-travel-right",
513 self.windage_travel_right_mil,
514 )?
515 .map(|(left, right)| TravelLimits {
516 down_mil: left,
517 up_mil: right,
518 });
519
520 let turret_state = require_angular_pair(
521 "--turret-elev",
522 self.turret_elevation_dialed_mil,
523 "--turret-wind",
524 self.turret_windage_dialed_mil,
525 )?
526 .map(|(elevation_mil, windage_mil)| TurretState {
527 elevation_mil,
528 windage_mil,
529 });
530
531 let reticle_hold_bounds = require_hold_bounds(
532 self.hold_bound_up_mil,
533 self.hold_bound_down_mil,
534 self.hold_bound_left_mil,
535 self.hold_bound_right_mil,
536 )?;
537
538 let Some(elev_str) = &self.elevation_click else {
539 // MBA-1348 review fix: every one of the other eleven fields is meaningless
540 // without a click graduation -- `OpticProfile` cannot even be constructed
541 // without one, structurally -- so silently accepting them here (the way a
542 // bare `Ok(None)` would) lets a save persist turret/hold data that no
543 // downstream code, including this profile's own future re-saves, could ever
544 // use. A profile that has genuinely never touched any of the twelve fields
545 // still returns Ok(None), unchanged.
546 if self.clicks_per_revolution.is_some()
547 || self.zero_stop.is_some()
548 || elevation_travel.is_some()
549 || windage_travel.is_some()
550 || turret_state.is_some()
551 || reticle_hold_bounds.is_some()
552 {
553 return Err(
554 "turret/hold fields are set but --elevation-click is not -- a turret \
555 model needs a click graduation to be usable at all; supply \
556 --elevation-click, or also pass --clear-turret to clear the other \
557 fields (e.g. after --clear-click removed the click alone)"
558 .to_string(),
559 );
560 }
561 return Ok(None);
562 };
563 let elevation_click = parse_click_value(elev_str)?;
564 let windage_click = match &self.windage_click {
565 Some(s) => parse_click_value(s)?,
566 None => elevation_click,
567 };
568
569 Ok(Some(OpticProfile {
570 elevation_click,
571 windage_click,
572 clicks_per_revolution: self.clicks_per_revolution,
573 zero_stop: self.zero_stop.unwrap_or(false),
574 elevation_travel,
575 windage_travel,
576 turret_state,
577 reticle_hold_bounds,
578 }))
579 }
580
581 /// Parse this profile's `units` field into the CLI unit system it names.
582 ///
583 /// Factored out of the CLI's `converted_to` (which now calls this) so the bridge's
584 /// `profile.validate` applies the identical check with the identical message.
585 pub fn unit_system(&self) -> Result<UnitSystem, String> {
586 match self.units.trim().to_ascii_lowercase().as_str() {
587 "imperial" => Ok(UnitSystem::Imperial),
588 "metric" => Ok(UnitSystem::Metric),
589 other => Err(format!(
590 "Profile '{}' has unsupported units '{}'; expected 'imperial' or 'metric'",
591 self.name, other
592 )),
593 }
594 }
595
596 /// The stored `humidity`, checked by the engine's one validator,
597 /// [`crate::atmosphere::RelativeHumidity::try_percent`]. The CLI refuses to load a profile that
598 /// fails it, and the bridge's `profile.validate` reports it; the message names the profile and
599 /// the field, and says how to fix it.
600 ///
601 /// The fix it gives is an edit of the stored value, never a re-save: `profile save` is a
602 /// full overwrite of every field its flags can express (and it resets `bc_segments` and
603 /// `drag_curve`), so a re-save is not a safe way to repair one stored number.
604 pub fn validate_humidity(&self) -> Result<(), String> {
605 self.flown_humidity().map(|_| ())
606 }
607
608 /// The humidity, PERCENT, a flight of this profile flies: the stored `humidity` through
609 /// [`Self::validate_humidity`]'s one validator, so a stored sensor reading inside the band
610 /// is the end it reads as (102 flies as 100, -5 and -0 as 0) and anything farther out is
611 /// the same refusal.
612 ///
613 /// The one echo rule: a surface that reports the air FLOWN states this
614 /// value (the CLI's flight loader writes it into the profile it flies), and a surface that
615 /// displays the STORED document shows `humidity` as stored, saying what it flies as when
616 /// that is outside 0-100 ([`Self::flown_humidity_note`]).
617 pub fn flown_humidity(&self) -> Result<f64, String> {
618 crate::atmosphere::RelativeHumidity::try_percent(self.humidity)
619 .map(crate::atmosphere::RelativeHumidity::percent)
620 .map_err(|error| {
621 format!(
622 "{}; edit the humidity stored in the profile",
623 error.at_field(format!("profile '{}' field humidity", self.name))
624 )
625 })
626 }
627
628 /// What a STORED humidity outside 0-100 flies as, for a surface that shows the stored value:
629 /// `Some(100.0)` for a stored 102, `Some(0.0)` for a stored -5; `None` for a stored value in
630 /// 0-100 (it flies as itself) and for one that does not fly at all (beyond the band, or not
631 /// finite), which [`Self::validate_humidity`] reports instead.
632 pub fn flown_humidity_note(&self) -> Option<f64> {
633 // The one validator decides: it moves a stored value only when that value is a band
634 // reading outside 0-100 (-0 snaps to 0, which compares equal, so it needs no note).
635 let flown = self.flown_humidity().ok()?;
636 (flown != self.humidity).then_some(flown)
637 }
638
639 /// The station air a flight of this profile's OWN stored atmosphere flies, the way every
640 /// CLI command that takes a saved profile reads it when no station flag is typed (`dsf
641 /// --saved-profile` always): the stored readings in the profile's `units`, converted to
642 /// metric; a stored density altitude flies its derived station triple with both readings
643 /// supplied; a stored `pressure_reference` of `qnh` is reduced to station pressure at the
644 /// profile's altitude; otherwise each reading's presence is the profile's marker (a profile
645 /// written before 0.49.0 has none and keeps the legacy rule). An unmarked stored default
646 /// (29.92 inHg, 1013.25 hPa) is taken as stored here; the CLI flies the run's own default in
647 /// its place, which differs from it by at most the 0.04 hPa between the two.
648 ///
649 /// Returns the conditions (°C, hPa, the stored humidity percent, m), the presence a solver
650 /// resolves them with, and where the station's readings came from (the stored reading, a
651 /// stored QNH reduced here, kept as it is stored so a refusal quotes it, the standard
652 /// pressure at the altitude for an omitted one, or a stored density altitude's station, and
653 /// its temperature unless one is stored as a reading); an error for `units` or a
654 /// `pressure_reference` the profile cannot be read in.
655 pub fn stored_station(
656 &self,
657 ) -> Result<
658 (
659 crate::cli_api::AtmosphericConditions,
660 crate::atmosphere::StationAtmospherePresence,
661 crate::atmosphere::StationOrigin,
662 ),
663 String,
664 > {
665 use crate::atmosphere::{
666 reduce_qnh_to_station_pressure, resolve_atmosphere_for_density_altitude,
667 PressureReferenceMode, StationAtmospherePresence, StationOrigin,
668 };
669 let units = self.unit_system()?;
670 // The CLI's own `UnitConverter` factors and default pressures, in the same order.
671 let to_celsius = |value: f64| match units {
672 UnitSystem::Metric => value,
673 UnitSystem::Imperial => (value - 32.0) * 5.0 / 9.0,
674 };
675 let to_hpa = |value: f64, system: UnitSystem| match system {
676 UnitSystem::Metric => value,
677 UnitSystem::Imperial => value * 33.8639,
678 };
679 let to_meters = |value: f64| match units {
680 UnitSystem::Metric => value,
681 UnitSystem::Imperial => value * 0.3048,
682 };
683 let (temperature_c, pressure_hpa, altitude_m, presence, origin) = match self
684 .density_altitude
685 {
686 Some(density_altitude) => {
687 let explicit_temperature_c = self
688 .temperature_supplied
689 .then(|| to_celsius(self.temperature));
690 let (altitude_m, temperature_c, pressure_hpa) =
691 resolve_atmosphere_for_density_altitude(
692 to_meters(density_altitude),
693 explicit_temperature_c,
694 );
695 (
696 temperature_c,
697 pressure_hpa,
698 altitude_m,
699 StationAtmospherePresence::BOTH,
700 StationOrigin::density_altitude(explicit_temperature_c.is_some()),
701 )
702 }
703 None => {
704 let altitude_m = to_meters(self.altitude);
705 let entered_hpa = to_hpa(self.pressure, units);
706 let mode = match self.pressure_reference.as_deref().map(str::trim) {
707 None | Some("") => PressureReferenceMode::Absolute,
708 Some(text) => match text.to_ascii_lowercase().as_str() {
709 "absolute" => PressureReferenceMode::Absolute,
710 "qnh" => PressureReferenceMode::Qnh,
711 other => {
712 return Err(format!(
713 "invalid pressure_reference '{other}' (expected 'absolute' or \
714 'qnh')"
715 ))
716 }
717 },
718 };
719 let (pressure_hpa, pressure_supplied) = match mode {
720 PressureReferenceMode::Absolute => (entered_hpa, self.pressure_supplied),
721 PressureReferenceMode::Qnh => {
722 // A stored QNH is a reading unless it is the omitted default of either
723 // unit system (the CLI's `saved_pressure_is_reading`).
724 let reading = self.pressure_supplied
725 || [(UnitSystem::Metric, 1013.25), (UnitSystem::Imperial, 29.92)]
726 .into_iter()
727 .all(|(system, omitted)| {
728 (entered_hpa - to_hpa(omitted, system)).abs() >= 1e-6
729 });
730 (
731 reduce_qnh_to_station_pressure(entered_hpa, altitude_m),
732 reading,
733 )
734 }
735 };
736 let presence =
737 StationAtmospherePresence::new(self.temperature_supplied, pressure_supplied);
738 (
739 to_celsius(self.temperature),
740 pressure_hpa,
741 altitude_m,
742 presence,
743 // From the pressure as stored (a QNH before its reduction).
744 StationOrigin::resolving(entered_hpa, altitude_m, mode, presence),
745 )
746 }
747 };
748 Ok((
749 crate::cli_api::AtmosphericConditions {
750 temperature: temperature_c,
751 pressure: pressure_hpa,
752 humidity: self.humidity,
753 altitude: altitude_m,
754 },
755 presence,
756 origin,
757 ))
758 }
759
760 /// This profile's stored air refused by the rule a flight of it applies (a humidity outside
761 /// the sensor band, a temperature at or below absolute zero, a pressure at or below 0, a
762 /// density altitude no air has, air that cannot exist), named in the words of whoever reads
763 /// the profile (`fields`: humidity, temperature, pressure, altitude), with the temperature,
764 /// pressure and every altitude in the profile's own units; `None` when the air flies, or
765 /// when [`Self::stored_station`] cannot read the profile at all (its own refusal is reported
766 /// where that is checked).
767 ///
768 /// A profile with a stored density altitude flies its station
769 /// ([`crate::atmosphere::station_for_density_altitude`]), so a caller names the altitude and
770 /// the pressure (and the temperature, unless one is stored as a reading) by the density
771 /// altitude's field, as [`Self::air_refusal`] does.
772 pub fn air_refusal_in(
773 &self,
774 fields: [crate::atmosphere::AirField<'_>; 4],
775 ) -> Option<crate::atmosphere::AirRefusal> {
776 use crate::atmosphere::AirUnits;
777 let air_units = match self.unit_system().ok()? {
778 UnitSystem::Metric => AirUnits::METRIC,
779 UnitSystem::Imperial => AirUnits::IMPERIAL,
780 };
781 if let Some(density_altitude) = self.density_altitude {
782 let (to_celsius, to_meters) = self.station_converters().ok()?;
783 let explicit_temperature_c = self
784 .temperature_supplied
785 .then(|| to_celsius(self.temperature));
786 if let Err(error) = crate::atmosphere::station_for_density_altitude(
787 to_meters(density_altitude),
788 explicit_temperature_c,
789 ) {
790 let [humidity, temperature, pressure, altitude] = fields;
791 let temperature_c = explicit_temperature_c.unwrap_or(f64::NAN);
792 return Some(
793 error.refusal_in(
794 &crate::atmosphere::AirSpelling {
795 humidity,
796 temperature,
797 pressure,
798 altitude,
799 humidity_sent: self.humidity,
800 temperature_text: air_units.temperature.text(temperature_c),
801 temperature_unit: air_units.temperature,
802 temperature_origin: crate::atmosphere::StationOrigin::density_altitude(
803 explicit_temperature_c.is_some(),
804 )
805 .temperature,
806 pressure_text: String::new(),
807 pressure_origin:
808 crate::atmosphere::StationPressureOrigin::DensityAltitude,
809 qnh_text: None,
810 altitude_unit: air_units.altitude,
811 },
812 to_meters(density_altitude),
813 temperature_c,
814 f64::NAN,
815 ),
816 );
817 }
818 }
819 let (conditions, presence, origin) = self.stored_station().ok()?;
820 conditions.air_refusal_from(presence, origin, fields, self.humidity, air_units)
821 }
822
823 /// The profile's `units` conversions of a stored temperature to °C and an altitude to
824 /// metres, the CLI's own factors.
825 #[allow(clippy::type_complexity)]
826 fn station_converters(&self) -> Result<(fn(f64) -> f64, fn(f64) -> f64), String> {
827 Ok(match self.unit_system()? {
828 UnitSystem::Metric => (|value| value, |value| value),
829 UnitSystem::Imperial => (|value| (value - 32.0) * 5.0 / 9.0, |value| value * 0.3048),
830 })
831 }
832
833 /// [`Self::air_refusal_in`] in the stored profile's own words: `profile '<name>' field
834 /// humidity = 100 at 100 °C and 1013.25 hPa: no such air exists: ...`,
835 /// `profile '<name>' field pressure = -1 inHg: pressure must be greater than 0`, located at
836 /// the stored document's member (`$.humidity`, `$.temperature`, `$.pressure`,
837 /// `$.altitude`). A stored density altitude is the field of the altitude and the pressure
838 /// it gives the station, and of its temperature unless one is stored as a reading
839 /// (`profile '<name>' field density_altitude = 200000 ft: no air has this density altitude:
840 /// ...`, at `$.density_altitude`). The rule every flight of the profile applies, for the
841 /// surfaces that read a profile without flying it: `profile.validate`, `.a7p` export,
842 /// `profile show`.
843 pub fn air_refusal(&self) -> Option<crate::atmosphere::AirRefusal> {
844 let names = [
845 "humidity",
846 "temperature",
847 "pressure",
848 "altitude",
849 "density_altitude",
850 ]
851 .map(|field| format!("profile '{}' field {field}", self.name));
852 let field = |index: usize, path: &'static str| crate::atmosphere::AirField {
853 name: &names[index],
854 path,
855 };
856 let density_altitude = field(4, "$.density_altitude");
857 let derived = self.density_altitude.is_some();
858 self.air_refusal_in([
859 field(0, "$.humidity"),
860 if derived && !self.temperature_supplied {
861 density_altitude
862 } else {
863 field(1, "$.temperature")
864 },
865 if derived {
866 density_altitude
867 } else {
868 field(2, "$.pressure")
869 },
870 if derived {
871 density_altitude
872 } else {
873 field(3, "$.altitude")
874 },
875 ])
876 }
877
878 /// The cheap invariants the CLI already applies to a saved profile, collected instead
879 /// of short-circuited: the `units` string (`converted_to`'s gate), the stored humidity
880 /// ([`Self::validate_humidity`], `load_profile`'s gate) and, when it is one, whether the
881 /// stored air can exist at all ([`Self::air_refusal`], every flight's gate), the MBA-1358
882 /// tracking-CF band (`load_profile`'s gate), and the MBA-1348 turret/optic assembly +
883 /// validation (`profile save`'s gate, including `parse_click_value` on the stored
884 /// click graduations). No new physics checks — this is exactly the existing load/save
885 /// surface, aggregated for the bridge's `profile.validate`. Empty means the profile
886 /// passes every one of those gates.
887 pub fn validation_warnings(&self) -> Vec<String> {
888 let mut warnings = Vec::new();
889 if let Err(err) = self.unit_system() {
890 warnings.push(err);
891 }
892 if let Err(err) = self.validate_humidity() {
893 warnings.push(err);
894 } else if let Some(refusal) = self.air_refusal() {
895 // The rule every flight of this profile applies to its air, so a profile reported
896 // valid is one every solve of it can fly.
897 warnings.push(format!(
898 "{refusal}; edit the humidity, temperature, pressure, altitude or density \
899 altitude stored in the profile"
900 ));
901 }
902 if let Some(cf) = self.elevation_cf {
903 if let Err(err) = validate_tracking_cf(cf, "profile field elevation_cf") {
904 warnings.push(err);
905 }
906 }
907 if let Some(cf) = self.windage_cf {
908 if let Err(err) = validate_tracking_cf(cf, "profile field windage_cf") {
909 warnings.push(err);
910 }
911 }
912 match self.optic_profile() {
913 Err(err) => warnings.push(format!("turret/optic model: {err}")),
914 Ok(Some(optic)) => {
915 if let Err(err) = optic.validate() {
916 warnings.push(format!("turret/optic model: {err}"));
917 }
918 }
919 Ok(None) => {}
920 }
921 warnings
922 }
923}
924
925#[cfg(test)]
926mod tests {
927 use super::*;
928
929 /// A literal on-disk profile document exercising the big wire surface: the five
930 /// mandatory fields, bc_segments, drag_curve, dsf_points, tracking CFs, named zero
931 /// sets with POI corrections, the click graduations plus all twelve turret/hold
932 /// fields, and a reticle — PLUS a top-level key this build has never heard of
933 /// ("future_field") and an unknown key nested inside a zero set, because tolerating
934 /// unknown keys (no `deny_unknown_fields`) is the documented forward-compat behavior
935 /// this struct has always had and the move into the library must not change.
936 const FIXTURE: &str = r#"{
937 "name": "wire-shape-fixture",
938 "velocity": 762.0,
939 "bc": 0.243,
940 "mass": 11.33980925,
941 "diameter": 7.8232,
942 "drag_model": "G7",
943 "twist_rate": 254.0,
944 "sight_height": 50.8,
945 "zero_distance": 91.44,
946 "units": "metric",
947 "temperature": 15.0,
948 "pressure": 1013.207888,
949 "humidity": 55.0,
950 "altitude": 304.8,
951 "bullet_name": "175gr SMK",
952 "created": "1755400000",
953 "wind_speed": 4.4704,
954 "wind_direction": 90.0,
955 "shooting_angle": -5.0,
956 "auto_zero": 91.44,
957 "twist_right": false,
958 "use_bc_segments": true,
959 "bullet_length": 30.48,
960 "elevation_click": "0.1mil",
961 "windage_click": "0.25moa",
962 "bc_segments": [
963 {"bc": 0.243, "velocity_mps": 792.0},
964 {"bc": 0.230, "velocity_mps": 400.0}
965 ],
966 "drag_curve": [
967 {"mach": 0.5, "cd": 0.23},
968 {"mach": 1.2, "cd": 0.45},
969 {"mach": 3.0, "cd": 0.28}
970 ],
971 "dsf_points": [
972 {"mach": 0.9, "dsf": 1.04}
973 ],
974 "bc_reference": "army-standard-metro",
975 "pressure_reference": "qnh",
976 "density_altitude": 500.0,
977 "zero_poi_up_m": 0.05,
978 "zero_poi_right_m": -0.02,
979 "sight_offset_lateral_m": 0.01,
980 "elevation_cf": 0.97,
981 "windage_cf": 1.02,
982 "zero_sets": [
983 {"name": "suppressed", "zero_distance": 200.0, "poi_up_mil": -0.3,
984 "poi_right_mil": 0.1, "notes": "suppressed load",
985 "zero_set_future_field": true},
986 {"name": "match", "poi_up_mil": 0.25}
987 ],
988 "reticle": {
989 "name": "mil-grid 0.5/10",
990 "focal_plane": "ffp",
991 "reference_magnification": 10.0,
992 "marks": [
993 {"down_mil": 0.0, "right_mil": 0.0, "kind": "center"},
994 {"down_mil": 1.0, "right_mil": 0.0, "kind": "hash", "label": "1.0"}
995 ]
996 },
997 "clicks_per_revolution": 100,
998 "zero_stop": true,
999 "elevation_travel_up_mil": 26.0,
1000 "elevation_travel_down_mil": 4.0,
1001 "windage_travel_left_mil": 12.0,
1002 "windage_travel_right_mil": 12.0,
1003 "turret_elevation_dialed_mil": 5.4,
1004 "turret_windage_dialed_mil": -0.2,
1005 "hold_bound_up_mil": 5.0,
1006 "hold_bound_down_mil": 10.0,
1007 "hold_bound_left_mil": 6.0,
1008 "hold_bound_right_mil": 6.0,
1009 "future_field": {"nested": [1, 2, 3]}
1010 }"#;
1011
1012 /// deserialize -> serialize -> deserialize is the identity on every stored field,
1013 /// and the two serializations are byte-identical to each other (the engine's own
1014 /// output is stable). Unknown input keys are tolerated on the way in — the
1015 /// pre-existing behavior — and are NOT preserved on the way out (serde drops them;
1016 /// also pre-existing, documented in the module doc).
1017 #[test]
1018 fn wire_shape_round_trips_field_for_field() {
1019 let first: ProfileData = serde_json::from_str(FIXTURE).expect("fixture must load");
1020 let serialized = serde_json::to_string(&first).expect("serialize");
1021 let second: ProfileData = serde_json::from_str(&serialized).expect("reload");
1022
1023 // The engine re-serializes its own output identically.
1024 assert_eq!(
1025 serde_json::to_value(&first).unwrap(),
1026 serde_json::to_value(&second).unwrap()
1027 );
1028
1029 // Field-level equality across the whole surface (ProfileData does not derive
1030 // PartialEq, deliberately — nothing in production compares whole profiles).
1031 assert_eq!(second.name, "wire-shape-fixture");
1032 assert_eq!(second.velocity.to_bits(), 762.0f64.to_bits());
1033 assert_eq!(second.bc.to_bits(), 0.243f64.to_bits());
1034 assert_eq!(second.mass.to_bits(), 11.33980925f64.to_bits());
1035 assert_eq!(second.diameter.to_bits(), 7.8232f64.to_bits());
1036 assert_eq!(second.drag_model, "G7");
1037 assert_eq!(second.twist_rate, Some(254.0));
1038 assert_eq!(second.sight_height, Some(50.8));
1039 assert_eq!(second.zero_distance, Some(91.44));
1040 assert_eq!(second.units, "metric");
1041 assert_eq!(second.temperature.to_bits(), 15.0f64.to_bits());
1042 assert_eq!(second.pressure.to_bits(), 1013.207888f64.to_bits());
1043 assert_eq!(second.humidity.to_bits(), 55.0f64.to_bits());
1044 assert_eq!(second.altitude.to_bits(), 304.8f64.to_bits());
1045 assert_eq!(second.bullet_name.as_deref(), Some("175gr SMK"));
1046 assert_eq!(second.created.as_deref(), Some("1755400000"));
1047 assert_eq!(second.wind_speed, Some(4.4704));
1048 assert_eq!(second.wind_direction, Some(90.0));
1049 assert_eq!(second.shooting_angle, Some(-5.0));
1050 assert_eq!(second.auto_zero, Some(91.44));
1051 assert_eq!(second.twist_right, Some(false));
1052 assert_eq!(second.use_bc_segments, Some(true));
1053 assert_eq!(second.bullet_length, Some(30.48));
1054 assert_eq!(second.elevation_click.as_deref(), Some("0.1mil"));
1055 assert_eq!(second.windage_click.as_deref(), Some("0.25moa"));
1056 assert_eq!(
1057 second.bc_segments,
1058 Some(vec![
1059 ProfileBcSegment {
1060 bc: 0.243,
1061 velocity_mps: 792.0
1062 },
1063 ProfileBcSegment {
1064 bc: 0.230,
1065 velocity_mps: 400.0
1066 },
1067 ])
1068 );
1069 assert_eq!(
1070 second.drag_curve,
1071 Some(vec![
1072 ProfileDragPoint {
1073 mach: 0.5,
1074 cd: 0.23
1075 },
1076 ProfileDragPoint {
1077 mach: 1.2,
1078 cd: 0.45
1079 },
1080 ProfileDragPoint {
1081 mach: 3.0,
1082 cd: 0.28
1083 },
1084 ])
1085 );
1086 assert_eq!(
1087 second.dsf_points,
1088 Some(vec![DsfPoint {
1089 mach: 0.9,
1090 dsf: 1.04
1091 }])
1092 );
1093 assert_eq!(second.bc_reference.as_deref(), Some("army-standard-metro"));
1094 assert_eq!(second.pressure_reference.as_deref(), Some("qnh"));
1095 assert_eq!(second.density_altitude, Some(500.0));
1096 assert_eq!(second.zero_poi_up_m, Some(0.05));
1097 assert_eq!(second.zero_poi_right_m, Some(-0.02));
1098 assert_eq!(second.sight_offset_lateral_m, Some(0.01));
1099 assert_eq!(second.elevation_cf, Some(0.97));
1100 assert_eq!(second.windage_cf, Some(1.02));
1101 let sets = second.zero_sets.as_deref().expect("zero_sets kept");
1102 assert_eq!(sets.len(), 2);
1103 assert_eq!(sets[0].name, "suppressed");
1104 assert_eq!(sets[0].zero_distance, Some(200.0));
1105 assert_eq!(sets[0].poi_up_mil, Some(-0.3));
1106 assert_eq!(sets[0].poi_right_mil, Some(0.1));
1107 assert_eq!(sets[0].notes.as_deref(), Some("suppressed load"));
1108 assert_eq!(sets[1].name, "match");
1109 assert_eq!(sets[1].zero_distance, None);
1110 assert_eq!(sets[1].poi_up_mil, Some(0.25));
1111 assert_eq!(sets[1].poi_right_mil, None);
1112 let reticle = second.reticle.as_ref().expect("reticle kept");
1113 assert_eq!(reticle.name, "mil-grid 0.5/10");
1114 assert_eq!(reticle.marks.len(), 2);
1115 assert_eq!(reticle.marks[1].label.as_deref(), Some("1.0"));
1116 assert_eq!(second.clicks_per_revolution, Some(100));
1117 assert_eq!(second.zero_stop, Some(true));
1118 assert_eq!(second.elevation_travel_up_mil, Some(26.0));
1119 assert_eq!(second.elevation_travel_down_mil, Some(4.0));
1120 assert_eq!(second.windage_travel_left_mil, Some(12.0));
1121 assert_eq!(second.windage_travel_right_mil, Some(12.0));
1122 assert_eq!(second.turret_elevation_dialed_mil, Some(5.4));
1123 assert_eq!(second.turret_windage_dialed_mil, Some(-0.2));
1124 assert_eq!(second.hold_bound_up_mil, Some(5.0));
1125 assert_eq!(second.hold_bound_down_mil, Some(10.0));
1126 assert_eq!(second.hold_bound_left_mil, Some(6.0));
1127 assert_eq!(second.hold_bound_right_mil, Some(6.0));
1128
1129 // Unknown keys were tolerated (this test got this far) and dropped on re-save
1130 // (pre-existing serde behavior, documented in the module doc): no invented keys.
1131 let reserialized: serde_json::Value = serde_json::from_str(&serialized).unwrap();
1132 assert!(reserialized.get("future_field").is_none());
1133
1134 // This fixture also passes every load/save invariant `validation_warnings`
1135 // aggregates (units, CF band, optic assembly + validation).
1136 assert_eq!(second.validation_warnings(), Vec::<String>::new());
1137 }
1138
1139 /// The minimal legacy (pre-v2) document: only the five mandatory fields. The four
1140 /// defaulted scalars fill in (imperial / 59 F / 29.92 inHg / 50%), every `Option`
1141 /// stays `None`, and — load-bearing for on-disk compatibility — re-serialization
1142 /// keeps the non-`skip_serializing_if` optional keys (`twist_rate`, `sight_height`,
1143 /// `zero_distance`, `bullet_name`, `created`) present as JSON `null` while every
1144 /// `skip_serializing_if` key stays absent.
1145 #[test]
1146 fn legacy_minimal_document_defaults_and_reserializes_with_stable_keys() {
1147 let legacy = r#"{
1148 "name": "legacy",
1149 "velocity": 2500.0,
1150 "bc": 0.475,
1151 "mass": 175.0,
1152 "diameter": 0.308,
1153 "drag_model": "G1"
1154 }"#;
1155 let profile: ProfileData = serde_json::from_str(legacy).expect("legacy must load");
1156 assert_eq!(profile.units, "imperial");
1157 assert_eq!(profile.temperature.to_bits(), 59.0f64.to_bits());
1158 assert_eq!(profile.pressure.to_bits(), 29.92f64.to_bits());
1159 assert_eq!(profile.humidity.to_bits(), 50.0f64.to_bits());
1160 assert_eq!(profile.altitude.to_bits(), 0.0f64.to_bits());
1161 assert!(profile.bc_segments.is_none());
1162 assert!(profile.zero_sets.is_none());
1163
1164 let out: serde_json::Value =
1165 serde_json::from_str(&serde_json::to_string(&profile).unwrap()).unwrap();
1166 // Plain-`default` options serialize as explicit null (the historical shape)...
1167 assert!(out
1168 .get("twist_rate")
1169 .is_some_and(serde_json::Value::is_null));
1170 assert!(out
1171 .get("bullet_name")
1172 .is_some_and(serde_json::Value::is_null));
1173 assert!(out.get("created").is_some_and(serde_json::Value::is_null));
1174 // ...while `skip_serializing_if` options stay absent entirely.
1175 for absent in [
1176 "wind_speed",
1177 "bc_segments",
1178 "drag_curve",
1179 "dsf_points",
1180 "zero_sets",
1181 "reticle",
1182 "elevation_click",
1183 "elevation_cf",
1184 "clicks_per_revolution",
1185 ] {
1186 assert!(out.get(absent).is_none(), "{absent} must stay absent");
1187 }
1188 assert_eq!(profile.validation_warnings(), Vec::<String>::new());
1189 }
1190
1191 /// `validation_warnings` reports exactly the CLI's own gates: an out-of-band
1192 /// tracking CF (load gate), a bad units string (`converted_to` gate), and an
1193 /// incomplete turret pair / unparseable click (save gate) — and nothing for a
1194 /// profile that merely leaves everything optional unset.
1195 #[test]
1196 fn validation_warnings_mirror_the_cli_gates() {
1197 let mut profile: ProfileData = serde_json::from_str(FIXTURE).unwrap();
1198 profile.elevation_cf = Some(0.4); // outside the (0.5, 1.5) band
1199 profile.units = "nautical".to_string();
1200 profile.elevation_travel_down_mil = None; // breaks the all-or-nothing pair
1201 let warnings = profile.validation_warnings();
1202 assert_eq!(warnings.len(), 3, "{warnings:?}");
1203 assert!(
1204 warnings.iter().any(|w| w.contains("elevation_cf")),
1205 "{warnings:?}"
1206 );
1207 assert!(
1208 warnings.iter().any(|w| w.contains("unsupported units")),
1209 "{warnings:?}"
1210 );
1211 assert!(
1212 warnings.iter().any(|w| w.contains("--travel-down")),
1213 "{warnings:?}"
1214 );
1215 }
1216}