ballistics_engine/cli_api.rs
1// CLI API module - provides simplified interfaces for command-line tool
2use crate::cluster_bc::ClusterBCDegradation;
3use crate::pitch_damping::{calculate_pitch_damping_coefficient, PitchDampingCoefficients};
4use crate::precession_nutation::{
5 calculate_combined_angular_motion, AngularState, PrecessionNutationParams,
6};
7use crate::trajectory_sampling::{
8 sample_trajectory, TrajectoryData, TrajectoryOutputs, TrajectorySample,
9};
10use crate::wind_shear::WindShearModel;
11use crate::DragModel;
12use nalgebra::Vector3;
13use std::error::Error;
14use std::fmt;
15
16// Unit system for input/output
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub enum UnitSystem {
19 Imperial,
20 Metric,
21}
22
23// Output format for results
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub enum OutputFormat {
26 Table,
27 Json,
28 Csv,
29}
30
31// Error type for CLI operations
32#[derive(Debug)]
33pub struct BallisticsError {
34 message: String,
35}
36
37impl fmt::Display for BallisticsError {
38 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39 write!(f, "{}", self.message)
40 }
41}
42
43impl Error for BallisticsError {}
44
45impl From<String> for BallisticsError {
46 fn from(msg: String) -> Self {
47 BallisticsError { message: msg }
48 }
49}
50
51impl From<&str> for BallisticsError {
52 fn from(msg: &str) -> Self {
53 BallisticsError {
54 message: msg.to_string(),
55 }
56 }
57}
58
59// Ballistic input parameters - MBA-151 Reconciled Structure
60// Unified structure used by both ballistics-engine and ballistics_rust
61// Duplicates removed, all necessary fields included
62#[derive(Debug, Clone)]
63pub struct BallisticInputs {
64 // Core ballistics parameters (using intuitive names)
65 pub bc_value: f64, // Ballistic coefficient (G1, G7, etc.)
66 pub bc_type: DragModel, // Drag model (G1, G7, G8, etc.)
67 pub bullet_mass: f64, // kg
68 pub muzzle_velocity: f64, // m/s
69 pub bullet_diameter: f64, // meters
70 pub bullet_length: f64, // meters
71
72 // Targeting and positioning
73 pub muzzle_angle: f64, // radians (launch angle)
74 pub target_distance: f64, // meters
75 pub azimuth_angle: f64, // horizontal aiming angle in radians (small aim offset within the shot frame)
76 /// Compass bearing the shot is fired ALONG, radians, 0 = North, π/2 = East.
77 /// Used only by the Coriolis model (Earth-rotation depends on which way downrange
78 /// points relative to true North). Distinct from `azimuth_angle`, which is the
79 /// small horizontal *aiming* offset and rotates the launch velocity.
80 pub shot_azimuth: f64,
81 pub shooting_angle: f64, // uphill/downhill angle in radians
82 pub sight_height: f64, // meters above bore
83 pub muzzle_height: f64, // meters above ground
84 pub target_height: f64, // meters above ground for zeroing
85 pub ground_threshold: f64, // meters below which to stop
86
87 // Environmental conditions
88 pub altitude: f64, // meters
89 pub temperature: f64, // Celsius
90 pub pressure: f64, // millibars/hPa
91 /// Relative humidity as a FRACTION in `[0, 1]` (e.g. 0.5 = 50%). NOTE the scale
92 /// differs from [`AtmosphericConditions::humidity`], which is a PERCENT in `[0, 100]`.
93 /// The atmosphere helpers (`calculate_air_density_*`) expect percent, so convert via
94 /// [`BallisticInputs::humidity_percent`] before passing this value to them (MBA-722).
95 pub humidity: f64,
96 pub latitude: Option<f64>, // degrees
97
98 // Wind conditions
99 pub wind_speed: f64, // m/s
100 pub wind_angle: f64, // radians (0=headwind, 90=from right)
101
102 // Bullet characteristics
103 pub twist_rate: f64, // inches per turn
104 pub is_twist_right: bool, // right-hand twist
105 pub caliber_inches: f64, // diameter in inches
106 pub weight_grains: f64, // mass in grains
107 pub manufacturer: Option<String>, // Bullet manufacturer
108 pub bullet_model: Option<String>, // Bullet model name
109 pub bullet_id: Option<String>, // Unique bullet identifier
110 pub bullet_cluster: Option<usize>, // BC cluster ID for cluster_bc module
111
112 // Integration method selection
113 pub use_rk4: bool, // Use RK4 integration instead of Euler
114 pub use_adaptive_rk45: bool, // Use RK45 adaptive step size integration
115
116 // Advanced effects flags
117 pub enable_advanced_effects: bool,
118 pub enable_magnus: bool, // Magnus side force (independent of Coriolis)
119 pub enable_coriolis: bool, // Coriolis deflection (requires latitude)
120 pub use_powder_sensitivity: bool,
121 pub powder_temp_sensitivity: f64,
122 pub powder_temp: f64, // Celsius
123 /// Optional measured powder-temperature -> muzzle-velocity curve, as
124 /// (temperature_celsius, muzzle_velocity_m_s) points sorted ascending by
125 /// temperature. When present it supersedes the linear `powder_temp_sensitivity`
126 /// model: the muzzle velocity is interpolated from this table at the ambient
127 /// `temperature` (clamped to the endpoints — no extrapolation beyond measured
128 /// data). This is the data-driven, non-linear alternative to the constant slope.
129 pub powder_temp_curve: Option<Vec<(f64, f64)>>,
130 /// Temperature (Celsius) at which to interpolate `powder_temp_curve` — the POWDER
131 /// temperature, which may differ from the ambient `temperature` (air). `None` uses
132 /// `temperature`. Decouples the velocity lookup from the air-density temperature.
133 pub powder_curve_temp_c: Option<f64>,
134 pub tipoff_yaw: f64, // radians
135 pub tipoff_decay_distance: f64, // meters
136 pub use_bc_segments: bool,
137 pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-BC pairs
138 pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, // Velocity-BC segments
139 pub use_enhanced_spin_drift: bool,
140 pub use_form_factor: bool,
141 pub enable_wind_shear: bool,
142 pub wind_shear_model: String,
143 pub enable_trajectory_sampling: bool,
144 pub sample_interval: f64, // meters
145 pub enable_pitch_damping: bool,
146 pub enable_precession_nutation: bool,
147 // MBA-959: apply aerodynamic jump as a muzzle launch-angle perturbation.
148 // EXPERIMENTAL — the underlying model is heuristic and not yet validated; default OFF.
149 pub enable_aerodynamic_jump: bool,
150 pub use_cluster_bc: bool, // Use cluster-based BC degradation
151
152 // Custom drag model support
153 pub custom_drag_table: Option<crate::drag::DragTable>,
154
155 // Legacy field for compatibility
156 pub bc_type_str: Option<String>,
157}
158
159impl BallisticInputs {
160 /// `humidity` as a PERCENT in `[0, 100]`, clamped — the scale the atmosphere
161 /// density helpers expect. Centralizes the 0–1 → 0–100 conversion so callers don't
162 /// re-derive it (and can't accidentally feed the raw 0–1 fraction as a percentage).
163 /// See the field doc on [`BallisticInputs::humidity`] (MBA-722).
164 pub fn humidity_percent(&self) -> f64 {
165 (self.humidity * 100.0).clamp(0.0, 100.0)
166 }
167
168 /// Sectional density in lb/in²: `weight_grains / 7000 / diameter_in²`.
169 ///
170 /// Derived from the imperial mirror fields (`weight_grains` / `caliber_inches`), falling
171 /// back to the SI `bullet_mass` (kg) / `bullet_diameter` (meters) for SI-only callers
172 /// (mirrors the fallbacks in derivatives.rs). `None` when neither source is usable.
173 pub fn sectional_density_lb_in2(&self) -> Option<f64> {
174 let weight_gr = if self.weight_grains > 0.0 {
175 self.weight_grains
176 } else {
177 self.bullet_mass / 0.00006479891 // kg -> grains
178 };
179 let diameter_in = if self.caliber_inches > 0.0 {
180 self.caliber_inches
181 } else {
182 self.bullet_diameter / 0.0254 // meters -> inches
183 };
184 if weight_gr > 0.0 && diameter_in > 0.0 {
185 Some(weight_gr / 7000.0 / (diameter_in * diameter_in))
186 } else {
187 None
188 }
189 }
190
191 /// Retardation denominator to use when `custom_drag_table` is active.
192 ///
193 /// A custom drag table supplies the projectile's ACTUAL drag coefficient, so the
194 /// point-mass retardation formula must divide it by the projectile's SECTIONAL DENSITY
195 /// (lb/in²), not by a ballistic coefficient: BC = SD / i (form factor i vs the reference
196 /// projectile), and with the projectile's own curve i == 1, so Cd_own / SD == Cd_ref / BC.
197 /// Dividing the curve's Cd by `bc_value` made custom-table trajectories wrongly scale
198 /// with whatever BC happened to be set.
199 ///
200 /// Falls back to `fallback_bc` (with a one-time stderr warning) when mass/diameter are
201 /// unavailable, so degenerate inputs degrade to the old behavior instead of panicking.
202 pub fn custom_drag_denominator(&self, fallback_bc: f64) -> f64 {
203 match self.sectional_density_lb_in2() {
204 Some(sd) => sd,
205 None => {
206 static WARN_ONCE: std::sync::Once = std::sync::Once::new();
207 WARN_ONCE.call_once(|| {
208 eprintln!(
209 "Warning: custom drag table active but bullet mass/diameter are \
210 unavailable; falling back to bc_value for the retardation denominator"
211 );
212 });
213 fallback_bc
214 }
215 }
216 }
217}
218
219impl Default for BallisticInputs {
220 fn default() -> Self {
221 let mass_kg = 0.01;
222 let diameter_m = 0.00762;
223 let bc = 0.5;
224 let muzzle_angle_rad = 0.0;
225 let bc_type = DragModel::G1;
226
227 Self {
228 // Core ballistics parameters
229 bc_value: bc,
230 bc_type,
231 bullet_mass: mass_kg,
232 muzzle_velocity: 800.0,
233 bullet_diameter: diameter_m,
234 // MBA-1135: mass-based length estimate so the default is self-consistent with the
235 // default mass/diameter (was a mass-blind 4.5-caliber literal). The twist default below
236 // stays a fixed 1:12" per the ticket (a constant is a sensible velocity-agnostic default).
237 bullet_length: crate::stability::estimate_bullet_length_m(diameter_m, mass_kg),
238
239 // Targeting and positioning
240 muzzle_angle: muzzle_angle_rad,
241 target_distance: 100.0,
242 azimuth_angle: 0.0,
243 shot_azimuth: 0.0,
244 shooting_angle: 0.0,
245 sight_height: 0.05,
246 muzzle_height: 0.0, // Default 0 - height is in sight_height
247 target_height: 0.0, // Target at ground level by default
248 ground_threshold: -100.0, // Effectively disable ground detection (allow bullet to drop 100m below start)
249
250 // Environmental conditions
251 altitude: 0.0,
252 temperature: 15.0,
253 pressure: 1013.25, // Standard sea level pressure (millibars)
254 humidity: 0.5, // 50% relative humidity
255 latitude: None,
256
257 // Wind conditions
258 wind_speed: 0.0,
259 wind_angle: 0.0,
260
261 // Bullet characteristics
262 twist_rate: 12.0, // 1:12" typical
263 is_twist_right: true,
264 caliber_inches: diameter_m / 0.0254, // Convert to inches
265 weight_grains: mass_kg / 0.00006479891, // Convert to grains
266 manufacturer: None,
267 bullet_model: None,
268 bullet_id: None,
269 bullet_cluster: None,
270
271 // Integration method selection
272 use_rk4: true, // Use Runge-Kutta methods by default
273 use_adaptive_rk45: true, // Default to RK45 adaptive for best accuracy
274
275 // Advanced effects (disabled by default)
276 enable_advanced_effects: false,
277 enable_magnus: false,
278 enable_coriolis: false,
279 use_powder_sensitivity: false,
280 powder_temp_sensitivity: 0.0,
281 powder_temp: 15.0,
282 powder_temp_curve: None,
283 powder_curve_temp_c: None,
284 tipoff_yaw: 0.0,
285 tipoff_decay_distance: 50.0,
286 use_bc_segments: false,
287 bc_segments: None,
288 bc_segments_data: None,
289 use_enhanced_spin_drift: false,
290 use_form_factor: false,
291 enable_wind_shear: false,
292 wind_shear_model: "none".to_string(),
293 enable_trajectory_sampling: false,
294 sample_interval: 10.0, // Default 10 meter intervals
295 enable_pitch_damping: false,
296 enable_precession_nutation: false,
297 enable_aerodynamic_jump: false,
298 use_cluster_bc: false, // Disabled by default for backward compatibility
299
300 // Custom drag model support
301 custom_drag_table: None,
302
303 // Legacy field for compatibility
304 bc_type_str: None,
305 }
306 }
307}
308
309/// Interpolate a muzzle velocity (m/s) from a measured powder-temperature curve at
310/// `temp_c` (Celsius). `curve` is `(temperature_celsius, velocity_m_s)` points; it is
311/// sorted ascending by temperature before use. Values below the first point or above
312/// the last are CLAMPED to the endpoint velocity (no extrapolation beyond measured
313/// data), and segments are linearly interpolated. A single point yields a constant.
314pub fn interpolate_powder_temp_curve(curve: &[(f64, f64)], temp_c: f64) -> f64 {
315 debug_assert!(!curve.is_empty());
316 if curve.is_empty() {
317 return 0.0;
318 }
319 // Defensive: accept unsorted input by sorting a local copy only when needed.
320 // Callers (CLI/WASM parsers) already sort, so the common path is a no-op scan.
321 let mut sorted;
322 let pts: &[(f64, f64)] = if curve.windows(2).all(|w| w[0].0 <= w[1].0) {
323 curve
324 } else {
325 sorted = curve.to_vec();
326 sorted.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
327 &sorted
328 };
329 let n = pts.len();
330 if temp_c <= pts[0].0 {
331 return pts[0].1; // clamp below the coldest measured point
332 }
333 if temp_c >= pts[n - 1].0 {
334 return pts[n - 1].1; // clamp above the hottest measured point
335 }
336 for i in 1..n {
337 let (t0, v0) = pts[i - 1];
338 let (t1, v1) = pts[i];
339 if temp_c <= t1 {
340 let span = t1 - t0;
341 if span.abs() < f64::EPSILON {
342 return v1; // coincident temps: avoid divide-by-zero, take the upper
343 }
344 let f = (temp_c - t0) / span;
345 return v0 + f * (v1 - v0);
346 }
347 }
348 pts[n - 1].1
349}
350
351// Wind conditions
352#[derive(Debug, Clone)]
353pub struct WindConditions {
354 pub speed: f64, // m/s
355 // radians, wind-FROM convention: 0 = headwind, PI/2 = from the right,
356 // PI = tailwind, 3*PI/2 = from the left (matches WindSock / the bindings).
357 pub direction: f64,
358}
359
360impl Default for WindConditions {
361 fn default() -> Self {
362 Self {
363 speed: 0.0,
364 direction: 0.0,
365 }
366 }
367}
368
369// Atmospheric conditions
370#[derive(Debug, Clone)]
371pub struct AtmosphericConditions {
372 pub temperature: f64, // Celsius
373 pub pressure: f64, // hPa
374 /// Relative humidity as a PERCENT in `[0, 100]`. NOTE: [`BallisticInputs::humidity`]
375 /// uses a 0–1 FRACTION instead — convert with `BallisticInputs::humidity_percent` when
376 /// crossing between them (MBA-722).
377 pub humidity: f64,
378 pub altitude: f64, // meters
379}
380
381impl Default for AtmosphericConditions {
382 fn default() -> Self {
383 Self {
384 temperature: 15.0,
385 pressure: 1013.25,
386 humidity: 50.0,
387 altitude: 0.0,
388 }
389 }
390}
391
392// Trajectory point data
393#[derive(Debug, Clone)]
394pub struct TrajectoryPoint {
395 pub time: f64,
396 pub position: Vector3<f64>,
397 pub velocity_magnitude: f64,
398 pub kinetic_energy: f64,
399}
400
401// Trajectory result
402#[derive(Debug, Clone)]
403pub struct TrajectoryResult {
404 pub max_range: f64,
405 pub max_height: f64,
406 pub time_of_flight: f64,
407 pub impact_velocity: f64,
408 pub impact_energy: f64,
409 pub points: Vec<TrajectoryPoint>,
410 pub sampled_points: Option<Vec<TrajectorySample>>, // Trajectory samples at regular intervals
411 pub min_pitch_damping: Option<f64>, // Minimum pitch damping coefficient (for stability warning)
412 pub transonic_mach: Option<f64>, // Mach number when entering transonic regime
413 pub angular_state: Option<AngularState>, // Final angular state if precession/nutation enabled
414 pub max_yaw_angle: Option<f64>, // Maximum yaw angle during flight (radians)
415 pub max_precession_angle: Option<f64>, // Maximum precession angle (radians)
416 // MBA-959: aerodynamic-jump components applied at the muzzle (None unless
417 // enable_aerodynamic_jump). EXPERIMENTAL.
418 pub aerodynamic_jump: Option<crate::aerodynamic_jump::AerodynamicJumpComponents>,
419}
420
421impl TrajectoryResult {
422 /// Interpolate position at a given downrange distance (X coordinate, McCoy).
423 /// Returns the interpolated (x, y, z) position at that range.
424 /// If the target range exceeds the trajectory, returns the last point.
425 pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
426 if self.points.is_empty() {
427 return None;
428 }
429
430 // Find the two points that bracket the target range
431 for i in 0..self.points.len() - 1 {
432 let p1 = &self.points[i];
433 let p2 = &self.points[i + 1];
434
435 // Check if target range is between these two points (X is downrange)
436 if p1.position.x <= target_range && p2.position.x >= target_range {
437 // Linear interpolation factor
438 let dx = p2.position.x - p1.position.x;
439 if dx.abs() < 1e-10 {
440 return Some(p1.position);
441 }
442 let t = (target_range - p1.position.x) / dx;
443
444 // Interpolate Y and Z, use exact target_range for X
445 return Some(Vector3::new(
446 target_range,
447 p1.position.y + t * (p2.position.y - p1.position.y),
448 p1.position.z + t * (p2.position.z - p1.position.z),
449 ));
450 }
451 }
452
453 // Target range is beyond trajectory - return last point
454 self.points.last().map(|p| p.position)
455 }
456}
457
458// Trajectory solver
459pub struct TrajectorySolver {
460 inputs: BallisticInputs,
461 wind: WindConditions,
462 atmosphere: AtmosphericConditions,
463 max_range: f64,
464 time_step: f64,
465 cluster_bc: Option<ClusterBCDegradation>,
466 /// Optional downrange-segmented wind. When `Some`, the per-step wind vector is
467 /// looked up by downrange distance from this `WindSock` and the scalar `wind`
468 /// field is ignored. When `None`, the constant `wind` vector is used (default),
469 /// so a non-segmented solve is numerically identical to pre-feature behavior.
470 wind_sock: Option<crate::wind::WindSock>,
471}
472
473impl TrajectorySolver {
474 pub fn new(
475 mut inputs: BallisticInputs,
476 wind: WindConditions,
477 atmosphere: AtmosphericConditions,
478 ) -> Self {
479 // Compute derived fields from base units
480 inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
481 inputs.weight_grains = inputs.bullet_mass / 0.00006479891;
482
483 // Resolve the muzzle velocity for the ambient temperature before integration.
484 // A measured powder-temperature -> velocity curve (data-driven, non-linear)
485 // takes precedence when supplied; otherwise fall back to the linear
486 // powder-temperature-sensitivity model (MBA-963). Both operate in canonical
487 // SI (Celsius, m/s) and are applied here so every solver built from these
488 // inputs — the main trajectory AND the zero-angle search — sees the same
489 // temperature-resolved velocity. In particular, when a zero solve passes the
490 // zero-day temperature, the curve automatically yields the zero-day velocity.
491 if let Some(curve) = inputs.powder_temp_curve.as_ref() {
492 if !curve.is_empty() {
493 // Interpolate at the POWDER temperature, which defaults to the ambient
494 // air temperature but can be decoupled (powder warmed/cooled relative to
495 // the air) via powder_curve_temp_c. Air temperature still drives density
496 // separately; this only sets the velocity. Absolute override (idempotent).
497 let lookup_c = inputs.powder_curve_temp_c.unwrap_or(inputs.temperature);
498 inputs.muzzle_velocity = interpolate_powder_temp_curve(curve, lookup_c);
499 }
500 } else if inputs.use_powder_sensitivity {
501 let temp_delta_c = inputs.temperature - inputs.powder_temp;
502 inputs.muzzle_velocity += inputs.powder_temp_sensitivity * temp_delta_c;
503 }
504
505 // Initialize cluster BC if enabled
506 let cluster_bc = if inputs.use_cluster_bc {
507 Some(ClusterBCDegradation::new())
508 } else {
509 None
510 };
511
512 Self {
513 inputs,
514 wind,
515 atmosphere,
516 max_range: 1000.0,
517 time_step: 0.001,
518 cluster_bc,
519 wind_sock: None,
520 }
521 }
522
523 pub fn set_max_range(&mut self, range: f64) {
524 self.max_range = range;
525 }
526
527 pub fn set_time_step(&mut self, step: f64) {
528 self.time_step = step;
529 }
530
531 /// Supply downrange-segmented wind. Each segment is `(speed_kmh, angle_deg,
532 /// until_distance_m)`; the wind for a given downrange distance is the first
533 /// segment whose `until_distance_m` exceeds it (a step function), and wind is
534 /// zero beyond the last segment. An empty list clears segmented wind (reverts
535 /// to the scalar `wind`). The angle convention matches `WindConditions`
536 /// (0 = headwind, 90 = from the right).
537 pub fn set_wind_segments(&mut self, segments: Vec<crate::wind::WindSegment>) {
538 self.wind_sock = if segments.is_empty() {
539 None
540 } else {
541 Some(crate::wind::WindSock::new(segments))
542 };
543 }
544
545 /// Effective initial launch direction `(elevation, azimuth)` in radians, including
546 /// the aerodynamic-jump muzzle perturbation when `enable_aerodynamic_jump` is set.
547 ///
548 /// Aerodynamic jump is the fixed angular departure imparted as the projectile
549 /// transitions from the constrained bore to free flight; applying it as an initial
550 /// launch-angle offset is the physically correct integration point. Returns the bare
551 /// `(muzzle_angle, azimuth_angle)` when the flag is off, so a default solve is
552 /// numerically identical to pre-feature behavior. (MBA-959)
553 fn launch_angles_from(
554 &self,
555 aj: Option<&crate::aerodynamic_jump::AerodynamicJumpComponents>,
556 ) -> (f64, f64) {
557 let elev = self.inputs.muzzle_angle;
558 let azim = self.inputs.azimuth_angle;
559 match aj {
560 Some(c) => {
561 // vertical_/horizontal_jump_moa ARE the jump angles expressed in MOA.
562 const MOA_PER_RAD: f64 = 3437.7467707849;
563 (
564 elev + c.vertical_jump_moa / MOA_PER_RAD,
565 azim + c.horizontal_jump_moa / MOA_PER_RAD,
566 )
567 }
568 None => (elev, azim),
569 }
570 }
571
572 /// Compute the aerodynamic-jump components for the current inputs, or `None` when the
573 /// feature is disabled / inputs are degenerate.
574 ///
575 /// Uses Bryan Litz's crosswind aerodynamic-jump estimator
576 /// (`Y = 0.01*Sg - 0.0024*L + 0.032` MOA/mph) fed by the engine's own Miller Sg.
577 /// Aerodynamic jump is a vertical effect, so only the elevation is perturbed.
578 /// The estimator is a regression best near Sg ~ 1.75 — see MBA-959.
579 fn aerodynamic_jump_components(
580 &self,
581 ) -> Option<crate::aerodynamic_jump::AerodynamicJumpComponents> {
582 if !self.inputs.enable_aerodynamic_jump {
583 return None;
584 }
585 // Reject degenerate/non-finite inputs before they can reach the launch angle.
586 // A bare `<= 0.0` test lets NaN through (NaN comparisons are always false), and a
587 // NaN/Inf here would poison the muzzle angle and collapse the whole trajectory.
588 let diameter_m = self.inputs.bullet_diameter;
589 if !(self.inputs.twist_rate.is_finite() && self.inputs.twist_rate != 0.0)
590 || !(diameter_m.is_finite() && diameter_m > 0.0)
591 || !(self.inputs.bullet_length.is_finite() && self.inputs.bullet_length > 0.0)
592 || !self.inputs.muzzle_velocity.is_finite()
593 {
594 return None;
595 }
596
597 // Engine's own gyroscopic (Miller) stability factor — same Sg shown elsewhere.
598 let (_, _, temp_c, pressure_hpa) = self.resolved_atmosphere();
599 let sg = crate::stability::compute_stability_coefficient(
600 &self.inputs,
601 (self.atmosphere.altitude, temp_c, pressure_hpa, 0.0),
602 );
603 if !(sg.is_finite() && sg > 0.0) {
604 return None;
605 }
606 let length_calibers = self.inputs.bullet_length / diameter_m;
607
608 // Crosswind-from-the-right (mph) for Litz's estimator. Wind direction uses the
609 // wind-FROM convention (0 = headwind, +90deg = from the right), matching the
610 // fast-integrate path (fast_trajectory::aerodynamic_jump_launch_offset_rad) and
611 // the lateral windage sign, so a from-the-right wind on a right-twist barrel
612 // jumps the impact UP and drifts it left.
613 const MS_TO_MPH: f64 = 2.236_936_292_054_4;
614 let crosswind_from_right_mph = self.wind.speed * self.wind.direction.sin() * MS_TO_MPH;
615
616 let vertical_jump_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
617 sg,
618 length_calibers,
619 crosswind_from_right_mph,
620 self.inputs.is_twist_right,
621 );
622 if !vertical_jump_moa.is_finite() {
623 return None;
624 }
625
626 const MOA_PER_RAD: f64 = 3437.7467707849;
627 Some(crate::aerodynamic_jump::AerodynamicJumpComponents {
628 vertical_jump_moa,
629 // Aerodynamic jump is a vertical effect; the Litz estimator has no horizontal term.
630 horizontal_jump_moa: 0.0,
631 jump_angle_rad: vertical_jump_moa.abs() / MOA_PER_RAD,
632 magnus_component_moa: 0.0,
633 yaw_component_moa: 0.0,
634 stabilization_factor: (sg / 1.5).clamp(0.0, 1.0),
635 })
636 }
637
638 fn resolved_atmosphere(&self) -> (f64, f64, f64, f64) {
639 let (temp_c, pressure_hpa) = crate::atmosphere::resolve_station_conditions(
640 self.atmosphere.temperature,
641 self.atmosphere.pressure,
642 self.atmosphere.altitude,
643 );
644 let (density, speed_of_sound) = crate::atmosphere::calculate_atmosphere(
645 self.atmosphere.altitude,
646 Some(temp_c),
647 Some(pressure_hpa),
648 self.atmosphere.humidity,
649 );
650 (density, speed_of_sound, temp_c, pressure_hpa)
651 }
652
653 fn gravity_acceleration(&self) -> Vector3<f64> {
654 let theta = self.inputs.shooting_angle;
655 Vector3::new(
656 -crate::constants::G_ACCEL_MPS2 * theta.sin(),
657 -crate::constants::G_ACCEL_MPS2 * theta.cos(),
658 0.0,
659 )
660 }
661
662 fn get_wind_at_altitude(&self, altitude_m: f64) -> Vector3<f64> {
663 // Scale the operative surface wind by the boundary-layer multiplier. `altitude_m` is the
664 // bullet's height relative to the muzzle (McCoy Y). The multiplier is floored at 1.0, so
665 // flat-fire trajectories keep ~full wind and only high-arcing shots see increased wind.
666 //
667 // We build the vector with THIS solver's non-shear sign convention (X=-cos, Z=-sin; see
668 // the `wind_vector` used in solve_rk4/solve_euler, matching WindSock) and scale it, so that
669 // "shear on" equals "shear off" * ratio (ratio == 1.0 for flat fire). An earlier revision
670 // attenuated the wind near the line of sight and flipped its sign relative to the non-shear
671 // path; this keeps them sign-consistent.
672 // Map the requested model name to the boundary-layer model (MBA-965).
673 // Names match wind_shear::get_wind_at_position. Unknown strings should
674 // never reach here (the CLI parses an enum), but default to PowerLaw to
675 // preserve the historical "exponential" behaviour for any caller that
676 // forwards an unexpected value.
677 let model = match self.inputs.wind_shear_model.as_str() {
678 "logarithmic" => WindShearModel::Logarithmic,
679 "power_law" | "powerlaw" | "exponential" => WindShearModel::PowerLaw,
680 "ekman_spiral" | "ekman" => WindShearModel::EkmanSpiral,
681 "custom_layers" | "custom" => WindShearModel::CustomLayers,
682 _ => WindShearModel::PowerLaw,
683 };
684 let speed_ratio = crate::wind_shear::boundary_layer_speed_ratio(altitude_m, model);
685
686 // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
687 // WindConditions / WindSock); wind enters drag via velocity - wind.
688 Vector3::new(
689 -self.wind.speed * self.wind.direction.cos() * speed_ratio, // X: downrange head/tail
690 0.0,
691 -self.wind.speed * self.wind.direction.sin() * speed_ratio, // Z: lateral crosswind
692 )
693 }
694
695 pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
696 let mut result = if self.inputs.use_rk4 {
697 if self.inputs.use_adaptive_rk45 {
698 self.solve_rk45()?
699 } else {
700 self.solve_rk4()?
701 }
702 } else {
703 self.solve_euler()?
704 };
705 self.apply_spin_drift(&mut result);
706 Ok(result)
707 }
708
709 /// Gyroscopic spin drift via the empirical Litz model, applied in the engine
710 /// (not the WASM formatter) so it covers Euler/RK4/RK45 and all consumers.
711 /// Uses the canonical SI fields and converts to grains/inches correctly,
712 /// avoiding the kg/m-vs-grains/in unit bug in `calculate_enhanced_spin_drift`.
713 /// Frame (McCoy): Z = lateral (windage), so drift adds to `position.z`.
714 fn apply_spin_drift(&self, result: &mut TrajectoryResult) {
715 if !self.inputs.use_enhanced_spin_drift {
716 return;
717 }
718 let d_in = self.inputs.bullet_diameter / 0.0254; // m -> in
719 let m_gr = self.inputs.bullet_mass / 0.00006479891; // kg -> grains
720 let twist_in = self.inputs.twist_rate; // inches/turn
721 if d_in <= 0.0 || m_gr <= 0.0 || twist_in <= 0.0 {
722 return;
723 }
724
725 // MBA-1134 (rank 31): single source of truth for the muzzle Sg —
726 // stability::compute_stability_coefficient via spin_drift::effective_sg_from_inputs. This
727 // ADDS the (v/2800)^(1/3) muzzle-velocity term the bare miller_stability() lacked, so the
728 // spin-drift Sg now matches the reported SG and the aerodynamic-jump Sg. The linear Miller
729 // density correction ((T/T0)*(P0/P), a no-op at sea-level standard) and the 4.5-caliber
730 // length fallback are handled inside effective_sg_from_inputs.
731 let sg = self.effective_spin_drift_sg();
732
733 for p in result.points.iter_mut() {
734 if p.time <= 0.0 {
735 continue;
736 }
737 // Canonical Litz drift, shared with the fast / Monte-Carlo path (spin_drift::litz_*).
738 p.position.z +=
739 crate::spin_drift::litz_drift_meters(sg, p.time, self.inputs.is_twist_right);
740 }
741
742 // sampled_points are snapshotted from the PRE-drift trajectory inside each solver, so the
743 // sampled wind_drift_m column would omit the spin drift that result.points carry. Apply
744 // the same canonical Litz drift to keep the two user-facing outputs consistent.
745 if let Some(samples) = result.sampled_points.as_mut() {
746 for s in samples.iter_mut() {
747 if s.time_s <= 0.0 {
748 continue;
749 }
750 s.wind_drift_m +=
751 crate::spin_drift::litz_drift_meters(sg, s.time_s, self.inputs.is_twist_right);
752 }
753 }
754 }
755
756 /// Muzzle gyroscopic stability Sg used by the empirical Litz spin-drift post-process
757 /// (MBA-1134). Extracted so the exact value is unit-testable and provably identical to the Sg
758 /// the fast / Monte-Carlo path uses — both go through
759 /// [`crate::spin_drift::effective_sg_from_inputs`] with the resolved muzzle atmosphere.
760 fn effective_spin_drift_sg(&self) -> f64 {
761 let (_, _, temp_c, press_hpa) = self.resolved_atmosphere();
762 crate::spin_drift::effective_sg_from_inputs(&self.inputs, temp_c, press_hpa)
763 }
764
765 fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
766 // Simple trajectory integration using Euler method
767 let mut time = 0.0;
768 // Bullet starts at the BORE position, which is muzzle_height above ground
769 // The sight is sight_height ABOVE the bore, so we don't add sight_height here
770 let mut position = Vector3::new(
771 0.0,
772 self.inputs.muzzle_height, // Bore position above ground (NOT + sight_height)
773 0.0,
774 );
775 // Calculate initial velocity components with both elevation and azimuth
776 // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
777 // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
778 // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
779 // once here and reused for the result so it isn't evaluated twice per solve.
780 let aj_components = self.aerodynamic_jump_components();
781 let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
782 let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
783 let mut velocity = Vector3::new(
784 horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
785 self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
786 horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
787 );
788
789 let mut points = Vec::new();
790 let mut max_height = position.y;
791 let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
792 let mut transonic_mach = None; // Track when we enter transonic
793 // Downrange distances where the projectile crosses Mach 1.2 (transonic) then Mach 1.0
794 // (subsonic), so the sampled trajectory output can flag those transitions
795 // (trajectory_sampling::add_trajectory_flags consumes this).
796 let mut transonic_distances: Vec<f64> = Vec::new();
797 let mut crossed_transonic = false;
798 let mut crossed_subsonic = false;
799
800 // Initialize angular state for precession/nutation tracking
801 let mut angular_state = if self.inputs.enable_precession_nutation {
802 Some(AngularState {
803 pitch_angle: 0.001, // Small initial disturbance
804 yaw_angle: 0.001,
805 pitch_rate: 0.0,
806 yaw_rate: 0.0,
807 precession_angle: 0.0,
808 nutation_phase: 0.0,
809 })
810 } else {
811 None
812 };
813 let mut max_yaw_angle = 0.0;
814 let mut max_precession_angle = 0.0;
815
816 // Calculate air density
817 let (air_density, speed_of_sound, resolved_temp_c, resolved_press_hpa) = self.resolved_atmosphere();
818 // MBA-1136 (rank 30): base density RATIO for the local-altitude atmosphere recompute done
819 // per-substep inside calculate_acceleration. The `air_density` / `speed_of_sound` above
820 // stay the frozen station values, still used for the Mach-transition, pitch-damping and
821 // precession/nutation diagnostics (which are intentionally referenced to station Mach).
822 let base_ratio = air_density / 1.225;
823
824 // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
825 // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
826 // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
827 let wind_vector = Vector3::new(
828 -self.wind.speed * self.wind.direction.cos(), // X: downrange (head/tail wind)
829 0.0,
830 -self.wind.speed * self.wind.direction.sin(), // Z: lateral (crosswind)
831 );
832
833 // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
834 // instead of re-deriving them (with a to_lowercase alloc) every integration step.
835 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
836 self.inputs.bullet_model.as_deref().unwrap_or("default"),
837 );
838
839 // Main integration loop (X is downrange)
840 while position.x < self.max_range
841 && position.y > self.inputs.ground_threshold
842 && time < 100.0
843 {
844 // Store trajectory point
845 let velocity_magnitude = velocity.magnitude();
846 let kinetic_energy =
847 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
848
849 points.push(TrajectoryPoint {
850 time,
851 position: position,
852 velocity_magnitude,
853 kinetic_energy,
854 });
855
856 // Record Mach-transition distances (constant sea-level speed of sound, matching the
857 // transonic_mach tracking). Each threshold is recorded once, in descending order.
858 {
859 let mach_here = if speed_of_sound > 0.0 {
860 velocity_magnitude / speed_of_sound
861 } else {
862 0.0
863 };
864 if !crossed_transonic && mach_here < 1.2 {
865 crossed_transonic = true;
866 transonic_distances.push(position.x);
867 }
868 if !crossed_subsonic && mach_here < 1.0 {
869 crossed_subsonic = true;
870 transonic_distances.push(position.x);
871 }
872 }
873
874 // Debug: log first and every 100th point. Debug builds only — this was ungated and
875 // polluted release/WASM stderr on the --use-euler path (the other solvers have none).
876 // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral
877 #[cfg(debug_assertions)]
878 if points.len() == 1 || points.len() % 100 == 0 {
879 eprintln!("Trajectory point {}: time={:.3}s, downrange={:.2}m, vertical={:.2}m, lateral={:.2}m, vel={:.1}m/s",
880 points.len(), time, position.x, position.y, position.z, velocity_magnitude);
881 }
882
883 // Track max height
884 if position.y > max_height {
885 max_height = position.y;
886 }
887
888 // Calculate pitch damping if enabled
889 if self.inputs.enable_pitch_damping {
890 let mach = velocity_magnitude / speed_of_sound;
891
892 // Track when we enter transonic
893 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
894 transonic_mach = Some(mach);
895 }
896
897 // Calculate pitch damping coefficient
898 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
899
900 // Track minimum (most critical for stability)
901 if pitch_damping < min_pitch_damping {
902 min_pitch_damping = pitch_damping;
903 }
904 }
905
906 // Calculate precession/nutation if enabled
907 if self.inputs.enable_precession_nutation {
908 if let Some(ref mut state) = angular_state {
909 let velocity_magnitude = velocity.magnitude();
910 let mach = velocity_magnitude / speed_of_sound;
911
912 // Calculate spin rate from twist rate and velocity
913 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
914 let velocity_fps = velocity_magnitude * 3.28084;
915 let twist_rate_ft = self.inputs.twist_rate / 12.0;
916 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
917 } else {
918 0.0
919 };
920
921 // Create precession/nutation parameters
922 let params = PrecessionNutationParams {
923 mass_kg: self.inputs.bullet_mass,
924 caliber_m: self.inputs.bullet_diameter,
925 length_m: self.inputs.bullet_length,
926 spin_rate_rad_s,
927 spin_inertia: 6.94e-8, // Typical value
928 transverse_inertia: 9.13e-7, // Typical value
929 velocity_mps: velocity_magnitude,
930 air_density_kg_m3: air_density,
931 mach,
932 pitch_damping_coeff: -0.8,
933 nutation_damping_factor: 0.05,
934 };
935
936 // Update angular state
937 *state = calculate_combined_angular_motion(
938 ¶ms,
939 state,
940 time,
941 self.time_step,
942 0.001, // Initial disturbance
943 );
944
945 // Track maximums
946 if state.yaw_angle.abs() > max_yaw_angle {
947 max_yaw_angle = state.yaw_angle.abs();
948 }
949 if state.precession_angle.abs() > max_precession_angle {
950 max_precession_angle = state.precession_angle.abs();
951 }
952 }
953 }
954
955 // Use the same acceleration kernel as RK4/RK45 so all three solvers share ONE drag
956 // model. solve_euler previously used a bespoke frontal-area drag (0.5*rho*Cd*A*v^2/m)
957 // that IGNORED the ballistic coefficient entirely (diverging up to ~2.3x from the
958 // BC-retardation RK4/RK45 path), and also omitted the Magnus/Coriolis terms.
959 // calculate_acceleration applies BC-retardation drag, gravity, Coriolis, Magnus, wind
960 // shear, and the zero-relative-velocity gravity-only guard.
961 let acceleration =
962 self.calculate_acceleration(&position, &velocity,
963 &wind_vector,
964 (resolved_temp_c, resolved_press_hpa, base_ratio),
965 );
966
967 // Update state
968 velocity += acceleration * self.time_step;
969 position += velocity * self.time_step;
970 time += self.time_step;
971 }
972
973 // Get final values
974 let last_point = points.last().ok_or("No trajectory points generated")?;
975
976 // Create trajectory sampling data if enabled
977 let sampled_points = if self.inputs.enable_trajectory_sampling {
978 let trajectory_data = TrajectoryData {
979 times: points.iter().map(|p| p.time).collect(),
980 positions: points.iter().map(|p| p.position).collect(),
981 velocities: points
982 .iter()
983 .map(|p| {
984 // Reconstruct velocity vectors from magnitude (approximate)
985 Vector3::new(0.0, 0.0, p.velocity_magnitude)
986 })
987 .collect(),
988 transonic_distances, // populated above at each Mach-threshold crossing
989 };
990
991 // For LOS calculation in ground-referenced coordinates:
992 // sight_position_m is the sight's actual y-position above ground
993 // (muzzle_height + sight_height, not just sight_height)
994 // For flat shots, target is at same height as the sight (horizontal LOS)
995 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
996 let outputs = TrajectoryOutputs {
997 target_distance_horiz_m: last_point.position.x, // X is downrange
998 target_vertical_height_m: sight_position_m,
999 time_of_flight_s: last_point.time,
1000 max_ord_dist_horiz_m: max_height,
1001 sight_height_m: sight_position_m,
1002 };
1003
1004 // Sample at specified intervals
1005 let samples = sample_trajectory(
1006 &trajectory_data,
1007 &outputs,
1008 self.inputs.sample_interval,
1009 self.inputs.bullet_mass,
1010 );
1011 Some(samples)
1012 } else {
1013 None
1014 };
1015
1016 Ok(TrajectoryResult {
1017 max_range: last_point.position.x, // X is downrange
1018 max_height,
1019 time_of_flight: last_point.time,
1020 impact_velocity: last_point.velocity_magnitude,
1021 impact_energy: last_point.kinetic_energy,
1022 points,
1023 sampled_points,
1024 min_pitch_damping: if self.inputs.enable_pitch_damping {
1025 Some(min_pitch_damping)
1026 } else {
1027 None
1028 },
1029 transonic_mach,
1030 angular_state,
1031 max_yaw_angle: if self.inputs.enable_precession_nutation {
1032 Some(max_yaw_angle)
1033 } else {
1034 None
1035 },
1036 max_precession_angle: if self.inputs.enable_precession_nutation {
1037 Some(max_precession_angle)
1038 } else {
1039 None
1040 },
1041 aerodynamic_jump: aj_components,
1042 })
1043 }
1044
1045 fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
1046 // RK4 trajectory integration for better accuracy
1047 let mut time = 0.0;
1048 // Bullet starts at the BORE position, which is muzzle_height above ground
1049 // The sight is sight_height ABOVE the bore, so we don't add sight_height here
1050 // The sight_height affects the LOS calculation and zero angle, not the starting position
1051 let mut position = Vector3::new(
1052 0.0,
1053 self.inputs.muzzle_height, // Bore position above ground (NOT + sight_height)
1054 0.0,
1055 );
1056
1057 // Calculate initial velocity components with both elevation and azimuth
1058 // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
1059 // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
1060 // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
1061 // once here and reused for the result so it isn't evaluated twice per solve.
1062 let aj_components = self.aerodynamic_jump_components();
1063 let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
1064 let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
1065 let mut velocity = Vector3::new(
1066 horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
1067 self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
1068 horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
1069 );
1070
1071 let mut points = Vec::new();
1072 let mut max_height = position.y;
1073 let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
1074 let mut transonic_mach = None; // Track when we enter transonic
1075 // Downrange distances where the projectile crosses Mach 1.2 (transonic) then Mach 1.0
1076 // (subsonic), so the sampled trajectory output can flag those transitions
1077 // (trajectory_sampling::add_trajectory_flags consumes this).
1078 let mut transonic_distances: Vec<f64> = Vec::new();
1079 let mut crossed_transonic = false;
1080 let mut crossed_subsonic = false;
1081
1082 // Initialize angular state for precession/nutation tracking
1083 let mut angular_state = if self.inputs.enable_precession_nutation {
1084 Some(AngularState {
1085 pitch_angle: 0.001, // Small initial disturbance
1086 yaw_angle: 0.001,
1087 pitch_rate: 0.0,
1088 yaw_rate: 0.0,
1089 precession_angle: 0.0,
1090 nutation_phase: 0.0,
1091 })
1092 } else {
1093 None
1094 };
1095 let mut max_yaw_angle = 0.0;
1096 let mut max_precession_angle = 0.0;
1097
1098 // Calculate air density
1099 let (air_density, speed_of_sound, resolved_temp_c, resolved_press_hpa) = self.resolved_atmosphere();
1100 // MBA-1136 (rank 30): base density RATIO for the local-altitude atmosphere recompute done
1101 // per-substep inside calculate_acceleration. The `air_density` / `speed_of_sound` above
1102 // stay the frozen station values, still used for the Mach-transition, pitch-damping and
1103 // precession/nutation diagnostics (which are intentionally referenced to station Mach).
1104 let base_ratio = air_density / 1.225;
1105
1106 // Wind vector (McCoy): X=downrange (head/tail wind), Y=0, Z=lateral (crosswind)
1107 // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
1108 // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
1109 let wind_vector = Vector3::new(
1110 -self.wind.speed * self.wind.direction.cos(), // X: downrange (head/tail wind)
1111 0.0,
1112 -self.wind.speed * self.wind.direction.sin(), // Z: lateral (crosswind)
1113 );
1114
1115 // Pitch-damping coefficients depend only on the (constant) bullet_model; compute once
1116 // instead of re-deriving them (with a to_lowercase alloc) every integration step.
1117 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
1118 self.inputs.bullet_model.as_deref().unwrap_or("default"),
1119 );
1120
1121 // Main RK4 integration loop (X is downrange)
1122 while position.x < self.max_range
1123 && position.y > self.inputs.ground_threshold
1124 && time < 100.0
1125 {
1126 // Store trajectory point
1127 let velocity_magnitude = velocity.magnitude();
1128 let kinetic_energy =
1129 0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
1130
1131 points.push(TrajectoryPoint {
1132 time,
1133 position: position,
1134 velocity_magnitude,
1135 kinetic_energy,
1136 });
1137
1138 // Record Mach-transition distances (constant sea-level speed of sound, matching the
1139 // transonic_mach tracking). Each threshold is recorded once, in descending order.
1140 {
1141 let mach_here = if speed_of_sound > 0.0 {
1142 velocity_magnitude / speed_of_sound
1143 } else {
1144 0.0
1145 };
1146 if !crossed_transonic && mach_here < 1.2 {
1147 crossed_transonic = true;
1148 transonic_distances.push(position.x);
1149 }
1150 if !crossed_subsonic && mach_here < 1.0 {
1151 crossed_subsonic = true;
1152 transonic_distances.push(position.x);
1153 }
1154 }
1155
1156 if position.y > max_height {
1157 max_height = position.y;
1158 }
1159
1160 // Calculate pitch damping if enabled (RK4 solver)
1161 if self.inputs.enable_pitch_damping {
1162 let mach = velocity_magnitude / speed_of_sound;
1163
1164 // Track when we enter transonic
1165 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
1166 transonic_mach = Some(mach);
1167 }
1168
1169 // Calculate pitch damping coefficient
1170 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
1171
1172 // Track minimum (most critical for stability)
1173 if pitch_damping < min_pitch_damping {
1174 min_pitch_damping = pitch_damping;
1175 }
1176 }
1177
1178 // Calculate precession/nutation if enabled (RK4 solver)
1179 if self.inputs.enable_precession_nutation {
1180 if let Some(ref mut state) = angular_state {
1181 let velocity_magnitude = velocity.magnitude();
1182 let mach = velocity_magnitude / speed_of_sound;
1183
1184 // Calculate spin rate from twist rate and velocity
1185 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
1186 let velocity_fps = velocity_magnitude * 3.28084;
1187 let twist_rate_ft = self.inputs.twist_rate / 12.0;
1188 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
1189 } else {
1190 0.0
1191 };
1192
1193 // Create precession/nutation parameters
1194 let params = PrecessionNutationParams {
1195 mass_kg: self.inputs.bullet_mass,
1196 caliber_m: self.inputs.bullet_diameter,
1197 length_m: self.inputs.bullet_length,
1198 spin_rate_rad_s,
1199 spin_inertia: 6.94e-8, // Typical value
1200 transverse_inertia: 9.13e-7, // Typical value
1201 velocity_mps: velocity_magnitude,
1202 air_density_kg_m3: air_density,
1203 mach,
1204 pitch_damping_coeff: -0.8,
1205 nutation_damping_factor: 0.05,
1206 };
1207
1208 // Update angular state
1209 *state = calculate_combined_angular_motion(
1210 ¶ms,
1211 state,
1212 time,
1213 self.time_step,
1214 0.001, // Initial disturbance
1215 );
1216
1217 // Track maximums
1218 if state.yaw_angle.abs() > max_yaw_angle {
1219 max_yaw_angle = state.yaw_angle.abs();
1220 }
1221 if state.precession_angle.abs() > max_precession_angle {
1222 max_precession_angle = state.precession_angle.abs();
1223 }
1224 }
1225 }
1226
1227 // RK4 method
1228 let dt = self.time_step;
1229
1230 // k1
1231 let acc1 = self.calculate_acceleration(&position, &velocity, &wind_vector, (resolved_temp_c, resolved_press_hpa, base_ratio));
1232
1233 // k2
1234 let pos2 = position + velocity * (dt * 0.5);
1235 let vel2 = velocity + acc1 * (dt * 0.5);
1236 let acc2 = self.calculate_acceleration(&pos2, &vel2, &wind_vector, (resolved_temp_c, resolved_press_hpa, base_ratio));
1237
1238 // k3
1239 let pos3 = position + vel2 * (dt * 0.5);
1240 let vel3 = velocity + acc2 * (dt * 0.5);
1241 let acc3 = self.calculate_acceleration(&pos3, &vel3, &wind_vector, (resolved_temp_c, resolved_press_hpa, base_ratio));
1242
1243 // k4
1244 let pos4 = position + vel3 * dt;
1245 let vel4 = velocity + acc3 * dt;
1246 let acc4 = self.calculate_acceleration(&pos4, &vel4, &wind_vector, (resolved_temp_c, resolved_press_hpa, base_ratio));
1247
1248 // Update position and velocity
1249 position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
1250 velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
1251 time += dt;
1252 }
1253
1254 // Get final values
1255 let last_point = points.last().ok_or("No trajectory points generated")?;
1256
1257 // Create trajectory sampling data if enabled
1258 let sampled_points = if self.inputs.enable_trajectory_sampling {
1259 let trajectory_data = TrajectoryData {
1260 times: points.iter().map(|p| p.time).collect(),
1261 positions: points.iter().map(|p| p.position).collect(),
1262 velocities: points
1263 .iter()
1264 .map(|p| {
1265 // Reconstruct velocity vectors from magnitude (approximate)
1266 Vector3::new(0.0, 0.0, p.velocity_magnitude)
1267 })
1268 .collect(),
1269 transonic_distances, // populated above at each Mach-threshold crossing
1270 };
1271
1272 // For LOS calculation in ground-referenced coordinates:
1273 // sight_position_m is the sight's actual y-position above ground
1274 // (muzzle_height + sight_height, not just sight_height)
1275 // For flat shots, target is at same height as the sight (horizontal LOS)
1276 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
1277 let outputs = TrajectoryOutputs {
1278 target_distance_horiz_m: last_point.position.x, // X is downrange
1279 target_vertical_height_m: sight_position_m,
1280 time_of_flight_s: last_point.time,
1281 max_ord_dist_horiz_m: max_height,
1282 sight_height_m: sight_position_m,
1283 };
1284
1285 // Sample at specified intervals
1286 let samples = sample_trajectory(
1287 &trajectory_data,
1288 &outputs,
1289 self.inputs.sample_interval,
1290 self.inputs.bullet_mass,
1291 );
1292 Some(samples)
1293 } else {
1294 None
1295 };
1296
1297 Ok(TrajectoryResult {
1298 max_range: last_point.position.x, // X is downrange
1299 max_height,
1300 time_of_flight: last_point.time,
1301 impact_velocity: last_point.velocity_magnitude,
1302 impact_energy: last_point.kinetic_energy,
1303 points,
1304 sampled_points,
1305 min_pitch_damping: if self.inputs.enable_pitch_damping {
1306 Some(min_pitch_damping)
1307 } else {
1308 None
1309 },
1310 transonic_mach,
1311 angular_state,
1312 max_yaw_angle: if self.inputs.enable_precession_nutation {
1313 Some(max_yaw_angle)
1314 } else {
1315 None
1316 },
1317 max_precession_angle: if self.inputs.enable_precession_nutation {
1318 Some(max_precession_angle)
1319 } else {
1320 None
1321 },
1322 aerodynamic_jump: aj_components,
1323 })
1324 }
1325
1326 fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
1327 // RK45 adaptive step size integration (Dormand-Prince method)
1328 let mut time = 0.0;
1329 // Bullet starts at the BORE position, which is muzzle_height above ground
1330 // The sight is sight_height ABOVE the bore, so we don't add sight_height here
1331 let mut position = Vector3::new(
1332 0.0,
1333 self.inputs.muzzle_height, // Bore position above ground (NOT + sight_height)
1334 0.0,
1335 );
1336
1337 // Calculate initial velocity components
1338 // McCoy coordinate system: X=downrange, Y=vertical, Z=lateral (right)
1339 // Launch direction includes the aerodynamic-jump muzzle perturbation when enabled
1340 // (a no-op returning the bare muzzle/azimuth angles otherwise). MBA-959. Computed
1341 // once here and reused for the result so it isn't evaluated twice per solve.
1342 let aj_components = self.aerodynamic_jump_components();
1343 let (launch_elev, launch_azim) = self.launch_angles_from(aj_components.as_ref());
1344 let horizontal_velocity = self.inputs.muzzle_velocity * launch_elev.cos();
1345 let mut velocity = Vector3::new(
1346 horizontal_velocity * launch_azim.cos(), // X: downrange (forward)
1347 self.inputs.muzzle_velocity * launch_elev.sin(), // Y: vertical component
1348 horizontal_velocity * launch_azim.sin(), // Z: lateral (side deviation)
1349 );
1350
1351 let mut points = Vec::new();
1352 let mut max_height = position.y;
1353 let mut dt = 0.001; // Initial step size
1354 let tolerance = 1e-6; // Error tolerance
1355 let safety_factor = 0.9; // Safety factor for step size adjustment
1356 let max_dt = 0.01; // Maximum step size
1357 let min_dt = 1e-6; // Minimum step size
1358
1359 // Add a point counter to debug
1360 let mut iteration_count = 0;
1361 const MAX_ITERATIONS: usize = 100000;
1362
1363 // Air density and wind are constant for the whole solve (self.atmosphere / self.wind
1364 // are immutable); compute once instead of every iteration (mirrors solve_rk4).
1365 let (air_density, speed_of_sound, resolved_temp_c, resolved_press_hpa) = self.resolved_atmosphere();
1366 // MBA-1136 (rank 30): base density RATIO for the local-altitude atmosphere recompute done
1367 // per-substep inside calculate_acceleration. The `air_density` / `speed_of_sound` above
1368 // stay the frozen station values, still used for the Mach-transition, pitch-damping and
1369 // precession/nutation diagnostics (which are intentionally referenced to station Mach).
1370 let base_ratio = air_density / 1.225;
1371 // 0deg = headwind, 90deg = from the right (McCoy wind-FROM convention, matching
1372 // WindSock); wind enters drag via velocity - wind. Used when no segmented wind.
1373 let wind_vector = Vector3::new(
1374 -self.wind.speed * self.wind.direction.cos(), // X: downrange (head/tail wind)
1375 0.0,
1376 -self.wind.speed * self.wind.direction.sin(), // Z: lateral (crosswind)
1377 );
1378
1379 // Mach-transition distances for the sampled-output flags (see solve_euler/solve_rk4).
1380 let mut transonic_distances: Vec<f64> = Vec::new();
1381 let mut crossed_transonic = false;
1382 let mut crossed_subsonic = false;
1383
1384 // Pitch-damping / precession diagnostics (MBA-966). Previously only the
1385 // Euler and fixed-RK4 solvers tracked these, so the default adaptive
1386 // RK45 path always reported null even with --enable-pitch-damping /
1387 // --enable-precession set. Mirror the RK4 tracking here.
1388 let mut min_pitch_damping = 1.0;
1389 let mut transonic_mach: Option<f64> = None;
1390 let pitch_coeffs = PitchDampingCoefficients::from_bullet_type(
1391 self.inputs.bullet_model.as_deref().unwrap_or("default"),
1392 );
1393 let mut angular_state = if self.inputs.enable_precession_nutation {
1394 Some(AngularState {
1395 pitch_angle: 0.001,
1396 yaw_angle: 0.001,
1397 pitch_rate: 0.0,
1398 yaw_rate: 0.0,
1399 precession_angle: 0.0,
1400 nutation_phase: 0.0,
1401 })
1402 } else {
1403 None
1404 };
1405 let mut max_yaw_angle = 0.0;
1406 let mut max_precession_angle = 0.0;
1407
1408 while position.x < self.max_range
1409 && position.y > self.inputs.ground_threshold
1410 && time < 100.0
1411 {
1412 // X is downrange
1413 iteration_count += 1;
1414 if iteration_count > MAX_ITERATIONS {
1415 break; // Prevent infinite loop
1416 }
1417
1418 // Store current point
1419 let velocity_magnitude = velocity.magnitude();
1420 let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
1421
1422 points.push(TrajectoryPoint {
1423 time,
1424 position: position,
1425 velocity_magnitude,
1426 kinetic_energy,
1427 });
1428
1429 // Record Mach-transition distances (constant sea-level speed of sound, matching the
1430 // transonic_mach tracking). Each threshold is recorded once, in descending order.
1431 {
1432 let mach_here = if speed_of_sound > 0.0 {
1433 velocity_magnitude / speed_of_sound
1434 } else {
1435 0.0
1436 };
1437 if !crossed_transonic && mach_here < 1.2 {
1438 crossed_transonic = true;
1439 transonic_distances.push(position.x);
1440 }
1441 if !crossed_subsonic && mach_here < 1.0 {
1442 crossed_subsonic = true;
1443 transonic_distances.push(position.x);
1444 }
1445 }
1446
1447 if position.y > max_height {
1448 max_height = position.y;
1449 }
1450
1451 // Pitch damping (RK45 solver) — track the minimum coefficient and the
1452 // Mach at which the projectile enters the transonic band (MBA-966).
1453 if self.inputs.enable_pitch_damping {
1454 let mach = velocity_magnitude / speed_of_sound;
1455 if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
1456 transonic_mach = Some(mach);
1457 }
1458 let pitch_damping = calculate_pitch_damping_coefficient(mach, &pitch_coeffs);
1459 if pitch_damping < min_pitch_damping {
1460 min_pitch_damping = pitch_damping;
1461 }
1462 }
1463
1464 // Precession / nutation (RK45 solver). Uses the step `dt` actually
1465 // taken for this iteration so the angular integration stays in sync
1466 // with the variable-step trajectory.
1467 if self.inputs.enable_precession_nutation {
1468 if let Some(ref mut state) = angular_state {
1469 let mach = velocity_magnitude / speed_of_sound;
1470
1471 let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
1472 let velocity_fps = velocity_magnitude * 3.28084;
1473 let twist_rate_ft = self.inputs.twist_rate / 12.0;
1474 (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
1475 } else {
1476 0.0
1477 };
1478
1479 let params = PrecessionNutationParams {
1480 mass_kg: self.inputs.bullet_mass,
1481 caliber_m: self.inputs.bullet_diameter,
1482 length_m: self.inputs.bullet_length,
1483 spin_rate_rad_s,
1484 spin_inertia: 6.94e-8,
1485 transverse_inertia: 9.13e-7,
1486 velocity_mps: velocity_magnitude,
1487 air_density_kg_m3: air_density,
1488 mach,
1489 pitch_damping_coeff: -0.8,
1490 nutation_damping_factor: 0.05,
1491 };
1492
1493 *state = calculate_combined_angular_motion(¶ms, state, time, dt, 0.001);
1494
1495 if state.yaw_angle.abs() > max_yaw_angle {
1496 max_yaw_angle = state.yaw_angle.abs();
1497 }
1498 if state.precession_angle.abs() > max_precession_angle {
1499 max_precession_angle = state.precession_angle.abs();
1500 }
1501 }
1502 }
1503
1504 // RK45 step with adaptive step size (air_density / wind_vector hoisted above)
1505 let (new_pos, new_vel, new_dt) = self.rk45_step(
1506 &position,
1507 &velocity,
1508 dt,
1509 &wind_vector,
1510 tolerance,
1511 (resolved_temp_c, resolved_press_hpa, base_ratio),
1512 );
1513
1514 // Advance state and time by the dt actually used for THIS step. (Previously dt
1515 // was overwritten with the adapted next-step size BEFORE `time += dt`, so every
1516 // reported time advanced by the NEXT step's dt — desyncing time from state and
1517 // corrupting time_of_flight and per-point / sampled times.)
1518 position = new_pos;
1519 velocity = new_vel;
1520 time += dt;
1521
1522 // Adapt the step size for the NEXT iteration.
1523 dt = (safety_factor * new_dt).clamp(min_dt, max_dt);
1524 }
1525
1526 // Ensure we have at least one point
1527 if points.is_empty() {
1528 return Err(BallisticsError::from("No trajectory points calculated"));
1529 }
1530
1531 // Boundary interpolation to exactly max_range (MBA-968). The adaptive
1532 // loop stores the point at the TOP of each iteration, so the last stored
1533 // point sits one (possibly large) step SHORT of max_range while the
1534 // post-loop `position` has just overshot it. Without this, the default
1535 // RK45 solver reports ~2% short of --max-range, unlike the fixed-step
1536 // solvers. When the loop exited by crossing the range (not by hitting the
1537 // ground / time cap / iteration cap), append a linearly-interpolated
1538 // point at exactly max_range so the reported range matches the request.
1539 {
1540 let prev = points.last().unwrap().clone();
1541 let overshoot_x = position.x;
1542 let crossed_range = overshoot_x >= self.max_range && prev.position.x < self.max_range;
1543 if crossed_range {
1544 let span = overshoot_x - prev.position.x;
1545 if span > 1e-9 {
1546 let frac = (self.max_range - prev.position.x) / span;
1547 let interp_pos = prev.position + (position - prev.position) * frac;
1548 let interp_vel_mag = prev.velocity_magnitude
1549 + (velocity.magnitude() - prev.velocity_magnitude) * frac;
1550 let interp_time = prev.time + (time - prev.time) * frac;
1551 let interp_ke = 0.5 * self.inputs.bullet_mass * interp_vel_mag * interp_vel_mag;
1552 points.push(TrajectoryPoint {
1553 time: interp_time,
1554 position: interp_pos,
1555 velocity_magnitude: interp_vel_mag,
1556 kinetic_energy: interp_ke,
1557 });
1558 if interp_pos.y > max_height {
1559 max_height = interp_pos.y;
1560 }
1561 }
1562 }
1563 }
1564
1565 let last_point = points.last().unwrap();
1566
1567 // Generate sampled trajectory points if enabled
1568 let sampled_points = if self.inputs.enable_trajectory_sampling {
1569 // Build trajectory data for sampling
1570 let trajectory_data = TrajectoryData {
1571 times: points.iter().map(|p| p.time).collect(),
1572 positions: points.iter().map(|p| p.position).collect(),
1573 velocities: points
1574 .iter()
1575 .map(|p| {
1576 // Approximate velocity direction from position changes
1577 Vector3::new(0.0, 0.0, p.velocity_magnitude)
1578 })
1579 .collect(),
1580 transonic_distances, // populated at each Mach-threshold crossing
1581 };
1582
1583 // For LOS calculation in ground-referenced coordinates:
1584 // sight_position_m is the sight's actual y-position above ground
1585 // (muzzle_height + sight_height, not just sight_height)
1586 // For flat shots, target is at same height as the sight (horizontal LOS)
1587 let sight_position_m = self.inputs.muzzle_height + self.inputs.sight_height;
1588 let outputs = TrajectoryOutputs {
1589 target_distance_horiz_m: last_point.position.x,
1590 target_vertical_height_m: sight_position_m,
1591 time_of_flight_s: last_point.time,
1592 max_ord_dist_horiz_m: max_height,
1593 sight_height_m: sight_position_m,
1594 };
1595
1596 let samples = sample_trajectory(
1597 &trajectory_data,
1598 &outputs,
1599 self.inputs.sample_interval,
1600 self.inputs.bullet_mass,
1601 );
1602 Some(samples)
1603 } else {
1604 None
1605 };
1606
1607 Ok(TrajectoryResult {
1608 max_range: last_point.position.x, // X is downrange
1609 max_height,
1610 time_of_flight: last_point.time,
1611 impact_velocity: last_point.velocity_magnitude,
1612 impact_energy: last_point.kinetic_energy,
1613 points,
1614 sampled_points,
1615 min_pitch_damping: if self.inputs.enable_pitch_damping {
1616 Some(min_pitch_damping)
1617 } else {
1618 None
1619 },
1620 transonic_mach,
1621 angular_state,
1622 max_yaw_angle: if self.inputs.enable_precession_nutation {
1623 Some(max_yaw_angle)
1624 } else {
1625 None
1626 },
1627 max_precession_angle: if self.inputs.enable_precession_nutation {
1628 Some(max_precession_angle)
1629 } else {
1630 None
1631 },
1632 aerodynamic_jump: aj_components,
1633 })
1634 }
1635
1636 fn rk45_step(
1637 &self,
1638 position: &Vector3<f64>,
1639 velocity: &Vector3<f64>,
1640 dt: f64,
1641 wind_vector: &Vector3<f64>,
1642 tolerance: f64,
1643 resolved_atmo: (f64, f64, f64), // (base_temp_c, base_press_hpa, base_ratio)
1644 ) -> (Vector3<f64>, Vector3<f64>, f64) {
1645 // Dormand-Prince coefficients
1646 const A21: f64 = 1.0 / 5.0;
1647 const A31: f64 = 3.0 / 40.0;
1648 const A32: f64 = 9.0 / 40.0;
1649 const A41: f64 = 44.0 / 45.0;
1650 const A42: f64 = -56.0 / 15.0;
1651 const A43: f64 = 32.0 / 9.0;
1652 const A51: f64 = 19372.0 / 6561.0;
1653 const A52: f64 = -25360.0 / 2187.0;
1654 const A53: f64 = 64448.0 / 6561.0;
1655 const A54: f64 = -212.0 / 729.0;
1656 const A61: f64 = 9017.0 / 3168.0;
1657 const A62: f64 = -355.0 / 33.0;
1658 const A63: f64 = 46732.0 / 5247.0;
1659 const A64: f64 = 49.0 / 176.0;
1660 const A65: f64 = -5103.0 / 18656.0;
1661 const A71: f64 = 35.0 / 384.0;
1662 const A73: f64 = 500.0 / 1113.0;
1663 const A74: f64 = 125.0 / 192.0;
1664 const A75: f64 = -2187.0 / 6784.0;
1665 const A76: f64 = 11.0 / 84.0;
1666
1667 // 5th order coefficients
1668 const B1: f64 = 35.0 / 384.0;
1669 const B3: f64 = 500.0 / 1113.0;
1670 const B4: f64 = 125.0 / 192.0;
1671 const B5: f64 = -2187.0 / 6784.0;
1672 const B6: f64 = 11.0 / 84.0;
1673
1674 // 4th order coefficients for error estimation
1675 const B1_ERR: f64 = 5179.0 / 57600.0;
1676 const B3_ERR: f64 = 7571.0 / 16695.0;
1677 const B4_ERR: f64 = 393.0 / 640.0;
1678 const B5_ERR: f64 = -92097.0 / 339200.0;
1679 const B6_ERR: f64 = 187.0 / 2100.0;
1680 const B7_ERR: f64 = 1.0 / 40.0;
1681
1682 // Compute RK45 stages
1683 let k1_v = self.calculate_acceleration(position, velocity, wind_vector, resolved_atmo);
1684 let k1_p = *velocity;
1685
1686 let p2 = position + dt * A21 * k1_p;
1687 let v2 = velocity + dt * A21 * k1_v;
1688 let k2_v = self.calculate_acceleration(&p2, &v2, wind_vector, resolved_atmo);
1689 let k2_p = v2;
1690
1691 let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
1692 let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
1693 let k3_v = self.calculate_acceleration(&p3, &v3, wind_vector, resolved_atmo);
1694 let k3_p = v3;
1695
1696 let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
1697 let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
1698 let k4_v = self.calculate_acceleration(&p4, &v4, wind_vector, resolved_atmo);
1699 let k4_p = v4;
1700
1701 let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
1702 let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
1703 let k5_v = self.calculate_acceleration(&p5, &v5, wind_vector, resolved_atmo);
1704 let k5_p = v5;
1705
1706 let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
1707 let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
1708 let k6_v = self.calculate_acceleration(&p6, &v6, wind_vector, resolved_atmo);
1709 let k6_p = v6;
1710
1711 let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
1712 let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
1713 let k7_v = self.calculate_acceleration(&p7, &v7, wind_vector, resolved_atmo);
1714 let k7_p = v7;
1715
1716 // 5th order solution
1717 let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
1718 let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
1719
1720 // 4th order solution for error estimate
1721 let pos_err = position
1722 + dt * (B1_ERR * k1_p
1723 + B3_ERR * k3_p
1724 + B4_ERR * k4_p
1725 + B5_ERR * k5_p
1726 + B6_ERR * k6_p
1727 + B7_ERR * k7_p);
1728 let vel_err = velocity
1729 + dt * (B1_ERR * k1_v
1730 + B3_ERR * k3_v
1731 + B4_ERR * k4_v
1732 + B5_ERR * k5_v
1733 + B6_ERR * k6_v
1734 + B7_ERR * k7_v);
1735
1736 // Estimate error
1737 let pos_error = (new_pos - pos_err).magnitude();
1738 let vel_error = (new_vel - vel_err).magnitude();
1739 let error = (pos_error + vel_error) / (1.0 + position.magnitude() + velocity.magnitude());
1740
1741 // Calculate new step size
1742 let dt_new = if error < tolerance {
1743 dt * (tolerance / error).powf(0.2).min(2.0)
1744 } else {
1745 dt * (tolerance / error).powf(0.25).max(0.1)
1746 };
1747
1748 (new_pos, new_vel, dt_new)
1749 }
1750
1751 fn calculate_acceleration(
1752 &self,
1753 position: &Vector3<f64>,
1754 velocity: &Vector3<f64>,
1755 wind_vector: &Vector3<f64>,
1756 resolved_atmo: (f64, f64, f64), // (base_temp_c, base_press_hpa, base_ratio) hoisted per-solve
1757 ) -> Vector3<f64> {
1758 // Resolve the wind at this point. Downrange-segmented wind (when supplied)
1759 // takes precedence and is sampled by downrange distance (position.x) per
1760 // step; otherwise altitude-dependent shear (if enabled); otherwise the
1761 // constant `wind_vector`. Segmented wind is not combined with shear (the
1762 // CLI/WASM front-ends reject that combination), so the order is safe.
1763 let actual_wind = if let Some(ref sock) = self.wind_sock {
1764 sock.vector_for_range_stateless(position.x)
1765 } else if self.inputs.enable_wind_shear {
1766 self.get_wind_at_altitude(position.y)
1767 } else {
1768 *wind_vector
1769 };
1770
1771 let relative_velocity = velocity - actual_wind;
1772 let velocity_magnitude = relative_velocity.magnitude();
1773
1774 if velocity_magnitude < 0.001 {
1775 return self.gravity_acceleration();
1776 }
1777
1778 // MBA-1136 (rank 30): recompute the atmosphere at the LOCAL substep altitude instead of
1779 // holding the frozen station scalars for the whole flight. This mirrors what
1780 // derivatives.rs / fast_trajectory.rs already do, so all three solver families vary air
1781 // density AND speed of sound with altitude (matters on elevated / long-range shots; a
1782 // no-op at the shooter altitude, where the ratio-based density recovers the station value
1783 // exactly). base_* were resolved once per solve via resolved_atmosphere().
1784 let (base_temp_c, base_press_hpa, base_ratio) = resolved_atmo;
1785 let local_alt = self.atmosphere.altitude + position.y;
1786 let (air_density, speed_of_sound) = crate::atmosphere::get_local_atmosphere(
1787 local_alt,
1788 self.atmosphere.altitude,
1789 base_temp_c,
1790 base_press_hpa,
1791 base_ratio,
1792 );
1793
1794 // Get drag coefficient from drag model (Mach-indexed from drag tables)
1795 let cd = self.calculate_drag_coefficient(velocity_magnitude, speed_of_sound);
1796
1797 // Convert velocity to fps for BC lookups
1798 let velocity_fps = velocity_magnitude * 3.28084;
1799
1800 // Look up BC from segments if available (highest priority - most accurate)
1801 let base_bc = if let Some(ref segments) = self.inputs.bc_segments_data {
1802 // Find matching segment for current velocity
1803 segments
1804 .iter()
1805 .find(|seg| velocity_fps >= seg.velocity_min && velocity_fps < seg.velocity_max)
1806 .map(|seg| seg.bc_value)
1807 .unwrap_or(self.inputs.bc_value)
1808 } else {
1809 self.inputs.bc_value
1810 };
1811
1812 // Apply cluster BC correction if enabled (on top of segment BC)
1813 let effective_bc = if let Some(ref cluster_bc) = self.cluster_bc {
1814 cluster_bc.apply_correction(
1815 base_bc,
1816 self.inputs.caliber_inches, // predict_cluster normalizes against an inches range
1817 self.inputs.weight_grains,
1818 velocity_fps,
1819 )
1820 } else {
1821 base_bc
1822 };
1823 // Guard bc_value == 0 (allowed on the FFI/WASM surfaces, which lack the CLI's 0.001
1824 // lower bound): dividing by effective_bc below would be Inf -> NaN. Inert for valid
1825 // BCs (>= 0.001).
1826 let effective_bc = effective_bc.max(1e-6);
1827
1828 // When a custom drag table is active, calculate_drag_coefficient returned the
1829 // projectile's ACTUAL Cd, so the retardation denominator must be the sectional
1830 // density (lb/in²), not a BC: Cd_own / SD == Cd_ref / BC
1831 // (see BallisticInputs::custom_drag_denominator).
1832 let retard_denom = if self.inputs.custom_drag_table.is_some() {
1833 self.inputs.custom_drag_denominator(effective_bc)
1834 } else {
1835 effective_bc
1836 };
1837
1838 // Use proper ballistics retardation formula
1839 // This matches the proven formula from fast_trajectory.rs
1840 // The standard retardation factor converts Cd to drag deceleration
1841 // Note: velocity_fps already calculated above for BC segment lookup
1842 let cd_to_retard = crate::constants::CD_TO_RETARD;
1843 let standard_factor = cd * cd_to_retard;
1844 let density_scale = air_density / 1.225; // Scale relative to standard air (1.225 kg/m³)
1845
1846 // Drag acceleration in ft/s² then convert to m/s²
1847 let a_drag_ft_s2 =
1848 (velocity_fps * velocity_fps) * standard_factor * density_scale / retard_denom;
1849 let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s² to m/s²
1850
1851 // Apply drag opposite to velocity direction
1852 let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
1853
1854 // Total acceleration = drag + gravity. `shooting_angle` rotates gravity into the shot
1855 // frame for inclined fire; at 0 deg this is the normal vertical-only gravity vector.
1856 let mut accel = drag_acceleration + self.gravity_acceleration();
1857
1858 // Coriolis (Earth rotation). McCoy frame: X=downrange, Y=vertical, Z=lateral,
1859 // azimuth 0 = North. McCoy frame: X=downrange, Y=vertical, Z=lateral.
1860 if self.inputs.enable_coriolis {
1861 if let Some(lat_deg) = self.inputs.latitude {
1862 let omega_earth = 7.2921159e-5_f64; // rad/s
1863 let lat = lat_deg.to_radians();
1864 let az = self.inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
1865 // Earth's angular velocity in the shot frame (X=downrange, Y=up,
1866 // Z=lateral). Projecting Omega=(0, Ω cosφ, Ω sinφ) [local E,N,U] onto
1867 // the azimuth-rotated shot axes gives a NEGATIVE lateral component:
1868 // lateral = downrange × up points East for a North shot, and
1869 // Omega·East = -Ω cosφ sin(az). The previous code dropped that sign.
1870 let omega = Vector3::new(
1871 omega_earth * lat.cos() * az.cos(), // X: downrange
1872 omega_earth * lat.sin(), // Y: vertical
1873 -omega_earth * lat.cos() * az.sin(), // Z: lateral (MBA-938: corrected sign)
1874 );
1875 // Coriolis acceleration is the physical -2 Ω×v (MBA-938). The old +2 with
1876 // an "output-preserving relabel" justification produced left-ward drift for
1877 // a North shot in the Northern hemisphere; first principles (and the +Eötvös
1878 // lift for East shots) require -2 with the corrected omega above.
1879 accel += -2.0 * omega.cross(velocity);
1880 }
1881 }
1882
1883 // Magnus side force (spinning projectile). SI units in this solver.
1884 // MBA-1134 (rank 35): the canonical empirical Litz spin-drift post-process
1885 // (apply_spin_drift) already captures the gyroscopic yaw-of-repose lateral, so the
1886 // explicit Magnus side force must NOT be added on top of it — otherwise the two lateral
1887 // models stack and double-count the drift. Suppress Magnus whenever Litz spin drift is
1888 // active. (The inverse is intentionally NOT done: Litz is not suppressed when Magnus is on.)
1889 if self.inputs.enable_magnus
1890 && !self.inputs.use_enhanced_spin_drift
1891 && self.inputs.bullet_diameter > 0.0
1892 && self.inputs.twist_rate > 0.0
1893 {
1894 let (_, spin_rad_s) =
1895 crate::spin_drift::calculate_spin_rate(velocity_magnitude, self.inputs.twist_rate);
1896 // Stability (Sg) is a launch property, so its Miller density correction uses the
1897 // STATION temperature/pressure (base_*); the Mach that feeds the Magnus-moment
1898 // coefficient uses the LOCAL speed of sound recomputed above.
1899 let temp_k = base_temp_c + 273.15;
1900 let mach = velocity_magnitude / speed_of_sound;
1901
1902 // Imperial conversions for the stability / yaw-of-repose helpers.
1903 let d_in = self.inputs.bullet_diameter / 0.0254;
1904 let m_gr = self.inputs.bullet_mass / 0.00006479891;
1905 let l_in = if self.inputs.bullet_length > 0.0 {
1906 self.inputs.bullet_length / 0.0254
1907 } else {
1908 // MBA-1135: mass-based length estimate (was a mass-blind 4.5-caliber default).
1909 let est_m = crate::stability::estimate_bullet_length_m(
1910 self.inputs.bullet_diameter,
1911 self.inputs.bullet_mass,
1912 );
1913 if est_m > 0.0 {
1914 est_m / 0.0254
1915 } else {
1916 4.5 * d_in
1917 }
1918 };
1919 // MBA-958: apply the canonical linear Miller density correction (T/T0)*(P0/P) to the
1920 // Magnus/yaw-of-repose Sg too, matching the spin-drift Sg (MBA-942) and stability.rs.
1921 // No-op at sea-level standard (15 C, 1013.25 hPa -> factor 1.0).
1922 let density_correction = if base_press_hpa > 0.0 && temp_k > 0.0 {
1923 (temp_k / 288.15) * (1013.25 / base_press_hpa)
1924 } else {
1925 1.0
1926 };
1927 let sg = crate::spin_drift::miller_stability(d_in, m_gr, self.inputs.twist_rate, l_in)
1928 * density_correction;
1929
1930 // Yaw of repose (radians); zero for unstable bullets (Sg <= 1).
1931 let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
1932 sg,
1933 velocity_magnitude,
1934 spin_rad_s,
1935 0.0, // crosswind handled elsewhere
1936 0.0, // pitch rate not tracked
1937 air_density,
1938 d_in,
1939 l_in,
1940 m_gr,
1941 mach,
1942 "match",
1943 false,
1944 );
1945
1946 // Proper McCoy Magnus FORCE: F = q S C_Npa (pd/2V) sin(alpha_R).
1947 let diameter_m = self.inputs.bullet_diameter; // already meters
1948 let spin_param = spin_rad_s * diameter_m / (2.0 * velocity_magnitude);
1949 let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
1950 let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
1951 let magnus_force = 0.5
1952 * air_density
1953 * velocity_magnitude.powi(2)
1954 * area
1955 * c_np
1956 * spin_param
1957 * yaw_rad.sin();
1958
1959 // Horizontal direction perpendicular to velocity. In McCoy (RH) frame,
1960 // v_unit × up = +Z (right) for a downrange shot, matching spin-drift sign.
1961 let velocity_unit = relative_velocity / velocity_magnitude;
1962 let up = Vector3::new(0.0, 1.0, 0.0);
1963 let mut dir = velocity_unit.cross(&up);
1964 let dir_norm = dir.norm();
1965 if dir_norm > 1e-12 && magnus_force.abs() > 1e-12 {
1966 dir /= dir_norm;
1967 if !self.inputs.is_twist_right {
1968 dir = -dir;
1969 }
1970 accel += (magnus_force / self.inputs.bullet_mass) * dir;
1971 }
1972 }
1973
1974 accel
1975 }
1976
1977 fn calculate_drag_coefficient(&self, velocity: f64, speed_of_sound: f64) -> f64 {
1978 let mach = velocity / speed_of_sound;
1979
1980 // MBA-940: a user-supplied custom drag table is the final Cd, used as-is — no G-model
1981 // lookup, no transonic shape correction, no form factor. The supplied curve already
1982 // encodes the projectile's true drag, so applying those would distort/double-count it.
1983 if let Some(ref table) = self.inputs.custom_drag_table {
1984 return table.interpolate(mach);
1985 }
1986
1987 // Get drag coefficient from the drag tables (Mach-indexed)
1988 let base_cd = crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type);
1989
1990 // MBA-948: honor use_form_factor here too — previously only derivatives.rs applied it,
1991 // so cli_api and fast_trajectory silently ignored the flag. apply_form_factor_to_drag
1992 // short-circuits when the flag is false, so this is a no-op for every current consumer
1993 // (the flag is false on all CLI/FFI/WASM/binding surfaces and defaults false).
1994 crate::form_factor::apply_form_factor_to_drag(
1995 base_cd,
1996 self.inputs.bullet_model.as_deref(),
1997 &self.inputs.bc_type,
1998 self.inputs.use_form_factor,
1999 )
2000 }
2001}
2002
2003// Monte Carlo parameters
2004#[derive(Debug, Clone)]
2005pub struct MonteCarloParams {
2006 pub num_simulations: usize,
2007 pub velocity_std_dev: f64,
2008 pub angle_std_dev: f64,
2009 pub bc_std_dev: f64,
2010 pub wind_speed_std_dev: f64,
2011 pub target_distance: Option<f64>,
2012 pub base_wind_speed: f64,
2013 pub base_wind_direction: f64,
2014 pub azimuth_std_dev: f64, // Horizontal aiming variation in radians
2015}
2016
2017impl Default for MonteCarloParams {
2018 fn default() -> Self {
2019 Self {
2020 num_simulations: 1000,
2021 velocity_std_dev: 1.0,
2022 angle_std_dev: 0.001,
2023 bc_std_dev: 0.01,
2024 wind_speed_std_dev: 1.0,
2025 target_distance: None,
2026 base_wind_speed: 0.0,
2027 base_wind_direction: 0.0,
2028 azimuth_std_dev: 0.001, // Default horizontal spread ~0.057 degrees
2029 }
2030 }
2031}
2032
2033// Monte Carlo results
2034#[derive(Debug, Clone)]
2035pub struct MonteCarloResults {
2036 pub ranges: Vec<f64>,
2037 pub impact_velocities: Vec<f64>,
2038 pub impact_positions: Vec<Vector3<f64>>,
2039}
2040
2041/// Default hit-zone radius (meters) around the point of aim at the target plane — a 30 cm
2042/// circle. Shared by the CLI, FFI, and WASM so "hit probability" means the same thing everywhere.
2043pub const DEFAULT_HIT_RADIUS_M: f64 = 0.3;
2044
2045impl MonteCarloResults {
2046 /// Fraction of simulations whose impact at the target plane lands within `hit_radius_m`
2047 /// of the point of aim. `impact_positions` are deviations from the baseline at the target
2048 /// plane (the downrange component is 0), so the vector norm is the radial miss distance.
2049 /// Samples that fall short of the target are clamped to their ground impact (a large
2050 /// deviation) and so correctly count as misses. Returns 0.0 when there are no samples.
2051 ///
2052 /// Single source of truth for hit probability — previously the CLI used a range-precision
2053 /// notion and the FFI a position notion with a redundant clause, so they disagreed.
2054 pub fn hit_probability(&self, hit_radius_m: f64) -> f64 {
2055 if self.impact_positions.is_empty() {
2056 return 0.0;
2057 }
2058 let hits = self
2059 .impact_positions
2060 .iter()
2061 .filter(|p| p.norm() < hit_radius_m)
2062 .count();
2063 hits as f64 / self.impact_positions.len() as f64
2064 }
2065}
2066
2067// Run Monte Carlo simulation (backwards compatibility)
2068pub fn run_monte_carlo(
2069 base_inputs: BallisticInputs,
2070 params: MonteCarloParams,
2071) -> Result<MonteCarloResults, BallisticsError> {
2072 let base_wind = WindConditions {
2073 speed: params.base_wind_speed,
2074 direction: params.base_wind_direction,
2075 };
2076 run_monte_carlo_with_wind(base_inputs, base_wind, params)
2077}
2078
2079// Run Monte Carlo simulation with wind
2080pub fn run_monte_carlo_with_wind(
2081 base_inputs: BallisticInputs,
2082 base_wind: WindConditions,
2083 params: MonteCarloParams,
2084) -> Result<MonteCarloResults, BallisticsError> {
2085 use rand_distr::{Distribution, Normal};
2086
2087 let mut rng = rand::rng();
2088 let mut ranges = Vec::new();
2089 let mut impact_velocities = Vec::new();
2090 let mut impact_positions = Vec::new();
2091
2092 let atmosphere = AtmosphericConditions {
2093 temperature: base_inputs.temperature,
2094 pressure: base_inputs.pressure,
2095 humidity: base_inputs.humidity_percent(),
2096 altitude: base_inputs.altitude,
2097 };
2098 let target_hint = params
2099 .target_distance
2100 .unwrap_or(base_inputs.target_distance);
2101 let solver_max_range = target_hint.max(1000.0) * 2.0;
2102
2103 // First, calculate baseline trajectory with no variations
2104 let mut baseline_solver =
2105 TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), atmosphere.clone());
2106 baseline_solver.set_max_range(solver_max_range);
2107 let baseline_result = baseline_solver.solve()?;
2108
2109 // Determine target distance: use explicit target or baseline max range
2110 let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
2111
2112 // Get baseline position at target distance (interpolated)
2113 let baseline_at_target = baseline_result
2114 .position_at_range(target_distance)
2115 .ok_or("Could not interpolate baseline at target distance")?;
2116
2117 // Create normal distributions for variations
2118 let velocity_dist = Normal::new(base_inputs.muzzle_velocity, params.velocity_std_dev)
2119 .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
2120 let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
2121 .map_err(|e| format!("Invalid angle distribution: {}", e))?;
2122 let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
2123 .map_err(|e| format!("Invalid BC distribution: {}", e))?;
2124 let wind_speed_dist = Normal::new(base_wind.speed, params.wind_speed_std_dev)
2125 .map_err(|e| format!("Invalid wind speed distribution: {}", e))?;
2126 // MBA-952: wind-direction spread is APPROXIMATED from the wind-SPEED std dev (×0.1), a unit
2127 // conflation (m/s scaled as radians) — there is no dedicated wind_direction_std_dev field yet.
2128 // The dead WASM `--wind-dir-std` setter was removed (it set nothing). A proper fix is an
2129 // API-breaking wind_direction_std_dev on MonteCarloParams plumbed through WASM/FFI/main.
2130 let wind_dir_dist = Normal::new(base_wind.direction, params.wind_speed_std_dev * 0.1)
2131 .map_err(|e| format!("Invalid wind direction distribution: {}", e))?;
2132 let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
2133 .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
2134
2135 for _ in 0..params.num_simulations {
2136 // Create varied inputs
2137 let mut inputs = base_inputs.clone();
2138 inputs.muzzle_velocity = velocity_dist.sample(&mut rng).max(0.0);
2139 inputs.muzzle_angle = angle_dist.sample(&mut rng);
2140 inputs.bc_value = bc_dist.sample(&mut rng).max(0.01);
2141 inputs.azimuth_angle = azimuth_dist.sample(&mut rng); // Add horizontal variation
2142
2143 // Create varied wind (now based on base wind conditions)
2144 let wind = WindConditions {
2145 speed: wind_speed_dist.sample(&mut rng).abs(),
2146 direction: wind_dir_dist.sample(&mut rng),
2147 };
2148
2149 // Run trajectory
2150 let mut solver = TrajectorySolver::new(inputs, wind, atmosphere.clone());
2151 solver.set_max_range(solver_max_range);
2152 match solver.solve() {
2153 Ok(result) => {
2154 // MBA-967: do NOT skip samples that fall short of the target. range/velocity are
2155 // recorded at GROUND IMPACT for EVERY sample, so "Mean Range" is the ground-impact
2156 // distribution — independent of target_distance and consistent with `trajectory`.
2157 // All three result vectors still grow together per sample, so the equal-length FFI
2158 // ABI (exposed under one count) is preserved.
2159 let deviation = if result.max_range < target_distance {
2160 // This sample never reached the target plane -> definite miss. Keep the
2161 // encoded miss finite but far outside any practical target radius.
2162 Vector3::new(0.0, -1.0e9, 0.0)
2163 } else {
2164 let pos_at_target = match result.position_at_range(target_distance) {
2165 Some(p) => p,
2166 None => continue, // defensive: skip the whole sample (keeps vectors aligned)
2167 };
2168 // Deviation from baseline at the SAME target distance (McCoy): X = downrange
2169 // (0 here), Y = vertical (elevation), Z = lateral (windage). Muzzle-angle
2170 // sampling already models vertical pointing dispersion, so do not add a
2171 // second independent vertical pointing draw here.
2172 Vector3::new(
2173 0.0,
2174 pos_at_target.y - baseline_at_target.y,
2175 pos_at_target.z - baseline_at_target.z,
2176 )
2177 };
2178
2179 ranges.push(result.max_range);
2180 impact_velocities.push(result.impact_velocity);
2181 impact_positions.push(deviation);
2182 }
2183 Err(_) => {
2184 // Skip failed simulations
2185 continue;
2186 }
2187 }
2188 }
2189
2190 if ranges.is_empty() {
2191 return Err("No successful simulations".into());
2192 }
2193
2194 Ok(MonteCarloResults {
2195 ranges,
2196 impact_velocities,
2197 impact_positions,
2198 })
2199}
2200
2201// Calculate zero angle for a target
2202pub fn calculate_zero_angle(
2203 inputs: BallisticInputs,
2204 target_distance: f64,
2205 target_height: f64,
2206) -> Result<f64, BallisticsError> {
2207 calculate_zero_angle_with_conditions(
2208 inputs,
2209 target_distance,
2210 target_height,
2211 WindConditions::default(),
2212 AtmosphericConditions::default(),
2213 )
2214}
2215
2216pub fn calculate_zero_angle_with_conditions(
2217 inputs: BallisticInputs,
2218 target_distance: f64,
2219 target_height: f64,
2220 wind: WindConditions,
2221 atmosphere: AtmosphericConditions,
2222) -> Result<f64, BallisticsError> {
2223 // Helper function to get height at target distance for a given angle
2224 let get_height_at_angle = |angle: f64| -> Result<Option<f64>, BallisticsError> {
2225 let mut test_inputs = inputs.clone();
2226 test_inputs.muzzle_angle = angle;
2227 // MBA-959: zero on the bare bore. Aerodynamic jump is a constant elevation
2228 // offset, so leaving it on here would let the zero search silently absorb the
2229 // vertical jump. Disabling it makes AJ an additive POI shift relative to the
2230 // no-jump zero, regardless of the conditions the caller zeroes in.
2231 test_inputs.enable_aerodynamic_jump = false;
2232
2233 let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
2234 solver.set_max_range(target_distance * 2.0);
2235 solver.set_time_step(0.001);
2236 let result = solver.solve()?;
2237
2238 // X is downrange in McCoy coordinates
2239 for i in 0..result.points.len() {
2240 if result.points[i].position.x >= target_distance {
2241 if i > 0 {
2242 let p1 = &result.points[i - 1];
2243 let p2 = &result.points[i];
2244 let t = (target_distance - p1.position.x) / (p2.position.x - p1.position.x);
2245 return Ok(Some(p1.position.y + t * (p2.position.y - p1.position.y)));
2246 } else {
2247 return Ok(Some(result.points[i].position.y));
2248 }
2249 }
2250 }
2251 Ok(None)
2252 };
2253
2254 // Binary search for the angle that hits the target
2255 // Use only positive angles to ensure proper ballistic arc (upward trajectory)
2256 let mut low_angle = 0.0; // radians (horizontal)
2257 let mut high_angle = 0.2; // radians (about 11 degrees)
2258 let tolerance = 1e-7; // radians
2259 let max_iterations = 60;
2260
2261 // MBA-194: Validate bracketing before starting binary search
2262 // Check that the target height is actually between low and high angle trajectories
2263 let low_height = get_height_at_angle(low_angle)?;
2264 let high_height = get_height_at_angle(high_angle)?;
2265
2266 match (low_height, high_height) {
2267 (Some(lh), Some(hh)) => {
2268 let low_error = lh - target_height;
2269 let high_error = hh - target_height;
2270
2271 // For proper bracketing, low angle should undershoot (negative error)
2272 // and high angle should overshoot (positive error)
2273 if low_error > 0.0 && high_error > 0.0 {
2274 // Both angles overshoot - target is too close or height too low
2275 // This shouldn't happen for typical zeroing, but handle gracefully
2276 // Try to find a valid bracket by reducing low_angle (can't go negative)
2277 // Since we can't go below 0, just proceed and let binary search find best
2278 } else if low_error < 0.0 && high_error < 0.0 {
2279 // Both angles undershoot - target is beyond effective range
2280 // Try expanding high_angle up to 45 degrees (0.785 rad)
2281 let mut expanded = false;
2282 for multiplier in [2.0, 3.0, 4.0] {
2283 let new_high = (high_angle * multiplier).min(0.785);
2284 if let Ok(Some(h)) = get_height_at_angle(new_high) {
2285 if h - target_height > 0.0 {
2286 high_angle = new_high;
2287 expanded = true;
2288 break;
2289 }
2290 }
2291 if new_high >= 0.785 {
2292 break;
2293 }
2294 }
2295 if !expanded {
2296 return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
2297 }
2298 }
2299 // If signs are opposite, we have valid bracketing - proceed
2300 }
2301 (None, Some(_hh)) => {
2302 // Low angle doesn't reach target, high does - this is fine
2303 // Binary search will increase low_angle until trajectory reaches
2304 }
2305 (Some(_lh), None) => {
2306 // High angle doesn't reach target - shouldn't happen
2307 return Err(
2308 "Cannot find zero angle: high angle trajectory doesn't reach target distance"
2309 .into(),
2310 );
2311 }
2312 (None, None) => {
2313 // Neither reaches target - target too far
2314 return Err(
2315 "Cannot find zero angle: trajectory cannot reach target distance at any angle"
2316 .into(),
2317 );
2318 }
2319 }
2320
2321 for _iteration in 0..max_iterations {
2322 let mid_angle = (low_angle + high_angle) / 2.0;
2323
2324 let mut test_inputs = inputs.clone();
2325 test_inputs.muzzle_angle = mid_angle;
2326 // MBA-959: zero on the bare bore so aerodynamic jump is not absorbed (see above).
2327 test_inputs.enable_aerodynamic_jump = false;
2328
2329 let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
2330 // Make sure we calculate far enough to reach the target
2331 solver.set_max_range(target_distance * 2.0);
2332 solver.set_time_step(0.001);
2333 let result = solver.solve()?;
2334
2335 // Find the height at target distance (X is downrange)
2336 let mut height_at_target = None;
2337 for i in 0..result.points.len() {
2338 if result.points[i].position.x >= target_distance {
2339 if i > 0 {
2340 // Linear interpolation
2341 let p1 = &result.points[i - 1];
2342 let p2 = &result.points[i];
2343 let t = (target_distance - p1.position.x) / (p2.position.x - p1.position.x);
2344 height_at_target = Some(p1.position.y + t * (p2.position.y - p1.position.y));
2345 } else {
2346 height_at_target = Some(result.points[i].position.y);
2347 }
2348 break;
2349 }
2350 }
2351
2352 match height_at_target {
2353 Some(height) => {
2354 let error = height - target_height;
2355 // MBA-193: Check height error FIRST (primary convergence criterion)
2356 // Height accuracy is what matters for zeroing - angle tolerance is secondary.
2357 // 0.0001 m (0.1 mm) at the zero distance: fine enough that the (small)
2358 // zero-day atmosphere effect on a short zero still resolves the zero angle
2359 // instead of quantizing two very different atmospheres to an identical angle.
2360 if error.abs() < 0.0001 {
2361 return Ok(mid_angle);
2362 }
2363
2364 // Only use angle tolerance as convergence criterion if we have
2365 // exhausted angle precision AND height error is still acceptable
2366 // (within 10mm which is reasonable for long range)
2367 if (high_angle - low_angle).abs() < tolerance {
2368 if error.abs() < 0.01 {
2369 // Height error within 10mm - acceptable for practical use
2370 return Ok(mid_angle);
2371 }
2372 // Angle bracket collapsed but the height error is still too large: the
2373 // target is not actually reachable / was never bracketed. Returning
2374 // Ok(mid_angle) here reported a NOT-zeroed angle as success (callers use
2375 // it directly as muzzle_angle); surface it as an error instead.
2376 return Err("Zero angle did not converge: residual height error too large (target not reachable / not bracketed)".into());
2377 }
2378
2379 if error > 0.0 {
2380 high_angle = mid_angle;
2381 } else {
2382 low_angle = mid_angle;
2383 }
2384 }
2385 None => {
2386 // Trajectory didn't reach target distance, increase angle
2387 low_angle = mid_angle;
2388
2389 // MBA-193: Check angle tolerance for None case too
2390 if (high_angle - low_angle).abs() < tolerance {
2391 return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
2392 }
2393 }
2394 }
2395 }
2396
2397 Err("Failed to find zero angle".into())
2398}
2399
2400/// What a BC estimate is fit against.
2401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2402pub enum BcFitMode {
2403 /// Data points are `(distance_m, drop_m)` — the classic drop-curve fit.
2404 Drop,
2405 /// Data points are `(distance_m, velocity_mps)` — a velocity-retention fit,
2406 /// which is immune to zero / sight-height / launch-angle error.
2407 Velocity,
2408}
2409
2410/// The result of a single BC fit (one drag model, one fit basis).
2411#[derive(Debug, Clone, Copy)]
2412pub struct BcEstimate {
2413 /// The estimated ballistic coefficient.
2414 pub bc: f64,
2415 /// RMS residual across the data points, in fit units (meters of drop, or m/s of speed).
2416 pub rms_error: f64,
2417 /// Which standard drag model this BC is referenced to.
2418 pub drag_model: DragModel,
2419 /// Whether the fit was against drop or velocity data.
2420 pub mode: BcFitMode,
2421 /// True if the best fit landed at the edge of the physical BC search range — i.e. the
2422 /// data did not pin down an interior optimum (too sparse/short-range, or wrong units /
2423 /// atmosphere / zero). The reported `bc` is then a floor/ceiling, not a real estimate.
2424 pub at_bound: bool,
2425}
2426
2427/// Interpolate the fitted quantity (drop in meters, or speed in m/s) at a downrange
2428/// distance from a solved trajectory. `None` if the trajectory never reaches `target_dist`.
2429///
2430/// `drop_offset` is subtracted-from convention: for `Drop` the returned value is
2431/// `drop_offset - y`. With `drop_offset = 0` this is bore-referenced drop (flat fire);
2432/// with `drop_offset = sight_height` and a zeroed trajectory it is drop below the
2433/// (horizontal) line of sight — i.e. dope-card drop.
2434fn fit_value_at(
2435 points: &[TrajectoryPoint],
2436 target_dist: f64,
2437 mode: BcFitMode,
2438 drop_offset: f64,
2439) -> Option<f64> {
2440 let val = |p: &TrajectoryPoint| match mode {
2441 BcFitMode::Drop => drop_offset - p.position.y,
2442 BcFitMode::Velocity => p.velocity_magnitude,
2443 };
2444 for i in 0..points.len() {
2445 if points[i].position.x >= target_dist {
2446 if i == 0 {
2447 return Some(val(&points[0]));
2448 }
2449 let p1 = &points[i - 1];
2450 let p2 = &points[i];
2451 let dx = p2.position.x - p1.position.x;
2452 if dx.abs() < 1e-9 {
2453 return Some(val(p2));
2454 }
2455 let t = (target_dist - p1.position.x) / dx;
2456 return Some(val(p1) + t * (val(p2) - val(p1)));
2457 }
2458 }
2459 None
2460}
2461
2462/// Estimate a BC by fitting a simulated trajectory to measured data, for a chosen drag
2463/// model (G1, G7, …) and fit basis (drop or velocity). Uses a coarse 0.01 sweep over
2464/// plausible BCs followed by a 0.001 local refine around the coarse best.
2465///
2466/// `points` are `(distance_m, value_m_or_mps)` where the second element is drop in meters
2467/// (`BcFitMode::Drop`) or remaining speed in m/s (`BcFitMode::Velocity`).
2468///
2469/// The fit runs under `atmosphere` — BC is only meaningful relative to the air density the
2470/// data was measured at, so this must match the conditions the drop/velocity came from
2471/// (pass ICAO standard for a standard-atmosphere dope card).
2472///
2473/// `zero_range` selects the drop reference frame (ignored for velocity fits):
2474/// - `None` → **bore-referenced**: flat 0° fire, drop below the extended bore axis.
2475/// - `Some(range_m)` → **sight/dope-card-referenced**: the trajectory is zeroed at
2476/// `range_m` (using `sight_height`), and drop is measured below the horizontal line of
2477/// sight — i.e. exactly what a dope card zeroed at that range prints.
2478pub fn estimate_bc_fit(
2479 velocity: f64,
2480 mass: f64,
2481 diameter: f64,
2482 points: &[(f64, f64)],
2483 drag_model: DragModel,
2484 mode: BcFitMode,
2485 atmosphere: AtmosphericConditions,
2486 zero_range: Option<f64>,
2487 sight_height: f64,
2488) -> Result<BcEstimate, BallisticsError> {
2489 if points.is_empty() {
2490 return Err(BallisticsError::from(
2491 "No data points provided for BC estimation.".to_string(),
2492 ));
2493 }
2494 let max_dist = points.iter().map(|(d, _)| *d).fold(0.0_f64, f64::max);
2495 // For a zeroed drop fit, drop is below the horizontal LOS which sits `sight_height`
2496 // above the bore at the muzzle: drop = sight_height - y. Bore-referenced fits use 0.
2497 let drop_offset = if zero_range.is_some() { sight_height } else { 0.0 };
2498
2499 // Sum of squared residuals for a trial BC; None if the solve can't reach the data.
2500 let sse = |bc_value: f64| -> Option<f64> {
2501 let mut inputs = BallisticInputs {
2502 muzzle_velocity: velocity,
2503 bc_value,
2504 bc_type: drag_model,
2505 bullet_mass: mass,
2506 bullet_diameter: diameter,
2507 sight_height,
2508 ..Default::default()
2509 };
2510 // Zeroed fit: tilt the bore so the bullet crosses LOS at the zero range, so the
2511 // downrange drops match a dope card zeroed there. Bore fit leaves muzzle_angle = 0.
2512 if let Some(zr) = zero_range {
2513 // MBA-1130: zero to the LINE OF SIGHT (y = sight_height) at the zero range,
2514 // not the bore line (y = 0). Drop is measured as `drop_offset - y` with
2515 // drop_offset = sight_height, so a bore-referenced zero left drop != 0 at the
2516 // zero range and the drop-fit no longer round-tripped to the true BC. This
2517 // matches how range-table / come-up / dope-card generation zero.
2518 let za = calculate_zero_angle_with_conditions(
2519 inputs.clone(),
2520 zr,
2521 sight_height,
2522 WindConditions::default(),
2523 atmosphere.clone(),
2524 )
2525 .ok()?;
2526 inputs.muzzle_angle = za;
2527 }
2528 let mut solver =
2529 TrajectorySolver::new(inputs, WindConditions::default(), atmosphere.clone());
2530 solver.set_max_range(max_dist * 1.5);
2531 let result = solver.solve().ok()?;
2532 let mut total = 0.0;
2533 let mut matched = 0;
2534 for (target_dist, target_val) in points {
2535 if let Some(v) = fit_value_at(&result.points, *target_dist, mode, drop_offset) {
2536 let e = v - target_val;
2537 total += e * e;
2538 matched += 1;
2539 }
2540 }
2541 if matched == 0 {
2542 None
2543 } else {
2544 Some(total)
2545 }
2546 };
2547
2548 // Physical BC search range, per drag model. Real G7 BCs top out well under 0.5 (0.7 is
2549 // a generous ceiling); G1 BCs run higher. Keeping G7 out of G1 territory means a fit
2550 // that runs to the ceiling reports a sane bound, not a nonsensical 1.2.
2551 let (bc_min, bc_max) = match drag_model {
2552 DragModel::G7 => (0.05, 0.70),
2553 _ => (0.10, 1.20),
2554 };
2555
2556 // Coarse sweep across the physical range.
2557 let mut best_bc = f64::NAN;
2558 let mut best_sse = f64::MAX;
2559 let mut bc = bc_min;
2560 while bc <= bc_max + 1e-9 {
2561 if let Some(s) = sse(bc) {
2562 if s < best_sse {
2563 best_sse = s;
2564 best_bc = bc;
2565 }
2566 }
2567 bc += 0.01;
2568 }
2569 if !best_bc.is_finite() {
2570 return Err(BallisticsError::from(
2571 "Unable to estimate BC from provided data. Check that the values and units are correct."
2572 .to_string(),
2573 ));
2574 }
2575
2576 // Local refine at 0.001 resolution around the coarse best (kept within the range).
2577 let lo = (best_bc - 0.01).max(bc_min);
2578 let hi = (best_bc + 0.01).min(bc_max);
2579 let mut bc = lo;
2580 while bc <= hi + 1e-9 {
2581 if let Some(s) = sse(bc) {
2582 if s < best_sse {
2583 best_sse = s;
2584 best_bc = bc;
2585 }
2586 }
2587 bc += 0.001;
2588 }
2589
2590 // A solution sitting on the search boundary means the data didn't determine an interior
2591 // optimum — the fit ran to the floor/ceiling. Flag it so callers don't trust the number.
2592 let at_bound = best_bc <= bc_min + 0.011 || best_bc >= bc_max - 0.011;
2593 let rms_error = (best_sse / points.len() as f64).sqrt();
2594 Ok(BcEstimate {
2595 bc: best_bc,
2596 rms_error,
2597 drag_model,
2598 mode,
2599 at_bound,
2600 })
2601}
2602
2603/// Estimate a G1 BC from a drop curve. Back-compatible wrapper over [`estimate_bc_fit`];
2604/// `points` are `(distance_m, drop_m)`.
2605pub fn estimate_bc_from_trajectory(
2606 velocity: f64,
2607 mass: f64,
2608 diameter: f64,
2609 points: &[(f64, f64)], // (distance, drop) pairs
2610) -> Result<f64, BallisticsError> {
2611 estimate_bc_fit(
2612 velocity,
2613 mass,
2614 diameter,
2615 points,
2616 DragModel::G1,
2617 BcFitMode::Drop,
2618 AtmosphericConditions::default(),
2619 None,
2620 0.05,
2621 )
2622 .map(|e| e.bc)
2623}
2624
2625// Add rand dependencies for Monte Carlo
2626use rand;
2627use rand_distr;
2628
2629#[cfg(test)]
2630mod ground_termination_tests {
2631 use super::*;
2632
2633 // Regression lock for the unified ground termination: solve_euler/solve_rk4/solve_rk45 all
2634 // loop while `position.y > ground_threshold` (default -100.0), so they agree with RK45. A
2635 // lofted shot that returns to launch level before reaching max_range must keep descending to
2636 // the -100 m floor instead of stopping at y = 0 — and RK4-fixed and RK45 must behave the same.
2637 #[test]
2638 fn rk4_and_rk45_descend_to_ground_threshold() {
2639 for adaptive in [false, true] {
2640 let mut inputs = BallisticInputs::default();
2641 inputs.muzzle_angle = 0.1; // ~5.7 deg: arcs up, then descends past launch level
2642 inputs.use_rk4 = true;
2643 inputs.use_adaptive_rk45 = adaptive;
2644 assert_eq!(
2645 inputs.ground_threshold, -100.0,
2646 "default ground_threshold is -100 m"
2647 );
2648
2649 let mut solver = TrajectorySolver::new(
2650 inputs,
2651 WindConditions::default(),
2652 AtmosphericConditions::default(),
2653 );
2654 // Huge max range: termination must be driven by ground_threshold, not the range cap.
2655 solver.set_max_range(1.0e7);
2656
2657 let result = solver.solve().expect("solve should succeed");
2658 let final_y = result
2659 .points
2660 .last()
2661 .expect("trajectory has points")
2662 .position
2663 .y;
2664 assert!(
2665 final_y < -1.0,
2666 "adaptive_rk45={adaptive}: final y = {final_y} m; a lofted shot should descend \
2667 past launch level toward the ground_threshold floor, not stop at y = 0"
2668 );
2669 }
2670 }
2671}
2672
2673#[cfg(test)]
2674mod coriolis_direction_tests {
2675 use super::*;
2676 use std::f64::consts::FRAC_PI_2;
2677
2678 #[test]
2679 fn transonic_crossing_flags_a_sampled_point() {
2680 // A supersonic shot that slows past Mach 1 must flag a sampled point as a Mach
2681 // transition. The underlying transonic_distances were a Vec::new() TODO, so this
2682 // flag was NEVER set regardless of trajectory — this is the regression guard.
2683 use crate::trajectory_sampling::TrajectoryFlag;
2684 let mut inputs = BallisticInputs::default();
2685 inputs.muzzle_velocity = 850.0; // ~2790 fps, well supersonic
2686 inputs.bc_value = 0.2; // low BC -> slows past Mach 1 within range
2687 inputs.bc_type = DragModel::G7;
2688 inputs.muzzle_angle = 0.03;
2689 inputs.enable_trajectory_sampling = true;
2690 inputs.sample_interval = 50.0;
2691 let mut solver = TrajectorySolver::new(
2692 inputs,
2693 WindConditions::default(),
2694 AtmosphericConditions::default(),
2695 );
2696 solver.set_max_range(2000.0);
2697 let r = solver.solve().expect("solve");
2698 let samples = r
2699 .sampled_points
2700 .expect("sampling enabled -> sampled_points present");
2701 assert!(
2702 samples
2703 .iter()
2704 .any(|s| s.flags.contains(&TrajectoryFlag::MachTransition)),
2705 "a shot that crosses Mach 1 must flag at least one Mach-transition sample"
2706 );
2707 }
2708
2709 #[test]
2710 fn humidity_percent_converts_and_clamps() {
2711 // MBA-722: BallisticInputs.humidity is a 0-1 fraction; the helper yields 0-100 percent.
2712 let mut i = BallisticInputs::default();
2713 i.humidity = 0.5;
2714 assert!((i.humidity_percent() - 50.0).abs() < 1e-9, "0.5 -> 50%");
2715 i.humidity = 0.0;
2716 assert_eq!(i.humidity_percent(), 0.0);
2717 i.humidity = 1.0;
2718 assert_eq!(i.humidity_percent(), 100.0);
2719 i.humidity = 1.5; // out of range -> clamped, never > 100
2720 assert_eq!(i.humidity_percent(), 100.0);
2721 }
2722
2723 /// Vertical position (m) at a given downrange `range_m`, for a shot fired along
2724 /// compass bearing `shot_azimuth` (radians, 0=N) with Coriolis enabled.
2725 fn vertical_at(shot_azimuth: f64, range_m: f64) -> f64 {
2726 let mut inputs = BallisticInputs::default();
2727 inputs.muzzle_velocity = 800.0;
2728 inputs.bc_value = 0.5;
2729 inputs.bc_type = DragModel::G7;
2730 inputs.muzzle_angle = 0.02; // ~20 mrad so it carries well past range_m
2731 inputs.enable_coriolis = true;
2732 inputs.latitude = Some(45.0);
2733 inputs.shot_azimuth = shot_azimuth;
2734 inputs.ground_threshold = f64::NEG_INFINITY; // never terminate early
2735 let mut solver = TrajectorySolver::new(
2736 inputs,
2737 WindConditions::default(),
2738 AtmosphericConditions::default(),
2739 );
2740 solver.set_max_range(range_m + 50.0);
2741 let r = solver.solve().expect("solve");
2742 let pts = &r.points;
2743 for i in 1..pts.len() {
2744 if pts[i].position.x >= range_m {
2745 let p1 = &pts[i - 1];
2746 let p2 = &pts[i];
2747 let t = (range_m - p1.position.x) / (p2.position.x - p1.position.x);
2748 return p1.position.y + t * (p2.position.y - p1.position.y);
2749 }
2750 }
2751 panic!("range {range_m} not reached");
2752 }
2753
2754 /// Regression for the shot-direction Coriolis bug: the Eötvös vertical term
2755 /// `a_up = +2Ω cosφ v_east` lifts an EAST shot and depresses a WEST shot, so at a
2756 /// common range east must sit HIGHER than west, with north in between. Before the
2757 /// fix, `--shot-direction` never reached the solver and E/W/N were identical.
2758 #[test]
2759 fn eotvos_east_higher_than_west() {
2760 let range = 600.0;
2761 let east = vertical_at(FRAC_PI_2, range); // 90° E
2762 let west = vertical_at(3.0 * FRAC_PI_2, range); // 270° W
2763 let north = vertical_at(0.0, range); // 0° N
2764 assert!(
2765 east > west,
2766 "east ({east:.5}) must be higher than west ({west:.5}) at {range} m (Eötvös)"
2767 );
2768 assert!(
2769 east > north && north > west,
2770 "north ({north:.5}) must lie between east ({east:.5}) and west ({west:.5})"
2771 );
2772 assert!(
2773 (east - west) > 1e-3,
2774 "E-W vertical separation ({:.6} m) should be physically meaningful, not FP noise",
2775 east - west
2776 );
2777 }
2778}