ballistics_engine/solve_json.rs
1//! Versioned, binding-neutral JSON data-transfer objects for trajectory solves.
2//!
3//! These types deliberately do not expose [`crate::BallisticInputs`]. The public JSON contract
4//! has its own names, units, defaults, and compatibility policy so engine internals can evolve
5//! without silently changing requests produced by language bindings.
6
7use serde::{
8 de::{self, Visitor},
9 ser::SerializeStruct,
10 Deserialize, Deserializer, Serialize, Serializer,
11};
12use serde_json::{Map, Value};
13use std::{fmt, num::NonZeroUsize};
14
15/// The only solve-json schema version understood by this module.
16pub const SOLVE_JSON_SCHEMA_VERSION_V1: u32 = 1;
17
18/// Exact, case-sensitive wire names accepted for solve-json v1 reference drag models.
19///
20/// Kept as the single metadata source for protocol validation and the MCP schema/engine-info
21/// mirrors so those public surfaces cannot drift apart when the engine gains a model.
22pub const DRAG_MODEL_WIRE_NAMES_V1: [&str; 9] =
23 ["G1", "G2", "G5", "G6", "G7", "G8", "GI", "GS", "RA4"];
24
25/// Maximum number of trajectory observations in one solve-json v1 success response.
26///
27/// Service implementations must reject a response above this limit with
28/// [`SolveSuccessV1::validate_for_serialization`] instead of truncating it.
29pub const MAX_SOLVE_JSON_SAMPLES_V1: usize = 10_000;
30
31/// Deserialize a request member that may be omitted but may not be JSON `null`.
32///
33/// Serde supplies [`Option::None`] from the field's `default` only when the member is absent.
34/// When the member is present, deserialize `T` directly so `null` is rejected for scalar,
35/// enum, object, and array values alike.
36fn deserialize_present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
37where
38 D: Deserializer<'de>,
39 T: Deserialize<'de>,
40{
41 T::deserialize(deserializer).map(Some)
42}
43
44/// An invariant solve-json v1 schema discriminator.
45///
46/// This unit type has no invalid public state: it always serializes as the JSON integer `1` and
47/// deserializes only from that integer.
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
49pub struct SchemaVersionV1;
50
51impl SchemaVersionV1 {
52 /// Return the integer represented on the wire.
53 pub const fn get(self) -> u32 {
54 SOLVE_JSON_SCHEMA_VERSION_V1
55 }
56}
57
58impl Serialize for SchemaVersionV1 {
59 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60 where
61 S: Serializer,
62 {
63 serializer.serialize_u32(SOLVE_JSON_SCHEMA_VERSION_V1)
64 }
65}
66
67impl<'de> Deserialize<'de> for SchemaVersionV1 {
68 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69 where
70 D: Deserializer<'de>,
71 {
72 struct SchemaVersionVisitor;
73
74 impl<'de> Visitor<'de> for SchemaVersionVisitor {
75 type Value = SchemaVersionV1;
76
77 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
78 formatter.write_str("the integer 1")
79 }
80
81 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
82 where
83 E: de::Error,
84 {
85 if value == u64::from(SOLVE_JSON_SCHEMA_VERSION_V1) {
86 Ok(SchemaVersionV1)
87 } else {
88 Err(E::custom(format!(
89 "unsupported schema_version {value}; expected {SOLVE_JSON_SCHEMA_VERSION_V1}"
90 )))
91 }
92 }
93
94 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
95 where
96 E: de::Error,
97 {
98 if value == i64::from(SOLVE_JSON_SCHEMA_VERSION_V1) {
99 Ok(SchemaVersionV1)
100 } else {
101 Err(E::custom(format!(
102 "unsupported schema_version {value}; expected {SOLVE_JSON_SCHEMA_VERSION_V1}"
103 )))
104 }
105 }
106 }
107
108 deserializer.deserialize_any(SchemaVersionVisitor)
109 }
110}
111
112/// A complete v1 trajectory-solve request.
113///
114/// All dimensional values use SI units named in the field. Every section is mandatory, even
115/// when all fields in a section have defaults; this keeps the top-level request shape explicit.
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117#[serde(deny_unknown_fields)]
118pub struct SolveRequestV1 {
119 /// Must be exactly [`SOLVE_JSON_SCHEMA_VERSION_V1`].
120 pub schema_version: SchemaVersionV1,
121 pub projectile: ProjectileV1,
122 pub rifle: RifleV1,
123 pub shot: ShotV1,
124 pub atmosphere: AtmosphereV1,
125 pub wind: WindV1,
126 pub solver: SolverV1,
127 pub effects: EffectsV1,
128 pub sampling: SamplingV1,
129 /// Optional reticle hold-point request (MBA-1361). Absent (the historical shape) leaves
130 /// both the solve and the response byte-identical; present adds
131 /// [`SolveSuccessV1::reticle_hold`] and echoes itself at
132 /// [`ResolvedSolveRequestV1::reticle`] (0.33.0 decision-support Task 1), and nothing
133 /// else. It is a pure post-processing read of the solved samples — it cannot change
134 /// the trajectory.
135 #[serde(
136 default,
137 skip_serializing_if = "Option::is_none",
138 deserialize_with = "deserialize_present"
139 )]
140 pub reticle: Option<ReticleRequestV1>,
141 /// Optional offline correction sources applied before the solve. Absent (the
142 /// historical shape) is byte-identical to every request from before the block
143 /// existed; present it is echoed at [`ResolvedSolveRequestV1::corrections`] so a
144 /// resolved request remains a complete description of the solve (the perturbation
145 /// kernel re-solves from it).
146 #[serde(
147 default,
148 skip_serializing_if = "Option::is_none",
149 deserialize_with = "deserialize_present"
150 )]
151 pub corrections: Option<CorrectionsV1>,
152}
153
154/// Offline correction sources for a solve (additive-optional).
155///
156/// `bc5d_table_path` names a caliber-specific BC5D correction table on the LOCAL
157/// filesystem (`bc5d_<caliber>.bin`, the exact dual-CRC binary format the CLI's
158/// `--bc-table-dir` consumes; mobile apps download tables themselves and hand the
159/// engine a path). The service CRC-verifies the file, generates the same
160/// velocity-keyed BC segment ladder the CLI does for this load, applies the table's
161/// muzzle correction to the scalar BC as the interior-gap fallback, and solves BOTH
162/// the zero search and the trajectory with that schedule. A table that carries no
163/// correction for the load (every sampled cell ~= 1.0) leaves the request's constant
164/// BC in place. On builds without filesystem access (wasm32) supplying the field is
165/// a structured `invalid_value` error, never a silent no-op.
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
167#[serde(deny_unknown_fields)]
168pub struct CorrectionsV1 {
169 /// Path to a BC5D `.bin` correction table on the local filesystem.
170 #[serde(
171 default,
172 skip_serializing_if = "Option::is_none",
173 deserialize_with = "deserialize_present"
174 )]
175 pub bc5d_table_path: Option<String>,
176}
177
178/// Ask for a reticle hold point alongside the trajectory (MBA-1361).
179///
180/// `description` is the shared [`crate::reticle::ReticleDescription`] schema — the very same
181/// JSON `ballistics reticle generate -o json` emits — so a service and a CLI user exchange
182/// one representation. It is deliberately permissive about extra keys inside the
183/// description (front ends carry render metadata there); the envelope around it stays
184/// strict.
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186#[serde(deny_unknown_fields)]
187pub struct ReticleRequestV1 {
188 /// Range at which the hold is evaluated, meters. Must be inside the sampled trajectory.
189 pub range_m: f64,
190 /// The optic's magnification in use. Must be finite and greater than zero on both
191 /// focal planes.
192 pub magnification: f64,
193 pub description: crate::reticle::ReticleDescription,
194}
195
196/// The reticle hold point for a solved trajectory (MBA-1361).
197///
198/// Angles are milliradians from the optical center: `down_mil` positive BELOW center,
199/// `right_mil` positive to the shooter's RIGHT.
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct ReticleHoldV1 {
203 /// Echo of the requested evaluation range, meters.
204 pub range_m: f64,
205 /// Echo of the requested magnification.
206 pub magnification: f64,
207 pub down_mil: f64,
208 pub right_mil: f64,
209 /// The subtension scale applied to the marks (`reference_magnification / magnification`
210 /// for SFP, exactly `1.0` for FFP).
211 pub mark_scale: f64,
212 /// Index into the request's `description.marks` of the nearest mark, in TRUE angular
213 /// space.
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub nearest_mark_index: Option<usize>,
216 /// That mark's label, when it carries one.
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub nearest_mark_label: Option<String>,
219 pub nearest_mark_distance_mil: f64,
220 /// True when the hold has run outside the marked area (see
221 /// [`crate::reticle::ReticleHold::off_reticle`] for the exact rule).
222 pub off_reticle: bool,
223}
224
225/// Projectile inputs supported by solve-json v1.
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227#[serde(deny_unknown_fields)]
228pub struct ProjectileV1 {
229 pub mass_kg: f64,
230 pub diameter_m: f64,
231 #[serde(
232 default,
233 skip_serializing_if = "Option::is_none",
234 deserialize_with = "deserialize_present"
235 )]
236 pub length_m: Option<f64>,
237 pub drag_model: DragModelV1,
238 pub ballistic_coefficient: f64,
239 /// A caller-supplied drag curve replacing `drag_model`'s (MBA-1597). See [`DragTableV1`].
240 /// Beside `bc_segments` it must be a [`DragTableKindV1::Reference`] curve, which the band
241 /// BCs are then measured against.
242 #[serde(
243 default,
244 skip_serializing_if = "Option::is_none",
245 deserialize_with = "deserialize_present"
246 )]
247 pub drag_table: Option<DragTableV1>,
248 /// A velocity-banded BC ladder (MBA-1598): solve-json's form of the CLI's `--bc-segment`.
249 /// See [`BcSegmentV1`] for the band rules.
250 ///
251 /// `ballistic_coefficient` stays required and validated beside it, but flies only in an
252 /// interior gap between two bands, and blended into the bands within up to 25 fps either
253 /// side of a gap edge. Below the lowest band, or at or above the highest, the nearest edge
254 /// band applies, so under a gapless ladder the scalar never flies. A one-band ladder's BC
255 /// must match `ballistic_coefficient` (see [`ONE_BAND_BC_RELATIVE_TOLERANCE_V1`]).
256 ///
257 /// Band BCs are referenced to the same curve as the scalar: `drag_model`'s, or a
258 /// [`DragTableKindV1::Reference`] `drag_table`'s, which then flies the bands exactly as a
259 /// built-in model does. The engine cannot check which curve a published band BC was
260 /// measured against; the caller must send the matching one. Bands are selected by airspeed
261 /// (speed relative to the air mass), and interior band and gap edges are smoothstep-blended
262 /// (`velocity_segment_bc` in `src/bc_estimation.rs`). Refused (`conflicting_fields`)
263 /// alongside a [`DragTableKindV1::Projectile`] `drag_table`, whose curve is the projectile's
264 /// own Cd with no BC for the bands to change, and alongside `corrections.bc5d_table_path`,
265 /// which builds its own ladder from `ballistic_coefficient`.
266 #[serde(
267 default,
268 skip_serializing_if = "Option::is_none",
269 deserialize_with = "deserialize_present"
270 )]
271 pub bc_segments: Option<Vec<BcSegmentV1>>,
272}
273
274/// One band of a [`ProjectileV1::bc_segments`] ladder: the BC that flies while the bullet's
275/// airspeed lies in `[velocity_min_mps, velocity_max_mps)`.
276///
277/// - Band BCs are in lb/in², referenced to the same curve as the scalar
278/// `ballistic_coefficient` (`projectile.drag_model`, or a reference-kind
279/// `projectile.drag_table`), and held to the same bounds.
280/// - Bands are selected by airspeed: the bullet's speed relative to the air mass, not over the
281/// ground.
282/// - The array runs from the fastest band to the slowest. `velocity_min_mps` strictly
283/// descends, and each band ends at or below the start of the band before it: touching edges
284/// and gaps are legal, overlaps are not. The order is only a validation rule; the lookup
285/// itself does not depend on it.
286/// - A ladder holds [`MIN_BC_SEGMENTS_V1`] to [`MAX_BC_SEGMENTS_V1`] bands.
287/// - In an interior gap between two bands the scalar `ballistic_coefficient` flies. Below the
288/// lowest band, or at or above the highest, the nearest edge band applies, so under a
289/// gapless ladder the scalar never flies.
290/// - A one-band ladder flies its band's BC at every speed, so that BC must match the scalar
291/// `ballistic_coefficient` to within [`ONE_BAND_BC_RELATIVE_TOLERANCE_V1`]; the band's edges
292/// then change nothing.
293/// - Every interior band-to-band edge and every gap edge is blended with a smoothstep across
294/// a narrow window centred on it, so the integrator never sees the drag jump in one step
295/// (`velocity_segment_bc` in `src/bc_estimation.rs`).
296#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
297#[serde(deny_unknown_fields)]
298pub struct BcSegmentV1 {
299 /// Lower edge of the band, m/s, inclusive. Finite and >= 0.
300 pub velocity_min_mps: f64,
301 /// Upper edge of the band, m/s, exclusive. Finite and > `velocity_min_mps`; there is no
302 /// upper bound.
303 pub velocity_max_mps: f64,
304 /// This band's BC, lb/in² against the same curve as the scalar `ballistic_coefficient`
305 /// (`projectile.drag_model`, or a reference-kind `projectile.drag_table`). Same bounds as
306 /// the scalar.
307 pub ballistic_coefficient: f64,
308}
309
310/// The fewest points a [`DragTableV1`] may hold — two define a curve.
311pub const MIN_DRAG_TABLE_POINTS_V1: usize = 2;
312
313/// The most points a [`DragTableV1`] may hold. Matches the `.drg`/CSV loader behind the CLI's
314/// `--drag-table` and the array FFI's `MAX_FFI_DRAG_TABLE_LEN`.
315pub const MAX_DRAG_TABLE_POINTS_V1: usize = 4096;
316
317/// The longest [`DragTableV1::name`], in characters (Unicode scalar values, not bytes). Room for
318/// a curve's name and where it came from, such as "GA (ChairGun Elite)"; not a document.
319pub const MAX_DRAG_TABLE_NAME_CHARS_V1: usize = 64;
320
321/// The fewest bands a [`ProjectileV1::bc_segments`] ladder may hold. An empty array is refused
322/// rather than read as "no ladder"; omit the field for that.
323pub const MIN_BC_SEGMENTS_V1: usize = 1;
324
325/// The most bands a [`ProjectileV1::bc_segments`] ladder may hold. The BC lookup scans the
326/// ladder on every derivative evaluation, so the cap bounds the per-step cost; it is far past
327/// the handful of bands a published multi-BC schedule lists.
328pub const MAX_BC_SEGMENTS_V1: usize = 64;
329
330/// How closely a one-band [`ProjectileV1::bc_segments`] ladder's BC must match the scalar
331/// `ballistic_coefficient`, relative to the larger of the two: one part in a million. That
332/// forgives rounding nobody chose, such as a BC held as an `f32` (`0.243f32` reads back as
333/// `0.24300000071525574`) or converted between units and back, but not a different value: 0.172
334/// against 0.1724 is still refused. Within it, the band's BC is the one that flies.
335pub const ONE_BAND_BC_RELATIVE_TOLERANCE_V1: f64 = 1.0e-6;
336
337/// A caller-supplied Cd-vs-Mach drag curve (MBA-1597): solve-json's form of the CLI's
338/// `--drag-table`.
339///
340/// `kind` says what `ballistic_coefficient` means beside it, and has no default: the two
341/// readings differ by the projectile's form factor, so a guess gives confident, wrong drops.
342/// While a table is present `drag_model` does not drive drag under either kind. Only a
343/// [`DragTableKindV1::Reference`] curve may be sent with a [`ProjectileV1::bc_segments`]
344/// ladder.
345#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
346#[serde(deny_unknown_fields)]
347pub struct DragTableV1 {
348 pub kind: DragTableKindV1,
349 /// Optional free-text label for the curve, such as "GA (ChairGun Elite)", echoed verbatim in
350 /// the resolved request and never read by the solver. `drag_model` cannot say which curve
351 /// flew, and two programs can ship different curves under one name, so the caller says it
352 /// here. 1 to [`MAX_DRAG_TABLE_NAME_CHARS_V1`] characters, not blank, one line (no control
353 /// characters, no U+2028/U+2029 line or paragraph separators); omitted from the echo when
354 /// absent, so requests without it are unchanged. Like every optional request member it may be
355 /// omitted but not sent as JSON `null`.
356 #[serde(
357 default,
358 skip_serializing_if = "Option::is_none",
359 deserialize_with = "deserialize_present"
360 )]
361 pub name: Option<String>,
362 /// Strictly ascending in Mach, [`MIN_DRAG_TABLE_POINTS_V1`] to
363 /// [`MAX_DRAG_TABLE_POINTS_V1`] points. Outside the table the nearest end value is held.
364 pub points: Vec<DragPointV1>,
365}
366
367/// What a [`DragTableV1`] describes, and therefore what the request's BC means.
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "snake_case")]
370pub enum DragTableKindV1 {
371 /// A standard curve — an airgun pellet law such as GA2, say — that `ballistic_coefficient`
372 /// was measured against. Flown exactly as a built-in model is flown with its own BC, and so
373 /// is a [`ProjectileV1::bc_segments`] ladder measured against it: at each airspeed the
374 /// curve is divided by the band BC that flies there.
375 Reference,
376 /// This projectile's own measured Cd (Doppler radar, for instance).
377 /// `ballistic_coefficient` is not used, exactly as with the CLI's `--drag-table`, and a
378 /// [`ProjectileV1::bc_segments`] ladder is refused beside it (`conflicting_fields`), since
379 /// no BC reaches the drag.
380 Projectile,
381}
382
383/// One point of a [`DragTableV1`]: Mach (finite, >= 0) and drag coefficient (finite, > 0).
384#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
385#[serde(deny_unknown_fields)]
386pub struct DragPointV1 {
387 pub mach: f64,
388 pub cd: f64,
389}
390
391/// Check a [`DragTableV1`]'s values: the point count, then each point in order, naming the
392/// exact entry at fault. The same rules `DragTable::try_new` enforces for `--drag-table`.
393///
394/// Called from both the decoder and the solve service, so a Rust caller that builds a request
395/// without [`decode_solve_request_v1`] hears about a bad table at the same path.
396pub(crate) fn validate_drag_table_v1(table: &DragTableV1) -> Result<(), SolveErrorEnvelopeV1> {
397 if let Some(name) = &table.name {
398 validate_drag_table_name_v1(name)?;
399 }
400 let points_path = "$.projectile.drag_table.points";
401 let count = table.points.len();
402 if !(MIN_DRAG_TABLE_POINTS_V1..=MAX_DRAG_TABLE_POINTS_V1).contains(&count) {
403 return Err(protocol_error(
404 SolveErrorCodeV1::InvalidValue,
405 format!(
406 "drag_table must have {MIN_DRAG_TABLE_POINTS_V1} to \
407 {MAX_DRAG_TABLE_POINTS_V1} points, got {count}"
408 ),
409 points_path,
410 ));
411 }
412 let mut previous_mach: Option<f64> = None;
413 for (index, point) in table.points.iter().enumerate() {
414 let mach_path = format!("{points_path}[{index}].mach");
415 if !point.mach.is_finite() || point.mach < 0.0 {
416 return Err(protocol_error(
417 SolveErrorCodeV1::InvalidValue,
418 format!("mach must be finite and >= 0, got {}", point.mach),
419 mach_path,
420 ));
421 }
422 if let Some(previous) = previous_mach.filter(|previous| point.mach <= *previous) {
423 return Err(protocol_error(
424 SolveErrorCodeV1::InvalidValue,
425 format!(
426 "mach must strictly ascend; {} follows {previous} at points[{}]",
427 point.mach,
428 index - 1
429 ),
430 mach_path,
431 ));
432 }
433 if !point.cd.is_finite() || point.cd <= 0.0 {
434 return Err(protocol_error(
435 SolveErrorCodeV1::InvalidValue,
436 format!("cd must be finite and > 0, got {}", point.cd),
437 format!("{points_path}[{index}].cd"),
438 ));
439 }
440 previous_mach = Some(point.mach);
441 }
442 Ok(())
443}
444
445/// Check a [`DragTableV1::name`]: not blank, one line (no control characters and no U+2028 or
446/// U+2029 separators: a stray line break or escape would corrupt any table or log the label is
447/// printed in), and at most [`MAX_DRAG_TABLE_NAME_CHARS_V1`] characters. Format characters
448/// such as bidi marks are left alone: they are not line breaks, and a right-to-left label may
449/// need them. Kept verbatim otherwise: no trimming, no
450/// normalization, so the echo is exactly what was sent.
451fn validate_drag_table_name_v1(name: &str) -> Result<(), SolveErrorEnvelopeV1> {
452 let path = "$.projectile.drag_table.name";
453 if name.trim().is_empty() {
454 return Err(protocol_error(
455 SolveErrorCodeV1::InvalidValue,
456 "name must not be blank; omit the field for an unnamed table",
457 path,
458 ));
459 }
460 if let Some(breaking) = name
461 .chars()
462 .find(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'))
463 {
464 return Err(protocol_error(
465 SolveErrorCodeV1::InvalidValue,
466 format!(
467 "name must be one line, with no control characters or line breaks; found U+{:04X}",
468 u32::from(breaking)
469 ),
470 path,
471 ));
472 }
473 let length = name.chars().count();
474 if length > MAX_DRAG_TABLE_NAME_CHARS_V1 {
475 return Err(protocol_error(
476 SolveErrorCodeV1::InvalidValue,
477 format!("name must be at most {MAX_DRAG_TABLE_NAME_CHARS_V1} characters, got {length}"),
478 path,
479 ));
480 }
481 Ok(())
482}
483
484/// Built-in reference-projectile drag models supported by solve-json v1.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
486pub enum DragModelV1 {
487 #[serde(rename = "G1")]
488 G1,
489 #[serde(rename = "G6")]
490 G6,
491 #[serde(rename = "G7")]
492 G7,
493 #[serde(rename = "G8")]
494 G8,
495 #[serde(rename = "G2")]
496 G2,
497 #[serde(rename = "G5")]
498 G5,
499 #[serde(rename = "GI")]
500 GI,
501 #[serde(rename = "GS")]
502 GS,
503 #[serde(rename = "RA4")]
504 RA4,
505}
506
507/// Rifle and sight geometry.
508#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
509#[serde(deny_unknown_fields)]
510pub struct RifleV1 {
511 pub muzzle_velocity_mps: f64,
512 #[serde(
513 default,
514 skip_serializing_if = "Option::is_none",
515 deserialize_with = "deserialize_present"
516 )]
517 pub sight_height_m: Option<f64>,
518 #[serde(
519 default,
520 skip_serializing_if = "Option::is_none",
521 deserialize_with = "deserialize_present"
522 )]
523 pub muzzle_height_m: Option<f64>,
524 /// Rifling travel per full turn, meters.
525 ///
526 /// Optional, which reads like "leave the twist out of it" — it is not. `None` defaults to
527 /// 0.3048 m, exactly 1:12 inches, raises a `default_applied` assumption, and materializes
528 /// that value at [`ResolvedRifleV1::twist_rate_m_per_turn`], after which nothing
529 /// downstream can tell an assumed barrel from a stated one.
530 ///
531 /// Omitting it is never free. `summary.stability_factor` is a function of the twist and is
532 /// computed on EVERY solve, so an omitted field reports the Sg of a 1:12 barrel — 1.665 on
533 /// a .308 175 gr against 3.746 at a stated 1:8, with no effect enabled — and raises
534 /// `stability_factor_assumed_twist_rate`. What the omission does not move, absent a
535 /// spin-driven effect, is the trajectory: `drop_m` and `windage_m` are bit-identical for
536 /// every twist rate.
537 ///
538 /// `effects.magnus`, `effects.enhanced_spin_drift` and `effects.aerodynamic_jump` each
539 /// read it as well, and each raises its own assumed-barrel warning when it is absent
540 /// (MBA-1484). The codes are distinct so that each names its own consumer; they are not
541 /// mutually exclusive, and one omitted twist can raise three of them at once.
542 #[serde(
543 default,
544 skip_serializing_if = "Option::is_none",
545 deserialize_with = "deserialize_present"
546 )]
547 pub twist_rate_m_per_turn: Option<f64>,
548 /// Rifling hand, viewed from the breech toward the muzzle. `None` defaults to `Right`
549 /// with a `default_applied` assumption. It flips the SIGN of the gyroscopic spin drift
550 /// rather than its magnitude, so an assumed hand on a left-twist barrel puts the drift on
551 /// the wrong side of the target.
552 #[serde(
553 default,
554 skip_serializing_if = "Option::is_none",
555 deserialize_with = "deserialize_present"
556 )]
557 pub twist_direction: Option<TwistDirectionV1>,
558 /// Lateral offset between the sight axis and the bore axis, meters (MBA-1396,
559 /// offset-mounted optics): positive = the sight sits RIGHT of the bore. The bore
560 /// starts that far left of the line of sight, and a solved zero adds the windage
561 /// convergence (`offset / zero_distance`) so the trajectory crosses the LOS laterally
562 /// at the zero range. Omitted (the default) is byte-identical to pre-MBA-1396
563 /// behavior. Echoed at [`ResolvedRifleV1::sight_offset_lateral_m`] when supplied
564 /// (0.33.0 decision-support Task 1).
565 #[serde(
566 default,
567 skip_serializing_if = "Option::is_none",
568 deserialize_with = "deserialize_present"
569 )]
570 pub sight_offset_lateral_m: Option<f64>,
571}
572
573/// Direction of rifling twist as viewed from the breech toward the muzzle.
574#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
575#[serde(rename_all = "snake_case")]
576pub enum TwistDirectionV1 {
577 Left,
578 #[default]
579 Right,
580}
581
582/// Shot geometry and termination range.
583#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
584#[serde(deny_unknown_fields)]
585pub struct ShotV1 {
586 pub max_range_m: f64,
587 #[serde(
588 default,
589 skip_serializing_if = "Option::is_none",
590 deserialize_with = "deserialize_present"
591 )]
592 pub zero_distance_m: Option<f64>,
593 #[serde(
594 default,
595 skip_serializing_if = "Option::is_none",
596 deserialize_with = "deserialize_present"
597 )]
598 pub muzzle_angle_rad: Option<f64>,
599 #[serde(
600 default,
601 skip_serializing_if = "Option::is_none",
602 deserialize_with = "deserialize_present"
603 )]
604 pub aim_azimuth_rad: Option<f64>,
605 #[serde(
606 default,
607 skip_serializing_if = "Option::is_none",
608 deserialize_with = "deserialize_present"
609 )]
610 pub shot_azimuth_rad: Option<f64>,
611 #[serde(
612 default,
613 skip_serializing_if = "Option::is_none",
614 deserialize_with = "deserialize_present"
615 )]
616 pub shooting_angle_rad: Option<f64>,
617 #[serde(
618 default,
619 skip_serializing_if = "Option::is_none",
620 deserialize_with = "deserialize_present"
621 )]
622 pub cant_angle_rad: Option<f64>,
623 /// World-vertical height above the local ground datum that the elevation search converges
624 /// the bullet to at `zero_distance_m`.
625 ///
626 /// Omitting it while the search runs (`zero_distance_m` present, `muzzle_angle_rad` absent)
627 /// defaults it to the LINE OF SIGHT of a level rifle — [`RifleV1::muzzle_height_m`] plus
628 /// [`RifleV1::sight_height_m`] — so a level shot's solved trajectory crosses the line of
629 /// sight at the zero distance, which is what a stated zero means and what the CLI and C ABI
630 /// zero surfaces already did (MBA-1537). A supplied value always wins, `0.0` included: that
631 /// is how a caller asks for a zero against the ground datum instead. The default raises a
632 /// `default_applied` assumption naming the height it used.
633 ///
634 /// The default is a LEVEL line of sight in a world-vertical field, so an inclined zero
635 /// still needs this stated — see `docs/SOLVE_JSON_V1.md` for the projection to supply.
636 ///
637 /// With no elevation search this still defaults to `0`, where it feeds only the
638 /// `drops_reference: "target"` sampler datum — which references `max_range_m`, not
639 /// `zero_distance_m`.
640 #[serde(
641 default,
642 skip_serializing_if = "Option::is_none",
643 deserialize_with = "deserialize_present"
644 )]
645 pub target_height_m: Option<f64>,
646 #[serde(
647 default,
648 skip_serializing_if = "Option::is_none",
649 deserialize_with = "deserialize_present"
650 )]
651 pub ground_threshold_m: Option<f64>,
652 /// Deliberate vertical POI offset AT the zero range, meters (MBA-1359, Kestrel "zero
653 /// height"): positive = the rifle is deliberately zeroed to impact HIGH by this much at
654 /// `zero_distance_m`. Meaningful only when `zero_distance_m` is supplied. Omitted (the
655 /// default) is byte-identical to pre-MBA-1359 behavior. Echoed at
656 /// [`ResolvedShotV1::zero_poi_up_m`] when supplied (0.33.0 decision-support Task 1).
657 #[serde(
658 default,
659 skip_serializing_if = "Option::is_none",
660 deserialize_with = "deserialize_present"
661 )]
662 pub zero_poi_up_m: Option<f64>,
663 /// Deliberate horizontal POI offset AT the zero range, meters (MBA-1359, Kestrel "zero
664 /// offset"): positive = impacts RIGHT by this much at `zero_distance_m`. Same contract
665 /// as `zero_poi_up_m`.
666 #[serde(
667 default,
668 skip_serializing_if = "Option::is_none",
669 deserialize_with = "deserialize_present"
670 )]
671 pub zero_poi_right_m: Option<f64>,
672 /// Which plane sampled `drop_m` values are referenced to (MBA-1403). `"los"` (the
673 /// default when omitted) keeps the historical LOS-perpendicular drop byte-identically;
674 /// `"target"` reports drop as vertical in the target plane — the LOS-perpendicular
675 /// drop scaled by `1 / cos(shooting_angle_rad)` (JBM's "target plane" reference).
676 /// Output-mode toggle only: the solved trajectory, `windage_m`, the summary block and
677 /// zeroing semantics are unchanged. Echoed at [`ResolvedShotV1::drops_reference`]
678 /// when supplied (0.33.0 decision-support Task 1).
679 #[serde(
680 default,
681 skip_serializing_if = "Option::is_none",
682 deserialize_with = "deserialize_present"
683 )]
684 pub drops_reference: Option<DropsReferenceV1>,
685}
686
687/// Wire values for [`ShotV1::drops_reference`] (MBA-1403).
688#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
689#[serde(rename_all = "snake_case")]
690pub enum DropsReferenceV1 {
691 /// Drop measured perpendicular to the line of sight (the historical default).
692 #[default]
693 Los,
694 /// Drop measured vertically in the target plane: LOS-perpendicular drop scaled by
695 /// `1 / cos(shooting_angle_rad)`.
696 Target,
697}
698
699/// Atmospheric station conditions.
700///
701/// Every field is `Option` behind a presence-preserving deserializer, so omission is stated
702/// directly on the wire and a SUPPLIED value is always authoritative — solve-json builds
703/// through [`crate::cli_api::TrajectorySolver::new_with_resolved_station_atmosphere`] and
704/// never re-interprets it (MBA-1397). In particular `temperature_k` of exactly 288.15 K or
705/// `pressure_pa` of exactly 101325 Pa mean those readings, not "omitted".
706///
707/// The C ABI (`crate::ffi`, behind the `ffi` feature) deliberately does NOT behave this way:
708/// `FFIAtmosphericConditions` is a `repr(C)` struct of plain doubles with no
709/// presence channel, so it keeps the legacy default-sentinel heuristic in which those same
710/// values at a nonzero altitude mean "resolve the ICAO standard here". The two surfaces
711/// therefore disagree on identical nominal inputs (~0.29 MOA on a 300 m zero at 2000 m); see
712/// that module's documentation for the full account.
713#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
714#[serde(deny_unknown_fields)]
715pub struct AtmosphereV1 {
716 #[serde(
717 default,
718 skip_serializing_if = "Option::is_none",
719 deserialize_with = "deserialize_present"
720 )]
721 pub altitude_m: Option<f64>,
722 /// Authoritative station temperature, or `None` to resolve ICAO standard temperature at
723 /// `altitude_m`.
724 #[serde(
725 default,
726 skip_serializing_if = "Option::is_none",
727 deserialize_with = "deserialize_present"
728 )]
729 pub temperature_k: Option<f64>,
730 /// Authoritative station pressure, or `None` to resolve ICAO standard pressure at
731 /// `altitude_m`. Interpreted per `pressure_reference` (MBA-1397): `absolute` (the
732 /// default) means this value already IS station pressure; `qnh` means it is a
733 /// sea-level-corrected altimeter setting that must be reduced to station pressure at
734 /// `altitude_m` before use.
735 #[serde(
736 default,
737 skip_serializing_if = "Option::is_none",
738 deserialize_with = "deserialize_present"
739 )]
740 pub pressure_pa: Option<f64>,
741 /// Whether `pressure_pa` is absolute station pressure or a sea-level-corrected altimeter
742 /// setting (QNH, MBA-1397). `None` (the omitted-field default, and every request from
743 /// before this field existed) means [`PressureReferenceV1::Absolute`] — byte-identical to
744 /// pre-MBA-1397 behavior. Has no effect when `pressure_pa` is omitted: an omitted pressure
745 /// resolves to the ICAO standard station pressure either way.
746 #[serde(
747 default,
748 skip_serializing_if = "Option::is_none",
749 deserialize_with = "deserialize_present"
750 )]
751 pub pressure_reference: Option<PressureReferenceV1>,
752 /// Relative humidity as a FRACTION, 0 to 1 (0.5 = 50 %), the SI wire's dimensionless form
753 /// and its only humidity field: there is no percent alias, so a percent sent by mistake
754 /// (`50`) is refused rather than flown as 5000 % or guessed at. A sensor reading within
755 /// 0.05 of the range ([`crate::HUMIDITY_SENSOR_TOLERANCE_PERCENT`], 5 points) is the
756 /// saturated or dry air it reads, and resolves to exactly 1 or 0; anything farther out is
757 /// an `invalid_value` at `$.atmosphere.relative_humidity`. Converted to the percent the
758 /// engine flies by [`crate::RelativeHumidity::try_fraction`]. `None` means
759 /// [`crate::RelativeHumidity::DEFAULT`], 0.5, and is announced in `assumptions`.
760 #[serde(
761 default,
762 skip_serializing_if = "Option::is_none",
763 deserialize_with = "deserialize_present"
764 )]
765 pub relative_humidity: Option<f64>,
766 #[serde(
767 default,
768 skip_serializing_if = "Option::is_none",
769 deserialize_with = "deserialize_present"
770 )]
771 pub latitude_rad: Option<f64>,
772}
773
774/// Whether an `AtmosphereV1.pressure_pa` value is absolute station pressure or a sea-level-
775/// corrected altimeter setting (QNH) that must be reduced to station pressure before use
776/// (MBA-1397). Mirrors [`crate::atmosphere::PressureReferenceMode`].
777#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
778#[serde(rename_all = "snake_case")]
779pub enum PressureReferenceV1 {
780 #[default]
781 Absolute,
782 Qnh,
783}
784
785/// Constant or downrange-segmented wind.
786///
787/// Omit all fields for still air. A constant wind supplies both `speed_mps` and
788/// `direction_from_rad`. Segmented wind supplies `segments` and no constant-wind fields.
789#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
790#[serde(deny_unknown_fields)]
791pub struct WindV1 {
792 #[serde(
793 default,
794 skip_serializing_if = "Option::is_none",
795 deserialize_with = "deserialize_present"
796 )]
797 pub speed_mps: Option<f64>,
798 #[serde(
799 default,
800 skip_serializing_if = "Option::is_none",
801 deserialize_with = "deserialize_present"
802 )]
803 pub direction_from_rad: Option<f64>,
804 #[serde(
805 default,
806 skip_serializing_if = "Option::is_none",
807 deserialize_with = "deserialize_present"
808 )]
809 pub vertical_speed_mps: Option<f64>,
810 #[serde(
811 default,
812 skip_serializing_if = "Option::is_none",
813 deserialize_with = "deserialize_present"
814 )]
815 pub segments: Option<Vec<WindSegmentV1>>,
816 /// Which frame every wind direction in this request is entered in (MBA-1368).
817 /// Omitted (or `"shooter"`) = shooter-relative wind-FROM radians, byte-identical to
818 /// pre-1368 behavior. `"compass"` = earth-fixed bearings (0 = north) — the constant
819 /// `direction_from_rad` AND every segment's — derived shooter-relative at resolve
820 /// time as `bearing - shot.shot_azimuth_rad` (normalized to [0, 2π)); the RESOLVED
821 /// wind echo therefore reports the converted shooter-relative direction (the QNH
822 /// fold-into-resolved-value precedent). Compass mode requires an explicit
823 /// `shot.shot_azimuth_rad` (a hard error otherwise, never a silent
824 /// treat-as-shooter-relative). The mode itself is echoed at
825 /// [`ResolvedConstantWindV1::wind_reference`] /
826 /// [`ResolvedSegmentedWindV1::wind_reference`] when supplied (0.33.0
827 /// decision-support Task 1).
828 #[serde(
829 default,
830 skip_serializing_if = "Option::is_none",
831 deserialize_with = "deserialize_present"
832 )]
833 pub wind_reference: Option<WindReferenceV1>,
834}
835
836/// Wire values for [`WindV1::wind_reference`] (MBA-1368).
837#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
838#[serde(rename_all = "snake_case")]
839pub enum WindReferenceV1 {
840 /// Shooter-relative wind-FROM directions (the historical default).
841 #[default]
842 Shooter,
843 /// Earth-fixed compass bearings, re-referenced against `shot.shot_azimuth_rad`.
844 Compass,
845}
846
847/// One wind segment, active through `until_distance_m`.
848#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
849#[serde(deny_unknown_fields)]
850pub struct WindSegmentV1 {
851 pub until_distance_m: f64,
852 pub speed_mps: f64,
853 pub direction_from_rad: f64,
854 #[serde(
855 default,
856 skip_serializing_if = "Option::is_none",
857 deserialize_with = "deserialize_present"
858 )]
859 pub vertical_speed_mps: Option<f64>,
860}
861
862/// Numerical integration configuration.
863#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
864#[serde(deny_unknown_fields)]
865pub struct SolverV1 {
866 #[serde(
867 default,
868 skip_serializing_if = "Option::is_none",
869 deserialize_with = "deserialize_present"
870 )]
871 pub method: Option<SolverMethodV1>,
872 /// Fixed step for RK4 and Euler. RK45 owns its adaptive step size.
873 #[serde(
874 default,
875 skip_serializing_if = "Option::is_none",
876 deserialize_with = "deserialize_present"
877 )]
878 pub time_step_s: Option<f64>,
879}
880
881/// Integration algorithms exposed by solve-json v1.
882#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
883#[serde(rename_all = "snake_case")]
884pub enum SolverMethodV1 {
885 Euler,
886 Rk4,
887 #[default]
888 Rk45,
889}
890
891/// Optional physical effects supported by solve-json v1.
892#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
893#[serde(deny_unknown_fields)]
894pub struct EffectsV1 {
895 /// Magnus side force and the yaw of repose it drives. EXPERIMENTAL: enabling it raises an
896 /// `experimental_effect` warning.
897 ///
898 /// Driven by the spin the rifling imparts, so it reads `rifle.twist_rate_m_per_turn`.
899 /// Omitting that field does not disable it — the 1:12 default is substituted and the force
900 /// is computed for that barrel — so enabling this without a stated twist raises
901 /// `spin_effect_assumed_twist_rate` (MBA-1484).
902 ///
903 /// Mutually exclusive with [`EffectsV1::enhanced_spin_drift`]: the legacy solver silently
904 /// suppresses Magnus in that combination, and the decoder reports `conflicting_fields`
905 /// rather than let the resolved request misstate which physics ran.
906 #[serde(
907 default,
908 skip_serializing_if = "Option::is_none",
909 deserialize_with = "deserialize_present"
910 )]
911 pub magnus: Option<bool>,
912 /// Earth-rotation (Coriolis and Eötvös) accelerations. Requires
913 /// `atmosphere.latitude_rad`, which is an `invalid_value` error when absent rather than a
914 /// default. Reads no barrel geometry.
915 #[serde(
916 default,
917 skip_serializing_if = "Option::is_none",
918 deserialize_with = "deserialize_present"
919 )]
920 pub coriolis: Option<bool>,
921 /// Gyroscopic spin drift via the empirical Litz model. EXPERIMENTAL: enabling it raises an
922 /// `experimental_effect` warning.
923 ///
924 /// The drift scales with the muzzle gyroscopic stability factor, which is a function of the
925 /// twist, so it reads `rifle.twist_rate_m_per_turn` (and `rifle.twist_direction`, which
926 /// sets its sign). Omitting the rate does not disable the effect and does not zero it: the
927 /// 1:12 default is substituted and the drift is computed for that barrel, which is why
928 /// enabling this without a stated twist raises `spin_effect_assumed_twist_rate`
929 /// (MBA-1484). Measured on a .308 175 gr at 800 m, `summary.spin_drift_m` is 0.183 m with
930 /// the twist omitted — bit-identical to a stated 1:12 — against 0.316 m at a stated 1:8.
931 ///
932 /// Mutually exclusive with [`EffectsV1::magnus`]; see that field.
933 #[serde(
934 default,
935 skip_serializing_if = "Option::is_none",
936 deserialize_with = "deserialize_present"
937 )]
938 pub enhanced_spin_drift: Option<bool>,
939 /// Altitude-dependent wind shear model (0.36.0). `None` (the omitted-field default, and
940 /// every request from before this field existed) means no shear at all — byte-identical
941 /// to pre-0.36.0 behavior, exactly as an explicit `"none"` solves. The model is echoed at
942 /// [`ResolvedEffectsV1::wind_shear_model`] whenever the raw request supplies one,
943 /// including an explicit `"none"`.
944 ///
945 /// An unrecognized model name is an `invalid_value` error at
946 /// `$.effects.wind_shear_model`, never a silent fall back to no shear: a typo'd model
947 /// must not quietly produce unsheared numbers that look like sheared ones.
948 #[serde(
949 default,
950 skip_serializing_if = "Option::is_none",
951 deserialize_with = "deserialize_present"
952 )]
953 pub wind_shear_model: Option<WindShearModelV1>,
954 /// Crosswind aerodynamic (gyroscopic) jump, as a muzzle launch-angle perturbation
955 /// (MBA-959). `None` — the omitted-field default, and every request from before this
956 /// field existed — means no jump, byte-identical to earlier behavior.
957 ///
958 /// EXPERIMENTAL, and the bridge says so: enabling it raises an `experimental_effect`
959 /// warning, the same as `magnus` and `enhanced_spin_drift`. The model is Bryan Litz's
960 /// regression `Y = 0.01*Sg - 0.0024*L + 0.032` MOA per mph of crosswind, a fit that is
961 /// best near Sg ~ 1.75 rather than a first-principles derivation.
962 ///
963 /// Two consequences a caller has to know, because neither is visible in the numbers:
964 /// the jump is VERTICAL and is computed from the crosswind AT THE MUZZLE, so a shot with
965 /// no crosswind there is unaffected however much wind it meets downrange; and its
966 /// magnitude is a function of stability, so it reads `rifle.twist_rate_m_per_turn` and
967 /// `projectile.length_m`. Omitting either does not disable the correction — it computes
968 /// one from an assumed barrel, which is why enabling this flag without them raises
969 /// `aerodynamic_jump_assumed_geometry`.
970 #[serde(
971 default,
972 skip_serializing_if = "Option::is_none",
973 deserialize_with = "deserialize_present"
974 )]
975 pub aerodynamic_jump: Option<bool>,
976}
977
978/// Wire values for [`EffectsV1::wind_shear_model`] (0.36.0).
979///
980/// These are the engine's own model names (see [`crate::wind_shear`]), so a v1 request and the
981/// CLI's `--wind-shear-model` name the same physics with the same spelling.
982/// [`crate::wind_shear::WindShearModel::CustomLayers`] is deliberately NOT exposed: it needs a
983/// caller-supplied layer table that this contract has no field for, and would silently degrade
984/// to the surface wind.
985#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
986#[serde(rename_all = "snake_case")]
987pub enum WindShearModelV1 {
988 /// No altitude dependence: the request's wind is used at every height (the historical
989 /// default, and what an omitted field means).
990 #[default]
991 None,
992 /// Logarithmic boundary-layer profile, `ln(z / z0) / ln(z_ref / z0)`.
993 Logarithmic,
994 /// 1/7 power-law boundary-layer profile, `(z / z_ref)^(1/7)`.
995 PowerLaw,
996 /// Ekman spiral. Accepted for parity with the CLI and the engine's model names, but this
997 /// solve path's boundary-layer evaluator has no near-ground closed form for it, so it
998 /// leaves the wind at the operative value. Enabling it emits a
999 /// `wind_shear_model_not_modeled` warning rather than passing silently.
1000 #[serde(alias = "ekman")]
1001 EkmanSpiral,
1002}
1003
1004impl WindShearModelV1 {
1005 /// The canonical lower-snake name the engine's `wind_shear` / `cli_api` code understands.
1006 ///
1007 /// Aliases resolve to their canonical spelling here, which is also what the resolved
1008 /// request echoes: `"ekman"` in, `"ekman_spiral"` out.
1009 pub fn as_engine_str(self) -> &'static str {
1010 match self {
1011 WindShearModelV1::None => "none",
1012 WindShearModelV1::Logarithmic => "logarithmic",
1013 WindShearModelV1::PowerLaw => "power_law",
1014 WindShearModelV1::EkmanSpiral => "ekman_spiral",
1015 }
1016 }
1017
1018 /// Whether this model asks the solver for altitude-dependent wind at all.
1019 ///
1020 /// `"none"` must map to `enable_wind_shear: false` rather than to an enabled solver
1021 /// holding the string `"none"`: [`crate::cli_api`]'s shear branch maps any unrecognized
1022 /// model name — `"none"` included — to the power law, so an enabled-but-`"none"` solve
1023 /// would quietly run power-law shear.
1024 pub fn is_enabled(self) -> bool {
1025 !matches!(self, WindShearModelV1::None)
1026 }
1027}
1028
1029/// Regular downrange output sampling configuration.
1030#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1031#[serde(deny_unknown_fields)]
1032pub struct SamplingV1 {
1033 #[serde(
1034 default,
1035 skip_serializing_if = "Option::is_none",
1036 deserialize_with = "deserialize_present"
1037 )]
1038 pub interval_m: Option<f64>,
1039}
1040
1041/// A solve request after the service has applied every documented v1 default.
1042///
1043/// This is intentionally distinct from [`SolveRequestV1`]. Request DTOs retain whether a
1044/// defaulted field was omitted, while resolved DTOs require a concrete value for every default
1045/// that affected the solve. Semantically optional inputs remain optional.
1046#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1047#[serde(deny_unknown_fields)]
1048pub struct ResolvedSolveRequestV1 {
1049 pub schema_version: SchemaVersionV1,
1050 pub projectile: ResolvedProjectileV1,
1051 pub rifle: ResolvedRifleV1,
1052 pub shot: ResolvedShotV1,
1053 pub atmosphere: ResolvedAtmosphereV1,
1054 pub wind: ResolvedWindV1,
1055 pub solver: ResolvedSolverV1,
1056 pub effects: ResolvedEffectsV1,
1057 pub sampling: ResolvedSamplingV1,
1058 /// Echo of the reticle hold-point request (MBA-1361), when one was supplied. Present
1059 /// only when the raw request supplied it — completes the resolved request as a
1060 /// full description of the solve.
1061 #[serde(default, skip_serializing_if = "Option::is_none")]
1062 pub reticle: Option<ReticleRequestV1>,
1063 /// Echo of the offline-corrections block, when one was supplied. Present only when
1064 /// the raw request supplied it, so a resolved request re-solve (perturbation,
1065 /// round-trip) re-applies the same table rather than silently dropping the
1066 /// correction. Re-applying is idempotent: segments are always generated from the
1067 /// request's PUBLISHED `ballistic_coefficient`, never from an already-corrected one.
1068 #[serde(default, skip_serializing_if = "Option::is_none")]
1069 pub corrections: Option<CorrectionsV1>,
1070}
1071
1072/// Resolved projectile inputs.
1073#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1074#[serde(deny_unknown_fields)]
1075pub struct ResolvedProjectileV1 {
1076 pub mass_kg: f64,
1077 pub diameter_m: f64,
1078 #[serde(default, skip_serializing_if = "Option::is_none")]
1079 pub length_m: Option<f64>,
1080 pub drag_model: DragModelV1,
1081 pub ballistic_coefficient: f64,
1082 /// Verbatim echo of the request's table (MBA-1597). It is carried rather than summarized
1083 /// because the perturbation kernels re-solve from this resolved request: dropping it would
1084 /// silently fly their re-solves on `drag_model`'s curve instead.
1085 #[serde(default, skip_serializing_if = "Option::is_none")]
1086 pub drag_table: Option<DragTableV1>,
1087 /// Verbatim echo of the request's BC ladder (MBA-1598), omitted when none was supplied. It
1088 /// is carried for the same reason as `drag_table`: the perturbation kernels re-solve from
1089 /// this resolved request, and dropping it would fly their re-solves on the scalar BC.
1090 #[serde(default, skip_serializing_if = "Option::is_none")]
1091 pub bc_segments: Option<Vec<BcSegmentV1>>,
1092}
1093
1094/// Resolved rifle and sight geometry.
1095#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1096#[serde(deny_unknown_fields)]
1097pub struct ResolvedRifleV1 {
1098 pub muzzle_velocity_mps: f64,
1099 pub sight_height_m: f64,
1100 pub muzzle_height_m: f64,
1101 pub twist_rate_m_per_turn: f64,
1102 pub twist_direction: TwistDirectionV1,
1103 /// Lateral sight offset for offset-mounted optics. Echoed so the resolved request
1104 /// is a complete description of the solve (required for counterfactual re-solve).
1105 #[serde(default, skip_serializing_if = "Option::is_none")]
1106 pub sight_offset_lateral_m: Option<f64>,
1107}
1108
1109/// Resolved shot geometry.
1110///
1111/// `zero_distance_m` records caller zeroing intent, while `muzzle_angle_rad` is always the
1112/// effective angle used by the engine. A zero-distance solve therefore populates both fields.
1113/// A raw request may also supply both together (0.33.0 decision-support Task 2's
1114/// `From<&ResolvedSolveRequestV1> for SolveRequestV1` always does, to round-trip a resolved
1115/// request): `muzzle_angle_rad` then wins outright for elevation and no elevation search
1116/// runs, but `zero_distance_m` is not otherwise inert -- it still drives the
1117/// windage-convergence bias (`sight_offset_lateral_m` / `zero_poi_right_m`), still gates
1118/// `equivalent_horizontal_range_m`, and still widens the required wind coverage. A
1119/// `zero_distance_elevation_not_resolved` warning names this whenever both are supplied.
1120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1121#[serde(deny_unknown_fields)]
1122pub struct ResolvedShotV1 {
1123 pub max_range_m: f64,
1124 #[serde(default, skip_serializing_if = "Option::is_none")]
1125 pub zero_distance_m: Option<f64>,
1126 pub muzzle_angle_rad: f64,
1127 pub aim_azimuth_rad: f64,
1128 pub shot_azimuth_rad: f64,
1129 pub shooting_angle_rad: f64,
1130 pub cant_angle_rad: f64,
1131 pub target_height_m: f64,
1132 pub ground_threshold_m: f64,
1133 /// Echo of the requested deliberate vertical POI offset at the zero range, meters
1134 /// (MBA-1359). Present only when the raw request supplied it.
1135 #[serde(default, skip_serializing_if = "Option::is_none")]
1136 pub zero_poi_up_m: Option<f64>,
1137 /// Echo of the requested deliberate horizontal POI offset at the zero range, meters
1138 /// (MBA-1359). Present only when the raw request supplied it.
1139 #[serde(default, skip_serializing_if = "Option::is_none")]
1140 pub zero_poi_right_m: Option<f64>,
1141 /// Echo of the requested drops-reference plane (MBA-1403). Present only when the raw
1142 /// request supplied it.
1143 #[serde(default, skip_serializing_if = "Option::is_none")]
1144 pub drops_reference: Option<DropsReferenceV1>,
1145}
1146
1147/// Resolved station conditions.
1148#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1149#[serde(deny_unknown_fields)]
1150pub struct ResolvedAtmosphereV1 {
1151 pub altitude_m: f64,
1152 pub temperature_k: f64,
1153 pub pressure_pa: f64,
1154 /// The relative humidity flown, as a FRACTION in `[0, 1]`: the request's own value with
1155 /// its bits unchanged, a sensor reading within the band as the end it reads as, or the
1156 /// default 0.5. Sending this echo back (see `SolveRequestV1::from`) flies the same air.
1157 pub relative_humidity: f64,
1158 #[serde(default, skip_serializing_if = "Option::is_none")]
1159 pub latitude_rad: Option<f64>,
1160 /// Echo of the requested pressure reference mode (MBA-1397). Present only when the raw
1161 /// request supplied it.
1162 #[serde(default, skip_serializing_if = "Option::is_none")]
1163 pub pressure_reference: Option<PressureReferenceV1>,
1164}
1165
1166/// Resolved constant or segmented wind.
1167///
1168/// The untagged representation retains the request's object shape while making the selected wind
1169/// variant explicit in Rust. Still air is a constant wind with three zero values.
1170#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1171#[serde(untagged)]
1172pub enum ResolvedWindV1 {
1173 Constant(ResolvedConstantWindV1),
1174 Segmented(ResolvedSegmentedWindV1),
1175}
1176
1177/// Resolved still-air or constant-wind values.
1178#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1179#[serde(deny_unknown_fields)]
1180pub struct ResolvedConstantWindV1 {
1181 pub speed_mps: f64,
1182 pub direction_from_rad: f64,
1183 pub vertical_speed_mps: f64,
1184 /// Echo of the requested wind-direction reference frame (MBA-1368). Present only when
1185 /// the raw request supplied it. `direction_from_rad` above is always already converted
1186 /// to shooter-relative, regardless of this value.
1187 #[serde(default, skip_serializing_if = "Option::is_none")]
1188 pub wind_reference: Option<WindReferenceV1>,
1189}
1190
1191/// Resolved downrange wind segments.
1192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1193#[serde(deny_unknown_fields)]
1194pub struct ResolvedSegmentedWindV1 {
1195 pub segments: Vec<ResolvedWindSegmentV1>,
1196 /// Echo of the requested wind-direction reference frame (MBA-1368). Present only when
1197 /// the raw request supplied it. Each segment's `direction_from_rad` above is always
1198 /// already converted to shooter-relative, regardless of this value.
1199 #[serde(default, skip_serializing_if = "Option::is_none")]
1200 pub wind_reference: Option<WindReferenceV1>,
1201}
1202
1203/// One resolved wind segment.
1204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1205#[serde(deny_unknown_fields)]
1206pub struct ResolvedWindSegmentV1 {
1207 pub until_distance_m: f64,
1208 pub speed_mps: f64,
1209 pub direction_from_rad: f64,
1210 pub vertical_speed_mps: f64,
1211}
1212
1213/// Resolved numerical integration configuration.
1214#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1215#[serde(deny_unknown_fields)]
1216pub struct ResolvedSolverV1 {
1217 pub method: SolverMethodV1,
1218 pub time_step_s: f64,
1219}
1220
1221/// Resolved physical-effect switches.
1222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1223#[serde(deny_unknown_fields)]
1224pub struct ResolvedEffectsV1 {
1225 pub magnus: bool,
1226 pub coriolis: bool,
1227 pub enhanced_spin_drift: bool,
1228 /// Echo of the wind shear model that was actually applied (0.36.0), in its canonical
1229 /// spelling. Present only when the raw request supplied one — an omitted field leaves
1230 /// this absent, so responses to pre-0.36.0 requests serialize byte-identically.
1231 #[serde(default, skip_serializing_if = "Option::is_none")]
1232 pub wind_shear_model: Option<WindShearModelV1>,
1233 /// Echo of the aerodynamic-jump switch (MBA-959). Present only when the raw request
1234 /// supplied one, so a response to a request written before this field existed serializes
1235 /// byte-identically.
1236 ///
1237 /// `Option<bool>` rather than the bare `bool` its three older siblings use, and
1238 /// deliberately: those are always echoed, so a `false` on them is indistinguishable from
1239 /// a default, whereas this field keeps supplied-`false` and omitted apart. That is the
1240 /// same additive-echo shape `wind_shear_model` above it uses, and it is the one that lets
1241 /// an echo round-trip back into an identical request.
1242 #[serde(default, skip_serializing_if = "Option::is_none")]
1243 pub aerodynamic_jump: Option<bool>,
1244}
1245
1246/// Resolved result-sampling configuration.
1247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1248#[serde(deny_unknown_fields)]
1249pub struct ResolvedSamplingV1 {
1250 pub interval_m: f64,
1251}
1252
1253/// A successful solve-json v1 response.
1254#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1255#[serde(deny_unknown_fields)]
1256pub struct SolveSuccessV1 {
1257 pub schema_version: SchemaVersionV1,
1258 pub engine_version: String,
1259 pub status: SuccessStatusV1,
1260 pub resolved_request: ResolvedSolveRequestV1,
1261 #[serde(default)]
1262 pub assumptions: Vec<SolveNoticeV1>,
1263 #[serde(default)]
1264 pub warnings: Vec<SolveNoticeV1>,
1265 pub summary: SolveSummaryV1,
1266 #[serde(default, serialize_with = "serialize_solve_samples_v1")]
1267 pub samples: Vec<TrajectorySampleV1>,
1268 /// The reticle hold point (MBA-1361), present only when the request carried a
1269 /// `reticle` block. Every response that predates the field, and every request without
1270 /// one, is byte-identical.
1271 #[serde(default, skip_serializing_if = "Option::is_none")]
1272 pub reticle_hold: Option<ReticleHoldV1>,
1273}
1274
1275fn serialize_solve_samples_v1<S>(
1276 samples: &[TrajectorySampleV1],
1277 serializer: S,
1278) -> Result<S::Ok, S::Error>
1279where
1280 S: Serializer,
1281{
1282 if samples.len() > MAX_SOLVE_JSON_SAMPLES_V1 {
1283 return Err(serde::ser::Error::custom(format_args!(
1284 "solve-json v1 response sample limit of {MAX_SOLVE_JSON_SAMPLES_V1} exceeded: response has {} samples",
1285 samples.len()
1286 )));
1287 }
1288 samples.serialize(serializer)
1289}
1290
1291impl SolveSuccessV1 {
1292 /// Validate service-level response limits immediately before serialization.
1293 ///
1294 /// The exact limit is accepted. A response with more samples returns a structured
1295 /// [`SolveErrorCodeV1::ResourceLimit`] error at the sampling interval that requested the
1296 /// oversized result. The response is never silently truncated.
1297 pub fn validate_for_serialization(&self) -> Result<(), SolveErrorEnvelopeV1> {
1298 if self.samples.len() <= MAX_SOLVE_JSON_SAMPLES_V1 {
1299 return Ok(());
1300 }
1301
1302 Err(SolveErrorEnvelopeV1::new(
1303 SolveErrorV1::new(
1304 SolveErrorCodeV1::ResourceLimit,
1305 format!(
1306 "solve-json v1 response sample limit of {MAX_SOLVE_JSON_SAMPLES_V1} exceeded: response has {} samples",
1307 self.samples.len()
1308 ),
1309 )
1310 .at_path("$.sampling.interval_m"),
1311 ))
1312 }
1313}
1314
1315/// The success discriminator serialized in a response envelope.
1316#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1317#[serde(rename_all = "snake_case")]
1318pub enum SuccessStatusV1 {
1319 Ok,
1320}
1321
1322/// A machine-readable assumption or warning.
1323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1324#[serde(deny_unknown_fields)]
1325pub struct SolveNoticeV1 {
1326 pub code: String,
1327 pub message: String,
1328 #[serde(default, skip_serializing_if = "Option::is_none")]
1329 pub path: Option<String>,
1330}
1331
1332/// Aggregate observations for a completed solve.
1333#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1334#[serde(deny_unknown_fields)]
1335pub struct SolveSummaryV1 {
1336 pub actual_range_m: f64,
1337 /// Greatest world-vertical projectile height above the request's local ground/reference
1338 /// datum. This is not shot-frame Y and is not height above the line of sight.
1339 pub maximum_height_m: f64,
1340 pub time_of_flight_s: f64,
1341 pub terminal_speed_mps: f64,
1342 pub terminal_energy_j: f64,
1343 /// Muzzle gyroscopic stability factor Sg evaluated with the resolved projectile, muzzle
1344 /// velocity, twist, and station atmosphere; absent only when it cannot be calculated.
1345 #[serde(default, skip_serializing_if = "Option::is_none")]
1346 pub stability_factor: Option<f64>,
1347 /// Signed gyroscopic spin-drift contribution at the terminal sample, positive to the
1348 /// shooter's right. This excludes wind drift and is absent when the effect is disabled or
1349 /// cannot be calculated.
1350 #[serde(default, skip_serializing_if = "Option::is_none")]
1351 pub spin_drift_m: Option<f64>,
1352 /// Equivalent horizontal range for an inclined shot (MBA-1395): the flat-fire range
1353 /// whose angular elevation correction against the same zero matches the inclined
1354 /// solution's at the terminal range — the BDC "shoot-to" range (SIG AMR / Leica EHR
1355 /// style, angular-match inversion, not the rifleman's-rule cosine). Present only when
1356 /// `shot.shooting_angle_rad != 0`, a `zero_distance_m` was solved, and the inverse is
1357 /// well-defined (terminal past the zero range, positive correction); absent otherwise
1358 /// — responses that predate the field, and every flat solve, are byte-identical.
1359 #[serde(default, skip_serializing_if = "Option::is_none")]
1360 pub equivalent_horizontal_range_m: Option<f64>,
1361 /// Vertical crosswind aerodynamic jump actually applied at the muzzle, in MOA, positive
1362 /// up (MBA-959). Present only when `effects.aerodynamic_jump` was enabled AND the solver
1363 /// produced components; absent otherwise, so every response that predates the field is
1364 /// byte-identical.
1365 ///
1366 /// This exists because the jump is otherwise unobservable from the response. It is a
1367 /// fixed launch-angle offset, so it does not appear as its own column anywhere — it is
1368 /// folded into every drop in the table, and a caller comparing two solves cannot tell a
1369 /// jump that applied from one that silently came out at zero. A present `0.0` says the
1370 /// flag took effect and the muzzle crosswind was nil; an absent field says the effect
1371 /// never ran.
1372 #[serde(default, skip_serializing_if = "Option::is_none")]
1373 pub aerodynamic_jump_moa: Option<f64>,
1374 pub termination: TerminationReasonV1,
1375}
1376
1377/// Why the trajectory ended.
1378#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1379#[serde(rename_all = "snake_case")]
1380pub enum TerminationReasonV1 {
1381 MaxRange,
1382 GroundThreshold,
1383 TimeLimit,
1384 VelocityFloor,
1385}
1386
1387/// One regularly sampled trajectory observation.
1388#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1389#[serde(deny_unknown_fields)]
1390pub struct TrajectorySampleV1 {
1391 pub distance_m: f64,
1392 pub time_s: f64,
1393 pub speed_mps: f64,
1394 pub energy_j: f64,
1395 /// Positive means below the line of sight.
1396 pub drop_m: f64,
1397 /// Positive means right of the line of sight from the shooter's perspective.
1398 pub windage_m: f64,
1399 pub mach: f64,
1400 #[serde(default)]
1401 pub flags: Vec<SampleFlagV1>,
1402}
1403
1404/// Stable annotations for trajectory samples.
1405#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1406#[serde(rename_all = "snake_case")]
1407pub enum SampleFlagV1 {
1408 Transonic,
1409 Subsonic,
1410 Terminal,
1411 GroundThreshold,
1412}
1413
1414/// A failed solve-json v1 response.
1415#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1416#[serde(deny_unknown_fields)]
1417pub struct SolveErrorEnvelopeV1 {
1418 pub schema_version: SchemaVersionV1,
1419 pub status: ErrorStatusV1,
1420 pub error: SolveErrorV1,
1421}
1422
1423impl SolveErrorEnvelopeV1 {
1424 /// Wrap a protocol error in a v1 envelope.
1425 pub fn new(error: SolveErrorV1) -> Self {
1426 Self {
1427 schema_version: SchemaVersionV1,
1428 status: ErrorStatusV1::Error,
1429 error,
1430 }
1431 }
1432}
1433
1434/// The error discriminator serialized in a response envelope.
1435#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1436#[serde(rename_all = "snake_case")]
1437pub enum ErrorStatusV1 {
1438 Error,
1439}
1440
1441/// A stable, machine-readable protocol error.
1442///
1443/// Location state is private so callers cannot construct a path together with a source location,
1444/// a partial line/column pair, or a zero source coordinate. The JSON representation retains the
1445/// flat `path`, `line`, and `column` fields.
1446#[derive(Debug, Clone, PartialEq, Eq)]
1447pub struct SolveErrorV1 {
1448 pub code: SolveErrorCodeV1,
1449 pub message: String,
1450 location: SolveErrorLocationV1,
1451}
1452
1453#[derive(Debug, Clone, PartialEq, Eq)]
1454enum SolveErrorLocationV1 {
1455 None,
1456 Path(String),
1457 Source {
1458 line: NonZeroUsize,
1459 column: NonZeroUsize,
1460 },
1461}
1462
1463/// Why a source location could not be attached to a protocol error.
1464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1465pub enum SolveErrorLocationErrorV1 {
1466 ZeroLine,
1467 ZeroColumn,
1468}
1469
1470impl fmt::Display for SolveErrorLocationErrorV1 {
1471 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1472 match self {
1473 Self::ZeroLine => formatter.write_str("error line must be one-based"),
1474 Self::ZeroColumn => formatter.write_str("error column must be one-based"),
1475 }
1476 }
1477}
1478
1479impl std::error::Error for SolveErrorLocationErrorV1 {}
1480
1481impl SolveErrorV1 {
1482 /// Construct an error without input-location information.
1483 pub fn new(code: SolveErrorCodeV1, message: impl Into<String>) -> Self {
1484 Self {
1485 code,
1486 message: message.into(),
1487 location: SolveErrorLocationV1::None,
1488 }
1489 }
1490
1491 /// Attach a JSONPath-like input location, replacing any source location.
1492 pub fn at_path(mut self, path: impl Into<String>) -> Self {
1493 self.location = SolveErrorLocationV1::Path(path.into());
1494 self
1495 }
1496
1497 /// Attach a one-based malformed-JSON source location, replacing any JSON path.
1498 pub fn at_location(
1499 mut self,
1500 line: usize,
1501 column: usize,
1502 ) -> Result<Self, SolveErrorLocationErrorV1> {
1503 let line = NonZeroUsize::new(line).ok_or(SolveErrorLocationErrorV1::ZeroLine)?;
1504 let column = NonZeroUsize::new(column).ok_or(SolveErrorLocationErrorV1::ZeroColumn)?;
1505 self.location = SolveErrorLocationV1::Source { line, column };
1506 Ok(self)
1507 }
1508
1509 /// Attach a parser location while keeping the public wire coordinates one-based.
1510 ///
1511 /// `serde_json` reports column zero for some end-of-file errors. Normalize either zero
1512 /// coordinate to one instead of allowing malformed input to trigger a panic.
1513 fn at_parser_location(mut self, line: usize, column: usize) -> Self {
1514 self.location = SolveErrorLocationV1::Source {
1515 line: NonZeroUsize::new(line).unwrap_or(NonZeroUsize::MIN),
1516 column: NonZeroUsize::new(column).unwrap_or(NonZeroUsize::MIN),
1517 };
1518 self
1519 }
1520
1521 /// Return the JSONPath-like input location, when present.
1522 pub fn path(&self) -> Option<&str> {
1523 match &self.location {
1524 SolveErrorLocationV1::Path(path) => Some(path),
1525 SolveErrorLocationV1::None | SolveErrorLocationV1::Source { .. } => None,
1526 }
1527 }
1528
1529 /// Return the one-based malformed-JSON source line, when present.
1530 pub fn line(&self) -> Option<usize> {
1531 match &self.location {
1532 SolveErrorLocationV1::Source { line, .. } => Some(line.get()),
1533 SolveErrorLocationV1::None | SolveErrorLocationV1::Path(_) => None,
1534 }
1535 }
1536
1537 /// Return the one-based malformed-JSON source column, when present.
1538 pub fn column(&self) -> Option<usize> {
1539 match &self.location {
1540 SolveErrorLocationV1::Source { column, .. } => Some(column.get()),
1541 SolveErrorLocationV1::None | SolveErrorLocationV1::Path(_) => None,
1542 }
1543 }
1544}
1545
1546impl Serialize for SolveErrorV1 {
1547 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1548 where
1549 S: Serializer,
1550 {
1551 let mut state = serializer.serialize_struct("SolveErrorV1", 5)?;
1552 state.serialize_field("code", &self.code)?;
1553 state.serialize_field("message", &self.message)?;
1554 state.serialize_field("path", &self.path())?;
1555 state.serialize_field("line", &self.line())?;
1556 state.serialize_field("column", &self.column())?;
1557 state.end()
1558 }
1559}
1560
1561impl<'de> Deserialize<'de> for SolveErrorV1 {
1562 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1563 where
1564 D: Deserializer<'de>,
1565 {
1566 #[derive(Deserialize)]
1567 #[serde(deny_unknown_fields)]
1568 struct SolveErrorWireV1 {
1569 code: SolveErrorCodeV1,
1570 message: String,
1571 path: Option<String>,
1572 line: Option<usize>,
1573 column: Option<usize>,
1574 }
1575
1576 let wire = SolveErrorWireV1::deserialize(deserializer)?;
1577 let location = match (wire.path, wire.line, wire.column) {
1578 (None, None, None) => SolveErrorLocationV1::None,
1579 (Some(path), None, None) => SolveErrorLocationV1::Path(path),
1580 (None, Some(line), Some(column)) => {
1581 let line = NonZeroUsize::new(line)
1582 .ok_or_else(|| de::Error::custom("error line must be one-based"))?;
1583 let column = NonZeroUsize::new(column)
1584 .ok_or_else(|| de::Error::custom("error column must be one-based"))?;
1585 SolveErrorLocationV1::Source { line, column }
1586 }
1587 _ => {
1588 return Err(de::Error::custom(
1589 "error location must contain either path or both line and column",
1590 ));
1591 }
1592 };
1593
1594 Ok(Self {
1595 code: wire.code,
1596 message: wire.message,
1597 location,
1598 })
1599 }
1600}
1601
1602/// Stable solve-json v1 error categories.
1603#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1604#[serde(rename_all = "snake_case")]
1605pub enum SolveErrorCodeV1 {
1606 InvalidJson,
1607 UnsupportedSchemaVersion,
1608 UnknownField,
1609 MissingField,
1610 InvalidValue,
1611 ConflictingFields,
1612 ResourceLimit,
1613 SolveFailed,
1614 IoError,
1615 InternalError,
1616}
1617
1618/// The code by its wire name (`invalid_value`, `solve_failed`, ...), the name a solve-json
1619/// reader branches on, so a message that quotes a code quotes that name and never the Rust
1620/// variant (`InvalidValue`).
1621impl fmt::Display for SolveErrorCodeV1 {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 f.write_str(match self {
1624 Self::InvalidJson => "invalid_json",
1625 Self::UnsupportedSchemaVersion => "unsupported_schema_version",
1626 Self::UnknownField => "unknown_field",
1627 Self::MissingField => "missing_field",
1628 Self::InvalidValue => "invalid_value",
1629 Self::ConflictingFields => "conflicting_fields",
1630 Self::ResourceLimit => "resource_limit",
1631 Self::SolveFailed => "solve_failed",
1632 Self::IoError => "io_error",
1633 Self::InternalError => "internal_error",
1634 })
1635 }
1636}
1637
1638/// Decode and structurally validate one solve-json v1 request.
1639///
1640/// In addition to Serde's `deny_unknown_fields` enforcement, this entry point attaches exact
1641/// JSONPath-like locations to unknown fields, missing required fields, invalid enums, and an
1642/// unsupported schema version. Transport implementations should use this function rather than
1643/// deserializing [`SolveRequestV1`] directly when they need a protocol error envelope.
1644pub fn decode_solve_request_v1(input: &str) -> Result<SolveRequestV1, SolveErrorEnvelopeV1> {
1645 let value: Value = serde_json::from_str(input).map_err(|error| {
1646 let error = SolveErrorV1::new(SolveErrorCodeV1::InvalidJson, error.to_string())
1647 .at_parser_location(error.line(), error.column());
1648 envelope(error)
1649 })?;
1650
1651 validate_request_shape(&value)?;
1652
1653 let request: SolveRequestV1 = serde_json::from_value(value).map_err(|error| {
1654 envelope(SolveErrorV1::new(SolveErrorCodeV1::InvalidValue, error.to_string()).at_path("$"))
1655 })?;
1656
1657 validate_request_ranges(&request)?;
1658
1659 Ok(request)
1660}
1661
1662/// Physically meaningful bounds for solve-json v1's numeric inputs (MBA-1413).
1663///
1664/// Deliberately enormous — the point is to exclude values that are not projectiles at all, not
1665/// to police calibers. Every bound below admits everything from an airgun pellet to naval
1666/// artillery, so a request rejected here was never going to produce a meaningful answer.
1667///
1668/// Found by fuzzing, which reached a request declaring a `mass_kg` of 1.1e-66 — about
1669/// 10^40 times lighter than a proton. The engine accepted it and solved. The visible symptom was
1670/// narrower: at that magnitude `serde_json`'s float parser is a bit off re-reading its own
1671/// output, so the request did not survive a JSON round trip and broke the protocol's stability
1672/// invariant. Tightening the float handling would have addressed the symptom; the actual defect
1673/// is that a number no projectile could have was accepted as a projectile.
1674///
1675/// Also bounds each `card.*` `bc_segments` band BC (MBA-1600).
1676pub(crate) mod limits {
1677 /// 1 mg to 100 kg. A .17 cal pellet is ~500 mg; a 16-inch naval shell is ~1200 kg, so the
1678 /// upper bound is the one a caller might conceivably reach — it is set past small artillery
1679 /// on purpose and can be raised without ceremony.
1680 pub const MASS_KG: (f64, f64) = (1.0e-6, 100.0);
1681 /// 0.1 mm to 1 m.
1682 pub const DIAMETER_M: (f64, f64) = (1.0e-4, 1.0);
1683 /// 0.1 mm to 10 m. Only checked when supplied.
1684 pub const LENGTH_M: (f64, f64) = (1.0e-4, 10.0);
1685 /// Ballistic coefficient, lb/in². Real values run ~0.1–1.5; the bound is far past both ends.
1686 pub const BALLISTIC_COEFFICIENT: (f64, f64) = (1.0e-4, 100.0);
1687
1688 // Deliberately NOT bounded here: muzzle_velocity_mps and max_range_m. The MCP server
1689 // documents — and tests — a split where a structurally valid request the engine cannot
1690 // solve returns a tool error rather than a protocol error, and an absurd muzzle velocity is
1691 // its worked example of that case. Bounding those two fields here would reclassify that
1692 // example as invalid params and change a contract MCP clients may rely on, which is a
1693 // separate decision from rejecting values that cannot describe a projectile.
1694}
1695
1696fn require_range(
1697 value: f64,
1698 (min, max): (f64, f64),
1699 path: &str,
1700) -> Result<(), SolveErrorEnvelopeV1> {
1701 if !value.is_finite() {
1702 return Err(protocol_error(
1703 SolveErrorCodeV1::InvalidValue,
1704 format!("{path} must be a finite number"),
1705 path,
1706 ));
1707 }
1708 if value < min || value > max {
1709 return Err(protocol_error(
1710 SolveErrorCodeV1::InvalidValue,
1711 format!("{path} must be between {min} and {max}, got {value}"),
1712 path,
1713 ));
1714 }
1715 Ok(())
1716}
1717
1718/// Reject requests whose numbers cannot describe a projectile, before any solve runs.
1719///
1720/// Runs after deserialization so the fields are typed and each error can carry the exact
1721/// JSONPath the caller used, matching how the shape errors above report.
1722fn validate_request_ranges(request: &SolveRequestV1) -> Result<(), SolveErrorEnvelopeV1> {
1723 require_range(
1724 request.projectile.mass_kg,
1725 limits::MASS_KG,
1726 "$.projectile.mass_kg",
1727 )?;
1728 require_range(
1729 request.projectile.diameter_m,
1730 limits::DIAMETER_M,
1731 "$.projectile.diameter_m",
1732 )?;
1733 require_range(
1734 request.projectile.ballistic_coefficient,
1735 limits::BALLISTIC_COEFFICIENT,
1736 "$.projectile.ballistic_coefficient",
1737 )?;
1738 if let Some(length_m) = request.projectile.length_m {
1739 require_range(length_m, limits::LENGTH_M, "$.projectile.length_m")?;
1740 }
1741 if let Some(drag_table) = &request.projectile.drag_table {
1742 validate_drag_table_v1(drag_table)?;
1743 }
1744 if let Some(bc_segments) = &request.projectile.bc_segments {
1745 validate_bc_segments_v1(bc_segments, request.projectile.ballistic_coefficient)?;
1746 }
1747 Ok(())
1748}
1749
1750fn envelope(error: SolveErrorV1) -> SolveErrorEnvelopeV1 {
1751 SolveErrorEnvelopeV1::new(error)
1752}
1753
1754fn protocol_error(
1755 code: SolveErrorCodeV1,
1756 message: impl Into<String>,
1757 path: impl Into<String>,
1758) -> SolveErrorEnvelopeV1 {
1759 envelope(SolveErrorV1::new(code, message).at_path(path))
1760}
1761
1762fn validate_request_shape(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
1763 let root = require_object(value, "$")?;
1764
1765 // Dispatch on the version before applying any v1-only shape rules. A future-version
1766 // request may legitimately contain fields unknown to v1 and must still receive the stable
1767 // unsupported-version error rather than an order-dependent unknown-field error.
1768 validate_schema_version(root)?;
1769 validate_members(
1770 root,
1771 "$",
1772 &[
1773 "schema_version",
1774 "projectile",
1775 "rifle",
1776 "shot",
1777 "atmosphere",
1778 "wind",
1779 "solver",
1780 "effects",
1781 "sampling",
1782 // MBA-1361: optional, additive. Omitting it is the historical shape.
1783 "reticle",
1784 // Offline corrections (BC5D table path): optional, additive.
1785 "corrections",
1786 ],
1787 &[
1788 "schema_version",
1789 "projectile",
1790 "rifle",
1791 "shot",
1792 "atmosphere",
1793 "wind",
1794 "solver",
1795 "effects",
1796 "sampling",
1797 ],
1798 )?;
1799
1800 validate_projectile(required_value(root, "projectile", "$")?)?;
1801 validate_rifle(required_value(root, "rifle", "$")?)?;
1802 validate_shot(required_value(root, "shot", "$")?)?;
1803 validate_atmosphere(required_value(root, "atmosphere", "$")?)?;
1804 validate_wind(required_value(root, "wind", "$")?)?;
1805 validate_solver(required_value(root, "solver", "$")?)?;
1806 validate_effects(required_value(root, "effects", "$")?)?;
1807 validate_sampling(required_value(root, "sampling", "$")?)?;
1808 if let Some(reticle) = root.get("reticle") {
1809 validate_reticle(reticle)?;
1810 }
1811 if let Some(corrections) = root.get("corrections") {
1812 validate_corrections(corrections)?;
1813 }
1814 Ok(())
1815}
1816
1817/// Shape-validate an optional `corrections` block: a strict envelope whose only
1818/// member today is `bc5d_table_path`, a string. The path's existence, format, and
1819/// CRC are solve-time concerns (an `invalid_value`/`io_error` from the service),
1820/// not protocol-shape ones — same split the reticle description uses.
1821fn validate_corrections(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
1822 let path = "$.corrections";
1823 let object = require_object(value, path)?;
1824 validate_members(object, path, &["bc5d_table_path"], &[])?;
1825 if let Some(table_path) = object.get("bc5d_table_path") {
1826 if !table_path.is_string() {
1827 return Err(protocol_error(
1828 SolveErrorCodeV1::InvalidValue,
1829 "expected a string",
1830 "$.corrections.bc5d_table_path",
1831 ));
1832 }
1833 }
1834 Ok(())
1835}
1836
1837/// Shape-validate an optional `reticle` block (MBA-1361).
1838///
1839/// The ENVELOPE is strict (exactly `range_m`, `magnification`, `description`, all
1840/// required); the description itself is handed to the shared reticle schema, whose own
1841/// `validate()` runs at solve time. Splitting it that way keeps the wire contract tight
1842/// without making the engine the arbiter of a front end's render metadata.
1843fn validate_reticle(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
1844 let path = "$.reticle";
1845 let object = require_object(value, path)?;
1846 validate_members(
1847 object,
1848 path,
1849 &["range_m", "magnification", "description"],
1850 &["range_m", "magnification", "description"],
1851 )?;
1852 validate_required_numbers(object, path, &["range_m", "magnification"])?;
1853 require_object(
1854 required_value(object, "description", path)?,
1855 "$.reticle.description",
1856 )?;
1857 Ok(())
1858}
1859
1860fn validate_schema_version(root: &Map<String, Value>) -> Result<(), SolveErrorEnvelopeV1> {
1861 let value = required_value(root, "schema_version", "$")?;
1862 let version = if let Some(version) = value.as_i64() {
1863 i128::from(version)
1864 } else if let Some(version) = value.as_u64() {
1865 i128::from(version)
1866 } else {
1867 return Err(protocol_error(
1868 SolveErrorCodeV1::InvalidValue,
1869 "schema_version must be the integer 1",
1870 "$.schema_version",
1871 ));
1872 };
1873 if version != i128::from(SOLVE_JSON_SCHEMA_VERSION_V1) {
1874 return Err(protocol_error(
1875 SolveErrorCodeV1::UnsupportedSchemaVersion,
1876 format!(
1877 "unsupported schema_version {version}; expected {SOLVE_JSON_SCHEMA_VERSION_V1}"
1878 ),
1879 "$.schema_version",
1880 ));
1881 }
1882 Ok(())
1883}
1884
1885fn validate_projectile(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
1886 let path = "$.projectile";
1887 let object = require_object(value, path)?;
1888 validate_members(
1889 object,
1890 path,
1891 &[
1892 "mass_kg",
1893 "diameter_m",
1894 "length_m",
1895 "drag_model",
1896 "ballistic_coefficient",
1897 // MBA-1597: optional caller-supplied drag curve.
1898 "drag_table",
1899 // MBA-1598: optional velocity-banded BC ladder.
1900 "bc_segments",
1901 ],
1902 &[
1903 "mass_kg",
1904 "diameter_m",
1905 "drag_model",
1906 "ballistic_coefficient",
1907 ],
1908 )?;
1909 validate_required_numbers(
1910 object,
1911 path,
1912 &["mass_kg", "diameter_m", "ballistic_coefficient"],
1913 )?;
1914 validate_optional_number(object, path, "length_m")?;
1915 validate_string_enum(
1916 required_value(object, "drag_model", path)?,
1917 "$.projectile.drag_model",
1918 &DRAG_MODEL_WIRE_NAMES_V1,
1919 )?;
1920 if let Some(drag_table) = object.get("drag_table") {
1921 validate_drag_table_shape(drag_table)?;
1922 }
1923 if let Some(bc_segments) = object.get("bc_segments") {
1924 validate_bc_segments_shape(bc_segments)?;
1925 }
1926 Ok(())
1927}
1928
1929/// The members of one [`BcSegmentV1`], all required numbers.
1930const BC_SEGMENT_FIELDS_V1: [&str; 3] = [
1931 "velocity_min_mps",
1932 "velocity_max_mps",
1933 "ballistic_coefficient",
1934];
1935
1936/// Shape-validate an optional `projectile.bc_segments` (MBA-1598): a non-empty array of strict
1937/// `{velocity_min_mps, velocity_max_mps, ballistic_coefficient}` objects, all numbers. `null`
1938/// is refused here, not read as omission. The values themselves (the band count, the bounds,
1939/// the order and the no-overlap rule) are range rules, checked by [`validate_bc_segments_v1`]
1940/// once the request is typed.
1941fn validate_bc_segments_shape(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
1942 let segments_path = "$.projectile.bc_segments";
1943 let Some(segments) = value.as_array() else {
1944 return Err(protocol_error(
1945 SolveErrorCodeV1::InvalidValue,
1946 "bc_segments must be an array",
1947 segments_path,
1948 ));
1949 };
1950 if segments.is_empty() {
1951 return Err(protocol_error(
1952 SolveErrorCodeV1::InvalidValue,
1953 bc_segment_count_message(0),
1954 segments_path,
1955 ));
1956 }
1957 for (index, segment) in segments.iter().enumerate() {
1958 let seg_path = format!("{segments_path}[{index}]");
1959 let segment = require_object(segment, &seg_path)?;
1960 validate_members(
1961 segment,
1962 &seg_path,
1963 &BC_SEGMENT_FIELDS_V1,
1964 &BC_SEGMENT_FIELDS_V1,
1965 )?;
1966 validate_required_numbers(segment, &seg_path, &BC_SEGMENT_FIELDS_V1)?;
1967 }
1968 Ok(())
1969}
1970
1971fn bc_segment_count_message(count: usize) -> String {
1972 format!("bc_segments must have {MIN_BC_SEGMENTS_V1} to {MAX_BC_SEGMENTS_V1} bands, got {count}")
1973}
1974
1975/// Check a [`ProjectileV1::bc_segments`] ladder's values: the band count, then each band in
1976/// order, naming the exact entry at fault.
1977///
1978/// Each band needs a finite `velocity_min_mps` >= 0, a finite `velocity_max_mps` above it, and
1979/// a `ballistic_coefficient` inside the scalar BC's own bounds. From the second band on,
1980/// `velocity_min_mps` must be below the previous band's (fastest band first), and
1981/// `velocity_max_mps` must not reach above the previous band's `velocity_min_mps` (no
1982/// overlaps; touching edges and gaps are legal).
1983///
1984/// A one-band ladder flies its band at every speed, so the scalar `ballistic_coefficient`
1985/// never flies beside it. Its band BC must match `scalar_bc` to within
1986/// [`ONE_BAND_BC_RELATIVE_TOLERANCE_V1`], or the pair is refused as `conflicting_fields` at the
1987/// band's BC: two different BCs for one projectile can only be a caller mistake, and flying
1988/// either one silently hides it.
1989///
1990/// Called from both the decoder and the solve service, so a Rust caller that builds a request
1991/// without [`decode_solve_request_v1`] hears about a bad band at the same path.
1992pub(crate) fn validate_bc_segments_v1(
1993 segments: &[BcSegmentV1],
1994 scalar_bc: f64,
1995) -> Result<(), SolveErrorEnvelopeV1> {
1996 let base = "$.projectile.bc_segments";
1997 let count = segments.len();
1998 if !(MIN_BC_SEGMENTS_V1..=MAX_BC_SEGMENTS_V1).contains(&count) {
1999 return Err(protocol_error(
2000 SolveErrorCodeV1::InvalidValue,
2001 bc_segment_count_message(count),
2002 base,
2003 ));
2004 }
2005 let mut previous: Option<BcSegmentV1> = None;
2006 for (index, seg) in segments.iter().enumerate() {
2007 let seg_path = format!("{base}[{index}]");
2008 let min_path = format!("{seg_path}.velocity_min_mps");
2009 let max_path = format!("{seg_path}.velocity_max_mps");
2010 if !seg.velocity_min_mps.is_finite() || seg.velocity_min_mps < 0.0 {
2011 return Err(protocol_error(
2012 SolveErrorCodeV1::InvalidValue,
2013 format!(
2014 "velocity_min_mps must be finite and >= 0, got {}",
2015 seg.velocity_min_mps
2016 ),
2017 min_path,
2018 ));
2019 }
2020 if !seg.velocity_max_mps.is_finite() || seg.velocity_max_mps <= seg.velocity_min_mps {
2021 return Err(protocol_error(
2022 SolveErrorCodeV1::InvalidValue,
2023 format!(
2024 "velocity_max_mps must be finite and > velocity_min_mps ({}), got {}",
2025 seg.velocity_min_mps, seg.velocity_max_mps
2026 ),
2027 max_path,
2028 ));
2029 }
2030 require_range(
2031 seg.ballistic_coefficient,
2032 limits::BALLISTIC_COEFFICIENT,
2033 &format!("{seg_path}.ballistic_coefficient"),
2034 )?;
2035 if let Some(prev) = previous {
2036 if seg.velocity_min_mps >= prev.velocity_min_mps {
2037 return Err(protocol_error(
2038 SolveErrorCodeV1::InvalidValue,
2039 format!(
2040 "velocity_min_mps must be below bc_segments[{}].velocity_min_mps ({}), \
2041 got {}: list the bands from the highest speed to the lowest, or \
2042 reverse the array",
2043 index - 1,
2044 prev.velocity_min_mps,
2045 seg.velocity_min_mps
2046 ),
2047 min_path,
2048 ));
2049 }
2050 if seg.velocity_max_mps > prev.velocity_min_mps {
2051 return Err(protocol_error(
2052 SolveErrorCodeV1::InvalidValue,
2053 format!(
2054 "velocity_max_mps ({}) overlaps bc_segments[{}], which starts at {} m/s: \
2055 a band must end at or below the start of the faster band before it",
2056 seg.velocity_max_mps,
2057 index - 1,
2058 prev.velocity_min_mps
2059 ),
2060 max_path,
2061 ));
2062 }
2063 }
2064 previous = Some(*seg);
2065 }
2066 if let [band] = segments {
2067 let difference = (band.ballistic_coefficient - scalar_bc).abs();
2068 let allowed = ONE_BAND_BC_RELATIVE_TOLERANCE_V1 * band.ballistic_coefficient.max(scalar_bc);
2069 if difference > allowed {
2070 return Err(protocol_error(
2071 SolveErrorCodeV1::ConflictingFields,
2072 format!(
2073 "a one-band ladder flies its band's BC at every speed, so \
2074 bc_segments[0].ballistic_coefficient ({}) must match \
2075 projectile.ballistic_coefficient ({scalar_bc}): send the same value in \
2076 both, or omit bc_segments",
2077 band.ballistic_coefficient
2078 ),
2079 format!("{base}[0].ballistic_coefficient"),
2080 ));
2081 }
2082 }
2083 Ok(())
2084}
2085
2086/// Shape-validate an optional `projectile.drag_table` (MBA-1597): a strict object with a
2087/// closed `kind` enum, an optional string `name`, and an array of strict `{mach, cd}` points.
2088/// The values themselves — the point count, ascending Mach, positive Cd, the name's length and
2089/// characters — are range rules, checked by [`validate_drag_table_v1`] once the request is
2090/// typed.
2091fn validate_drag_table_shape(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2092 let path = "$.projectile.drag_table";
2093 let object = require_object(value, path)?;
2094 validate_members(
2095 object,
2096 path,
2097 &["kind", "name", "points"],
2098 &["kind", "points"],
2099 )?;
2100 validate_string_enum(
2101 required_value(object, "kind", path)?,
2102 "$.projectile.drag_table.kind",
2103 &["reference", "projectile"],
2104 )?;
2105 if object.get("name").is_some_and(|name| !name.is_string()) {
2106 return Err(protocol_error(
2107 SolveErrorCodeV1::InvalidValue,
2108 "expected a string",
2109 "$.projectile.drag_table.name",
2110 ));
2111 }
2112 let points_path = "$.projectile.drag_table.points";
2113 let Some(points) = required_value(object, "points", path)?.as_array() else {
2114 return Err(protocol_error(
2115 SolveErrorCodeV1::InvalidValue,
2116 "points must be an array",
2117 points_path,
2118 ));
2119 };
2120 for (index, point) in points.iter().enumerate() {
2121 let point_path = format!("{points_path}[{index}]");
2122 let point = require_object(point, &point_path)?;
2123 validate_members(point, &point_path, &["mach", "cd"], &["mach", "cd"])?;
2124 validate_required_numbers(point, &point_path, &["mach", "cd"])?;
2125 }
2126 Ok(())
2127}
2128
2129fn validate_rifle(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2130 let path = "$.rifle";
2131 let object = require_object(value, path)?;
2132 validate_members(
2133 object,
2134 path,
2135 &[
2136 "muzzle_velocity_mps",
2137 "sight_height_m",
2138 "muzzle_height_m",
2139 "twist_rate_m_per_turn",
2140 "twist_direction",
2141 "sight_offset_lateral_m",
2142 ],
2143 &["muzzle_velocity_mps"],
2144 )?;
2145 validate_required_numbers(object, path, &["muzzle_velocity_mps"])?;
2146 validate_optional_numbers(
2147 object,
2148 path,
2149 &[
2150 "sight_height_m",
2151 "muzzle_height_m",
2152 "twist_rate_m_per_turn",
2153 "sight_offset_lateral_m",
2154 ],
2155 )?;
2156 if let Some(direction) = object.get("twist_direction") {
2157 validate_string_enum(direction, "$.rifle.twist_direction", &["left", "right"])?;
2158 }
2159 Ok(())
2160}
2161
2162fn validate_shot(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2163 let path = "$.shot";
2164 let object = require_object(value, path)?;
2165 validate_members(
2166 object,
2167 path,
2168 &[
2169 "max_range_m",
2170 "zero_distance_m",
2171 "muzzle_angle_rad",
2172 "aim_azimuth_rad",
2173 "shot_azimuth_rad",
2174 "shooting_angle_rad",
2175 "cant_angle_rad",
2176 "target_height_m",
2177 "ground_threshold_m",
2178 "zero_poi_up_m",
2179 "zero_poi_right_m",
2180 "drops_reference",
2181 ],
2182 &["max_range_m"],
2183 )?;
2184 validate_required_numbers(object, path, &["max_range_m"])?;
2185 validate_optional_number(object, path, "zero_distance_m")?;
2186 validate_optional_number(object, path, "muzzle_angle_rad")?;
2187 validate_optional_numbers(
2188 object,
2189 path,
2190 &[
2191 "aim_azimuth_rad",
2192 "shot_azimuth_rad",
2193 "shooting_angle_rad",
2194 "cant_angle_rad",
2195 "target_height_m",
2196 "ground_threshold_m",
2197 "zero_poi_up_m",
2198 "zero_poi_right_m",
2199 ],
2200 )?;
2201 // MBA-1403: string enum, not a number — same shape-validation pattern as
2202 // $.rifle.twist_direction.
2203 if let Some(reference) = object.get("drops_reference") {
2204 validate_string_enum(reference, "$.shot.drops_reference", &["los", "target"])?;
2205 }
2206 Ok(())
2207}
2208
2209pub(crate) fn validate_atmosphere(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2210 let path = "$.atmosphere";
2211 let object = require_object(value, path)?;
2212 validate_members(
2213 object,
2214 path,
2215 &[
2216 "altitude_m",
2217 "temperature_k",
2218 "pressure_pa",
2219 "pressure_reference",
2220 "relative_humidity",
2221 "latitude_rad",
2222 ],
2223 &[],
2224 )?;
2225 validate_optional_numbers(
2226 object,
2227 path,
2228 &[
2229 "altitude_m",
2230 "temperature_k",
2231 "pressure_pa",
2232 "relative_humidity",
2233 "latitude_rad",
2234 ],
2235 )?;
2236 // MBA-1397: string enum, not a number -- same shape-validation pattern as
2237 // $.shot.drops_reference / $.wind.wind_reference. This field has existed on
2238 // AtmosphereV1 and been consumed by resolve_atmosphere since MBA-1397, but was never
2239 // added to this hand-maintained allowlist, so decode_solve_request_v1 rejected it as
2240 // an unknown field even though direct SolveRequestV1 construction always accepted it.
2241 if let Some(reference) = object.get("pressure_reference") {
2242 validate_string_enum(
2243 reference,
2244 "$.atmosphere.pressure_reference",
2245 &["absolute", "qnh"],
2246 )?;
2247 }
2248 Ok(())
2249}
2250
2251fn validate_wind(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2252 let path = "$.wind";
2253 let object = require_object(value, path)?;
2254 validate_members(
2255 object,
2256 path,
2257 &[
2258 "speed_mps",
2259 "direction_from_rad",
2260 "vertical_speed_mps",
2261 "segments",
2262 "wind_reference",
2263 ],
2264 &[],
2265 )?;
2266 for field in ["speed_mps", "direction_from_rad", "vertical_speed_mps"] {
2267 validate_optional_number(object, path, field)?;
2268 }
2269 // MBA-1368: wind_reference is a closed string enum (shooter | compass).
2270 if let Some(reference) = object.get("wind_reference") {
2271 validate_string_enum(reference, "$.wind.wind_reference", &["shooter", "compass"])?;
2272 }
2273
2274 if let Some(segments) = object.get("segments") {
2275 let Some(segments) = segments.as_array() else {
2276 return Err(protocol_error(
2277 SolveErrorCodeV1::InvalidValue,
2278 "segments must be an array",
2279 "$.wind.segments",
2280 ));
2281 };
2282 for (index, segment) in segments.iter().enumerate() {
2283 let segment_path = format!("$.wind.segments[{index}]");
2284 let segment = require_object(segment, &segment_path)?;
2285 validate_members(
2286 segment,
2287 &segment_path,
2288 &[
2289 "until_distance_m",
2290 "speed_mps",
2291 "direction_from_rad",
2292 "vertical_speed_mps",
2293 ],
2294 &["until_distance_m", "speed_mps", "direction_from_rad"],
2295 )?;
2296 validate_required_numbers(
2297 segment,
2298 &segment_path,
2299 &["until_distance_m", "speed_mps", "direction_from_rad"],
2300 )?;
2301 validate_optional_number(segment, &segment_path, "vertical_speed_mps")?;
2302 }
2303 }
2304 Ok(())
2305}
2306
2307fn validate_solver(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2308 let path = "$.solver";
2309 let object = require_object(value, path)?;
2310 validate_members(object, path, &["method", "time_step_s"], &[])?;
2311 validate_optional_number(object, path, "time_step_s")?;
2312 if let Some(method) = object.get("method") {
2313 validate_string_enum(method, "$.solver.method", &["euler", "rk4", "rk45"])?;
2314 }
2315 Ok(())
2316}
2317
2318/// Every member name `effects` accepts on the v1 wire, in declaration order.
2319///
2320/// One list, because there are two readers: `validate_effects` rejects anything outside it,
2321/// and the MCP `solve` tool publishes an `inputSchema` with `additionalProperties: false` over
2322/// the same vocabulary. Those drifted apart once already — `wind_shear_model` reached the JSON
2323/// wire in 0.36.0 and never reached the MCP schema, so an MCP caller could not ask for shear
2324/// that the bridge underneath was perfectly willing to apply. `mcp_effect_schema_matches_the_wire`
2325/// in `src/mcp_command.rs` pins them together.
2326pub const SOLVE_JSON_EFFECT_NAMES_V1: &[&str] = &[
2327 "magnus",
2328 "coriolis",
2329 "enhanced_spin_drift",
2330 "wind_shear_model",
2331 "aerodynamic_jump",
2332];
2333
2334fn validate_effects(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2335 let path = "$.effects";
2336 let object = require_object(value, path)?;
2337 validate_members(object, path, SOLVE_JSON_EFFECT_NAMES_V1, &[])?;
2338 validate_optional_booleans(
2339 object,
2340 path,
2341 &[
2342 "magnus",
2343 "coriolis",
2344 "enhanced_spin_drift",
2345 "aerodynamic_jump",
2346 ],
2347 )?;
2348
2349 // An unknown shear model is rejected here, with the exact path and the accepted spellings,
2350 // rather than deserializing to the `none` default. Silently unsheared numbers are
2351 // indistinguishable from sheared ones downstream.
2352 if let Some(model) = object.get("wind_shear_model") {
2353 validate_string_enum(
2354 model,
2355 "$.effects.wind_shear_model",
2356 &[
2357 "none",
2358 "logarithmic",
2359 "power_law",
2360 "ekman_spiral",
2361 // Alias, canonicalized to `ekman_spiral` in the resolved echo.
2362 "ekman",
2363 ],
2364 )?;
2365 }
2366
2367 if object.get("magnus").and_then(Value::as_bool) == Some(true)
2368 && object.get("enhanced_spin_drift").and_then(Value::as_bool) == Some(true)
2369 {
2370 return Err(protocol_error(
2371 SolveErrorCodeV1::ConflictingFields,
2372 "magnus and enhanced_spin_drift cannot both be enabled",
2373 "$.effects",
2374 ));
2375 }
2376
2377 Ok(())
2378}
2379
2380fn validate_sampling(value: &Value) -> Result<(), SolveErrorEnvelopeV1> {
2381 let path = "$.sampling";
2382 let object = require_object(value, path)?;
2383 validate_members(object, path, &["interval_m"], &[])?;
2384 validate_optional_number(object, path, "interval_m")
2385}
2386
2387pub(crate) fn require_object<'a>(
2388 value: &'a Value,
2389 path: &str,
2390) -> Result<&'a Map<String, Value>, SolveErrorEnvelopeV1> {
2391 value
2392 .as_object()
2393 .ok_or_else(|| protocol_error(SolveErrorCodeV1::InvalidValue, "expected an object", path))
2394}
2395
2396fn required_value<'a>(
2397 object: &'a Map<String, Value>,
2398 field: &str,
2399 parent_path: &str,
2400) -> Result<&'a Value, SolveErrorEnvelopeV1> {
2401 object.get(field).ok_or_else(|| {
2402 protocol_error(
2403 SolveErrorCodeV1::MissingField,
2404 format!("missing required field `{field}`"),
2405 child_path(parent_path, field),
2406 )
2407 })
2408}
2409
2410pub(crate) fn validate_members(
2411 object: &Map<String, Value>,
2412 path: &str,
2413 allowed: &[&str],
2414 required: &[&str],
2415) -> Result<(), SolveErrorEnvelopeV1> {
2416 if let Some(field) = object
2417 .keys()
2418 .find(|field| !allowed.contains(&field.as_str()))
2419 {
2420 return Err(protocol_error(
2421 SolveErrorCodeV1::UnknownField,
2422 format!("unknown field `{field}`"),
2423 child_path(path, field),
2424 ));
2425 }
2426
2427 if let Some(field) = required.iter().find(|field| !object.contains_key(**field)) {
2428 return Err(protocol_error(
2429 SolveErrorCodeV1::MissingField,
2430 format!("missing required field `{field}`"),
2431 child_path(path, field),
2432 ));
2433 }
2434 Ok(())
2435}
2436
2437fn validate_string_enum(
2438 value: &Value,
2439 path: &str,
2440 allowed: &[&str],
2441) -> Result<(), SolveErrorEnvelopeV1> {
2442 let Some(value) = value.as_str() else {
2443 return Err(protocol_error(
2444 SolveErrorCodeV1::InvalidValue,
2445 "expected a string enum value",
2446 path,
2447 ));
2448 };
2449 if !allowed.contains(&value) {
2450 return Err(protocol_error(
2451 SolveErrorCodeV1::InvalidValue,
2452 format!(
2453 "invalid value `{value}`; expected one of {}",
2454 allowed.join(", ")
2455 ),
2456 path,
2457 ));
2458 }
2459 Ok(())
2460}
2461
2462fn validate_required_numbers(
2463 object: &Map<String, Value>,
2464 parent_path: &str,
2465 fields: &[&str],
2466) -> Result<(), SolveErrorEnvelopeV1> {
2467 for field in fields {
2468 let value = required_value(object, field, parent_path)?;
2469 validate_number(value, &child_path(parent_path, field))?;
2470 }
2471 Ok(())
2472}
2473
2474fn validate_optional_numbers(
2475 object: &Map<String, Value>,
2476 parent_path: &str,
2477 fields: &[&str],
2478) -> Result<(), SolveErrorEnvelopeV1> {
2479 for field in fields {
2480 validate_optional_number(object, parent_path, field)?;
2481 }
2482 Ok(())
2483}
2484
2485fn validate_optional_number(
2486 object: &Map<String, Value>,
2487 parent_path: &str,
2488 field: &str,
2489) -> Result<(), SolveErrorEnvelopeV1> {
2490 if let Some(value) = object.get(field) {
2491 validate_number(value, &child_path(parent_path, field))?;
2492 }
2493 Ok(())
2494}
2495
2496fn validate_number(value: &Value, path: &str) -> Result<(), SolveErrorEnvelopeV1> {
2497 if value.is_number() {
2498 Ok(())
2499 } else {
2500 Err(protocol_error(
2501 SolveErrorCodeV1::InvalidValue,
2502 "expected a number",
2503 path,
2504 ))
2505 }
2506}
2507
2508fn validate_optional_booleans(
2509 object: &Map<String, Value>,
2510 parent_path: &str,
2511 fields: &[&str],
2512) -> Result<(), SolveErrorEnvelopeV1> {
2513 for field in fields {
2514 if let Some(value) = object.get(*field) {
2515 if !value.is_boolean() {
2516 return Err(protocol_error(
2517 SolveErrorCodeV1::InvalidValue,
2518 "expected a boolean",
2519 child_path(parent_path, field),
2520 ));
2521 }
2522 }
2523 }
2524 Ok(())
2525}
2526
2527fn child_path(parent: &str, field: &str) -> String {
2528 format!("{parent}.{field}")
2529}
2530
2531/// MBA-1413: physical bounds on the projectile fields.
2532#[cfg(test)]
2533mod request_range_tests {
2534 use super::*;
2535
2536 /// A complete, ordinary request. Every range test below starts from this and perturbs one
2537 /// field, so a bound that accidentally rejects real data fails loudly here first.
2538 fn valid_request_json() -> String {
2539 r#"{"schema_version":1,
2540 "projectile":{"mass_kg":0.01134,"diameter_m":0.00782,"length_m":0.031,
2541 "drag_model":"G7","ballistic_coefficient":0.243},
2542 "rifle":{"muzzle_velocity_mps":823.0},
2543 "shot":{"max_range_m":1000.0},
2544 "atmosphere":{},"wind":{},"solver":{},"effects":{},"sampling":{}}"#
2545 .to_string()
2546 }
2547
2548 fn decode_err(json: &str) -> SolveErrorEnvelopeV1 {
2549 decode_solve_request_v1(json).expect_err("request should have been rejected")
2550 }
2551
2552 #[test]
2553 fn an_ordinary_request_still_decodes() {
2554 decode_solve_request_v1(&valid_request_json()).expect("a real load must not be rejected");
2555 }
2556
2557 /// The exact input cargo-fuzz found (MBA-1413). It declared a projectile mass of about
2558 /// 1.1e-66 kg — roughly 10^40 times lighter than a proton — and the engine accepted and
2559 /// solved it. The visible symptom was that the request did not survive a JSON round trip,
2560 /// because serde_json's float parser is a bit off re-reading its own output at that
2561 /// magnitude; the actual defect was accepting the number at all.
2562 #[test]
2563 fn the_fuzz_reproducer_is_now_a_clean_typed_rejection() {
2564 let reproducer = r#"{"schema_version":1,
2565 "projectile":{"mass_kg":0.011366666667e-64,"diameter_m":0.00782,
2566 "drag_model":"G7","ballistic_coefficient":1.2e2},
2567 "rifle":{"muzzle_velocity_mps":823.0},
2568 "shot":{"max_range_m":100.0},
2569 "atmosphere":{},"wind":{},"solver":{},"effects":{},"sampling":{}}"#;
2570
2571 let envelope = decode_err(reproducer);
2572 assert_eq!(envelope.error.code, SolveErrorCodeV1::InvalidValue);
2573 assert_eq!(envelope.error.path(), Some("$.projectile.mass_kg"));
2574 }
2575
2576 /// An error envelope must itself round-trip, since that is the invariant the fuzz target
2577 /// asserts on the rejection branch.
2578 #[test]
2579 fn the_rejection_envelope_round_trips() {
2580 let envelope = decode_err(
2581 r#"{"schema_version":1,
2582 "projectile":{"mass_kg":1.0e-66,"diameter_m":0.00782,
2583 "drag_model":"G7","ballistic_coefficient":0.243},
2584 "rifle":{"muzzle_velocity_mps":823.0},
2585 "shot":{"max_range_m":100.0},
2586 "atmosphere":{},"wind":{},"solver":{},"effects":{},"sampling":{}}"#,
2587 );
2588 let encoded = serde_json::to_string(&envelope).expect("serialize");
2589 let decoded: SolveErrorEnvelopeV1 = serde_json::from_str(&encoded).expect("deserialize");
2590 assert_eq!(decoded, envelope);
2591 }
2592
2593 #[test]
2594 fn each_bounded_field_reports_its_own_path() {
2595 for (field, bad_value, path) in [
2596 ("mass_kg", "1.0e-66", "$.projectile.mass_kg"),
2597 ("diameter_m", "1.0e-9", "$.projectile.diameter_m"),
2598 (
2599 "ballistic_coefficient",
2600 "1.0e6",
2601 "$.projectile.ballistic_coefficient",
2602 ),
2603 ("length_m", "1.0e-9", "$.projectile.length_m"),
2604 ] {
2605 let json = valid_request_json().replace(
2606 &format!("\"{field}\":{}", default_for(field)),
2607 &format!("\"{field}\":{bad_value}"),
2608 );
2609 let envelope = decode_err(&json);
2610 assert_eq!(envelope.error.path(), Some(path), "wrong path for {field}");
2611 assert_eq!(envelope.error.code, SolveErrorCodeV1::InvalidValue);
2612 }
2613 }
2614
2615 fn default_for(field: &str) -> &'static str {
2616 match field {
2617 "mass_kg" => "0.01134",
2618 "diameter_m" => "0.00782",
2619 "ballistic_coefficient" => "0.243",
2620 "length_m" => "0.031",
2621 other => panic!("no default recorded for {other}"),
2622 }
2623 }
2624
2625 /// Muzzle velocity is deliberately unbounded: the MCP server documents and tests a split
2626 /// where a structurally valid request the engine cannot solve returns a tool error rather
2627 /// than a protocol error, using an absurd muzzle velocity as its example.
2628 #[test]
2629 fn muzzle_velocity_is_deliberately_left_unbounded() {
2630 let json = valid_request_json().replace("823.0", "1.0e308");
2631 decode_solve_request_v1(&json)
2632 .expect("muzzle velocity must stay a solve-time concern, not a protocol one");
2633 }
2634}