ballistics_engine/lib.rs
1//! # Ballistics Engine
2//!
3//! High-performance ballistics trajectory calculation engine with comprehensive physics modeling.
4//!
5//! ## Interactive Web Demo
6//!
7//! Try the ballistics engine directly in your browser at [https://ballistics.rs/](https://ballistics.rs/)
8//!
9//! ## Features
10//!
11//! - Professional-grade trajectory calculations with multiple drag models
12//! - Advanced physics including spin drift, Coriolis effect, and Magnus force
13//! - Monte Carlo simulations for uncertainty analysis
14//! - WebAssembly support for browser-based applications
15//! - FFI bindings for iOS and Android development
16
17// Re-export the main types and functions
18pub use atmosphere::{AtmoSegment, AtmoSock};
19pub use cli_api::{
20 calculate_zero_angle, calculate_zero_angle_with_conditions,
21 calculate_zero_angle_with_resolved_conditions, calculate_zero_range_from_angle_with_conditions,
22 calculate_zero_range_from_angle_with_resolved_conditions, estimate_bc_fit,
23 estimate_bc_from_trajectory, interpolate_powder_temp_curve, resolve_powder_adjusted_velocity,
24 run_monte_carlo, run_monte_carlo_adaptive_seeded, run_monte_carlo_with_direction_std_dev,
25 run_monte_carlo_with_wind, run_monte_carlo_with_wind_and_direction_std_dev,
26 run_monte_carlo_with_wind_and_direction_std_dev_seeded, AdaptiveMcReportV1,
27 AtmosphericConditions, BallisticInputs, BallisticsError, BcEstimate, BcFitMode,
28 BcReferenceStandard, DropsReference, McConvergence, McStopReason, MonteCarloParams,
29 MonteCarloResults, TrajectoryPoint, TrajectoryResult, TrajectorySolver, WindConditions,
30 ZeroCrossings, DEFAULT_HIT_RADIUS_M, MAX_TRAJECTORY_POINTS, MC_ADAPTIVE_ASSUMPTIONS_V1,
31 MC_ADAPTIVE_METHOD_V1, MC_ADAPTIVE_SCHEMA_VERSION_V1, TARGET_NOT_REACHED_SENTINEL_M,
32 ZERO_RANGE_FROM_ANGLE_MAX_RANGE_M,
33};
34pub use drag_model::DragModel;
35pub use mc_stats::{wilson_interval, ConfidenceLevel};
36pub use moving_target::{
37 calculate_lead, lead_from_tof, mover_ring, LeadComponents, LeadError, LeadSolution,
38};
39pub use solve_json::{
40 decode_solve_request_v1, ResolvedSolveRequestV1, SolveErrorCodeV1, SolveErrorEnvelopeV1,
41 SolveRequestV1, SolveSuccessV1, MAX_SOLVE_JSON_SAMPLES_V1, SOLVE_JSON_SCHEMA_VERSION_V1,
42};
43pub use solve_v1::solve_v1;
44pub use trajectory_observation::{
45 TrajectoryObservation, TrajectoryObservationError, TrajectoryObservationFlag,
46 TrajectoryTermination,
47};
48pub use trajectory_sampling::MAX_TRAJECTORY_SAMPLES;
49
50// Module declarations
51pub mod cli_api;
52// MBA-1375: deterministic reference-family BC conversion and banded least-squares family
53// recommendation, shared by native and WASM front ends. Pure table math; no filesystem I/O.
54pub mod bc_conversion;
55mod drag_model;
56pub mod moving_target;
57// The C ABI. Gated behind the default-on `ffi` feature so a binary that links two versions of
58// this crate can disable it on one edge and avoid duplicate #[no_mangle] symbols.
59#[cfg(feature = "ffi")]
60pub mod ffi;
61pub mod solve_json;
62pub mod solve_v1;
63// 0.33.0 decision-support Task 2: reverse conversion from a resolved request back into a
64// solvable one (`impl From<&ResolvedSolveRequestV1> for SolveRequestV1`), the direction the
65// perturbation kernel needs to take a resolved request, change one input, and re-solve. No
66// public items of its own -- the trait impl is usable wherever solve_json's public types are.
67mod request_roundtrip;
68pub mod terminal_plot;
69// MBA-1343: multi-observation velocity/BC truing core, shared by the CLI and the WASM terminal.
70pub mod truing;
71// MBA-1346: observation-range experiment design for identifiable MV/BC truing.
72pub mod truing_plan;
73// MBA-1353: opt-in uncertainty-aware joint MV/BC truing.
74pub mod truing_uncertainty;
75// MBA-1357: Mach-keyed DSF (drop-scale-factor) truing table — a drop-only post-processing
76// correction applied to a solved TrajectoryResult. No feature gate: must compile for wasm32;
77// fs-free (profile persistence lives in main.rs).
78pub mod truing_dsf;
79// MBA-1392: back-solve the effective crosswind from an observed horizontal miss (wind-call
80// truing). Carries its own shared table/JSON/CSV formatter so the native CLI and the WASM
81// terminal render identical bytes. No feature gate: must compile for wasm32.
82pub mod truing_wind;
83// Task 6 (truing JSON bridge): the tall-target correction-factor arithmetic, extracted out
84// of the CLI's `Commands::TallTarget` arm so the CLI and a future bridge command share one
85// implementation. No feature gate: must compile for wasm32; fs-free (the CLI keeps its
86// println! formatting, only the arithmetic and validation moved here).
87pub mod truing_service;
88// MBA-1349: robust hold corridors across named segmented-wind scenarios. No feature gate:
89// must compile for wasm32 (the CLI surface is native-only this train, but the core and its
90// shared formatter are ready for the WASM follow-up); fs-free — file reading stays in
91// main.rs, this module parses TEXT.
92pub mod wind_scenarios;
93// MBA-1361: reticle schema, parametric generators, and the hold-point-in-reticle API,
94// shared by the CLI, the WASM terminal and the FFI. No feature gate: must compile for
95// wasm32; pure math + serde, no I/O (file reading stays in main.rs/wasm.rs).
96pub mod reticle;
97// MBA-1440: import Bero's "Ventum" reticle spec into `reticle::ReticleDescription` so a
98// reticle drawn in that tool can be hold-solved by `reticle::hold_point_in_reticle`. Pure
99// transform + serde, no I/O; must compile for wasm32. Deliberately NOT wired into the
100// CLI / solve-json / WASM / FFI surfaces yet (that exposure is held for review).
101pub mod reticle_import;
102// MBA-1545: named reticles by id — the per-vendor catalog `reticle`'s header defers
103// to, kept in its own module so that module's "no vendor reticle catalog" statement
104// stays true of the module it was made about. Provenance per entry is mandatory.
105pub mod reticle_catalog;
106// Cleanroom import of the third-party `.reticle` XML drawing format into
107// `reticle::ReticleDescription`, the sibling of `reticle_import` for a format that is a
108// picture rather than a mark list: its `<bdc>` entries are the holds, its `<elements>`
109// drawing is dropped (and counted, so the rule is visible). Pure transform, no I/O; must
110// compile for wasm32. Deliberately NOT wired into the CLI / solve-json / WASM / FFI
111// surfaces (that exposure is a separate decision).
112pub mod reticle_document_import;
113// MBA-1343 Phase B: WEZ (`monte-carlo --wez`) sweep core, shared by the CLI and the WASM terminal.
114pub mod wez;
115// MBA-1355: turret adjustment-unit conversions (SMOA/IPHY/clicks) and click-value parsing,
116// shared by the CLI and the WASM terminal. No feature gate: must compile for wasm32.
117pub mod adjustment;
118// MBA-1409: cleanroom `.drg` (Doppler drag-curve text file) parser, shared by the CLI and
119// the WASM terminal. No feature gate: must compile for wasm32; parses TEXT only (no
120// std::fs — file I/O stays in main.rs/wasm.rs).
121pub mod drag_file;
122// MBA-1372: SAAMI free-recoil momentum-balance calculator, shared by the CLI and the
123// WASM terminal. No feature gate: must compile for wasm32; pure math, no I/O.
124pub mod recoil;
125// MBA-1372: power-factor arithmetic and per-organization (USPSA/IDPA/SASS) rulebook
126// pass/fail thresholds, shared by the CLI and the WASM terminal. No feature gate: must
127// compile for wasm32; pure math + a data table, no I/O.
128pub mod power_factor;
129pub mod trajectory_observation;
130#[cfg(target_arch = "wasm32")]
131pub mod wasm;
132#[cfg(test)]
133mod wasm_tests;
134// MBA-154: Make constants public for ballistics_rust wrapping
135pub mod atmosphere;
136// `atmosphere.density_altitude`: describe an atmosphere the way a solve resolves it.
137// Unconditional -- pure arithmetic over the solve-json schema, so it exists on every
138// target the bridge does, including wasm32, which has no PDF card.
139pub mod atmosphere_service;
140pub mod constants;
141pub mod drag;
142pub mod wind;
143// MBA-153: Make wind_shear public for ballistics_rust wrapping
144pub mod wind_shear;
145// MBA-154: Make derivatives public for ballistics_rust wrapping
146pub mod derivatives;
147pub mod trajectory_sampling;
148// MBA-154: Make fast_trajectory public for ballistics_rust wrapping
149pub mod fast_trajectory;
150// MBA-155: Add advanced integration methods (RK4, RK45)
151pub mod trajectory_integration;
152// MBA-149 Phase 5 Priority 2: Export enhanced spin_drift
153pub mod pitch_damping;
154pub mod spin_decay;
155pub mod spin_drift;
156pub mod spin_drift_advanced;
157// MBA-149 Phase 5 Priority 2: Export enhanced precession_nutation
158pub mod precession_nutation;
159// MBA-153: Make aerodynamic_jump public for ballistics_rust wrapping
160pub mod aerodynamic_jump;
161// MBA-149 Phase 5 Priority 2: Export enhanced angle_calculations
162pub mod angle_calculations;
163pub mod transonic_drag;
164// MBA-153: Make reynolds public for ballistics_rust wrapping
165pub mod reynolds;
166// MBA-149 Phase 5 Priority 2: Export enhanced form_factor
167pub mod form_factor;
168// MBA-153: Make monte_carlo public for ballistics_rust wrapping
169pub mod bc_estimation;
170pub mod cluster_bc;
171// MBA-1352 Task 2: Monte Carlo hit-statistics foundation -- Welford streaming moments and
172// fixed-n Wilson score intervals. The anytime-valid confidence sequence (Task 3) extends this
173// module. No feature gate: must compile for wasm32; pure std math, no randomness.
174pub mod mc_stats;
175pub mod monte_carlo;
176pub mod stability;
177pub mod stability_advanced;
178// 0.33.0 decision-support Phase 1: shared input taxonomy for perturbation kernel and
179// uncertainty propagation. No feature gate: must compile for wasm32 (pure data + serde).
180pub mod perturbation;
181// MBA-1345: explain why two fully resolved solve results differ, by symmetric counterfactual
182// swap of each input group (built on `perturbation`'s Tasks 5-8 kernel). No feature gate: must
183// compile for wasm32 (depends only on perturbation/solve_json/solve_v1, all unconditional).
184pub mod explain;
185// MBA-1347: erf/erfc/normal_cdf for hit-probability integration (mass of a bivariate
186// normal over a target). In-crate rather than a dependency: the crate ships to thirteen
187// platforms including big-endian MIPS and wasm32 and already hand-rolls its statistical
188// constants. No feature gate: must compile for wasm32; pure std float math, no I/O.
189pub mod special;
190// 0.33.0 decision-support Task 10, MBA-1347: propagate declared per-input uncertainty to
191// impact covariance via the perturbation kernel's central differences, and rank sources by
192// variance share into a measurement-priority report. Built on `perturbation` (Tasks 5-8) and
193// reuses `truing_uncertainty::Symmetric2` for the 2x2 covariance/eigenvalue arithmetic. No
194// feature gate: must compile for wasm32 (depends only on perturbation/solve_json/
195// truing_uncertainty, all unconditional).
196pub mod error_budget;
197// 0.33.0 decision-support Task 12, MBA-1350: one-variable tolerance envelopes -- how far a
198// single input may drift from its own current value before the impact leaves an explicit
199// target, by monotone bisection outward from the nominal (`perturbation::bisect_axis`, Task 7).
200// Reuses `error_budget::TargetGeometryV1` and its unavailable-axis classification verbatim. No
201// feature gate: must compile for wasm32 (depends only on perturbation/error_budget/solve_json,
202// all unconditional).
203pub mod tolerance;
204// 0.33.0 decision-support Task 3, MBA-1348: turret + reticle geometry model (click
205// detents/revolutions, zero stop, travel limits, current turret state, reticle hold
206// bounds) that a later dial/hold/hybrid engagement planner will read. Pure data +
207// validation; no feature gate: must compile for wasm32 (depends only on `adjustment`,
208// itself unconditional).
209pub mod optic;
210// 0.33.0 decision-support Task 8: `HoldCurve`, the drop-vs-range interpolation core shared
211// by `mark-to-range`, `bdc-match`, `optimal-zero` and `reticle hold --range`, promoted out of
212// the CLI binary (together with the sampled-trajectory helpers it solves through) so the
213// range-card work its own doc comment already nominates can reuse it as a library dependency.
214// No feature gate: must compile for wasm32 (pure math over already-resolved inputs; no fs, no
215// clap -- CLI argument resolution stays in `main.rs`).
216pub mod card_service;
217pub mod hold_curve;
218// 0.33.0 decision-support Task 9: `CardRow`, the shared display-ready row type behind the
219// come-ups/range-table/wind-card/compare CLI surfaces, replacing four function-local row
220// structs that each said the same thing a different way. Pure data; no feature gate: must
221// compile for wasm32 (no fs, no clap, no pdf -- those stay in main.rs). Task 10 rewrites the
222// PDF dope card on `&[CardRow]`; Task 11 grows an adaptive-card engine here.
223pub mod card;
224// 0.33.0 decision-support Task 10: the PDF dope card, promoted out of the `ballistics`
225// binary (it was `mod pdf_dope_card;`, private to `main.rs`) so it can consume
226// `card::CardRow` directly instead of its own `DopeCardRow { range_yd: u32, .. }` -- that
227// u32-yards field couldn't express the non-integer ranges Task 11's adaptive card engine
228// produces. Feature-gated (unlike `card`): pulls in `printpdf` (PDF generation) and `dirs`
229// (font-file lookup), neither wasm32-safe nor free -- `pdf` is on by default but the
230// wasm32 build always passes `--no-default-features`.
231#[cfg(feature = "pdf")]
232pub mod pdf_dope_card;
233
234// Online mode: HTTP client for Flask API (feature-gated)
235#[cfg(feature = "online")]
236pub mod api_client;
237
238#[cfg(feature = "online")]
239pub mod credentials;
240
241// BC5D table auto-download (feature-gated)
242#[cfg(feature = "online")]
243pub mod bc_table_download;
244
245// BC correction table for offline mode
246pub mod bc_table;
247
248// 5D BC correction tables (caliber-specific, ML-derived)
249pub mod bc_table_5d;
250
251// Saved-profile data model (ProfileData & friends), moved from main.rs so the bridge's
252// profile.validate/profile.normalize/profile.import_a7p commands and the CLI share one
253// serde wire shape. No feature gate: must compile for wasm32; fs-free (profile
254// persistence and unit conversion of loaded profiles stay in main.rs).
255pub mod profile;
256
257// Import of third-party ballistic profile files (.a7p), feature-gated
258#[cfg(feature = "profile-import")]
259pub mod profile_import;
260
261// MBA-1556: the outbound direction — ProfileData -> .a7p — with the list of every
262// ProfileData field the format cannot carry. Its own feature because writing a
263// third-party format is a separate capability from reading one; it implies
264// `profile-import`, whose MD5 envelope helper (`wrap_payload`) it shares so both
265// directions agree on the envelope by construction rather than by review.
266#[cfg(feature = "profile-export")]
267pub mod profile_export;
268
269// Versioned JSON command bridge for embedded (mobile/FFI) consumers
270#[cfg(feature = "bridge")]
271pub mod bridge;
272
273// Internal type alias for compatibility
274pub(crate) type InternalBallisticInputs = BallisticInputs;
275
276// BC segment data for velocity-dependent BC
277#[derive(Debug, Clone)]
278pub struct BCSegmentData {
279 pub velocity_min: f64,
280 pub velocity_max: f64,
281 pub bc_value: f64,
282}