ballistics_engine/card_service.rs
1//! Transport-free card-generation services (come-ups, range table, wind card).
2//!
3//! These replicate the CLI's card commands exactly — same zero solve, same sampled
4//! trajectory, same nearest-sample row selection, same adjustment/bias/CF/click
5//! ordering via [`crate::adjustment`] — as versioned request/response types the
6//! bridge can expose to embedded consumers. The CLI remains the reference
7//! implementation; `tests/card_bridge_golden.rs` asserts row-for-row agreement.
8//!
9//! ## Unit convention
10//!
11//! Unlike solve-json (explicit SI), card requests are denominated in the shooter's own
12//! units, exactly like the CLI flags they mirror: imperial = fps, grains, inches, yards,
13//! °F, inHg, mph; metric = m/s, grams, mm, meters, °C, hPa, m/s. A DOPE card is a display
14//! artifact; its inputs and outputs share the shooter's unit world, and this keeps the
15//! request shape identical to the documented CLI surface.
16//!
17//! ### Per-dimension units (MBA-1519)
18//!
19//! Nobody shoots in one system. A Finnish shooter ranges in metres, dials MIL, and buys
20//! bullets labelled in grains, because that is how the industry sells them; European makers
21//! dual-print `grams / grains` rather than replacing one with the other, and mix within a
22//! single table. So the denominating state on this request is a unit PER DIMENSION, and
23//! [`CardUnits`] is a one-shot preset that fills in every dimension the request does not
24//! state for itself — not a mode the card is "in".
25//!
26//! Concretely: an explicit per-dimension field wins; an absent one falls back to what
27//! `units` implies. A request written before those fields existed states none of them, so
28//! every dimension falls back and the card is byte-for-byte the card it always was
29//! (`tests/card_units_per_dimension.rs` pins that against a stored document).
30//!
31//! The response needed no new FIELD for any of this: [`CardUnitsBlockV1`] has always carried
32//! seven independent label fields, so a card whose distance is metres and whose velocity is
33//! fps already had somewhere to say so. It did need the two angular labels to become
34//! requestable: `elevation_adjustment`/`windage_adjustment` print `"MIL"`/`"MOA"`/`"SMOA"`/
35//! `"IPHY"`/`"CLICKS"` and [`AdjustmentUnit`] deserialized lowercase only, so those two were
36//! the only fields of the block a caller could not echo back. They take the uppercase
37//! spellings as aliases now, which makes "echo the units block into the next request" true
38//! of all seven fields rather than five of them.
39//!
40//! Three candidates do NOT get a new field, and each for its own reason:
41//!
42//! * **Scope adjustment** is already per-dimension, and was first: `adjustment_unit` and
43//! `windage_unit` are separate fields with separate click graduations, because a shooter
44//! with a MIL rifle and an MOA rifle has two scopes rather than a preference. SMOA (and
45//! its `iphy` spelling) is already one of the values they take.
46//! * **Clicks** is not a units dimension. A click is meaningless without a graduation, and
47//! this module already enforces that: `adjustment_unit == Clicks` without an
48//! `elevation_click_value` is a refusal. The graduation belongs beside the turret's
49//! MIL/MOA/SMOA marking, not in a units picker.
50//! * **Twist rate** is a dimension of the design but not of this request — a card request
51//! carries no twist, so there is nothing here for a twist unit to denominate.
52//!
53//! And the linear-at-distance spellings are NOT units: "inches@100yd" IS SMOA — the same
54//! 1/3600 rad, the same printed number, no conversion — and "cm/100m" is 0.1 mrad, i.e. MIL
55//! with a factor-of-ten display. They are alternate HEADER TEXT for units this request
56//! already has, and adding them as values would give a caller two spellings that produce
57//! identical numbers.
58//!
59//! ### What the response does NOT tell a caller
60//!
61//! Like every other default on this request — `sight_height`, `temperature`, `pressure`,
62//! `humidity`, `windage_unit` — a per-dimension unit taken from the preset is applied
63//! silently, and this surface has no notice channel at all (there is no `assumptions` array
64//! on [`CardResponseV1`], unlike solve-json's `SolveSuccessV1`).
65//!
66//! Be precise about what that costs, because a paragraph of prose can argue it away. The `units`
67//! block names the unit of the SEVEN OUTPUT COLUMNS and nothing else. It says nothing about
68//! the six dimensions that are input-only — `mass`, `diameter`, `sight_height`,
69//! `temperature`, `pressure`, `altitude` — so for those a caller cannot read back off the
70//! card which unit the engine settled on.
71//!
72//! `altitude` is the sharp one, because it is the dimension whose fallback is deliberately
73//! NOT the preset's: an imperial `card.range_table` carrying `altitude: 5000` and no
74//! `altitude_unit` — which a US caller writing an imperial card means as feet — is solved at
75//! 5000 METRES, and no field of the response says so. On a .308 175 gr that is ~1.9 MIL of
76//! elevation at 1000 yd against the same card with `altitude_unit: "feet"`. The BEHAVIOUR
77//! predates the per-dimension fields (`altitude` has always reached
78//! [`AtmosphericConditions`] unconverted); what is new is that the request can now name the
79//! dimension, so the gap is describable instead of merely present.
80//!
81//! No notice was added here, and the reason is narrow rather than principled: any notice —
82//! an `assumptions` array, or extra label fields on the units block — is a change to the
83//! RESPONSE bytes of every card, including the stored documents the reprint path compares
84//! label-for-label and the six goldens that are the whole evidence for this change being
85//! additive on the wire. A response-schema change belongs to a ticket that can move those
86//! goldens honestly. Until then the remedy is on the request: a caller that cares which
87//! altitude it got states `altitude_unit`, and a card built by an app should state every
88//! dimension rather than lean on a preset.
89
90use serde::{Deserialize, Serialize};
91
92use crate::adjustment::{
93 adjustment_display, adjustment_unit_label, parse_click_value, windage_adjustment_display,
94 AdjustmentUnit, ClickValue,
95};
96use crate::hold_curve::{
97 card_sample_max_range_m, range_not_sampled_message, run_sampled_flight, sample_at_range,
98 CardTruncation, SampledFlight, CARD_SAMPLE_INTERVAL_M,
99};
100use crate::{AtmosphericConditions, BallisticInputs, BCSegmentData, DragModel, WindConditions};
101
102/// Schema version of the card request/response contract.
103pub const CARD_SCHEMA_VERSION_V1: u32 = 1;
104
105const GRAINS_TO_KG: f64 = crate::constants::GRAINS_TO_KG;
106
107/// The unit PRESET for a card request: a one-shot bulk action that fills in every
108/// per-dimension unit the request does not state for itself, not a mode the card is in.
109///
110/// It stays because it is the whole of the pre-MBA-1519 contract and because "give me an
111/// imperial card" remains the overwhelmingly common request. What changed is its standing:
112/// it is now the FALLBACK for each dimension rather than the denominator of all of them.
113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "lowercase")]
115pub enum CardUnits {
116 #[default]
117 Imperial,
118 Metric,
119}
120
121// --- Per-dimension units (MBA-1519) ------------------------------------------------------
122//
123// One enum per dimension the card request actually denominates. Each is a plain value list;
124// the mapping from a value to a conversion factor and to a printed label lives in exactly
125// one place, `Units` below, so a dimension cannot convert one way and be labelled another.
126//
127// Every enum carries serde aliases for the spelling the RESPONSE prints for that unit
128// (`"m/s"`, `"ft-lb"`, `"in"`, `"yd"`, ...), and so does [`AdjustmentUnit`] over in
129// `adjustment.rs` for the two uppercase dial labels. A caller that reads a card's `units`
130// block and writes those strings straight back into the next request is doing the obvious
131// thing, and it now works — for all seven fields of the block — instead of failing on a
132// request that denies unknown values.
133
134/// Range axis: what `zero_distance`, `start`/`end`/`step` and every row's `range` are in.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(rename_all = "lowercase")]
137pub enum CardDistanceUnit {
138 #[serde(alias = "yd", alias = "yard")]
139 Yards,
140 #[serde(alias = "m", alias = "metres", alias = "meter", alias = "metre")]
141 Meters,
142}
143
144/// Speed of the bullet: `muzzle_velocity`, `bc_segments` band edges, the `velocity` column.
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(rename_all = "lowercase")]
147pub enum CardVelocityUnit {
148 #[serde(alias = "ft/s")]
149 Fps,
150 #[serde(alias = "m/s")]
151 Mps,
152}
153
154/// Bullet weight. Grains and grams differ by 15.43x, and on the BC path mass never enters
155/// the drag denominator — it touches energy and stability only — so a grams-for-grains slip
156/// yields a trajectory that looks entirely normal. Which is exactly why the unit has to be
157/// stated per-dimension rather than inferred: the dual-printed `g / gr` box a European
158/// shooter is holding is the normal case, not an edge one.
159///
160/// The one-character wire tokens `"g"` and `"gr"` are deliberately NOT accepted, though
161/// `"gram"`/`"grams"` and `"grain"`/`"grains"` are. Those two tokens are the slip this
162/// dimension exists to prevent: a 175-grain load sent as `"g"` solves to bit-identical
163/// dials, drift, velocity and time — only the energy column moves, 1009 ft-lb to 15575 — and
164/// the response has no mass label for a reader to catch it on. Nor can a plausibility guard
165/// catch it: bullets run roughly 5–800 grains and roughly 0.3–52 grams, so the two ranges
166/// OVERLAP across 5–52, where 48 grains (a .22 varmint bullet) and 48 grams (a .50 BMG) are
167/// both ordinary. There is no threshold to put a guard at, so the defence has to be the
168/// spelling, and the spelled-out name is the one thing a caller cannot typo into the other
169/// unit.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "lowercase")]
172pub enum CardMassUnit {
173 #[serde(alias = "grain")]
174 Grains,
175 #[serde(alias = "gram")]
176 Grams,
177}
178
179/// A small linear length. Shared by the request's two TARGET-SIDE linear dimensions
180/// (sight-to-bore geometry and the linear drop column) because they take the same values,
181/// never because they are the same setting: they are separate fields and resolve
182/// independently.
183///
184/// Bullet diameter is NOT one of them — it has [`CardDiameterUnit`], a narrower vocabulary.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "lowercase")]
187pub enum CardLinearUnit {
188 #[serde(alias = "in", alias = "inch")]
189 Inches,
190 #[serde(alias = "centimeters", alias = "centimetres")]
191 Cm,
192 #[serde(alias = "millimeters", alias = "millimetres")]
193 Mm,
194}
195
196/// Bullet diameter: inches or millimetres, the two units a calibre is ever quoted in.
197///
198/// Its own enum rather than a third user of [`CardLinearUnit`], which would also accept
199/// `cm`. The design's dimension table lists inches and mm for this dimension and no third
200/// value, and a wire vocabulary on a `deny_unknown_fields` paid contract is far cheaper to
201/// widen later than to narrow: nobody quotes a calibre in centimetres, so `0.782` cm is
202/// likelier to be a slipped `7.82` mm than a request anyone meant.
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
204#[serde(rename_all = "lowercase")]
205pub enum CardDiameterUnit {
206 #[serde(alias = "in", alias = "inch")]
207 Inches,
208 #[serde(alias = "millimeters", alias = "millimetres")]
209 Mm,
210}
211
212/// Wind and crossing-target speed. Four values, not two: a European card reads km/h and a
213/// coastal one reads knots, and neither is expressible by picking a system.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215#[serde(rename_all = "lowercase")]
216pub enum CardWindSpeedUnit {
217 Mph,
218 #[serde(alias = "m/s")]
219 Mps,
220 #[serde(alias = "km/h", alias = "kmh")]
221 Kph,
222 #[serde(alias = "kn", alias = "kt", alias = "knot")]
223 Knots,
224}
225
226/// Air temperature.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "lowercase")]
229pub enum CardTemperatureUnit {
230 #[serde(alias = "f", alias = "degf")]
231 Fahrenheit,
232 #[serde(alias = "c", alias = "degc")]
233 Celsius,
234}
235
236/// Station pressure. `hpa` and `mbar` are the same number, which is why mbar is an alias
237/// rather than a value of its own.
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(rename_all = "lowercase")]
240pub enum CardPressureUnit {
241 #[serde(alias = "in-hg", alias = "inchesofmercury")]
242 InHg,
243 #[serde(alias = "mbar", alias = "millibar")]
244 HPa,
245}
246
247/// Terminal energy column.
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "lowercase")]
250pub enum CardEnergyUnit {
251 #[serde(alias = "ft-lb", alias = "ftlbs", alias = "footpounds")]
252 FtLb,
253 // "J" as well as "j": the response's energy label is the capitalized SI symbol, and the
254 // aliases exist precisely so a caller can echo a card's own labels back at it.
255 #[serde(alias = "j", alias = "J", alias = "joule")]
256 Joules,
257}
258
259/// Site elevation. See [`CardRequestV1::altitude_unit`] for why this one dimension's
260/// default does not come from the preset.
261#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "lowercase")]
263pub enum CardAltitudeUnit {
264 #[serde(alias = "ft", alias = "foot")]
265 Feet,
266 #[serde(alias = "m", alias = "metres", alias = "meter", alias = "metre")]
267 Meters,
268}
269
270/// Everything the three card surfaces share: load, zero, atmosphere, display axes.
271///
272/// Field values are in this request's PER-DIMENSION units: each dimensional field names the
273/// `*_unit` field that denominates it, and each of those falls back to what `units` implies
274/// when it is absent (see the module docs). Stating none of them is the pre-MBA-1519 shape
275/// and reproduces the pre-MBA-1519 card exactly.
276///
277/// ## Adding a field here is additive on the WIRE and breaking in RUST
278///
279/// This is a deserialization target: the supported way to build one is
280/// `serde_json::from_str`/`from_value` on a JSON document, which is what the bridge and every
281/// binding do, and an optional new field costs such a caller nothing. A downstream Rust crate
282/// that constructs it with a struct literal has no such luck — every added field is an
283/// `E0063: missing fields` against code that compiled before, which is exactly what MBA-1519's
284/// eleven fields do to a crate written against 0.39.x. The remedy is one line per field
285/// (`altitude_unit: None`, and so on for the rest); the intended path is to deserialize.
286///
287/// `#[non_exhaustive]` was considered and NOT applied. It would break the same callers in the
288/// same release, and — with no `Default` and no builder on this type — it would leave a
289/// downstream crate no way to construct the request at all, trading one fixable compile error
290/// for a permanent one. So the breakage is stated in the CHANGELOG for the release that causes
291/// it rather than encoded in the type, and a future field will be stated the same way.
292#[derive(Debug, Clone, Deserialize)]
293#[serde(deny_unknown_fields)]
294pub struct CardRequestV1 {
295 /// The preset that fills in every `*_unit` field below that this request leaves absent.
296 #[serde(default)]
297 pub units: CardUnits,
298
299 // Load
300 /// Muzzle speed, in `velocity_unit`.
301 pub muzzle_velocity: f64,
302 pub ballistic_coefficient: f64,
303 /// Bullet weight, in `mass_unit`.
304 pub mass: f64,
305 /// Bullet diameter, in `diameter_unit`.
306 pub diameter: f64,
307 #[serde(default)]
308 pub drag_model: DragModelV1,
309 /// Sight height over bore, in `sight_height_unit`; CLI default 1.5 in.
310 #[serde(default = "sight_height_unset")]
311 pub sight_height: f64,
312
313 // Zero
314 /// Zero range, in `distance_unit`.
315 pub zero_distance: f64,
316 /// Deliberate POI offset at the zero range, in `drop_unit` — it is a displacement on
317 /// the target, which is the dimension the drop column reports; 0 = zeroed dead-on.
318 #[serde(default)]
319 pub zero_poi_vertical: f64,
320 /// Deliberate lateral POI offset at the zero range, in `drop_unit`.
321 #[serde(default)]
322 pub zero_poi_horizontal: f64,
323 /// Lateral sight-to-bore mount offset, in `sight_height_unit` — it is rifle geometry
324 /// measured beside the sight height, not a figure read off a target.
325 #[serde(default)]
326 pub sight_offset_lateral: f64,
327
328 // Atmosphere (CLI defaults: 59 °F / 15 °C, 29.92 inHg / 1013.25 hPa, 50 %, 0 alt)
329 /// Station temperature, in `temperature_unit`.
330 #[serde(default)]
331 pub temperature: Option<f64>,
332 /// Station pressure, in `pressure_unit`.
333 #[serde(default)]
334 pub pressure: Option<f64>,
335 /// Relative humidity, percent. Dimensionless, so no unit field governs it.
336 #[serde(default = "default_humidity")]
337 pub humidity: f64,
338 /// Site elevation, in `altitude_unit` — which defaults to METRES whatever `units` says.
339 #[serde(default)]
340 pub altitude: f64,
341
342 // Wind for the flight (in `wind_speed_unit`; wind-FROM degrees). The wind card ignores
343 // these and sweeps its own speed list.
344 #[serde(default)]
345 pub wind_speed: f64,
346 #[serde(default)]
347 pub wind_direction_deg: f64,
348
349 // Card domain, in `distance_unit`
350 pub start: f64,
351 pub end: f64,
352 pub step: f64,
353
354 // --- Per-dimension units (MBA-1519) --------------------------------------------------
355 //
356 // Every one of these is `Option`al and `#[serde(default)]`: `CardRequestV1` denies
357 // unknown fields and backs paid surfaces (the Pro DOPE card, the saved-card reprint, the
358 // PDF export), so a stored request written before they existed has to keep parsing and
359 // keep producing the identical document. `None` means "take it from `units`", which is
360 // what every such request says about every dimension.
361 //
362 // What is deliberately NOT here: a scope-adjustment unit (`adjustment_unit` /
363 // `windage_unit` below already are that dimension, SMOA included), a clicks unit (a
364 // click needs a graduation, which is `elevation_click_value`), a twist-rate unit (this
365 // request carries no twist), and the linear-at-distance spellings (header text for SMOA
366 // and MIL, not units). The module docs give the full reasoning.
367 /// Unit of `zero_distance`, `start`, `end`, `step` and every row's `range`.
368 /// Default: yards (imperial) / metres (metric).
369 ///
370 /// Distance is the dimension where reinterpreting the number does the most damage the
371 /// most quietly: "300" yards and "300" metres are targets 9.36% apart, and a stored zero,
372 /// a DOPE row and a target-size hold are all attached to a PHYSICAL distance rather than
373 /// to a unit-free label. So a card's distance unit is stated, never inferred from a
374 /// neighbouring dimension.
375 #[serde(default)]
376 pub distance_unit: Option<CardDistanceUnit>,
377 /// Unit of `muzzle_velocity`, the `bc_segments` band edges and the `velocity` column.
378 /// Default: fps (imperial) / m/s (metric).
379 #[serde(default)]
380 pub velocity_unit: Option<CardVelocityUnit>,
381 /// Unit of `mass`. Default: grains (imperial) / grams (metric).
382 #[serde(default)]
383 pub mass_unit: Option<CardMassUnit>,
384 /// Unit of `diameter`. Default: inches (imperial) / mm (metric). Those two values and no
385 /// others — see [`CardDiameterUnit`].
386 #[serde(default)]
387 pub diameter_unit: Option<CardDiameterUnit>,
388 /// Unit of `sight_height` and `sight_offset_lateral` — the sight-to-bore geometry.
389 /// Default: inches (imperial) / mm (metric).
390 ///
391 /// This is a dimension the design's table does not contain, added deliberately rather
392 /// than by oversight: without it, the only home for the sight height would be
393 /// `drop_unit`, and then asking for a drop column in centimetres would silently reread a
394 /// 1.5-inch sight height as 1.5 cm. It is a twelfth field on a `deny_unknown_fields`
395 /// contract that cannot be withdrawn without a breaking change, which is the cost being
396 /// accepted here.
397 ///
398 /// Separate from `drop_unit` on purpose. They are the same unit today only because both
399 /// presets happen to give them the same value; they are different measurements (one is
400 /// taken on the rifle with calipers, the other is read off a target downrange), and
401 /// folding them together would mean a caller who asks for a drop column in centimetres
402 /// silently reinterprets a 1.5-inch sight height as 1.5 cm.
403 #[serde(default)]
404 pub sight_height_unit: Option<CardLinearUnit>,
405 /// Unit of the `drop_linear` / `wind_linear` columns and of `zero_poi_vertical` /
406 /// `zero_poi_horizontal`. Default: inches (imperial) / mm (metric).
407 ///
408 /// The ANGULAR half of the design's drop dimension is `adjustment_unit` /
409 /// `windage_unit`, which have always been separate fields; this is the linear half, and
410 /// `cm` is available here because a metric card prints 250 cm of drop, not 2500 mm.
411 #[serde(default)]
412 pub drop_unit: Option<CardLinearUnit>,
413 /// Unit of `wind_speed`, of every entry in `wind_speeds`, and of `pdf.target_speed`.
414 /// Default: mph (imperial) / m/s (metric).
415 #[serde(default)]
416 pub wind_speed_unit: Option<CardWindSpeedUnit>,
417 /// Unit of `temperature` and of the temperature default. Default: °F (imperial) / °C
418 /// (metric).
419 #[serde(default)]
420 pub temperature_unit: Option<CardTemperatureUnit>,
421 /// Unit of `pressure` and of the pressure default. Default: inHg (imperial) / hPa
422 /// (metric).
423 #[serde(default)]
424 pub pressure_unit: Option<CardPressureUnit>,
425 /// Unit of the `energy` column. Default: ft-lb (imperial) / J (metric).
426 #[serde(default)]
427 pub energy_unit: Option<CardEnergyUnit>,
428 /// Unit of `altitude`. Default: **metres, whatever `units` says** — this is the one
429 /// dimension whose fallback is not the preset's.
430 ///
431 /// `altitude` has ignored the `units` scalar since this module was written: it is passed
432 /// to [`AtmosphericConditions`] unconverted, and that field is documented metres, so an
433 /// imperial card's altitude has always been metres too (the PDF header divides it by
434 /// 0.3048 regardless of `units` for exactly that reason). Letting the imperial preset
435 /// start filling this with `feet` would therefore not be additive: every stored imperial
436 /// card carrying `altitude: 1000` would silently become a card shot at 304.8 m instead
437 /// of 1000 m, which is a different density altitude and a different trajectory.
438 ///
439 /// So the preset does not reach this field. A caller that wants feet says `"feet"`, and
440 /// gets the first way this request has ever had to express one.
441 #[serde(default)]
442 pub altitude_unit: Option<CardAltitudeUnit>,
443
444 // Display axes
445 #[serde(default)]
446 pub adjustment_unit: AdjustmentUnit,
447 /// Windage axis unit; defaults to the elevation axis.
448 #[serde(default)]
449 pub windage_unit: Option<AdjustmentUnit>,
450 /// Turret graduations as suffixed strings ("0.1mil", "0.25moa"); required when
451 /// the corresponding axis unit is `clicks`. Windage falls back to elevation.
452 #[serde(default)]
453 pub elevation_click_value: Option<String>,
454 #[serde(default)]
455 pub windage_click_value: Option<String>,
456 /// Scope tracking correction factors (MBA-1358); 1.0 = tracks true.
457 #[serde(default = "default_cf")]
458 pub elevation_cf: f64,
459 #[serde(default = "default_cf")]
460 pub windage_cf: f64,
461 /// Selected zero set's dial corrections, true angular MIL (MBA-1360).
462 #[serde(default)]
463 pub zero_set_elevation_bias_mil: f64,
464 #[serde(default)]
465 pub zero_set_windage_bias_mil: f64,
466
467 /// Wind card only: the sweep of wind speeds, each in `wind_speed_unit` (so km/h and
468 /// knots are available here too), one output column each.
469 #[serde(default)]
470 pub wind_speeds: Vec<f64>,
471 /// Wind card only: wind-FROM angles in degrees; default `[90]` (full-value from
472 /// the right), matching the CLI.
473 #[serde(default)]
474 pub wind_angles_deg: Vec<f64>,
475
476 /// Explicit velocity-banded BC schedule, mirroring the CLI's repeatable
477 /// `--bc-segment VMIN:VMAX:BC`. Velocities are in the request's `velocity_unit`,
478 /// exactly like the CLI flag. When supplied it
479 /// wins over `bc5d_table_path`, and — CLI parity — the scalar
480 /// `ballistic_coefficient` remains the interior-gap fallback unchanged. The
481 /// schedule feeds BOTH the zero solve and every sampled trajectory.
482 #[serde(default)]
483 pub bc_segments: Option<Vec<CardBcSegmentV1>>,
484 /// Filesystem path to a caliber-specific BC5D correction table
485 /// (`bc5d_<caliber>.bin`, the exact format the CLI's `--bc-table-dir`
486 /// consumes). The table is CRC-verified, a velocity-keyed BC schedule is
487 /// generated for this load (same ladder as the CLI), and the scalar BC gets the
488 /// table's muzzle correction as the interior-gap fallback. Ignored when
489 /// `bc_segments` is supplied. Not available on wasm32 builds (no filesystem);
490 /// there it is rejected with an invalid-request error.
491 #[serde(default)]
492 pub bc5d_table_path: Option<String>,
493
494 /// Presentation-only options for the printable PDF dope card (`card.pdf`). Nothing in
495 /// here touches the ballistics: the numbers in the PDF are the rows
496 /// [`range_table_v1`] returns, computed by the same call.
497 ///
498 /// It lives on the shared request — rather than in a `card.pdf`-only wrapper type — so
499 /// an app stores ONE `CardRequestV1` per saved card and replays that exact document
500 /// against either surface: `card.range_table` for the screen, `card.pdf` for the
501 /// printout. The on-screen commands ignore this block.
502 ///
503 /// Deliberately NOT `#[cfg(feature = "pdf")]`, even though everything that consumes it
504 /// is: `CardRequestV1` denies unknown fields, so gating the field would make a
505 /// pdf-less build REJECT a stored request that carries it, breaking exactly the
506 /// round-trip the field exists to support. A pdf-less build parses it and never reads
507 /// it; only the `card.pdf` command itself disappears.
508 #[serde(default)]
509 pub pdf: Option<PdfCardOptionsV1>,
510}
511
512/// Presentation knobs for the PDF dope card: the header/footer labels the printed card
513/// carries and the table's font size. The ballistics axes it prints (elevation unit,
514/// windage unit, click graduations, tracking CFs, zero-set biases) are NOT here — they are
515/// already fields on [`CardRequestV1`], shared with the on-screen card, precisely so the
516/// two cannot disagree about what a row means.
517///
518/// Every field is optional and defaults to the CLI dope card's own default.
519#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
520#[serde(deny_unknown_fields)]
521pub struct PdfCardOptionsV1 {
522 /// Leading text of header line 1 — the CLI's rifle/profile name. Default
523 /// `"Dope Card"`. Long headers are truncated to fit the page.
524 #[serde(default)]
525 pub title: Option<String>,
526 /// Header `Loc:` label. Default empty.
527 #[serde(default)]
528 pub location: Option<String>,
529 /// Footer `Powder:` label. Default empty.
530 #[serde(default)]
531 pub powder: Option<String>,
532 /// Footer `Bullet:` label. Default empty.
533 #[serde(default)]
534 pub bullet: Option<String>,
535 /// Crossing-target speed for the Lead column, in the request's `wind_speed_unit` — the
536 /// same convention as the CLI's `--target-speed`
537 /// (MBA-1325). The lead is `speed * time-of-flight` for a full-value 90° crossing,
538 /// held on the windage axis, exactly as `trajectory -o pdf` computes it.
539 ///
540 /// Absent means "this card carries no lead data": the Lead column renders as em-dashes
541 /// rather than a column of confident-looking zeroes. An explicit `0.0` is a different
542 /// statement — a stationary target, whose lead genuinely is zero — and prints zeroes,
543 /// matching the CLI's `--target-speed 0` default.
544 #[serde(default)]
545 pub target_speed: Option<f64>,
546 /// Data-table font scale. Must be finite and within
547 /// [`crate::pdf_dope_card::FONT_SCALE_RANGE`] (0.5..=3.0); out-of-band values are
548 /// rejected rather than silently clamped, so what a stored request asks for is what it
549 /// gets. Mutually exclusive with `font_preset`. Default 1.0.
550 #[serde(default)]
551 pub font_scale: Option<f64>,
552 /// Named font scale: `"small"` (0.8), `"medium"` (1.0), `"large"` (1.4) — the CLI's
553 /// `--font-preset` vocabulary, single-letter aliases included. An unrecognized preset
554 /// is an error here (the CLI warns and falls back to medium; a stored request should
555 /// not silently render at a size it did not ask for). Mutually exclusive with
556 /// `font_scale`.
557 #[serde(default)]
558 pub font_preset: Option<String>,
559 /// Render the data rows in bold. Default false.
560 #[serde(default)]
561 pub bold_data: bool,
562}
563
564/// One velocity band of an explicit velocity-keyed BC schedule
565/// (`CardRequestV1::bc_segments`). `velocity_min`/`velocity_max` are in the
566/// request's `velocity_unit` and must satisfy `velocity_min < velocity_max`;
567/// `bc` is the BC (for the request's `drag_model`) that applies inside the band.
568#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
569#[serde(deny_unknown_fields)]
570pub struct CardBcSegmentV1 {
571 pub velocity_min: f64,
572 pub velocity_max: f64,
573 pub bc: f64,
574}
575
576/// The `sight_height` sentinel for "not supplied".
577///
578/// A serde field default is a nullary function: it cannot see the request, so it cannot know
579/// which `sight_height_unit` the figure would have to be in. NaN stands in until `resolve()`
580/// swaps it for `Units::default_sight_height`, which does know.
581fn sight_height_unset() -> f64 {
582 f64::NAN
583}
584fn default_humidity() -> f64 {
585 50.0
586}
587fn default_cf() -> f64 {
588 1.0
589}
590
591/// Drag model selector mirroring the CLI's `--drag-model` strings.
592#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
593#[serde(rename_all = "lowercase")]
594pub enum DragModelV1 {
595 G1,
596 #[default]
597 G7,
598 G2,
599 G5,
600 G6,
601 G8,
602 GI,
603 GS,
604 RA4,
605}
606
607impl From<DragModelV1> for DragModel {
608 fn from(v: DragModelV1) -> Self {
609 match v {
610 DragModelV1::G1 => DragModel::G1,
611 DragModelV1::G7 => DragModel::G7,
612 DragModelV1::G2 => DragModel::G2,
613 DragModelV1::G5 => DragModel::G5,
614 DragModelV1::G6 => DragModel::G6,
615 DragModelV1::G8 => DragModel::G8,
616 DragModelV1::GI => DragModel::GI,
617 DragModelV1::GS => DragModel::GS,
618 DragModelV1::RA4 => DragModel::RA4,
619 }
620 }
621}
622
623#[derive(Debug, Clone, Serialize)]
624pub struct CardRowV1 {
625 /// Range in the request's `distance_unit`; `CardUnitsBlockV1::distance` names it.
626 pub range: f64,
627 #[serde(skip_serializing_if = "Option::is_none")]
628 pub drop_linear: Option<f64>,
629 #[serde(skip_serializing_if = "Option::is_none")]
630 pub drop_adj: Option<f64>,
631 #[serde(skip_serializing_if = "Option::is_none")]
632 pub come_up: Option<f64>,
633 #[serde(skip_serializing_if = "Option::is_none")]
634 pub wind_linear: Option<f64>,
635 #[serde(skip_serializing_if = "Option::is_none")]
636 pub wind_adj: Option<f64>,
637 #[serde(skip_serializing_if = "Option::is_none")]
638 pub velocity: Option<f64>,
639 #[serde(skip_serializing_if = "Option::is_none")]
640 pub energy: Option<f64>,
641 #[serde(skip_serializing_if = "Option::is_none")]
642 pub time: Option<f64>,
643 #[serde(skip_serializing_if = "Vec::is_empty", default)]
644 pub wind_columns: Vec<f64>,
645}
646
647#[derive(Debug, Clone, Serialize)]
648pub struct CardUnitsBlockV1 {
649 pub distance: &'static str,
650 pub velocity: &'static str,
651 pub energy: &'static str,
652 pub drop: &'static str,
653 pub wind_speed: &'static str,
654 pub elevation_adjustment: String,
655 pub windage_adjustment: String,
656}
657
658#[derive(Debug, Clone, Serialize)]
659pub struct CardResponseV1 {
660 pub schema_version: u32,
661 pub kind: &'static str,
662 pub zero_distance: f64,
663 /// The scalar BC these rows were actually computed with: the request's published
664 /// `ballistic_coefficient` unless a `bc5d_table_path` applied its muzzle correction, in
665 /// which case it is the corrected value (the same scalar the solve and every sampled
666 /// flight ran with).
667 ///
668 /// A saved card must be able to state the BC its numbers came from — the printed
669 /// footer's `BC:` — long after the correction table it used has been replaced on disk.
670 /// Without this on the response there is nothing for an app to store, and a reprint
671 /// could only quote the BC the request nominated.
672 pub bc_for_solve: f64,
673 pub units: CardUnitsBlockV1,
674 /// Wind card only: the swept speeds, one per `wind_columns` entry.
675 #[serde(skip_serializing_if = "Vec::is_empty", default)]
676 pub wind_speeds: Vec<f64>,
677 /// Wind card only: one block of rows per wind angle.
678 #[serde(skip_serializing_if = "Vec::is_empty", default)]
679 pub wind_angles_deg: Vec<f64>,
680 pub rows: Vec<CardRowV1>,
681 /// Wind card with multiple angles: rows for angles beyond the first.
682 #[serde(skip_serializing_if = "Vec::is_empty", default)]
683 pub extra_angle_rows: Vec<Vec<CardRowV1>>,
684 /// Present ONLY when the solved flight stopped short of the rows requested, in which case
685 /// `rows` holds every row it did reach and nothing past them (MBA-1476 follow-up).
686 ///
687 /// Additive and absent on every card that ran to its requested `end`, so a caller reading
688 /// an untruncated card sees byte-identical JSON to before. It is a field rather than only
689 /// a log line because the apps and the Flask layer consume this shape: a card that quietly
690 /// returns fewer rows than were asked for, with nothing on the response saying so, is the
691 /// same class of silent failure as the substituted row this work removed.
692 #[serde(skip_serializing_if = "Option::is_none", default)]
693 pub truncation: Option<CardTruncationV1>,
694}
695
696/// The wire form of [`CardTruncation`]: the rows a card could not print and why.
697/// Distances are in the response's own `units.distance`.
698#[derive(Debug, Clone, Copy, Serialize)]
699pub struct CardTruncationV1 {
700 /// The furthest row the request asked for.
701 pub requested_end: f64,
702 /// The last row actually present in `rows`.
703 pub last_row: f64,
704 /// How far the solved flight got — a property of the load, not of the request.
705 pub reach: f64,
706}
707
708impl CardTruncationV1 {
709 fn new(truncation: CardTruncation) -> Self {
710 Self {
711 requested_end: truncation.requested_end,
712 last_row: truncation.last_row,
713 reach: truncation.reach,
714 }
715 }
716}
717
718/// Back to the engine type, so the wording lives on [`CardTruncation`] alone and no surface
719/// has to restate the field mapping in order to say the same sentence.
720impl From<CardTruncationV1> for CardTruncation {
721 fn from(wire: CardTruncationV1) -> Self {
722 Self {
723 requested_end: wire.requested_end,
724 last_row: wire.last_row,
725 reach: wire.reach,
726 }
727 }
728}
729
730#[derive(Debug, thiserror::Error)]
731pub enum CardServiceError {
732 #[error("invalid request: {0}")]
733 InvalidRequest(String),
734 #[error("zero solve failed: {0}")]
735 ZeroSolve(String),
736 #[error("trajectory failed: {0}")]
737 Trajectory(String),
738 /// PDF rendering itself failed (font load/parse, or an empty row set). Gated with the
739 /// only code path that can produce it, so a build without `pdf` sees an unchanged enum.
740 #[cfg(feature = "pdf")]
741 #[error("pdf generation failed: {0}")]
742 Pdf(String),
743 /// The card is too big to print ([`MAX_PDF_ROWS`] / [`MAX_PDF_PAGES`]). A resource
744 /// refusal, not a failure: the request was well formed and the caller can be told
745 /// exactly what is true of the card (how many rows, how many pages), so the message is
746 /// carried verbatim rather than prefixed.
747 #[cfg(feature = "pdf")]
748 #[error("{0}")]
749 TooLarge(String),
750}
751
752// --- Unit conversions: byte-identical constants to the CLI's UnitConverter ---
753//
754// One resolved unit per dimension, and one place where a unit becomes a factor. Every
755// imperial arm and every metric arm below is the SAME EXPRESSION the single-scalar version
756// of this module used for that dimension — the imperial arm for the dimensions the imperial
757// preset fills, the metric arm for the metric preset's — so a request that states no
758// per-dimension unit performs exactly the multiplications it always performed, in the same
759// order, and lands on the same bits. The only genuinely new arms are the values neither
760// preset produces (cm, km/h, knots, and feet of altitude), which no pre-existing request can
761// select.
762//
763// The reverse conversions are deliberately NOT expressed as `to_metric` composed with a
764// division. `Mph -> v` and `Mph -> (v * 0.44704) / 0.44704` are not the same f64, and the
765// pre-existing behaviour is the former.
766
767/// m/s per km/h.
768const KPH_TO_MPS: f64 = 1.0 / 3.6;
769/// m/s per knot: one nautical mile (1852 m) per hour, exactly.
770const KNOTS_TO_MPS: f64 = 1852.0 / 3600.0;
771
772struct Units {
773 distance: CardDistanceUnit,
774 velocity: CardVelocityUnit,
775 mass: CardMassUnit,
776 diameter: CardDiameterUnit,
777 sight_height: CardLinearUnit,
778 drop: CardLinearUnit,
779 wind_speed: CardWindSpeedUnit,
780 temperature: CardTemperatureUnit,
781 pressure: CardPressureUnit,
782 energy: CardEnergyUnit,
783 altitude: CardAltitudeUnit,
784}
785
786impl Units {
787 /// Settle every dimension: the request's own field where it states one, otherwise what
788 /// the [`CardUnits`] preset implies.
789 ///
790 /// Pure, cheap, and free of validation, so the PDF path can settle the axes it prints in
791 /// the header without repeating the request checks `resolve_inner` performs.
792 fn resolve(req: &CardRequestV1) -> Self {
793 let imperial = req.units == CardUnits::Imperial;
794 let linear = if imperial { CardLinearUnit::Inches } else { CardLinearUnit::Mm };
795 Self {
796 distance: req.distance_unit.unwrap_or(if imperial {
797 CardDistanceUnit::Yards
798 } else {
799 CardDistanceUnit::Meters
800 }),
801 velocity: req.velocity_unit.unwrap_or(if imperial {
802 CardVelocityUnit::Fps
803 } else {
804 CardVelocityUnit::Mps
805 }),
806 mass: req.mass_unit.unwrap_or(if imperial {
807 CardMassUnit::Grains
808 } else {
809 CardMassUnit::Grams
810 }),
811 diameter: req.diameter_unit.unwrap_or(if imperial {
812 CardDiameterUnit::Inches
813 } else {
814 CardDiameterUnit::Mm
815 }),
816 sight_height: req.sight_height_unit.unwrap_or(linear),
817 drop: req.drop_unit.unwrap_or(linear),
818 wind_speed: req.wind_speed_unit.unwrap_or(if imperial {
819 CardWindSpeedUnit::Mph
820 } else {
821 CardWindSpeedUnit::Mps
822 }),
823 temperature: req.temperature_unit.unwrap_or(if imperial {
824 CardTemperatureUnit::Fahrenheit
825 } else {
826 CardTemperatureUnit::Celsius
827 }),
828 pressure: req.pressure_unit.unwrap_or(if imperial {
829 CardPressureUnit::InHg
830 } else {
831 CardPressureUnit::HPa
832 }),
833 energy: req.energy_unit.unwrap_or(if imperial {
834 CardEnergyUnit::FtLb
835 } else {
836 CardEnergyUnit::Joules
837 }),
838 // NOT `imperial`-dependent: `altitude` has always been metres in both systems.
839 // See CardRequestV1::altitude_unit for why the preset must never reach it.
840 altitude: req.altitude_unit.unwrap_or(CardAltitudeUnit::Meters),
841 }
842 }
843
844 // --- into SI, for the solver ---
845
846 fn velocity_to_metric(&self, v: f64) -> f64 {
847 match self.velocity {
848 CardVelocityUnit::Fps => v * 0.3048,
849 CardVelocityUnit::Mps => v,
850 }
851 }
852 fn mass_to_kg(&self, v: f64) -> f64 {
853 match self.mass {
854 CardMassUnit::Grains => v * GRAINS_TO_KG,
855 CardMassUnit::Grams => v * 0.001,
856 }
857 }
858 fn distance_to_metric(&self, v: f64) -> f64 {
859 match self.distance {
860 CardDistanceUnit::Yards => v * 0.9144,
861 CardDistanceUnit::Meters => v,
862 }
863 }
864 fn linear_to_metric(unit: CardLinearUnit, v: f64) -> f64 {
865 match unit {
866 CardLinearUnit::Inches => v * 0.0254,
867 CardLinearUnit::Cm => v * 0.01,
868 CardLinearUnit::Mm => v * 0.001,
869 }
870 }
871 fn diameter_to_metric(&self, v: f64) -> f64 {
872 match self.diameter {
873 CardDiameterUnit::Inches => v * 0.0254,
874 CardDiameterUnit::Mm => v * 0.001,
875 }
876 }
877 fn sight_height_to_metric(&self, v: f64) -> f64 {
878 Self::linear_to_metric(self.sight_height, v)
879 }
880 fn drop_to_metric(&self, v: f64) -> f64 {
881 Self::linear_to_metric(self.drop, v)
882 }
883 fn wind_to_metric(&self, v: f64) -> f64 {
884 match self.wind_speed {
885 CardWindSpeedUnit::Mph => v * 0.44704,
886 CardWindSpeedUnit::Mps => v,
887 CardWindSpeedUnit::Kph => v * KPH_TO_MPS,
888 CardWindSpeedUnit::Knots => v * KNOTS_TO_MPS,
889 }
890 }
891 fn temperature_to_metric(&self, v: f64) -> f64 {
892 match self.temperature {
893 CardTemperatureUnit::Fahrenheit => (v - 32.0) * 5.0 / 9.0,
894 CardTemperatureUnit::Celsius => v,
895 }
896 }
897 fn pressure_to_metric(&self, v: f64) -> f64 {
898 match self.pressure {
899 CardPressureUnit::InHg => v * 33.8639,
900 CardPressureUnit::HPa => v,
901 }
902 }
903 /// `altitude` in metres, which is what [`AtmosphericConditions::altitude`] wants and
904 /// what every request that predates `altitude_unit` already supplied.
905 fn altitude_to_metric(&self, v: f64) -> f64 {
906 match self.altitude {
907 CardAltitudeUnit::Feet => v * 0.3048,
908 CardAltitudeUnit::Meters => v,
909 }
910 }
911
912 // --- back out, for the printed row ---
913
914 fn velocity_from_metric(&self, v: f64) -> f64 {
915 match self.velocity {
916 CardVelocityUnit::Fps => v / 0.3048,
917 CardVelocityUnit::Mps => v,
918 }
919 }
920 fn distance_from_metric(&self, v: f64) -> f64 {
921 match self.distance {
922 CardDistanceUnit::Yards => v / 0.9144,
923 CardDistanceUnit::Meters => v,
924 }
925 }
926 fn energy_from_metric(&self, v: f64) -> f64 {
927 match self.energy {
928 CardEnergyUnit::FtLb => v * 0.737562,
929 CardEnergyUnit::Joules => v,
930 }
931 }
932 fn drop_linear_from_metric(&self, v: f64) -> f64 {
933 match self.drop {
934 CardLinearUnit::Inches => v / 0.0254,
935 CardLinearUnit::Cm => v * 100.0,
936 CardLinearUnit::Mm => v * 1000.0,
937 }
938 }
939
940 // --- column labels; the response's `units` block IS this, field for field ---
941
942 /// Label for the distance axis, for error messages that must name a range.
943 fn distance_label(&self) -> &'static str {
944 match self.distance {
945 CardDistanceUnit::Yards => "yd",
946 CardDistanceUnit::Meters => "m",
947 }
948 }
949 fn velocity_label(&self) -> &'static str {
950 match self.velocity {
951 CardVelocityUnit::Fps => "fps",
952 CardVelocityUnit::Mps => "m/s",
953 }
954 }
955 fn energy_label(&self) -> &'static str {
956 match self.energy {
957 CardEnergyUnit::FtLb => "ft-lb",
958 CardEnergyUnit::Joules => "J",
959 }
960 }
961 fn drop_label(&self) -> &'static str {
962 match self.drop {
963 CardLinearUnit::Inches => "in",
964 CardLinearUnit::Cm => "cm",
965 CardLinearUnit::Mm => "mm",
966 }
967 }
968 fn wind_speed_label(&self) -> &'static str {
969 match self.wind_speed {
970 CardWindSpeedUnit::Mph => "mph",
971 CardWindSpeedUnit::Mps => "m/s",
972 CardWindSpeedUnit::Kph => "km/h",
973 CardWindSpeedUnit::Knots => "kn",
974 }
975 }
976
977 // --- the CLI's own axes, for the call sites that are pinned to CLI constants ---
978 //
979 // These do NOT reuse the conversions above. The BC5D path and the PDF header each
980 // hardcode a factor that `main.rs` hardcodes at the same call site (3.280_839_895 vs
981 // 1/0.3048; 15.4324 vs the exact grains-per-gram), and the golden tests pin the CLI's
982 // digits. Sharing one factor between them would change numbers this work must not.
983 //
984 // Each of these helpers is compiled exactly where its call site is, rather than being
985 // blanket-allowed as dead code, so that a helper which stops being called anywhere is
986 // still a warning. For most of them that means a cfg attribute; `velocity_to_fps_bc5d`
987 // carries none because its call site is the always-compiled `bc_segments` arm of
988 // `resolve_bc_schedule`, so it is reached in every build.
989
990 /// Display velocity -> fps using `parse_bc_segment`'s factor.
991 fn velocity_to_fps_bc5d(&self, v: f64) -> f64 {
992 match self.velocity {
993 CardVelocityUnit::Fps => v,
994 CardVelocityUnit::Mps => v * 3.280_839_895,
995 }
996 }
997 /// Bullet weight -> grains using the CLI's BC5D/PDF factor.
998 #[cfg(any(feature = "pdf", not(target_arch = "wasm32")))]
999 fn mass_to_grains_cli(&self, v: f64) -> f64 {
1000 match self.mass {
1001 CardMassUnit::Grains => v,
1002 CardMassUnit::Grams => v * 15.4324,
1003 }
1004 }
1005 /// Bullet diameter -> inches, the BC5D table's caliber axis (which no wasm32 build has,
1006 /// there being no filesystem to read a table from).
1007 #[cfg(not(target_arch = "wasm32"))]
1008 fn diameter_to_inches(&self, v: f64) -> f64 {
1009 match self.diameter {
1010 CardDiameterUnit::Inches => v,
1011 CardDiameterUnit::Mm => v / 25.4,
1012 }
1013 }
1014 /// Muzzle velocity -> fps for the PDF header (`main.rs` divides by 0.3048 here).
1015 #[cfg(feature = "pdf")]
1016 fn velocity_to_fps_pdf(&self, v: f64) -> f64 {
1017 match self.velocity {
1018 CardVelocityUnit::Fps => v,
1019 CardVelocityUnit::Mps => v / 0.3048,
1020 }
1021 }
1022 /// Pressure -> inHg for the PDF header (`main.rs` uses 33.8639 on both PDF call sites,
1023 /// NOT `pdf_dope_card::INHG_TO_HPA`).
1024 #[cfg(feature = "pdf")]
1025 fn pressure_to_inhg(&self, v: f64) -> f64 {
1026 match self.pressure {
1027 CardPressureUnit::InHg => v,
1028 CardPressureUnit::HPa => v / 33.8639,
1029 }
1030 }
1031 /// Pressure -> hPa for the PDF header, same factor.
1032 #[cfg(feature = "pdf")]
1033 fn pressure_to_hpa(&self, v: f64) -> f64 {
1034 match self.pressure {
1035 CardPressureUnit::InHg => v * 33.8639,
1036 CardPressureUnit::HPa => v,
1037 }
1038 }
1039 /// Temperature -> °F for the PDF header.
1040 #[cfg(feature = "pdf")]
1041 fn temperature_to_fahrenheit(&self, v: f64) -> f64 {
1042 match self.temperature {
1043 CardTemperatureUnit::Fahrenheit => v,
1044 CardTemperatureUnit::Celsius => v * 9.0 / 5.0 + 32.0,
1045 }
1046 }
1047 /// Wind or crossing speed -> mph for the PDF header.
1048 #[cfg(feature = "pdf")]
1049 fn wind_to_mph(&self, v: f64) -> f64 {
1050 match self.wind_speed {
1051 CardWindSpeedUnit::Mph => v,
1052 CardWindSpeedUnit::Mps => v / 0.44704,
1053 CardWindSpeedUnit::Kph => v * KPH_TO_MPS / 0.44704,
1054 CardWindSpeedUnit::Knots => v * KNOTS_TO_MPS / 0.44704,
1055 }
1056 }
1057 /// Altitude -> feet for the PDF header, which reports the altitude the SOLVE used.
1058 #[cfg(feature = "pdf")]
1059 fn altitude_to_feet(&self, v: f64) -> f64 {
1060 match self.altitude {
1061 CardAltitudeUnit::Feet => v,
1062 CardAltitudeUnit::Meters => v / 0.3048,
1063 }
1064 }
1065
1066 // --- defaults that are themselves denominated ---
1067
1068 /// The CLI's 1.5-inch sight height, restated in this request's `sight_height_unit`.
1069 /// The millimetre figure is the module's long-standing 38.0 (a rounded 1.5 in, not a
1070 /// conversion of it), and the centimetre figure is that same length, exactly.
1071 fn default_sight_height(&self) -> f64 {
1072 match self.sight_height {
1073 CardLinearUnit::Inches => 1.5,
1074 CardLinearUnit::Cm => 3.8,
1075 CardLinearUnit::Mm => 38.0,
1076 }
1077 }
1078 /// The CLI's 59 °F / 15 °C standard temperature, in this request's `temperature_unit`.
1079 fn default_temperature(&self) -> f64 {
1080 match self.temperature {
1081 CardTemperatureUnit::Fahrenheit => 59.0,
1082 CardTemperatureUnit::Celsius => 15.0,
1083 }
1084 }
1085 /// The CLI's 29.92 inHg / 1013.25 hPa standard pressure, in this request's
1086 /// `pressure_unit`.
1087 fn default_pressure(&self) -> f64 {
1088 match self.pressure {
1089 CardPressureUnit::InHg => 29.92,
1090 CardPressureUnit::HPa => 1013.25,
1091 }
1092 }
1093}
1094
1095struct Resolved {
1096 u: Units,
1097 velocity_m: f64,
1098 mass_kg: f64,
1099 diameter_m: f64,
1100 sight_height_m: f64,
1101 zero_distance_m: f64,
1102 zero_poi_vertical_m: f64,
1103 zero_poi_horizontal_m: f64,
1104 sight_offset_lateral_m: f64,
1105 temperature_c: f64,
1106 pressure_hpa: f64,
1107 /// Site elevation in metres — which is what `altitude` already was for every request
1108 /// that states no `altitude_unit`, so this is a rename of an identity, not a conversion.
1109 altitude_m: f64,
1110 end_m: f64,
1111 elevation_click: Option<ClickValue>,
1112 windage_click: Option<ClickValue>,
1113 windage_unit: AdjustmentUnit,
1114 drag_model: DragModel,
1115 /// Scalar BC actually fed to the zero solve and every sampled run. Equals the
1116 /// request's `ballistic_coefficient` unless a BC5D table applied its muzzle
1117 /// correction (CLI parity: the scalar is the schedule's interior-gap fallback).
1118 bc_for_solve: f64,
1119 /// Velocity-keyed BC schedule (velocities in fps, the unit the solver compares
1120 /// against), from explicit `bc_segments` or generated from `bc5d_table_path`.
1121 bc_segments_fps: Option<Vec<BCSegmentData>>,
1122}
1123
1124fn resolve(req: &CardRequestV1) -> Result<Resolved, CardServiceError> {
1125 resolve_inner(req, true)
1126}
1127
1128/// [`resolve`] WITHOUT the BC-schedule step — the request's declared axes, click
1129/// graduations and unit conversions, and nothing that touches the filesystem.
1130///
1131/// This is the resolve `card.pdf` performs when it prints caller-supplied rows: those rows
1132/// were computed elsewhere (they are the stored `card.range_table` response), so opening
1133/// `bc5d_table_path` here would do nothing but couple a reprint to whether that file is
1134/// still on the device — which is exactly the coupling printing stored rows exists to
1135/// break. `bc_for_solve` is left at the request's published BC and is not used for the
1136/// footer on that path (the stored card's own `bc_for_solve` is).
1137#[cfg(feature = "pdf")]
1138fn resolve_axes_only(req: &CardRequestV1) -> Result<Resolved, CardServiceError> {
1139 resolve_inner(req, false)
1140}
1141
1142fn resolve_inner(req: &CardRequestV1, load_bc_schedule: bool) -> Result<Resolved, CardServiceError> {
1143 let u = Units::resolve(req);
1144
1145 for (name, v) in [
1146 ("muzzle_velocity", req.muzzle_velocity),
1147 ("ballistic_coefficient", req.ballistic_coefficient),
1148 ("mass", req.mass),
1149 ("diameter", req.diameter),
1150 ("zero_distance", req.zero_distance),
1151 ("start", req.start),
1152 ("end", req.end),
1153 ("step", req.step),
1154 ] {
1155 if !v.is_finite() || v <= 0.0 {
1156 return Err(CardServiceError::InvalidRequest(format!(
1157 "{name} must be finite and positive, got {v}"
1158 )));
1159 }
1160 }
1161 if req.end < req.start {
1162 return Err(CardServiceError::InvalidRequest(
1163 "end must be >= start".into(),
1164 ));
1165 }
1166 if !(0.5..=1.5).contains(&req.elevation_cf) || !(0.5..=1.5).contains(&req.windage_cf) {
1167 return Err(CardServiceError::InvalidRequest(
1168 "tracking correction factors must lie in (0.5, 1.5)".into(),
1169 ));
1170 }
1171
1172 // Each of these three defaults is itself denominated, so it is taken from the dimension
1173 // that governs the field rather than from the preset (`Units` restates the CLI's own
1174 // figures per unit). `sight_height`'s sentinel is NaN because a serde field default
1175 // cannot see the request it belongs to.
1176 let sight_height = if req.sight_height.is_nan() {
1177 u.default_sight_height()
1178 } else {
1179 req.sight_height
1180 };
1181 let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
1182 let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());
1183
1184 let parse_click = |label: &str, s: &Option<String>| -> Result<Option<ClickValue>, CardServiceError> {
1185 s.as_deref()
1186 .map(|raw| {
1187 parse_click_value(raw).map_err(|e| {
1188 CardServiceError::InvalidRequest(format!("{label}: {e}"))
1189 })
1190 })
1191 .transpose()
1192 };
1193 let elevation_click = parse_click("elevation_click_value", &req.elevation_click_value)?;
1194 let windage_click =
1195 parse_click("windage_click_value", &req.windage_click_value)?.or(elevation_click);
1196
1197 if req.adjustment_unit == AdjustmentUnit::Clicks && elevation_click.is_none() {
1198 return Err(CardServiceError::InvalidRequest(
1199 "adjustment_unit 'clicks' requires elevation_click_value".into(),
1200 ));
1201 }
1202 let windage_unit = req.windage_unit.unwrap_or(req.adjustment_unit);
1203 if windage_unit == AdjustmentUnit::Clicks && windage_click.is_none() {
1204 return Err(CardServiceError::InvalidRequest(
1205 "windage_unit 'clicks' requires a click graduation".into(),
1206 ));
1207 }
1208
1209 let (bc_for_solve, bc_segments_fps) = if load_bc_schedule {
1210 resolve_bc_schedule(req, &u)?
1211 } else {
1212 (req.ballistic_coefficient, None)
1213 };
1214
1215 Ok(Resolved {
1216 bc_for_solve,
1217 bc_segments_fps,
1218 velocity_m: u.velocity_to_metric(req.muzzle_velocity),
1219 mass_kg: u.mass_to_kg(req.mass),
1220 diameter_m: u.diameter_to_metric(req.diameter),
1221 sight_height_m: u.sight_height_to_metric(sight_height),
1222 zero_distance_m: u.distance_to_metric(req.zero_distance),
1223 zero_poi_vertical_m: u.drop_to_metric(req.zero_poi_vertical),
1224 zero_poi_horizontal_m: u.drop_to_metric(req.zero_poi_horizontal),
1225 sight_offset_lateral_m: u.sight_height_to_metric(req.sight_offset_lateral),
1226 temperature_c: u.temperature_to_metric(temperature),
1227 pressure_hpa: u.pressure_to_metric(pressure),
1228 altitude_m: u.altitude_to_metric(req.altitude),
1229 end_m: u.distance_to_metric(req.end),
1230 elevation_click,
1231 windage_click,
1232 windage_unit,
1233 drag_model: req.drag_model.into(),
1234 u,
1235 })
1236}
1237
1238/// Resolve the velocity-keyed BC schedule for a card request, mirroring the CLI's
1239/// precedence exactly: explicit `bc_segments` win outright (and leave the scalar BC
1240/// untouched, like `--bc-segment` restoring the pre-table BC); otherwise a
1241/// `bc5d_table_path` generates the same segment ladder `--bc-table-dir` does and
1242/// applies the table's muzzle correction to the scalar fallback BC.
1243///
1244/// Returns `(scalar BC for the solve, optional fps-keyed schedule)`.
1245fn resolve_bc_schedule(
1246 req: &CardRequestV1,
1247 u: &Units,
1248) -> Result<(f64, Option<Vec<BCSegmentData>>), CardServiceError> {
1249 if let Some(segments) = req.bc_segments.as_ref().filter(|s| !s.is_empty()) {
1250 let mut converted = Vec::with_capacity(segments.len());
1251 for (index, segment) in segments.iter().enumerate() {
1252 if !segment.velocity_min.is_finite()
1253 || !segment.velocity_max.is_finite()
1254 || !segment.bc.is_finite()
1255 {
1256 return Err(CardServiceError::InvalidRequest(format!(
1257 "bc_segments[{index}]: velocity_min, velocity_max, and bc must be finite"
1258 )));
1259 }
1260 if segment.velocity_min >= segment.velocity_max {
1261 return Err(CardServiceError::InvalidRequest(format!(
1262 "bc_segments[{index}]: velocity_min must be < velocity_max"
1263 )));
1264 }
1265 if segment.bc <= 0.0 {
1266 return Err(CardServiceError::InvalidRequest(format!(
1267 "bc_segments[{index}]: bc must be > 0"
1268 )));
1269 }
1270 converted.push(BCSegmentData {
1271 // Display velocity -> fps with the exact factor the CLI's parse_bc_segment
1272 // uses; the band edges are in `velocity_unit`, like `muzzle_velocity`.
1273 velocity_min: u.velocity_to_fps_bc5d(segment.velocity_min),
1274 velocity_max: u.velocity_to_fps_bc5d(segment.velocity_max),
1275 bc_value: segment.bc,
1276 });
1277 }
1278 return Ok((req.ballistic_coefficient, Some(converted)));
1279 }
1280
1281 let Some(path) = req.bc5d_table_path.as_deref() else {
1282 return Ok((req.ballistic_coefficient, None));
1283 };
1284
1285 #[cfg(target_arch = "wasm32")]
1286 {
1287 let _ = (path, u);
1288 Err(CardServiceError::InvalidRequest(
1289 "bc5d_table_path is not supported on this target (no filesystem); supply \
1290 bc_segments instead"
1291 .into(),
1292 ))
1293 }
1294 #[cfg(not(target_arch = "wasm32"))]
1295 {
1296 // The table's CONTENT must be for this shot's caliber, not merely CRC-valid: a
1297 // wrong-caliber table silently biases every row of the card (see
1298 // Bc5dTable::ensure_caliber_matches), so a mismatch is refused here rather than
1299 // applied — and rather than quietly falling back to an uncorrected card, which
1300 // the caller could not distinguish from a corrected one.
1301 let diameter_in = u.diameter_to_inches(req.diameter);
1302 let table = crate::bc_table_5d::path_cache::load_verified_for_caliber(
1303 std::path::Path::new(path),
1304 diameter_in,
1305 )
1306 .map_err(|e| CardServiceError::InvalidRequest(format!("bc5d_table_path: {e}")))?;
1307
1308 // The BC5D axes are grains + fps; convert from the request's units the same
1309 // way the CLI does. The v2 tables carry only G1/G7 planes — anything else is
1310 // typed as G1, matching the CLI/WASM coercion.
1311 let weight_grains = u.mass_to_grains_cli(req.mass);
1312 let muzzle_fps = u.velocity_to_fps_bc5d(req.muzzle_velocity);
1313 let drag_type = if req.drag_model == DragModelV1::G7 { "G7" } else { "G1" };
1314 let base_bc = req.ballistic_coefficient;
1315
1316 match table.generate_segments(base_bc, drag_type, weight_grains, Some(muzzle_fps)) {
1317 Some(segments) => {
1318 // CLI parity: the scalar BC becomes the muzzle-corrected fallback for
1319 // interior coverage gaps (main.rs: trued_bc = base * muzzle_correction).
1320 let fallback_bc =
1321 table.get_effective_bc(weight_grains, base_bc, muzzle_fps, muzzle_fps, drag_type);
1322 Ok((fallback_bc, Some(segments)))
1323 }
1324 // A neutral table (every sampled cell ~= 1.0) carries no correction:
1325 // keep the published scalar BC, exactly like the CLI.
1326 None => Ok((base_bc, None)),
1327 }
1328 }
1329}
1330
1331fn solve_zero(req: &CardRequestV1, r: &Resolved) -> Result<f64, CardServiceError> {
1332 let zero_inputs = BallisticInputs {
1333 bc_value: r.bc_for_solve,
1334 bc_type: r.drag_model,
1335 bullet_mass: r.mass_kg,
1336 muzzle_velocity: r.velocity_m,
1337 bullet_diameter: r.diameter_m,
1338 bullet_length: crate::truing::fallback_bullet_length_m(r.diameter_m, r.mass_kg),
1339 sight_height: r.sight_height_m,
1340 use_rk4: true,
1341 zero_poi_vertical_m: r.zero_poi_vertical_m,
1342 zero_poi_horizontal_m: r.zero_poi_horizontal_m,
1343 sight_offset_lateral_m: r.sight_offset_lateral_m,
1344 // The zero MUST be solved with the same velocity-keyed BC schedule the
1345 // sampled flights use (the 0.22.11 auto-zero lesson: a schedule that changes
1346 // early-flight drag would otherwise mis-zero every row).
1347 use_bc_segments: r.bc_segments_fps.is_some(),
1348 bc_segments_data: r.bc_segments_fps.clone(),
1349 ..Default::default()
1350 };
1351 let atmosphere = AtmosphericConditions {
1352 temperature: r.temperature_c,
1353 pressure: r.pressure_hpa,
1354 humidity: req.humidity,
1355 altitude: r.altitude_m,
1356 };
1357 crate::calculate_zero_angle_with_conditions(
1358 zero_inputs,
1359 r.zero_distance_m,
1360 r.sight_height_m,
1361 WindConditions::default(),
1362 atmosphere,
1363 )
1364 .map_err(|e| CardServiceError::ZeroSolve(e.to_string()))
1365}
1366
1367#[allow(clippy::too_many_arguments)]
1368fn sampled(
1369 req: &CardRequestV1,
1370 r: &Resolved,
1371 wind_speed_m: f64,
1372 wind_direction_deg: f64,
1373 zero_angle: f64,
1374) -> Result<SampledFlight, CardServiceError> {
1375 run_sampled_flight(
1376 r.velocity_m,
1377 r.bc_for_solve,
1378 r.mass_kg,
1379 r.diameter_m,
1380 r.drag_model,
1381 r.sight_height_m,
1382 r.temperature_c,
1383 r.pressure_hpa,
1384 req.humidity,
1385 r.altitude_m,
1386 wind_speed_m,
1387 wind_direction_deg,
1388 // MBA-1476: at least one whole grid cell past the last row asked for — see
1389 // card_sample_max_range_m for why that headroom decides reachability.
1390 card_sample_max_range_m(r.end_m),
1391 // MBA-1476: the engine's own card grid, never the request's row spacing.
1392 CARD_SAMPLE_INTERVAL_M,
1393 zero_angle,
1394 // The same schedule as the zero solve above, on every card surface
1395 // (come-ups, range table, wind card) consistently.
1396 r.bc_segments_fps.clone(),
1397 None,
1398 None,
1399 r.zero_poi_vertical_m,
1400 r.zero_poi_horizontal_m,
1401 r.sight_offset_lateral_m,
1402 Some(r.zero_distance_m),
1403 )
1404 .map_err(|e| CardServiceError::Trajectory(e.to_string()))
1405}
1406
1407/// Read one card row's sample off a solved flight, or `None` when the flight does not span it
1408/// (MBA-1476).
1409///
1410/// The nearest-sample-within-one-and-a-half-steps search this replaces answered a range the
1411/// flight had no sample for with a neighbour's numbers, invisibly. There is no tolerance to
1412/// tune here: [`sample_at_range`] interpolates exactly at the requested range whenever the
1413/// flight spans it, and a range it cannot span yields nothing at all. The caller ends the card
1414/// there and records a [`CardTruncation`] — it never substitutes, and it never drops the row
1415/// without saying so.
1416fn row_sample(
1417 samples: &[crate::trajectory_sampling::TrajectorySample],
1418 range_m: f64,
1419) -> Option<crate::trajectory_sampling::TrajectorySample> {
1420 sample_at_range(samples, range_m)
1421}
1422
1423/// The error a card returns when its flight reaches NONE of the rows requested — there is no
1424/// card to truncate, so this stays a refusal (MBA-1476 follow-up).
1425fn no_rows_error(first_row_display: f64, reach_m: f64, u: &Units) -> CardServiceError {
1426 CardServiceError::Trajectory(range_not_sampled_message(
1427 first_row_display,
1428 u.distance_from_metric(reach_m),
1429 u.distance_label(),
1430 ))
1431}
1432
1433/// Record the truncation of a card whose row loop stopped early, in display units.
1434fn truncation_of(
1435 requested_end: f64,
1436 last_row: f64,
1437 reach_m: f64,
1438 u: &Units,
1439) -> Option<CardTruncationV1> {
1440 Some(CardTruncationV1::new(CardTruncation {
1441 requested_end,
1442 last_row,
1443 reach: u.distance_from_metric(reach_m),
1444 }))
1445}
1446
1447/// The response's per-dimension label block: one label per dimension, read off the same
1448/// resolved [`Units`] the rows were converted with, so a column cannot be computed in one
1449/// unit and headed with another.
1450fn units_block(req: &CardRequestV1, u: &Units, windage_unit: AdjustmentUnit) -> CardUnitsBlockV1 {
1451 CardUnitsBlockV1 {
1452 distance: u.distance_label(),
1453 velocity: u.velocity_label(),
1454 energy: u.energy_label(),
1455 drop: u.drop_label(),
1456 wind_speed: u.wind_speed_label(),
1457 elevation_adjustment: adjustment_unit_label(req.adjustment_unit),
1458 windage_adjustment: adjustment_unit_label(windage_unit),
1459 }
1460}
1461
1462/// Come-ups: elevation dial per range plus the incremental come-up between rows.
1463/// Mirrors the CLI's `come-ups` command row-for-row.
1464pub fn come_ups_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
1465 let r = resolve(req)?;
1466 let zero_angle = solve_zero(req, &r)?;
1467 let flight = sampled(
1468 req,
1469 &r,
1470 r.u.wind_to_metric(req.wind_speed),
1471 req.wind_direction_deg,
1472 zero_angle,
1473 )?;
1474
1475 let mut rows: Vec<CardRowV1> = Vec::new();
1476 let mut truncation = None;
1477 let mut prev_drop_adj: f64 = 0.0;
1478 let mut current_range = req.start;
1479 while current_range <= req.end + 0.1 {
1480 let range_m = r.u.distance_to_metric(current_range);
1481 let Some(sample) = row_sample(&flight.samples, range_m) else {
1482 let Some(last) = rows.last() else {
1483 return Err(no_rows_error(current_range, flight.reach_m, &r.u));
1484 };
1485 truncation = truncation_of(req.end, last.range, flight.reach_m, &r.u);
1486 break;
1487 };
1488 let drop_yd = r.u.distance_from_metric(sample.drop_m);
1489 // MBA-1476: the row's OWN range, not a nearby sample's — the angular conversion
1490 // divides by the distance the row is labelled with.
1491 let drop_adj = adjustment_display(
1492 drop_yd,
1493 current_range,
1494 req.adjustment_unit,
1495 r.elevation_click,
1496 req.zero_set_elevation_bias_mil,
1497 req.elevation_cf,
1498 )
1499 .value;
1500 rows.push(CardRowV1 {
1501 range: current_range,
1502 drop_linear: None,
1503 drop_adj: Some(drop_adj),
1504 come_up: Some(drop_adj - prev_drop_adj),
1505 wind_linear: None,
1506 wind_adj: None,
1507 velocity: Some(r.u.velocity_from_metric(sample.velocity_mps)),
1508 energy: Some(r.u.energy_from_metric(sample.energy_j)),
1509 time: Some(sample.time_s),
1510 wind_columns: Vec::new(),
1511 });
1512 prev_drop_adj = drop_adj;
1513 current_range += req.step;
1514 }
1515
1516 Ok(CardResponseV1 {
1517 schema_version: CARD_SCHEMA_VERSION_V1,
1518 kind: "come_ups",
1519 zero_distance: req.zero_distance,
1520 bc_for_solve: r.bc_for_solve,
1521 units: units_block(req, &r.u, req.adjustment_unit),
1522 wind_speeds: Vec::new(),
1523 wind_angles_deg: Vec::new(),
1524 rows,
1525 extra_angle_rows: Vec::new(),
1526 truncation,
1527 })
1528}
1529
1530/// Range table: drop and wind on possibly different display axes.
1531/// Mirrors the CLI's `range-table` command row-for-row (two solves: with wind for
1532/// drift, without wind for the pure elevation axis).
1533pub fn range_table_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
1534 // Discards the PDF-only extras; see `range_table_rows`.
1535 range_table_rows(req, None).map(|(card, _lead, _bc)| card)
1536}
1537
1538/// The one range-table computation, shared by the on-screen `card.range_table` and the
1539/// printable `card.pdf`.
1540///
1541/// Returns `(the card, the Lead column, the scalar BC the solve ran with)`:
1542///
1543/// * The card is exactly what `card.range_table` serializes — `range_table_v1` is a
1544/// discarding wrapper, so the PDF's Range/Drop/Wind figures ARE the on-screen figures.
1545/// They are taken from here rather than recomputed because recomputing them is the one
1546/// way the printed card could ever disagree with the rows the shooter already read.
1547/// * The Lead column parallels `card.rows` one-to-one. `lead_target_speed` is in the
1548/// request's `wind_speed_unit`; `None` (no lead requested) yields all `None`, which the
1549/// PDF renders as em-dashes rather than fake zeroes.
1550/// * The BC is `Resolved::bc_for_solve` — the published BC unless a BC5D table applied its
1551/// muzzle correction — which the PDF footer prints. The footer must state the BC the
1552/// numbers above it came from, not the one the request nominated.
1553fn range_table_rows(
1554 req: &CardRequestV1,
1555 lead_target_speed: Option<f64>,
1556) -> Result<(CardResponseV1, Vec<Option<f64>>, f64), CardServiceError> {
1557 let r = resolve(req)?;
1558 let zero_angle = solve_zero(req, &r)?;
1559 let wind_flight = sampled(
1560 req,
1561 &r,
1562 r.u.wind_to_metric(req.wind_speed),
1563 req.wind_direction_deg,
1564 zero_angle,
1565 )?;
1566 let no_wind_flight = sampled(req, &r, 0.0, 0.0, zero_angle)?;
1567 // Both flights feed every row, so the card can only run as far as the shorter of them.
1568 let reach_m = wind_flight.reach_m.min(no_wind_flight.reach_m);
1569 let lead_speed_mps = lead_target_speed.map(|speed| r.u.wind_to_metric(speed));
1570
1571 let mut rows: Vec<CardRowV1> = Vec::new();
1572 let mut lead_adj = Vec::new();
1573 let mut truncation = None;
1574 let mut current_range = req.start;
1575 while current_range <= req.end + 0.1 {
1576 let range_m = r.u.distance_to_metric(current_range);
1577 let (Some(nw), Some(w)) = (
1578 row_sample(&no_wind_flight.samples, range_m),
1579 row_sample(&wind_flight.samples, range_m),
1580 ) else {
1581 let Some(last) = rows.last() else {
1582 return Err(no_rows_error(current_range, reach_m, &r.u));
1583 };
1584 truncation = truncation_of(req.end, last.range, reach_m, &r.u);
1585 break;
1586 };
1587 // MBA-1476: the row's OWN range on both axes.
1588 let range_display = current_range;
1589 let drop_yd = r.u.distance_from_metric(nw.drop_m);
1590 let drop_adj = adjustment_display(
1591 drop_yd,
1592 range_display,
1593 req.adjustment_unit,
1594 r.elevation_click,
1595 req.zero_set_elevation_bias_mil,
1596 req.elevation_cf,
1597 )
1598 .value;
1599 let drift_yd = r.u.distance_from_metric(w.wind_drift_m);
1600 let wind_adj = windage_adjustment_display(
1601 drift_yd,
1602 range_display,
1603 r.windage_unit,
1604 r.windage_click,
1605 req.zero_set_windage_bias_mil,
1606 req.windage_cf,
1607 )
1608 .value;
1609 // Lead is the windage-axis hold for a full-value 90° crossing target:
1610 // `speed * time-of-flight` (MBA-1287's shared moving-target math), on the
1611 // no-wind sample whose time this row already reports. It is a COMPONENT
1612 // hold composed on top of the wind dial, which already carries the
1613 // zero-set bias, so it stays bias-free (bias 0.0) while still being
1614 // divided by the windage tracking CF — the same treatment
1615 // `main.rs::dope_card_row_from_sample` gives the CLI's Lead column.
1616 lead_adj.push(lead_speed_mps.map(|speed_mps| {
1617 let lead_display = r.u.distance_from_metric(
1618 crate::lead_from_tof(speed_mps, 90.0, nw.time_s, nw.distance_m).lead_m,
1619 );
1620 windage_adjustment_display(
1621 lead_display,
1622 range_display,
1623 r.windage_unit,
1624 r.windage_click,
1625 0.0,
1626 req.windage_cf,
1627 )
1628 .value
1629 }));
1630 rows.push(CardRowV1 {
1631 range: current_range,
1632 drop_linear: Some(r.u.drop_linear_from_metric(nw.drop_m)),
1633 drop_adj: Some(drop_adj),
1634 come_up: None,
1635 wind_linear: Some(r.u.drop_linear_from_metric(w.wind_drift_m)),
1636 wind_adj: Some(wind_adj),
1637 velocity: Some(r.u.velocity_from_metric(nw.velocity_mps)),
1638 energy: Some(r.u.energy_from_metric(nw.energy_j)),
1639 time: Some(nw.time_s),
1640 wind_columns: Vec::new(),
1641 });
1642 current_range += req.step;
1643 }
1644
1645 debug_assert_eq!(rows.len(), lead_adj.len(), "Lead column must parallel rows");
1646 Ok((
1647 CardResponseV1 {
1648 schema_version: CARD_SCHEMA_VERSION_V1,
1649 kind: "range_table",
1650 zero_distance: req.zero_distance,
1651 bc_for_solve: r.bc_for_solve,
1652 units: units_block(req, &r.u, r.windage_unit),
1653 wind_speeds: Vec::new(),
1654 wind_angles_deg: Vec::new(),
1655 rows,
1656 extra_angle_rows: Vec::new(),
1657 truncation,
1658 },
1659 lead_adj,
1660 r.bc_for_solve,
1661 ))
1662}
1663
1664/// Wind card: drift matrix, ranges x wind speeds, per wind-FROM angle.
1665/// Mirrors the CLI's `wind-card` command cell-for-cell. The windage axis uses
1666/// `adjustment_unit` (the CLI's wind-card has a single unit for the matrix).
1667pub fn wind_card_v1(req: &CardRequestV1) -> Result<CardResponseV1, CardServiceError> {
1668 if req.wind_speeds.is_empty() {
1669 return Err(CardServiceError::InvalidRequest(
1670 "wind_card requires at least one entry in wind_speeds".into(),
1671 ));
1672 }
1673 let r = resolve(req)?;
1674 let zero_angle = solve_zero(req, &r)?;
1675
1676 let angles: Vec<f64> = if req.wind_angles_deg.is_empty() {
1677 vec![90.0]
1678 } else {
1679 req.wind_angles_deg.clone()
1680 };
1681
1682 let mut ranges: Vec<f64> = Vec::new();
1683 let mut current = req.start;
1684 while current <= req.end + 0.1 {
1685 ranges.push(current);
1686 current += req.step;
1687 }
1688
1689 // Every angle/speed combination is its own flight and they do not all reach equally far
1690 // (a crosswind bleeds a little velocity), but the matrix has ONE range axis. So the card
1691 // runs to the shortest of them: `reachable` is the number of leading ranges every flight
1692 // supplies, and the ragged tails are trimmed once, below.
1693 let mut reachable = ranges.len();
1694 let mut reach_m = f64::INFINITY;
1695 let mut per_angle_drifts: Vec<Vec<Vec<f64>>> = Vec::new();
1696 for &angle_deg in &angles {
1697 let mut all_drifts: Vec<Vec<f64>> = vec![Vec::new(); ranges.len()];
1698 for &ws in &req.wind_speeds {
1699 let flight = sampled(req, &r, r.u.wind_to_metric(ws), angle_deg, zero_angle)?;
1700 reach_m = reach_m.min(flight.reach_m);
1701 for (ri, &range_display) in ranges.iter().enumerate().take(reachable) {
1702 let range_m = r.u.distance_to_metric(range_display);
1703 // MBA-1476: a range the flight cannot supply used to become a 0.0 cell —
1704 // indistinguishable from "no drift at all" on a wind card.
1705 let Some(sample) = row_sample(&flight.samples, range_m) else {
1706 reachable = ri;
1707 break;
1708 };
1709 let drift_yd = r.u.distance_from_metric(sample.wind_drift_m);
1710 let drift_adj = adjustment_display(
1711 drift_yd,
1712 range_display,
1713 req.adjustment_unit,
1714 r.windage_click,
1715 req.zero_set_windage_bias_mil,
1716 req.windage_cf,
1717 )
1718 .value;
1719 all_drifts[ri].push(drift_adj);
1720 }
1721 }
1722 per_angle_drifts.push(all_drifts);
1723 }
1724
1725 let truncation = if reachable < ranges.len() {
1726 if reachable == 0 {
1727 return Err(no_rows_error(ranges[0], reach_m, &r.u));
1728 }
1729 let last = ranges[reachable - 1];
1730 ranges.truncate(reachable);
1731 truncation_of(req.end, last, reach_m, &r.u)
1732 } else {
1733 None
1734 };
1735
1736 let mut per_angle_rows: Vec<Vec<CardRowV1>> = per_angle_drifts
1737 .into_iter()
1738 .map(|all_drifts| {
1739 ranges
1740 .iter()
1741 .zip(all_drifts)
1742 .map(|(&range, wind_columns)| CardRowV1 {
1743 range,
1744 drop_linear: None,
1745 drop_adj: None,
1746 come_up: None,
1747 wind_linear: None,
1748 wind_adj: None,
1749 velocity: None,
1750 energy: None,
1751 time: None,
1752 wind_columns,
1753 })
1754 .collect()
1755 })
1756 .collect();
1757
1758 let first = per_angle_rows.remove(0);
1759 Ok(CardResponseV1 {
1760 schema_version: CARD_SCHEMA_VERSION_V1,
1761 kind: "wind_card",
1762 zero_distance: req.zero_distance,
1763 bc_for_solve: r.bc_for_solve,
1764 units: units_block(req, &r.u, req.adjustment_unit),
1765 wind_speeds: req.wind_speeds.clone(),
1766 wind_angles_deg: angles,
1767 rows: first,
1768 extra_angle_rows: per_angle_rows,
1769 truncation,
1770 })
1771}
1772
1773// ---------------------------------------------------------------------------------------
1774// Printable PDF dope card (`card.pdf`), feature `pdf`.
1775//
1776// Two ways in, one renderer:
1777//
1778// * REPRINT — the caller supplies the rows: `StoredCardV1` carries the stored
1779// `card.range_table` response verbatim. Nothing is solved, no correction table is opened,
1780// and the footer's BC and provenance come from that document. Only under this construction
1781// is a reprint of a saved card actually a reprint: it cannot drift when the engine is
1782// bumped, or when the BC5D table file at the stored path is overwritten in place by a
1783// table-set refresh.
1784// * SOLVE — no rows supplied: `range_table_rows` runs, which is the same call
1785// `card.range_table` makes (`range_table_v1` is a discarding wrapper over it). This is the
1786// pre-existing behaviour, unchanged, and what the CLI-shaped caller gets.
1787//
1788// Neither path recomputes an adjustment, a unit conversion or a trajectory that the card it
1789// prints already performed.
1790// ---------------------------------------------------------------------------------------
1791
1792/// The one card kind `card.pdf` can print, in the `kind` spelling
1793/// [`CardResponseV1::kind`] uses.
1794///
1795/// A come-ups card's Come-Up column and a wind card's swept drift matrix are not columns a
1796/// range-table card has, so a request for either is REFUSED rather than answered with a
1797/// range table — an `ok` response whose defining field was silently ignored is the defect
1798/// (a stored wind card exported as a range table asserted 0.0 drift on every row while the
1799/// screen showed up to -0.42 MIL).
1800#[cfg(feature = "pdf")]
1801pub const PDF_CARD_KIND: &str = "range_table";
1802
1803/// Rows a printable card may carry.
1804///
1805/// Checked from the row count itself, before a document exists — the byte cap
1806/// (`bridge::MAX_PDF_BYTES`) can only refuse a 26 MB `Vec<u8>` that has already been built
1807/// and paginated. At ~0.5 KiB/row over the ~815 KiB font floor this bound keeps every
1808/// accepted card comfortably inside that cap, which remains the backstop for the other way
1809/// to make a huge document: header/footer labels, which are drawn verbatim on every page.
1810#[cfg(feature = "pdf")]
1811pub const MAX_PDF_ROWS: usize = 5_000;
1812
1813/// Pages a printable card may run to. Bounds the one row set the row cap above cannot:
1814/// few enough rows, but at a font scale that fits very few of them per page.
1815#[cfg(feature = "pdf")]
1816pub const MAX_PDF_PAGES: usize = 60;
1817
1818/// Where the printed rows came from — reported so a caller can verify it got a reprint
1819/// rather than a re-solve, which is otherwise indistinguishable from the document.
1820#[cfg(feature = "pdf")]
1821#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1822pub enum PdfRowSource {
1823 /// Solved by this call, exactly as `card.range_table` would for the same request.
1824 Solve,
1825 /// Supplied by the caller: a stored `card.range_table` response, printed as-is.
1826 StoredRows,
1827}
1828
1829#[cfg(feature = "pdf")]
1830impl PdfRowSource {
1831 /// Wire spelling for the bridge's `source` field.
1832 pub fn as_str(self) -> &'static str {
1833 match self {
1834 Self::Solve => "solve",
1835 Self::StoredRows => "stored_rows",
1836 }
1837 }
1838}
1839
1840/// A card whose rows already exist: print THESE numbers instead of solving.
1841///
1842/// `card` is the stored `card.range_table` response, pasted verbatim — an app keeps that
1843/// document for every saved card and shows it on screen, so handing the same bytes back is
1844/// what makes the paper and the screen the same card by construction rather than by
1845/// coincidence. The two provenance strings are printed in the footer so a card in a
1846/// shooter's pocket can be reconciled with a screen afterwards; both are optional, and an
1847/// absent or empty one prints nothing at all rather than a placeholder.
1848#[cfg(feature = "pdf")]
1849#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
1850#[serde(deny_unknown_fields)]
1851pub struct StoredCardV1 {
1852 /// The stored response, exactly as this engine emitted it.
1853 pub card: StoredCardResponseV1,
1854 /// Engine version that produced the rows (`engine_version` from the bridge envelope of
1855 /// the call that produced them). Absent/empty prints no engine line.
1856 #[serde(default)]
1857 pub engine_version: Option<String>,
1858 /// Correction-table version the rows were solved against — the published BC5D table-set
1859 /// version an app records at save time. Absent/empty prints no table line, which is the
1860 /// honest rendering of "this card used no correction table".
1861 #[serde(default)]
1862 pub bc5d_table_version: Option<String>,
1863}
1864
1865/// A stored [`CardResponseV1`], as a deserializable mirror.
1866///
1867/// [`CardResponseV1`] is `Serialize` only (and its `units` block holds `&'static str`s), so
1868/// a stored response is read back through this twin. It accepts the response document
1869/// unchanged, field for field: `kind` and `units` are load-bearing here — they say what the
1870/// rows ARE and what a row MEANS — while the descriptive scalars are optional so a card
1871/// stored by an older engine still prints.
1872///
1873/// **Deliberately NOT `deny_unknown_fields`** (unlike [`CardRequestV1`], where the caller
1874/// really is the author of the document). What arrives here is this engine's own output,
1875/// round-tripped through an app's storage — never hand-written input — so strictness buys
1876/// no validation and costs a hard cross-version break: the FIRST field ever added to
1877/// `CardResponseV1` would make every card saved by the newer platform completely
1878/// unexportable on the older one. The two apps carry independent engine pins and ship
1879/// through separate stores, so that staggering is the normal case, not a downgrade. An
1880/// unknown field is therefore ignored, exactly as the apps' own decoders ignore it, and the
1881/// stored cells still reach the paper. The same reasoning applies to
1882/// [`StoredCardUnitsBlockV1`] and [`StoredCardRowV1`] below.
1883#[cfg(feature = "pdf")]
1884#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
1885pub struct StoredCardResponseV1 {
1886 /// Which card this is. Anything but [`PDF_CARD_KIND`] is refused.
1887 pub kind: String,
1888 /// Column labels and the range unit of the stored rows. The printed headings are
1889 /// these, not the request's, because these are what the rows were computed in.
1890 pub units: StoredCardUnitsBlockV1,
1891 /// The rows to print, in order.
1892 pub rows: Vec<StoredCardRowV1>,
1893 #[serde(default)]
1894 pub schema_version: Option<u32>,
1895 #[serde(default)]
1896 pub zero_distance: Option<f64>,
1897 /// The BC the stored rows were computed with; printed in the footer. Absent (a card
1898 /// saved by an engine before [`CardResponseV1::bc_for_solve`] existed) falls back to the
1899 /// request's published `ballistic_coefficient`.
1900 #[serde(default)]
1901 pub bc_for_solve: Option<f64>,
1902 /// Present only on a wind card, and therefore a refusal here.
1903 #[serde(default)]
1904 pub wind_speeds: Vec<f64>,
1905 #[serde(default)]
1906 pub wind_angles_deg: Vec<f64>,
1907 #[serde(default)]
1908 pub extra_angle_rows: Vec<Vec<StoredCardRowV1>>,
1909 /// Present only when the stored card itself stopped short of the rows its request asked
1910 /// for — the [`CardResponseV1::truncation`] block, round-tripped (MBA-1477).
1911 ///
1912 /// Without this the reprint path loses the notice: `StoredCardResponseV1` ignores unknown
1913 /// fields by design, so a saved card whose rows stopped short came back through here as an
1914 /// unremarkable short card and printed with nothing on the paper saying rows were missing.
1915 /// The screen it was saved from said so; the paper made from that very document did not.
1916 ///
1917 /// A card saved before this field existed simply has no block, which is indistinguishable
1918 /// from an untruncated card and is the best that can be said of it.
1919 #[serde(default)]
1920 pub truncation: Option<StoredCardTruncationV1>,
1921}
1922
1923/// The truncation block of a stored response (see [`CardTruncationV1`], which this mirrors).
1924///
1925/// All three numbers are REQUIRED, unlike the descriptive scalars elsewhere in a stored card:
1926/// they are printed together as one sentence, and a block missing one of them would print
1927/// "TRUNCATED at 0 yd" on a field card. A card that was not truncated omits the whole block,
1928/// which is the only shape that means "nothing to say".
1929#[cfg(feature = "pdf")]
1930#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
1931pub struct StoredCardTruncationV1 {
1932 pub requested_end: f64,
1933 pub last_row: f64,
1934 pub reach: f64,
1935}
1936
1937#[cfg(feature = "pdf")]
1938impl From<StoredCardTruncationV1> for CardTruncationV1 {
1939 fn from(stored: StoredCardTruncationV1) -> Self {
1940 Self {
1941 requested_end: stored.requested_end,
1942 last_row: stored.last_row,
1943 reach: stored.reach,
1944 }
1945 }
1946}
1947
1948/// The `units` block of a stored response (see [`CardUnitsBlockV1`], which this mirrors).
1949/// Unknown fields are ignored, for the reason [`StoredCardResponseV1`] gives.
1950#[cfg(feature = "pdf")]
1951#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
1952pub struct StoredCardUnitsBlockV1 {
1953 /// `"yd"` / `"m"` — the unit the stored `range` values are in.
1954 pub distance: String,
1955 /// Drop column label ("MIL"/"MOA"/"SMOA"/"IPHY"/"CLICKS").
1956 pub elevation_adjustment: String,
1957 /// Wind and Lead column label; may differ from the elevation label (MBA-1410).
1958 pub windage_adjustment: String,
1959 #[serde(default)]
1960 pub velocity: Option<String>,
1961 #[serde(default)]
1962 pub energy: Option<String>,
1963 #[serde(default)]
1964 pub drop: Option<String>,
1965 #[serde(default)]
1966 pub wind_speed: Option<String>,
1967}
1968
1969/// One stored row (see [`CardRowV1`], which this mirrors). Only `range` is required; a
1970/// column the stored card did not carry stays `None` and prints as an em-dash rather than a
1971/// fabricated zero. Unknown fields are ignored, for the reason [`StoredCardResponseV1`]
1972/// gives.
1973#[cfg(feature = "pdf")]
1974#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
1975pub struct StoredCardRowV1 {
1976 pub range: f64,
1977 #[serde(default)]
1978 pub drop_linear: Option<f64>,
1979 #[serde(default)]
1980 pub drop_adj: Option<f64>,
1981 #[serde(default)]
1982 pub come_up: Option<f64>,
1983 #[serde(default)]
1984 pub wind_linear: Option<f64>,
1985 #[serde(default)]
1986 pub wind_adj: Option<f64>,
1987 #[serde(default)]
1988 pub velocity: Option<f64>,
1989 #[serde(default)]
1990 pub energy: Option<f64>,
1991 /// Time of flight, seconds. The Lead column of a reprint is derived from this — pure
1992 /// arithmetic on a number the stored card already carries, not a new trajectory. A row
1993 /// without it prints an em-dash for Lead.
1994 #[serde(default)]
1995 pub time: Option<f64>,
1996 #[serde(default)]
1997 pub wind_columns: Vec<f64>,
1998}
1999
2000/// A rendered PDF dope card: the document plus the facts a transport needs to describe it
2001/// without re-parsing the bytes.
2002#[cfg(feature = "pdf")]
2003#[derive(Debug, Clone)]
2004pub struct PdfCardV1 {
2005 pub pdf_bytes: Vec<u8>,
2006 /// Pages in `pdf_bytes`, from [`crate::pdf_dope_card::dope_card_page_count`] — the
2007 /// same function the generator paginated by, not a second estimate of it.
2008 pub page_count: usize,
2009 /// Rows printed. On the solve path this is the on-screen `card.range_table` row count;
2010 /// on the reprint path it is the stored row count, so a caller can confirm every stored
2011 /// row reached the paper.
2012 pub row_count: usize,
2013 /// Solved here, or printed from caller-supplied rows.
2014 pub source: PdfRowSource,
2015 /// Characters of the header title (`pdf.title`) the card's font could not draw —
2016 /// distinct, in order of first use, and empty when the title printed in full.
2017 ///
2018 /// Not an error: the document is complete and every ROW printed. But a title is how a
2019 /// shooter tells one card from another, and Liberation Sans covers no CJK, Arabic,
2020 /// Hebrew, Thai or emoji, so a name in any of those used to vanish from the paper with
2021 /// `ok: true` and nothing said. Each such character prints as
2022 /// [`crate::pdf_dope_card::UNPRINTABLE_SUBSTITUTE`] and is named here, so a caller that
2023 /// accepts any non-empty card name (both apps do) can warn at export time instead of
2024 /// handing over an unidentifiable card.
2025 pub unprintable_title_chars: String,
2026 /// Present ONLY when the printed rows stop short of the card that was asked for — the
2027 /// same block [`CardResponseV1::truncation`] carries, for the same reason (MBA-1477).
2028 ///
2029 /// Both paths fill it: a SOLVE takes the truncation of the very `card.range_table` rows
2030 /// it printed, and a REPRINT takes the one the stored card was saved with. Until this
2031 /// existed the PDF was the only card surface with no truncation signal at all — not the
2032 /// stderr warning a CLI reader gets, not the `truncated` block in CLI JSON, not
2033 /// `CardResponseV1::truncation` on the bridge — so a caller could not even tell that the
2034 /// document it was about to hand a shooter was short. It is also printed in the
2035 /// document's own footer, which is the half that survives being carried to a range.
2036 pub truncation: Option<CardTruncationV1>,
2037}
2038
2039/// Resolve the effective table font scale from the mutually exclusive `font_scale` /
2040/// `font_preset` options.
2041#[cfg(feature = "pdf")]
2042fn resolve_font_scale(opts: &PdfCardOptionsV1) -> Result<f32, CardServiceError> {
2043 use crate::pdf_dope_card::{FontSizePreset, FONT_SCALE_RANGE};
2044
2045 match (opts.font_scale, opts.font_preset.as_deref()) {
2046 (Some(_), Some(_)) => Err(CardServiceError::InvalidRequest(
2047 "pdf.font_scale and pdf.font_preset are mutually exclusive; supply one".into(),
2048 )),
2049 (Some(scale), None) => {
2050 let scale = scale as f32;
2051 if !scale.is_finite() || !FONT_SCALE_RANGE.contains(&scale) {
2052 return Err(CardServiceError::InvalidRequest(format!(
2053 "pdf.font_scale must be finite and within {}..={}, got {}",
2054 FONT_SCALE_RANGE.start(),
2055 FONT_SCALE_RANGE.end(),
2056 opts.font_scale.unwrap_or(f64::NAN)
2057 )));
2058 }
2059 Ok(scale)
2060 }
2061 (None, Some(preset)) => FontSizePreset::from_str(preset).map(|p| p.scale()).ok_or_else(|| {
2062 CardServiceError::InvalidRequest(format!(
2063 "pdf.font_preset '{preset}' is not one of small, medium, large"
2064 ))
2065 }),
2066 (None, None) => Ok(1.0),
2067 }
2068}
2069
2070/// The rows to print plus everything the header/footer states about where they came from.
2071/// Filled by exactly one of the two paths in [`pdf_card_v1`], which then share one
2072/// renderer, so a reprint and a solve cannot be laid out or labelled differently.
2073#[cfg(feature = "pdf")]
2074struct RowsToPrint {
2075 rows: Vec<crate::card::CardRow>,
2076 source: PdfRowSource,
2077 /// Footer `BC:` — the BC these rows were computed with.
2078 bc: f64,
2079 /// Footer `Engine:` — empty prints nothing.
2080 engine_version: String,
2081 /// Footer `Table:` — empty prints nothing.
2082 table_version: String,
2083 /// Drop column label.
2084 elevation_unit_label: String,
2085 /// Wind and Lead column label.
2086 windage_unit_label: String,
2087 /// Footer truncation notice — `None` on a card that reached every row it asked for.
2088 /// Both paths fill it, so the printed notice cannot depend on where the rows came from.
2089 truncation: Option<CardTruncationV1>,
2090}
2091
2092/// Turn a stored response's rows into printable rows, deriving only the Lead column.
2093///
2094/// The Drop and Wind cells are the stored values, untouched. Lead is `target_speed x stored
2095/// ToF` held on the windage axis — the same [`crate::lead_from_tof`] arithmetic
2096/// `range_table_rows` performs, applied to the time of flight the stored row already
2097/// carries. No trajectory, no zero solve, no correction table.
2098#[cfg(feature = "pdf")]
2099fn stored_rows_to_print(
2100 stored: &StoredCardResponseV1,
2101 req: &CardRequestV1,
2102 r: &Resolved,
2103 target_speed: Option<f64>,
2104) -> Vec<crate::card::CardRow> {
2105 use crate::card::CardRow;
2106
2107 let lead_speed_mps = target_speed.map(|speed| r.u.wind_to_metric(speed));
2108 stored
2109 .rows
2110 .iter()
2111 .map(|row| CardRow {
2112 range: row.range,
2113 drop_linear: row.drop_linear,
2114 drop_adj: row.drop_adj,
2115 come_up: row.come_up,
2116 wind_linear: row.wind_linear,
2117 wind_adj: row.wind_adj,
2118 velocity: row.velocity,
2119 energy: row.energy,
2120 time: row.time,
2121 lead_adj: lead_speed_mps.zip(row.time).map(|(speed_mps, tof_s)| {
2122 let range_m = r.u.distance_to_metric(row.range);
2123 let lead_display =
2124 r.u.distance_from_metric(crate::lead_from_tof(speed_mps, 90.0, tof_s, range_m).lead_m);
2125 // Bias-free (it composes on top of the wind dial, which carries the
2126 // zero-set bias) but still divided by the windage tracking CF — the exact
2127 // treatment `range_table_rows` and the CLI's Lead column give it.
2128 windage_adjustment_display(
2129 lead_display,
2130 row.range,
2131 r.windage_unit,
2132 r.windage_click,
2133 0.0,
2134 req.windage_cf,
2135 )
2136 .value
2137 }),
2138 wind_columns: row.wind_columns.clone(),
2139 })
2140 .collect()
2141}
2142
2143/// Reject a stored card that is not the range table it must be, cell values included.
2144#[cfg(feature = "pdf")]
2145fn validate_stored_card(
2146 stored: &StoredCardV1,
2147 req: &CardRequestV1,
2148 r: &Resolved,
2149) -> Result<(), CardServiceError> {
2150 let card = &stored.card;
2151 if card.kind != PDF_CARD_KIND {
2152 return Err(CardServiceError::InvalidRequest(format!(
2153 "card.pdf prints a {PDF_CARD_KIND} card; the stored card's kind is '{}'. Its \
2154 columns are not a range table's, so it is refused rather than reprinted as one",
2155 card.kind
2156 )));
2157 }
2158 // The same "this is not a range table" test the REQUEST gets (see the `wind_speeds` /
2159 // `wind_angles_deg` loop in `pdf_card_v1`), field for field. The two halves used to
2160 // disagree — `wind_angles_deg` was refused on the request and accepted here — and the
2161 // stored half is the one that has to hold when a future kind starts emitting it.
2162 for (field, present) in [
2163 ("wind_speeds", !card.wind_speeds.is_empty()),
2164 ("wind_angles_deg", !card.wind_angles_deg.is_empty()),
2165 ("extra_angle_rows", !card.extra_angle_rows.is_empty()),
2166 ] {
2167 if present {
2168 return Err(CardServiceError::InvalidRequest(format!(
2169 "the stored card carries {field}, a wind card's defining field, so it is not the \
2170 {PDF_CARD_KIND} response it claims to be"
2171 )));
2172 }
2173 }
2174 if card.rows.is_empty() {
2175 return Err(CardServiceError::InvalidRequest(
2176 "the stored card has no rows; an empty dope card is not a document".into(),
2177 ));
2178 }
2179
2180 // A row means something only in a unit. If the stored labels and the request's own axes
2181 // disagree, the two are not the same card — printing anyway would put one unit's numbers
2182 // under another unit's heading, which is precisely the failure the shared request shape
2183 // exists to prevent.
2184 let elevation = adjustment_unit_label(req.adjustment_unit);
2185 let windage = adjustment_unit_label(r.windage_unit);
2186 let distance = r.u.distance_label();
2187 for (field, stored_label, request_label) in [
2188 ("units.distance", card.units.distance.as_str(), distance),
2189 (
2190 "units.elevation_adjustment",
2191 card.units.elevation_adjustment.as_str(),
2192 elevation.as_str(),
2193 ),
2194 (
2195 "units.windage_adjustment",
2196 card.units.windage_adjustment.as_str(),
2197 windage.as_str(),
2198 ),
2199 ] {
2200 if stored_label != request_label {
2201 return Err(CardServiceError::InvalidRequest(format!(
2202 "the stored card's {field} is '{stored_label}' but this request's own axes say \
2203 '{request_label}' — the stored rows and the request are not the same card"
2204 )));
2205 }
2206 }
2207
2208 // Same rule as the cells below: a non-finite figure would print "NaN"/"inf" — here in a
2209 // sentence telling a shooter where their card stops, which is worse than in a column.
2210 if let Some(t) = &card.truncation {
2211 for (field, value) in [
2212 ("requested_end", t.requested_end),
2213 ("last_row", t.last_row),
2214 ("reach", t.reach),
2215 ] {
2216 if !value.is_finite() {
2217 return Err(CardServiceError::InvalidRequest(format!(
2218 "the stored card's truncation.{field} is not a finite number"
2219 )));
2220 }
2221 }
2222 }
2223
2224 // A non-finite cell would print "NaN"/"inf" on a field card.
2225 for (index, row) in card.rows.iter().enumerate() {
2226 for (field, value) in [
2227 ("range", Some(row.range)),
2228 ("drop_adj", row.drop_adj),
2229 ("wind_adj", row.wind_adj),
2230 ("time", row.time),
2231 ] {
2232 if value.is_some_and(|v| !v.is_finite()) {
2233 return Err(CardServiceError::InvalidRequest(format!(
2234 "the stored card's rows[{index}].{field} is not a finite number"
2235 )));
2236 }
2237 }
2238 }
2239 Ok(())
2240}
2241
2242/// Render the printable PDF dope card for a card request.
2243///
2244/// `stored` decides where the numbers come from, and it is the whole point of this surface:
2245///
2246/// * `Some(card)` — REPRINT. The rows are the caller's: the stored `card.range_table`
2247/// response for this same request. Nothing is solved, `bc5d_table_path` is never opened,
2248/// and the footer's BC, engine version and table version are the stored card's. A saved
2249/// card therefore reprints identically after an engine bump, after the correction table at
2250/// the stored path is overwritten in place, and even after that file is deleted.
2251/// * `None` — SOLVE. `range_table_rows` runs, i.e. literally the rows [`range_table_v1`]
2252/// would return for this request, and the footer states THIS build's version. Unchanged
2253/// behaviour for a caller that has no stored rows.
2254///
2255/// Either way this prints a [`PDF_CARD_KIND`] card and nothing else: a request carrying a
2256/// wind card's `wind_speeds`/`wind_angles_deg`, or a stored card of another kind, is refused.
2257/// Both paths map their rows onto the CLI's Range/Drop/Wind/Lead dope card, plus the Lead
2258/// column that `CardRequestV1::pdf`'s `target_speed` asks for. The Range column is
2259/// denominated in the stored/requested `distance_unit`, unlike `trajectory -o pdf`, whose
2260/// dope card is always yards.
2261///
2262/// The header/footer block is always imperial, matching both CLI PDF call sites: whatever the
2263/// request's velocity/temperature/pressure/altitude/wind/weight dimensions are denominated in,
2264/// they are converted for display only. The `Solver:` label reports this build (`online` with
2265/// the `online` feature, otherwise `offline`) and the timestamp is generation time, so neither
2266/// is caller-settable — and neither is a number a shooter dials.
2267#[cfg(feature = "pdf")]
2268pub fn pdf_card_v1(
2269 req: &CardRequestV1,
2270 stored: Option<&StoredCardV1>,
2271) -> Result<PdfCardV1, CardServiceError> {
2272 use crate::pdf_dope_card::{
2273 calculate_density_altitude, dope_card_page_count, generate_dope_card_pdf, DopeCardConfig,
2274 RangeUnit,
2275 };
2276
2277 let opts = req.pdf.clone().unwrap_or_default();
2278 // Validate presentation options BEFORE spending a zero solve and two trajectories on a
2279 // request that cannot be rendered anyway.
2280 let font_scale = resolve_font_scale(&opts)?;
2281 // A non-finite crossing speed would print "inf"/"NaN" in every Lead cell rather than
2282 // failing. (A NEGATIVE speed is accepted, matching the CLI: it reads as the mover
2283 // crossing the other way and simply flips the sign of the hold.)
2284 if opts.target_speed.is_some_and(|speed| !speed.is_finite()) {
2285 return Err(CardServiceError::InvalidRequest(
2286 "pdf.target_speed must be finite".into(),
2287 ));
2288 }
2289
2290 // A wind card's defining fields cannot be honoured by a range-table PDF. Refuse them
2291 // instead of returning a document whose Wind column contradicts the screen.
2292 for (field, present) in [
2293 ("wind_speeds", !req.wind_speeds.is_empty()),
2294 ("wind_angles_deg", !req.wind_angles_deg.is_empty()),
2295 ] {
2296 if present {
2297 return Err(CardServiceError::InvalidRequest(format!(
2298 "card.pdf prints a {PDF_CARD_KIND} card; this request carries {field}, a wind \
2299 card's defining field, which a range-table PDF cannot show and would silently \
2300 ignore. There is no wind_card or come_ups PDF in this build"
2301 )));
2302 }
2303 }
2304
2305 let to_print = match stored {
2306 Some(stored) => {
2307 // Axes and click graduations only: no BC schedule, so no correction table is
2308 // opened for a card whose numbers are already decided.
2309 let r = resolve_axes_only(req)?;
2310 validate_stored_card(stored, req, &r)?;
2311 RowsToPrint {
2312 rows: stored_rows_to_print(&stored.card, req, &r, opts.target_speed),
2313 source: PdfRowSource::StoredRows,
2314 bc: stored.card.bc_for_solve.unwrap_or(req.ballistic_coefficient),
2315 engine_version: stored.engine_version.clone().unwrap_or_default(),
2316 table_version: stored.bc5d_table_version.clone().unwrap_or_default(),
2317 elevation_unit_label: stored.card.units.elevation_adjustment.clone(),
2318 windage_unit_label: stored.card.units.windage_adjustment.clone(),
2319 // The truncation the card was SAVED with. Nothing is re-derived from the
2320 // stored row set here — a reprint prints the card it was handed, and that
2321 // includes what the card already said about itself.
2322 truncation: stored.card.truncation.map(CardTruncationV1::from),
2323 }
2324 }
2325 None => {
2326 let (card, lead_adj, bc_for_solve) = range_table_rows(req, opts.target_speed)?;
2327 if card.rows.is_empty() {
2328 // `generate_dope_card_pdf` refuses an empty row set, and rightly: an empty
2329 // dope card is not a document. Name the cause the caller can act on instead.
2330 return Err(CardServiceError::InvalidRequest(format!(
2331 "no card rows in {}..={} — the trajectory does not reach this range domain, \
2332 or step is coarser than the samples",
2333 req.start, req.end
2334 )));
2335 }
2336 RowsToPrint {
2337 rows: card
2338 .rows
2339 .iter()
2340 .zip(&lead_adj)
2341 .map(|(row, lead)| crate::card::CardRow {
2342 range: row.range,
2343 drop_linear: row.drop_linear,
2344 drop_adj: row.drop_adj,
2345 come_up: row.come_up,
2346 wind_linear: row.wind_linear,
2347 wind_adj: row.wind_adj,
2348 velocity: row.velocity,
2349 energy: row.energy,
2350 time: row.time,
2351 lead_adj: *lead,
2352 wind_columns: row.wind_columns.clone(),
2353 })
2354 .collect(),
2355 source: PdfRowSource::Solve,
2356 bc: bc_for_solve,
2357 // No table version is knowable from a path, so none is claimed; the engine
2358 // version is this build's, which is what produced these rows.
2359 engine_version: env!("CARGO_PKG_VERSION").to_string(),
2360 table_version: String::new(),
2361 // The labels `card.range_table`'s `units` block reports for this request:
2362 // Drop in the elevation unit, Wind AND Lead in the (possibly different,
2363 // MBA-1410) windage unit.
2364 elevation_unit_label: card.units.elevation_adjustment.clone(),
2365 windage_unit_label: card.units.windage_adjustment.clone(),
2366 // The truncation of the very rows above, not a second determination of it:
2367 // `range_table_rows` IS `card.range_table`, so the paper and the screen
2368 // truncate identically or not at all.
2369 truncation: card.truncation,
2370 }
2371 }
2372 };
2373
2374 // Refuse on the row/page count now that the rows are known — before a document is built.
2375 // The byte cap downstream can only measure a document it already paid for.
2376 let page_count = dope_card_page_count(to_print.rows.len(), font_scale);
2377 if to_print.rows.len() > MAX_PDF_ROWS || page_count > MAX_PDF_PAGES {
2378 return Err(CardServiceError::TooLarge(format!(
2379 "this card has too many rows to print: {} rows, {page_count} pages (the limits are \
2380 {MAX_PDF_ROWS} rows and {MAX_PDF_PAGES} pages)",
2381 to_print.rows.len()
2382 )));
2383 }
2384
2385 // The request's own axes, for the header. Resolved here rather than taken from above
2386 // because neither branch hands a `Resolved` back — the reprint's is scoped to its arm and
2387 // the solve's lives inside `range_table_rows`. Resolving twice is safe precisely because
2388 // `Units::resolve` is a pure function of the request: the header cannot land on axes the
2389 // rows were not computed in.
2390 let u = Units::resolve(req);
2391 // The atmosphere defaults `resolve()` applies, restated for the header so the printed
2392 // conditions are the ones the solve used rather than blanks.
2393 let temperature = req.temperature.unwrap_or_else(|| u.default_temperature());
2394 let pressure = req.pressure.unwrap_or_else(|| u.default_pressure());
2395 // inHg <-> hPa via the CLI dope card's own factor (main.rs uses 33.8639 on both PDF
2396 // call sites), NOT pdf_dope_card::INHG_TO_HPA — matching the shipped header exactly.
2397 let pressure_inhg = u.pressure_to_inhg(pressure);
2398 let pressure_hpa = u.pressure_to_hpa(pressure);
2399 let temperature_f = u.temperature_to_fahrenheit(temperature);
2400 // NOTE: `CardRequestV1::altitude` defaults to METRES whatever the `units` preset says —
2401 // the one dimension whose fallback is not the preset's, because it never was (see
2402 // `CardRequestV1::altitude_unit`). The header reports the altitude the solve actually
2403 // used, so it converts out of whatever `altitude_unit` settled on.
2404 let altitude_ft = u.altitude_to_feet(req.altitude);
2405
2406 let config = DopeCardConfig {
2407 rifle_name: opts.title.clone().unwrap_or_else(|| "Dope Card".to_string()),
2408 location: opts.location.clone().unwrap_or_default(),
2409 density_altitude_ft: calculate_density_altitude(altitude_ft, pressure_inhg, temperature_f),
2410 pressure_inhg,
2411 pressure_hpa,
2412 temperature_f,
2413 altitude_ft,
2414 wind_speed_mph: u.wind_to_mph(req.wind_speed),
2415 // Absent target speed prints 0 here (there is no lead to state) while the Lead
2416 // column itself stays em-dashed; an explicit 0.0 prints the same 0 and zeroes.
2417 target_speed_mph: match opts.target_speed {
2418 Some(speed) => u.wind_to_mph(speed),
2419 None => 0.0,
2420 },
2421 solver_mode: if cfg!(feature = "online") { "online".to_string() } else { "offline".to_string() },
2422 powder: opts.powder.clone().unwrap_or_default(),
2423 bullet: opts.bullet.clone().unwrap_or_default(),
2424 weight_gr: u.mass_to_grains_cli(req.mass),
2425 // The BC these rows came from: the stored card's own, or this solve's (which is the
2426 // muzzle-corrected value when a BC5D table applied one).
2427 bc: to_print.bc,
2428 drag_model: DragModel::from(req.drag_model).to_string(),
2429 velocity_fps: u.velocity_to_fps_pdf(req.muzzle_velocity),
2430 font_scale,
2431 bold_data: opts.bold_data,
2432 // The card's own axes: Drop in the elevation unit, Wind AND Lead in the (possibly
2433 // different, MBA-1410) windage unit — from the document that owns the rows.
2434 elevation_unit_label: to_print.elevation_unit_label.clone(),
2435 windage_unit_label: to_print.windage_unit_label.clone(),
2436 // Provenance on the paper, so a printed card and a screen can be reconciled later.
2437 engine_version: to_print.engine_version.clone(),
2438 table_version: to_print.table_version.clone(),
2439 // MBA-1477: and the truncation on the paper too, in the one wording every card
2440 // surface uses, denominated in the card's own distance unit (which
2441 // `validate_stored_card` has already forced to agree with the request's).
2442 truncation_note: to_print
2443 .truncation
2444 .map(|t| CardTruncation::from(t).printed_note(u.distance_label()))
2445 .unwrap_or_default(),
2446 };
2447
2448 let range_unit = match u.distance {
2449 CardDistanceUnit::Yards => RangeUnit::Yards,
2450 CardDistanceUnit::Meters => RangeUnit::Meters,
2451 };
2452 // Read BEFORE the document is built, off the same string the header will draw, so the
2453 // report describes this card's own title rather than a truncation of it.
2454 let unprintable_title_chars = crate::pdf_dope_card::unprintable_chars(&config.rifle_name);
2455 let pdf_bytes = generate_dope_card_pdf(&config, &to_print.rows, range_unit)
2456 .map_err(|e| CardServiceError::Pdf(e.to_string()))?;
2457
2458 Ok(PdfCardV1 {
2459 page_count,
2460 row_count: to_print.rows.len(),
2461 source: to_print.source,
2462 pdf_bytes,
2463 unprintable_title_chars,
2464 truncation: to_print.truncation,
2465 })
2466}