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::transonic_drag::{get_projectile_shape, transonic_correction, ProjectileShape};
11use crate::wind_shear::{WindLayer, WindShearModel, WindShearProfile};
12use crate::DragModel;
13use nalgebra::Vector3;
14use std::error::Error;
15use std::fmt;
16
17// Unit system for input/output
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub enum UnitSystem {
20    Imperial,
21    Metric,
22}
23
24// Output format for results
25#[derive(Debug, Clone, Copy, PartialEq)]
26pub enum OutputFormat {
27    Table,
28    Json,
29    Csv,
30}
31
32// Error type for CLI operations
33#[derive(Debug)]
34pub struct BallisticsError {
35    message: String,
36}
37
38impl fmt::Display for BallisticsError {
39    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40        write!(f, "{}", self.message)
41    }
42}
43
44impl Error for BallisticsError {}
45
46impl From<String> for BallisticsError {
47    fn from(msg: String) -> Self {
48        BallisticsError { message: msg }
49    }
50}
51
52impl From<&str> for BallisticsError {
53    fn from(msg: &str) -> Self {
54        BallisticsError {
55            message: msg.to_string(),
56        }
57    }
58}
59
60// Ballistic input parameters - MBA-151 Reconciled Structure
61// Unified structure used by both ballistics-engine and ballistics_rust
62// Duplicates removed, all necessary fields included
63#[derive(Debug, Clone)]
64pub struct BallisticInputs {
65    // Core ballistics parameters (using intuitive names)
66    pub bc_value: f64,        // Ballistic coefficient (G1, G7, etc.)
67    pub bc_type: DragModel,   // Drag model (G1, G7, G8, etc.)
68    pub bullet_mass: f64,     // kg
69    pub muzzle_velocity: f64, // m/s
70    pub bullet_diameter: f64, // meters
71    pub bullet_length: f64,   // meters
72
73    // Targeting and positioning
74    pub muzzle_angle: f64,     // radians (launch angle)
75    pub target_distance: f64,  // meters
76    pub azimuth_angle: f64,    // horizontal aiming angle in radians
77    pub shooting_angle: f64,   // uphill/downhill angle in radians
78    pub sight_height: f64,     // meters above bore
79    pub muzzle_height: f64,    // meters above ground
80    pub target_height: f64,    // meters above ground for zeroing
81    pub ground_threshold: f64, // meters below which to stop
82
83    // Environmental conditions
84    pub altitude: f64,         // meters
85    pub temperature: f64,      // Celsius
86    pub pressure: f64,         // millibars/hPa
87    pub humidity: f64,         // relative humidity (0-1)
88    pub latitude: Option<f64>, // degrees
89
90    // Wind conditions
91    pub wind_speed: f64, // m/s
92    pub wind_angle: f64, // radians (0=headwind, 90=from right)
93
94    // Bullet characteristics
95    pub twist_rate: f64,               // inches per turn
96    pub is_twist_right: bool,          // right-hand twist
97    pub caliber_inches: f64,           // diameter in inches
98    pub weight_grains: f64,            // mass in grains
99    pub manufacturer: Option<String>,  // Bullet manufacturer
100    pub bullet_model: Option<String>,  // Bullet model name
101    pub bullet_id: Option<String>,     // Unique bullet identifier
102    pub bullet_cluster: Option<usize>, // BC cluster ID for cluster_bc module
103
104    // Integration method selection
105    pub use_rk4: bool,           // Use RK4 integration instead of Euler
106    pub use_adaptive_rk45: bool, // Use RK45 adaptive step size integration
107
108    // Advanced effects flags
109    pub enable_advanced_effects: bool,
110    pub use_powder_sensitivity: bool,
111    pub powder_temp_sensitivity: f64,
112    pub powder_temp: f64,           // Celsius
113    pub tipoff_yaw: f64,            // radians
114    pub tipoff_decay_distance: f64, // meters
115    pub use_bc_segments: bool,
116    pub bc_segments: Option<Vec<(f64, f64)>>, // Mach-BC pairs
117    pub bc_segments_data: Option<Vec<crate::BCSegmentData>>, // Velocity-BC segments
118    pub use_enhanced_spin_drift: bool,
119    pub use_form_factor: bool,
120    pub enable_wind_shear: bool,
121    pub wind_shear_model: String,
122    pub enable_trajectory_sampling: bool,
123    pub sample_interval: f64, // meters
124    pub enable_pitch_damping: bool,
125    pub enable_precession_nutation: bool,
126    pub use_cluster_bc: bool, // Use cluster-based BC degradation
127
128    // Custom drag model support
129    pub custom_drag_table: Option<crate::drag::DragTable>,
130
131    // Legacy field for compatibility
132    pub bc_type_str: Option<String>,
133}
134
135impl Default for BallisticInputs {
136    fn default() -> Self {
137        let mass_kg = 0.01;
138        let diameter_m = 0.00762;
139        let bc = 0.5;
140        let muzzle_angle_rad = 0.0;
141        let bc_type = DragModel::G1;
142
143        Self {
144            // Core ballistics parameters
145            bc_value: bc,
146            bc_type,
147            bullet_mass: mass_kg,
148            muzzle_velocity: 800.0,
149            bullet_diameter: diameter_m,
150            bullet_length: diameter_m * 4.0, // Approximate
151
152            // Targeting and positioning
153            muzzle_angle: muzzle_angle_rad,
154            target_distance: 100.0,
155            azimuth_angle: 0.0,
156            shooting_angle: 0.0,
157            sight_height: 0.05,
158            muzzle_height: 0.0,       // Default 0 - height is in sight_height
159            target_height: 0.0,       // Target at ground level by default
160            ground_threshold: -100.0, // Effectively disable ground detection (allow bullet to drop 100m below start)
161
162            // Environmental conditions
163            altitude: 0.0,
164            temperature: 15.0,
165            pressure: 1013.25, // Standard sea level pressure (millibars)
166            humidity: 0.5,     // 50% relative humidity
167            latitude: None,
168
169            // Wind conditions
170            wind_speed: 0.0,
171            wind_angle: 0.0,
172
173            // Bullet characteristics
174            twist_rate: 12.0, // 1:12" typical
175            is_twist_right: true,
176            caliber_inches: diameter_m / 0.0254, // Convert to inches
177            weight_grains: mass_kg / 0.00006479891, // Convert to grains
178            manufacturer: None,
179            bullet_model: None,
180            bullet_id: None,
181            bullet_cluster: None,
182
183            // Integration method selection
184            use_rk4: true,           // Use Runge-Kutta methods by default
185            use_adaptive_rk45: true, // Default to RK45 adaptive for best accuracy
186
187            // Advanced effects (disabled by default)
188            enable_advanced_effects: false,
189            use_powder_sensitivity: false,
190            powder_temp_sensitivity: 0.0,
191            powder_temp: 15.0,
192            tipoff_yaw: 0.0,
193            tipoff_decay_distance: 50.0,
194            use_bc_segments: false,
195            bc_segments: None,
196            bc_segments_data: None,
197            use_enhanced_spin_drift: false,
198            use_form_factor: false,
199            enable_wind_shear: false,
200            wind_shear_model: "none".to_string(),
201            enable_trajectory_sampling: false,
202            sample_interval: 10.0, // Default 10 meter intervals
203            enable_pitch_damping: false,
204            enable_precession_nutation: false,
205            use_cluster_bc: false, // Disabled by default for backward compatibility
206
207            // Custom drag model support
208            custom_drag_table: None,
209
210            // Legacy field for compatibility
211            bc_type_str: None,
212        }
213    }
214}
215
216// Wind conditions
217#[derive(Debug, Clone)]
218pub struct WindConditions {
219    pub speed: f64,     // m/s
220    pub direction: f64, // radians (0 = North, PI/2 = East)
221}
222
223impl Default for WindConditions {
224    fn default() -> Self {
225        Self {
226            speed: 0.0,
227            direction: 0.0,
228        }
229    }
230}
231
232// Atmospheric conditions
233#[derive(Debug, Clone)]
234pub struct AtmosphericConditions {
235    pub temperature: f64, // Celsius
236    pub pressure: f64,    // hPa
237    pub humidity: f64,    // percentage (0-100)
238    pub altitude: f64,    // meters
239}
240
241impl Default for AtmosphericConditions {
242    fn default() -> Self {
243        Self {
244            temperature: 15.0,
245            pressure: 1013.25,
246            humidity: 50.0,
247            altitude: 0.0,
248        }
249    }
250}
251
252// Trajectory point data
253#[derive(Debug, Clone)]
254pub struct TrajectoryPoint {
255    pub time: f64,
256    pub position: Vector3<f64>,
257    pub velocity_magnitude: f64,
258    pub kinetic_energy: f64,
259}
260
261// Trajectory result
262#[derive(Debug, Clone)]
263pub struct TrajectoryResult {
264    pub max_range: f64,
265    pub max_height: f64,
266    pub time_of_flight: f64,
267    pub impact_velocity: f64,
268    pub impact_energy: f64,
269    pub points: Vec<TrajectoryPoint>,
270    pub sampled_points: Option<Vec<TrajectorySample>>, // Trajectory samples at regular intervals
271    pub min_pitch_damping: Option<f64>, // Minimum pitch damping coefficient (for stability warning)
272    pub transonic_mach: Option<f64>,    // Mach number when entering transonic regime
273    pub angular_state: Option<AngularState>, // Final angular state if precession/nutation enabled
274    pub max_yaw_angle: Option<f64>,     // Maximum yaw angle during flight (radians)
275    pub max_precession_angle: Option<f64>, // Maximum precession angle (radians)
276}
277
278impl TrajectoryResult {
279    /// Interpolate position at a given downrange distance (Z coordinate).
280    /// Returns the interpolated (x, y, z) position at that range.
281    /// If the target range exceeds the trajectory, returns the last point.
282    pub fn position_at_range(&self, target_range: f64) -> Option<Vector3<f64>> {
283        if self.points.is_empty() {
284            return None;
285        }
286
287        // Find the two points that bracket the target range
288        for i in 0..self.points.len() - 1 {
289            let p1 = &self.points[i];
290            let p2 = &self.points[i + 1];
291
292            // Check if target range is between these two points
293            if p1.position.z <= target_range && p2.position.z >= target_range {
294                // Linear interpolation factor
295                let dz = p2.position.z - p1.position.z;
296                if dz.abs() < 1e-10 {
297                    return Some(p1.position);
298                }
299                let t = (target_range - p1.position.z) / dz;
300
301                // Interpolate X and Y, use exact target_range for Z
302                return Some(Vector3::new(
303                    p1.position.x + t * (p2.position.x - p1.position.x),
304                    p1.position.y + t * (p2.position.y - p1.position.y),
305                    target_range,
306                ));
307            }
308        }
309
310        // Target range is beyond trajectory - return last point
311        self.points.last().map(|p| p.position)
312    }
313}
314
315// Trajectory solver
316pub struct TrajectorySolver {
317    inputs: BallisticInputs,
318    wind: WindConditions,
319    atmosphere: AtmosphericConditions,
320    max_range: f64,
321    time_step: f64,
322    cluster_bc: Option<ClusterBCDegradation>,
323}
324
325impl TrajectorySolver {
326    pub fn new(
327        mut inputs: BallisticInputs,
328        wind: WindConditions,
329        atmosphere: AtmosphericConditions,
330    ) -> Self {
331        // Compute derived fields from base units
332        inputs.caliber_inches = inputs.bullet_diameter / 0.0254;
333        inputs.weight_grains = inputs.bullet_mass / 0.00006479891;
334
335        // Initialize cluster BC if enabled
336        let cluster_bc = if inputs.use_cluster_bc {
337            Some(ClusterBCDegradation::new())
338        } else {
339            None
340        };
341
342        Self {
343            inputs,
344            wind,
345            atmosphere,
346            max_range: 1000.0,
347            time_step: 0.001,
348            cluster_bc,
349        }
350    }
351
352    pub fn set_max_range(&mut self, range: f64) {
353        self.max_range = range;
354    }
355
356    pub fn set_time_step(&mut self, step: f64) {
357        self.time_step = step;
358    }
359
360    fn get_wind_at_altitude(&self, altitude_m: f64) -> Vector3<f64> {
361        // Create wind shear profile based on surface wind
362        let profile = WindShearProfile {
363            model: if self.inputs.wind_shear_model == "logarithmic" {
364                WindShearModel::Logarithmic
365            } else if self.inputs.wind_shear_model == "power" {
366                WindShearModel::PowerLaw
367            } else {
368                WindShearModel::PowerLaw // Default to power law
369            },
370            surface_wind: WindLayer {
371                altitude_m: 0.0,
372                speed_mps: self.wind.speed,
373                direction_deg: self.wind.direction.to_degrees(),
374            },
375            reference_height: 10.0, // Standard meteorological measurement height
376            roughness_length: 0.03, // Short grass
377            power_exponent: 1.0 / 7.0, // Neutral stability
378            geostrophic_wind: None,
379            custom_layers: Vec::new(),
380        };
381
382        profile.get_wind_at_altitude(altitude_m)
383    }
384
385    pub fn solve(&self) -> Result<TrajectoryResult, BallisticsError> {
386        if self.inputs.use_rk4 {
387            if self.inputs.use_adaptive_rk45 {
388                self.solve_rk45()
389            } else {
390                self.solve_rk4()
391            }
392        } else {
393            self.solve_euler()
394        }
395    }
396
397    fn solve_euler(&self) -> Result<TrajectoryResult, BallisticsError> {
398        // Simple trajectory integration using Euler method
399        let mut time = 0.0;
400        let mut position = Vector3::new(
401            0.0,
402            self.inputs.sight_height + self.inputs.muzzle_height,
403            0.0,
404        );
405        // Calculate initial velocity components with both elevation and azimuth
406        // Standard ballistics coordinate system: X=lateral, Y=vertical, Z=downrange
407        let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
408        let mut velocity = Vector3::new(
409            horizontal_velocity * self.inputs.azimuth_angle.sin(), // X: lateral (side deviation)
410            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
411            horizontal_velocity * self.inputs.azimuth_angle.cos(), // Z: downrange (forward)
412        );
413
414        let mut points = Vec::new();
415        let mut max_height = position.y;
416        let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
417        let mut transonic_mach = None; // Track when we enter transonic
418
419        // Initialize angular state for precession/nutation tracking
420        let mut angular_state = if self.inputs.enable_precession_nutation {
421            Some(AngularState {
422                pitch_angle: 0.001, // Small initial disturbance
423                yaw_angle: 0.001,
424                pitch_rate: 0.0,
425                yaw_rate: 0.0,
426                precession_angle: 0.0,
427                nutation_phase: 0.0,
428            })
429        } else {
430            None
431        };
432        let mut max_yaw_angle = 0.0;
433        let mut max_precession_angle = 0.0;
434
435        // Calculate air density
436        let air_density = calculate_air_density(&self.atmosphere);
437
438        // Wind vector: X=lateral (crosswind), Y=0, Z=downrange (head/tail wind)
439        let wind_vector = Vector3::new(
440            self.wind.speed * self.wind.direction.sin(), // X: lateral (crosswind)
441            0.0,
442            self.wind.speed * self.wind.direction.cos(), // Z: downrange (head/tail wind)
443        );
444
445        // Main integration loop (Z is downrange)
446        while position.z < self.max_range && position.y >= 0.0 && time < 100.0 {
447            // Store trajectory point
448            let velocity_magnitude = velocity.magnitude();
449            let kinetic_energy =
450                0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
451
452            points.push(TrajectoryPoint {
453                time,
454                position: position,
455                velocity_magnitude,
456                kinetic_energy,
457            });
458
459            // Debug: Log first and every 100th point
460            // Coordinate system: X=lateral, Y=vertical, Z=downrange
461            if points.len() == 1 || points.len() % 100 == 0 {
462                eprintln!("Trajectory point {}: time={:.3}s, lateral={:.2}m, vertical={:.2}m, downrange={:.2}m, vel={:.1}m/s",
463                    points.len(), time, position.x, position.y, position.z, velocity_magnitude);
464            }
465
466            // Track max height
467            if position.y > max_height {
468                max_height = position.y;
469            }
470
471            // Calculate pitch damping if enabled
472            if self.inputs.enable_pitch_damping {
473                let temp_c = self.atmosphere.temperature;
474                let temp_k = temp_c + 273.15;
475                let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
476                let mach = velocity_magnitude / speed_of_sound;
477
478                // Track when we enter transonic
479                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
480                    transonic_mach = Some(mach);
481                }
482
483                // Calculate pitch damping coefficient
484                let bullet_type = if let Some(ref model) = self.inputs.bullet_model {
485                    model.as_str()
486                } else {
487                    "default"
488                };
489                let coeffs = PitchDampingCoefficients::from_bullet_type(bullet_type);
490                let pitch_damping = calculate_pitch_damping_coefficient(mach, &coeffs);
491
492                // Track minimum (most critical for stability)
493                if pitch_damping < min_pitch_damping {
494                    min_pitch_damping = pitch_damping;
495                }
496            }
497
498            // Calculate precession/nutation if enabled
499            if self.inputs.enable_precession_nutation {
500                if let Some(ref mut state) = angular_state {
501                    let velocity_magnitude = velocity.magnitude();
502                    let temp_c = self.atmosphere.temperature;
503                    let temp_k = temp_c + 273.15;
504                    let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
505                    let mach = velocity_magnitude / speed_of_sound;
506
507                    // Calculate spin rate from twist rate and velocity
508                    let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
509                        let velocity_fps = velocity_magnitude * 3.28084;
510                        let twist_rate_ft = self.inputs.twist_rate / 12.0;
511                        (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
512                    } else {
513                        0.0
514                    };
515
516                    // Create precession/nutation parameters
517                    let params = PrecessionNutationParams {
518                        mass_kg: self.inputs.bullet_mass,
519                        caliber_m: self.inputs.bullet_diameter,
520                        length_m: self.inputs.bullet_length,
521                        spin_rate_rad_s,
522                        spin_inertia: 6.94e-8,       // Typical value
523                        transverse_inertia: 9.13e-7, // Typical value
524                        velocity_mps: velocity_magnitude,
525                        air_density_kg_m3: air_density,
526                        mach,
527                        pitch_damping_coeff: -0.8,
528                        nutation_damping_factor: 0.05,
529                    };
530
531                    // Update angular state
532                    *state = calculate_combined_angular_motion(
533                        &params,
534                        state,
535                        time,
536                        self.time_step,
537                        0.001, // Initial disturbance
538                    );
539
540                    // Track maximums
541                    if state.yaw_angle.abs() > max_yaw_angle {
542                        max_yaw_angle = state.yaw_angle.abs();
543                    }
544                    if state.precession_angle.abs() > max_precession_angle {
545                        max_precession_angle = state.precession_angle.abs();
546                    }
547                }
548            }
549
550            // Calculate drag with altitude-dependent wind if enabled
551            let actual_wind = if self.inputs.enable_wind_shear {
552                self.get_wind_at_altitude(position.y)
553            } else {
554                wind_vector
555            };
556            let velocity_rel = velocity - actual_wind;
557            let velocity_rel_mag = velocity_rel.magnitude();
558            let drag_coefficient = self.calculate_drag_coefficient(velocity_rel_mag);
559
560            // Calculate drag force
561            let drag_force = 0.5
562                * air_density
563                * drag_coefficient
564                * self.inputs.bullet_diameter
565                * self.inputs.bullet_diameter
566                * std::f64::consts::PI
567                / 4.0
568                * velocity_rel_mag
569                * velocity_rel_mag;
570
571            // Calculate acceleration
572            let drag_acceleration = -drag_force / self.inputs.bullet_mass;
573            let acceleration = Vector3::new(
574                drag_acceleration * velocity_rel.x / velocity_rel_mag,
575                drag_acceleration * velocity_rel.y / velocity_rel_mag - 9.80665,
576                drag_acceleration * velocity_rel.z / velocity_rel_mag,
577            );
578
579            // Update state
580            velocity += acceleration * self.time_step;
581            position += velocity * self.time_step;
582            time += self.time_step;
583        }
584
585        // Get final values
586        let last_point = points.last().ok_or("No trajectory points generated")?;
587
588        // Create trajectory sampling data if enabled
589        let sampled_points = if self.inputs.enable_trajectory_sampling {
590            let trajectory_data = TrajectoryData {
591                times: points.iter().map(|p| p.time).collect(),
592                positions: points.iter().map(|p| p.position).collect(),
593                velocities: points
594                    .iter()
595                    .map(|p| {
596                        // Reconstruct velocity vectors from magnitude (approximate)
597                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
598                    })
599                    .collect(),
600                transonic_distances: Vec::new(), // TODO: Track Mach transitions
601            };
602
603            let outputs = TrajectoryOutputs {
604                target_distance_horiz_m: last_point.position.z, // Z is downrange
605                target_vertical_height_m: last_point.position.y,
606                time_of_flight_s: last_point.time,
607                max_ord_dist_horiz_m: max_height,
608            };
609
610            // Sample at specified intervals
611            let samples = sample_trajectory(
612                &trajectory_data,
613                &outputs,
614                self.inputs.sample_interval,
615                self.inputs.bullet_mass,
616            );
617            Some(samples)
618        } else {
619            None
620        };
621
622        Ok(TrajectoryResult {
623            max_range: last_point.position.z, // Z is downrange
624            max_height,
625            time_of_flight: last_point.time,
626            impact_velocity: last_point.velocity_magnitude,
627            impact_energy: last_point.kinetic_energy,
628            points,
629            sampled_points,
630            min_pitch_damping: if self.inputs.enable_pitch_damping {
631                Some(min_pitch_damping)
632            } else {
633                None
634            },
635            transonic_mach,
636            angular_state,
637            max_yaw_angle: if self.inputs.enable_precession_nutation {
638                Some(max_yaw_angle)
639            } else {
640                None
641            },
642            max_precession_angle: if self.inputs.enable_precession_nutation {
643                Some(max_precession_angle)
644            } else {
645                None
646            },
647        })
648    }
649
650    fn solve_rk4(&self) -> Result<TrajectoryResult, BallisticsError> {
651        // RK4 trajectory integration for better accuracy
652        let mut time = 0.0;
653        let mut position = Vector3::new(
654            0.0,
655            self.inputs.sight_height + self.inputs.muzzle_height,
656            0.0,
657        );
658
659        // Calculate initial velocity components with both elevation and azimuth
660        // Standard ballistics coordinate system: X=lateral, Y=vertical, Z=downrange
661        let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
662        let mut velocity = Vector3::new(
663            horizontal_velocity * self.inputs.azimuth_angle.sin(), // X: lateral (side deviation)
664            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
665            horizontal_velocity * self.inputs.azimuth_angle.cos(), // Z: downrange (forward)
666        );
667
668        let mut points = Vec::new();
669        let mut max_height = position.y;
670        let mut min_pitch_damping = 1.0; // Track minimum pitch damping coefficient
671        let mut transonic_mach = None; // Track when we enter transonic
672
673        // Initialize angular state for precession/nutation tracking
674        let mut angular_state = if self.inputs.enable_precession_nutation {
675            Some(AngularState {
676                pitch_angle: 0.001, // Small initial disturbance
677                yaw_angle: 0.001,
678                pitch_rate: 0.0,
679                yaw_rate: 0.0,
680                precession_angle: 0.0,
681                nutation_phase: 0.0,
682            })
683        } else {
684            None
685        };
686        let mut max_yaw_angle = 0.0;
687        let mut max_precession_angle = 0.0;
688
689        // Calculate air density
690        let air_density = calculate_air_density(&self.atmosphere);
691
692        // Wind vector: X=lateral (crosswind), Y=0, Z=downrange (head/tail wind)
693        let wind_vector = Vector3::new(
694            self.wind.speed * self.wind.direction.sin(), // X: lateral (crosswind)
695            0.0,
696            self.wind.speed * self.wind.direction.cos(), // Z: downrange (head/tail wind)
697        );
698
699        // Main RK4 integration loop (Z is downrange)
700        while position.z < self.max_range && position.y >= 0.0 && time < 100.0 {
701            // Store trajectory point
702            let velocity_magnitude = velocity.magnitude();
703            let kinetic_energy =
704                0.5 * self.inputs.bullet_mass * velocity_magnitude * velocity_magnitude;
705
706            points.push(TrajectoryPoint {
707                time,
708                position: position,
709                velocity_magnitude,
710                kinetic_energy,
711            });
712
713            if position.y > max_height {
714                max_height = position.y;
715            }
716
717            // Calculate pitch damping if enabled (RK4 solver)
718            if self.inputs.enable_pitch_damping {
719                let temp_c = self.atmosphere.temperature;
720                let temp_k = temp_c + 273.15;
721                let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
722                let mach = velocity_magnitude / speed_of_sound;
723
724                // Track when we enter transonic
725                if transonic_mach.is_none() && mach < 1.2 && mach > 0.8 {
726                    transonic_mach = Some(mach);
727                }
728
729                // Calculate pitch damping coefficient
730                let bullet_type = if let Some(ref model) = self.inputs.bullet_model {
731                    model.as_str()
732                } else {
733                    "default"
734                };
735                let coeffs = PitchDampingCoefficients::from_bullet_type(bullet_type);
736                let pitch_damping = calculate_pitch_damping_coefficient(mach, &coeffs);
737
738                // Track minimum (most critical for stability)
739                if pitch_damping < min_pitch_damping {
740                    min_pitch_damping = pitch_damping;
741                }
742            }
743
744            // Calculate precession/nutation if enabled (RK4 solver)
745            if self.inputs.enable_precession_nutation {
746                if let Some(ref mut state) = angular_state {
747                    let velocity_magnitude = velocity.magnitude();
748                    let temp_c = self.atmosphere.temperature;
749                    let temp_k = temp_c + 273.15;
750                    let speed_of_sound = (1.4 * 287.05 * temp_k).sqrt();
751                    let mach = velocity_magnitude / speed_of_sound;
752
753                    // Calculate spin rate from twist rate and velocity
754                    let spin_rate_rad_s = if self.inputs.twist_rate > 0.0 {
755                        let velocity_fps = velocity_magnitude * 3.28084;
756                        let twist_rate_ft = self.inputs.twist_rate / 12.0;
757                        (velocity_fps / twist_rate_ft) * 2.0 * std::f64::consts::PI
758                    } else {
759                        0.0
760                    };
761
762                    // Create precession/nutation parameters
763                    let params = PrecessionNutationParams {
764                        mass_kg: self.inputs.bullet_mass,
765                        caliber_m: self.inputs.bullet_diameter,
766                        length_m: self.inputs.bullet_length,
767                        spin_rate_rad_s,
768                        spin_inertia: 6.94e-8,       // Typical value
769                        transverse_inertia: 9.13e-7, // Typical value
770                        velocity_mps: velocity_magnitude,
771                        air_density_kg_m3: air_density,
772                        mach,
773                        pitch_damping_coeff: -0.8,
774                        nutation_damping_factor: 0.05,
775                    };
776
777                    // Update angular state
778                    *state = calculate_combined_angular_motion(
779                        &params,
780                        state,
781                        time,
782                        self.time_step,
783                        0.001, // Initial disturbance
784                    );
785
786                    // Track maximums
787                    if state.yaw_angle.abs() > max_yaw_angle {
788                        max_yaw_angle = state.yaw_angle.abs();
789                    }
790                    if state.precession_angle.abs() > max_precession_angle {
791                        max_precession_angle = state.precession_angle.abs();
792                    }
793                }
794            }
795
796            // RK4 method
797            let dt = self.time_step;
798
799            // k1
800            let acc1 = self.calculate_acceleration(&position, &velocity, air_density, &wind_vector);
801
802            // k2
803            let pos2 = position + velocity * (dt * 0.5);
804            let vel2 = velocity + acc1 * (dt * 0.5);
805            let acc2 = self.calculate_acceleration(&pos2, &vel2, air_density, &wind_vector);
806
807            // k3
808            let pos3 = position + vel2 * (dt * 0.5);
809            let vel3 = velocity + acc2 * (dt * 0.5);
810            let acc3 = self.calculate_acceleration(&pos3, &vel3, air_density, &wind_vector);
811
812            // k4
813            let pos4 = position + vel3 * dt;
814            let vel4 = velocity + acc3 * dt;
815            let acc4 = self.calculate_acceleration(&pos4, &vel4, air_density, &wind_vector);
816
817            // Update position and velocity
818            position += (velocity + vel2 * 2.0 + vel3 * 2.0 + vel4) * (dt / 6.0);
819            velocity += (acc1 + acc2 * 2.0 + acc3 * 2.0 + acc4) * (dt / 6.0);
820            time += dt;
821        }
822
823        // Get final values
824        let last_point = points.last().ok_or("No trajectory points generated")?;
825
826        // Create trajectory sampling data if enabled
827        let sampled_points = if self.inputs.enable_trajectory_sampling {
828            let trajectory_data = TrajectoryData {
829                times: points.iter().map(|p| p.time).collect(),
830                positions: points.iter().map(|p| p.position).collect(),
831                velocities: points
832                    .iter()
833                    .map(|p| {
834                        // Reconstruct velocity vectors from magnitude (approximate)
835                        Vector3::new(0.0, 0.0, p.velocity_magnitude)
836                    })
837                    .collect(),
838                transonic_distances: Vec::new(), // TODO: Track Mach transitions
839            };
840
841            let outputs = TrajectoryOutputs {
842                target_distance_horiz_m: last_point.position.z, // Z is downrange
843                target_vertical_height_m: last_point.position.y,
844                time_of_flight_s: last_point.time,
845                max_ord_dist_horiz_m: max_height,
846            };
847
848            // Sample at specified intervals
849            let samples = sample_trajectory(
850                &trajectory_data,
851                &outputs,
852                self.inputs.sample_interval,
853                self.inputs.bullet_mass,
854            );
855            Some(samples)
856        } else {
857            None
858        };
859
860        Ok(TrajectoryResult {
861            max_range: last_point.position.z, // Z is downrange
862            max_height,
863            time_of_flight: last_point.time,
864            impact_velocity: last_point.velocity_magnitude,
865            impact_energy: last_point.kinetic_energy,
866            points,
867            sampled_points,
868            min_pitch_damping: if self.inputs.enable_pitch_damping {
869                Some(min_pitch_damping)
870            } else {
871                None
872            },
873            transonic_mach,
874            angular_state,
875            max_yaw_angle: if self.inputs.enable_precession_nutation {
876                Some(max_yaw_angle)
877            } else {
878                None
879            },
880            max_precession_angle: if self.inputs.enable_precession_nutation {
881                Some(max_precession_angle)
882            } else {
883                None
884            },
885        })
886    }
887
888    fn solve_rk45(&self) -> Result<TrajectoryResult, BallisticsError> {
889        // RK45 adaptive step size integration (Dormand-Prince method)
890        let mut time = 0.0;
891        let mut position = Vector3::new(
892            0.0,
893            self.inputs.sight_height + self.inputs.muzzle_height,
894            0.0,
895        );
896
897        // Calculate initial velocity components
898        // Standard ballistics coordinate system: X=lateral, Y=vertical, Z=downrange
899        let horizontal_velocity = self.inputs.muzzle_velocity * self.inputs.muzzle_angle.cos();
900        let mut velocity = Vector3::new(
901            horizontal_velocity * self.inputs.azimuth_angle.sin(), // X: lateral (side deviation)
902            self.inputs.muzzle_velocity * self.inputs.muzzle_angle.sin(), // Y: vertical component
903            horizontal_velocity * self.inputs.azimuth_angle.cos(), // Z: downrange (forward)
904        );
905
906        let mut points = Vec::new();
907        let mut max_height = position.y;
908        let mut dt = 0.001; // Initial step size
909        let tolerance = 1e-6; // Error tolerance
910        let safety_factor = 0.9; // Safety factor for step size adjustment
911        let max_dt = 0.01; // Maximum step size
912        let min_dt = 1e-6; // Minimum step size
913
914        // Add a point counter to debug
915        let mut iteration_count = 0;
916        const MAX_ITERATIONS: usize = 100000;
917
918        while position.z < self.max_range
919            && position.y > self.inputs.ground_threshold
920            && time < 100.0
921        {
922            // Z is downrange
923            iteration_count += 1;
924            if iteration_count > MAX_ITERATIONS {
925                break; // Prevent infinite loop
926            }
927
928            // Store current point
929            let velocity_magnitude = velocity.magnitude();
930            let kinetic_energy = 0.5 * self.inputs.bullet_mass * velocity_magnitude.powi(2);
931
932            points.push(TrajectoryPoint {
933                time,
934                position: position,
935                velocity_magnitude,
936                kinetic_energy,
937            });
938
939            if position.y > max_height {
940                max_height = position.y;
941            }
942
943            // Get atmospheric conditions and wind: X=lateral (crosswind), Y=0, Z=downrange (head/tail wind)
944            let air_density = calculate_air_density(&self.atmosphere);
945            let wind_vector = Vector3::new(
946                self.wind.speed * self.wind.direction.sin(), // X: lateral (crosswind)
947                0.0,
948                self.wind.speed * self.wind.direction.cos(), // Z: downrange (head/tail wind)
949            );
950
951            // RK45 step with adaptive step size
952            let (new_pos, new_vel, new_dt) = self.rk45_step(
953                &position,
954                &velocity,
955                dt,
956                air_density,
957                &wind_vector,
958                tolerance,
959            );
960
961            // Update step size with safety factor and bounds
962            dt = (safety_factor * new_dt).clamp(min_dt, max_dt);
963
964            // Update state
965            position = new_pos;
966            velocity = new_vel;
967            time += dt;
968        }
969
970        // Ensure we have at least one point
971        if points.is_empty() {
972            return Err(BallisticsError::from("No trajectory points calculated"));
973        }
974
975        let last_point = points.last().unwrap();
976
977        Ok(TrajectoryResult {
978            max_range: last_point.position.z, // Z is downrange
979            max_height,
980            time_of_flight: last_point.time,
981            impact_velocity: last_point.velocity_magnitude,
982            impact_energy: last_point.kinetic_energy,
983            points,
984            sampled_points: None, // Simplified - no trajectory sampling in RK45 for now
985            min_pitch_damping: None,
986            transonic_mach: None,
987            angular_state: None,
988            max_yaw_angle: None,
989            max_precession_angle: None,
990        })
991    }
992
993    fn rk45_step(
994        &self,
995        position: &Vector3<f64>,
996        velocity: &Vector3<f64>,
997        dt: f64,
998        air_density: f64,
999        wind_vector: &Vector3<f64>,
1000        tolerance: f64,
1001    ) -> (Vector3<f64>, Vector3<f64>, f64) {
1002        // Dormand-Prince coefficients
1003        const A21: f64 = 1.0 / 5.0;
1004        const A31: f64 = 3.0 / 40.0;
1005        const A32: f64 = 9.0 / 40.0;
1006        const A41: f64 = 44.0 / 45.0;
1007        const A42: f64 = -56.0 / 15.0;
1008        const A43: f64 = 32.0 / 9.0;
1009        const A51: f64 = 19372.0 / 6561.0;
1010        const A52: f64 = -25360.0 / 2187.0;
1011        const A53: f64 = 64448.0 / 6561.0;
1012        const A54: f64 = -212.0 / 729.0;
1013        const A61: f64 = 9017.0 / 3168.0;
1014        const A62: f64 = -355.0 / 33.0;
1015        const A63: f64 = 46732.0 / 5247.0;
1016        const A64: f64 = 49.0 / 176.0;
1017        const A65: f64 = -5103.0 / 18656.0;
1018        const A71: f64 = 35.0 / 384.0;
1019        const A73: f64 = 500.0 / 1113.0;
1020        const A74: f64 = 125.0 / 192.0;
1021        const A75: f64 = -2187.0 / 6784.0;
1022        const A76: f64 = 11.0 / 84.0;
1023
1024        // 5th order coefficients
1025        const B1: f64 = 35.0 / 384.0;
1026        const B3: f64 = 500.0 / 1113.0;
1027        const B4: f64 = 125.0 / 192.0;
1028        const B5: f64 = -2187.0 / 6784.0;
1029        const B6: f64 = 11.0 / 84.0;
1030
1031        // 4th order coefficients for error estimation
1032        const B1_ERR: f64 = 5179.0 / 57600.0;
1033        const B3_ERR: f64 = 7571.0 / 16695.0;
1034        const B4_ERR: f64 = 393.0 / 640.0;
1035        const B5_ERR: f64 = -92097.0 / 339200.0;
1036        const B6_ERR: f64 = 187.0 / 2100.0;
1037        const B7_ERR: f64 = 1.0 / 40.0;
1038
1039        // Compute RK45 stages
1040        let k1_v = self.calculate_acceleration(position, velocity, air_density, wind_vector);
1041        let k1_p = *velocity;
1042
1043        let p2 = position + dt * A21 * k1_p;
1044        let v2 = velocity + dt * A21 * k1_v;
1045        let k2_v = self.calculate_acceleration(&p2, &v2, air_density, wind_vector);
1046        let k2_p = v2;
1047
1048        let p3 = position + dt * (A31 * k1_p + A32 * k2_p);
1049        let v3 = velocity + dt * (A31 * k1_v + A32 * k2_v);
1050        let k3_v = self.calculate_acceleration(&p3, &v3, air_density, wind_vector);
1051        let k3_p = v3;
1052
1053        let p4 = position + dt * (A41 * k1_p + A42 * k2_p + A43 * k3_p);
1054        let v4 = velocity + dt * (A41 * k1_v + A42 * k2_v + A43 * k3_v);
1055        let k4_v = self.calculate_acceleration(&p4, &v4, air_density, wind_vector);
1056        let k4_p = v4;
1057
1058        let p5 = position + dt * (A51 * k1_p + A52 * k2_p + A53 * k3_p + A54 * k4_p);
1059        let v5 = velocity + dt * (A51 * k1_v + A52 * k2_v + A53 * k3_v + A54 * k4_v);
1060        let k5_v = self.calculate_acceleration(&p5, &v5, air_density, wind_vector);
1061        let k5_p = v5;
1062
1063        let p6 = position + dt * (A61 * k1_p + A62 * k2_p + A63 * k3_p + A64 * k4_p + A65 * k5_p);
1064        let v6 = velocity + dt * (A61 * k1_v + A62 * k2_v + A63 * k3_v + A64 * k4_v + A65 * k5_v);
1065        let k6_v = self.calculate_acceleration(&p6, &v6, air_density, wind_vector);
1066        let k6_p = v6;
1067
1068        let p7 = position + dt * (A71 * k1_p + A73 * k3_p + A74 * k4_p + A75 * k5_p + A76 * k6_p);
1069        let v7 = velocity + dt * (A71 * k1_v + A73 * k3_v + A74 * k4_v + A75 * k5_v + A76 * k6_v);
1070        let k7_v = self.calculate_acceleration(&p7, &v7, air_density, wind_vector);
1071        let k7_p = v7;
1072
1073        // 5th order solution
1074        let new_pos = position + dt * (B1 * k1_p + B3 * k3_p + B4 * k4_p + B5 * k5_p + B6 * k6_p);
1075        let new_vel = velocity + dt * (B1 * k1_v + B3 * k3_v + B4 * k4_v + B5 * k5_v + B6 * k6_v);
1076
1077        // 4th order solution for error estimate
1078        let pos_err = position
1079            + dt * (B1_ERR * k1_p
1080                + B3_ERR * k3_p
1081                + B4_ERR * k4_p
1082                + B5_ERR * k5_p
1083                + B6_ERR * k6_p
1084                + B7_ERR * k7_p);
1085        let vel_err = velocity
1086            + dt * (B1_ERR * k1_v
1087                + B3_ERR * k3_v
1088                + B4_ERR * k4_v
1089                + B5_ERR * k5_v
1090                + B6_ERR * k6_v
1091                + B7_ERR * k7_v);
1092
1093        // Estimate error
1094        let pos_error = (new_pos - pos_err).magnitude();
1095        let vel_error = (new_vel - vel_err).magnitude();
1096        let error = (pos_error + vel_error) / (1.0 + position.magnitude() + velocity.magnitude());
1097
1098        // Calculate new step size
1099        let dt_new = if error < tolerance {
1100            dt * (tolerance / error).powf(0.2).min(2.0)
1101        } else {
1102            dt * (tolerance / error).powf(0.25).max(0.1)
1103        };
1104
1105        (new_pos, new_vel, dt_new)
1106    }
1107
1108    fn calculate_acceleration(
1109        &self,
1110        position: &Vector3<f64>,
1111        velocity: &Vector3<f64>,
1112        air_density: f64,
1113        wind_vector: &Vector3<f64>,
1114    ) -> Vector3<f64> {
1115        // Calculate altitude-dependent wind if wind shear is enabled
1116        let actual_wind = if self.inputs.enable_wind_shear {
1117            self.get_wind_at_altitude(position.y)
1118        } else {
1119            *wind_vector
1120        };
1121
1122        let relative_velocity = velocity - actual_wind;
1123        let velocity_magnitude = relative_velocity.magnitude();
1124
1125        if velocity_magnitude < 0.001 {
1126            return Vector3::new(0.0, -9.81, 0.0);
1127        }
1128
1129        // Get drag coefficient from drag model (Mach-indexed from drag tables)
1130        let cd = self.calculate_drag_coefficient(velocity_magnitude);
1131
1132        // Apply cluster BC correction if enabled
1133        let effective_bc = if let Some(ref cluster_bc) = self.cluster_bc {
1134            // Convert velocity to fps for cluster BC calculation
1135            let velocity_fps = velocity_magnitude * 3.28084;
1136            cluster_bc.apply_correction(
1137                self.inputs.bc_value,
1138                self.inputs.caliber_inches * 0.0254, // Convert back to meters for consistency
1139                self.inputs.weight_grains,
1140                velocity_fps,
1141            )
1142        } else {
1143            self.inputs.bc_value
1144        };
1145
1146        // Use proper ballistics retardation formula
1147        // This matches the proven formula from fast_trajectory.rs
1148        // The standard retardation factor converts Cd to drag deceleration
1149        let velocity_fps = velocity_magnitude * 3.28084; // m/s to fps
1150        let cd_to_retard = 0.000683 * 0.30; // Standard ballistics constant
1151        let standard_factor = cd * cd_to_retard;
1152        let density_scale = air_density / 1.225; // Scale relative to standard air (1.225 kg/m³)
1153
1154        // Drag acceleration in ft/s² then convert to m/s²
1155        let a_drag_ft_s2 =
1156            (velocity_fps * velocity_fps) * standard_factor * density_scale / effective_bc;
1157        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s² to m/s²
1158
1159        // Apply drag opposite to velocity direction
1160        let drag_acceleration = -a_drag_m_s2 * (relative_velocity / velocity_magnitude);
1161
1162        // Total acceleration = drag + gravity
1163        drag_acceleration + Vector3::new(0.0, -9.81, 0.0)
1164    }
1165
1166    fn calculate_drag_coefficient(&self, velocity: f64) -> f64 {
1167        // Calculate speed of sound based on atmospheric temperature
1168        let temp_c = self.atmosphere.temperature;
1169        let temp_k = temp_c + 273.15;
1170        let gamma = 1.4; // Ratio of specific heats for air
1171        let r_specific = 287.05; // Specific gas constant for air (J/kg·K)
1172        let speed_of_sound = (gamma * r_specific * temp_k).sqrt();
1173        let mach = velocity / speed_of_sound;
1174
1175        // Get drag coefficient from the drag tables (Mach-indexed)
1176        let base_cd = crate::drag::get_drag_coefficient(mach, &self.inputs.bc_type);
1177
1178        // Determine projectile shape for transonic corrections
1179        let projectile_shape = if let Some(ref model) = self.inputs.bullet_model {
1180            // Try to determine shape from bullet model string
1181            if model.to_lowercase().contains("boat") || model.to_lowercase().contains("bt") {
1182                ProjectileShape::BoatTail
1183            } else if model.to_lowercase().contains("round") || model.to_lowercase().contains("rn")
1184            {
1185                ProjectileShape::RoundNose
1186            } else if model.to_lowercase().contains("flat") || model.to_lowercase().contains("fb") {
1187                ProjectileShape::FlatBase
1188            } else {
1189                // Use heuristic based on caliber, weight, and drag model
1190                get_projectile_shape(
1191                    self.inputs.bullet_diameter,
1192                    self.inputs.bullet_mass / 0.00006479891, // Convert kg to grains
1193                    &self.inputs.bc_type.to_string(),
1194                )
1195            }
1196        } else {
1197            // Use heuristic based on caliber, weight, and drag model
1198            get_projectile_shape(
1199                self.inputs.bullet_diameter,
1200                self.inputs.bullet_mass / 0.00006479891, // Convert kg to grains
1201                &self.inputs.bc_type.to_string(),
1202            )
1203        };
1204
1205        // Apply transonic corrections
1206        // Enable wave drag if advanced effects are enabled
1207        let include_wave_drag = self.inputs.enable_advanced_effects;
1208        transonic_correction(mach, base_cd, projectile_shape, include_wave_drag)
1209    }
1210}
1211
1212// Monte Carlo parameters
1213#[derive(Debug, Clone)]
1214pub struct MonteCarloParams {
1215    pub num_simulations: usize,
1216    pub velocity_std_dev: f64,
1217    pub angle_std_dev: f64,
1218    pub bc_std_dev: f64,
1219    pub wind_speed_std_dev: f64,
1220    pub target_distance: Option<f64>,
1221    pub base_wind_speed: f64,
1222    pub base_wind_direction: f64,
1223    pub azimuth_std_dev: f64, // Horizontal aiming variation in radians
1224}
1225
1226impl Default for MonteCarloParams {
1227    fn default() -> Self {
1228        Self {
1229            num_simulations: 1000,
1230            velocity_std_dev: 1.0,
1231            angle_std_dev: 0.001,
1232            bc_std_dev: 0.01,
1233            wind_speed_std_dev: 1.0,
1234            target_distance: None,
1235            base_wind_speed: 0.0,
1236            base_wind_direction: 0.0,
1237            azimuth_std_dev: 0.001, // Default horizontal spread ~0.057 degrees
1238        }
1239    }
1240}
1241
1242// Monte Carlo results
1243#[derive(Debug, Clone)]
1244pub struct MonteCarloResults {
1245    pub ranges: Vec<f64>,
1246    pub impact_velocities: Vec<f64>,
1247    pub impact_positions: Vec<Vector3<f64>>,
1248}
1249
1250// Run Monte Carlo simulation (backwards compatibility)
1251pub fn run_monte_carlo(
1252    base_inputs: BallisticInputs,
1253    params: MonteCarloParams,
1254) -> Result<MonteCarloResults, BallisticsError> {
1255    let base_wind = WindConditions {
1256        speed: params.base_wind_speed,
1257        direction: params.base_wind_direction,
1258    };
1259    run_monte_carlo_with_wind(base_inputs, base_wind, params)
1260}
1261
1262// Run Monte Carlo simulation with wind
1263pub fn run_monte_carlo_with_wind(
1264    base_inputs: BallisticInputs,
1265    base_wind: WindConditions,
1266    params: MonteCarloParams,
1267) -> Result<MonteCarloResults, BallisticsError> {
1268    use rand::thread_rng;
1269    use rand_distr::{Distribution, Normal};
1270
1271    let mut rng = thread_rng();
1272    let mut ranges = Vec::new();
1273    let mut impact_velocities = Vec::new();
1274    let mut impact_positions = Vec::new();
1275
1276    // First, calculate baseline trajectory with no variations
1277    let baseline_solver =
1278        TrajectorySolver::new(base_inputs.clone(), base_wind.clone(), Default::default());
1279    let baseline_result = baseline_solver.solve()?;
1280
1281    // Determine target distance: use explicit target or baseline max range
1282    let target_distance = params.target_distance.unwrap_or(baseline_result.max_range);
1283
1284    // Get baseline position at target distance (interpolated)
1285    let baseline_at_target = baseline_result
1286        .position_at_range(target_distance)
1287        .ok_or("Could not interpolate baseline at target distance")?;
1288
1289    // Create normal distributions for variations
1290    let velocity_dist = Normal::new(base_inputs.muzzle_velocity, params.velocity_std_dev)
1291        .map_err(|e| format!("Invalid velocity distribution: {}", e))?;
1292    let angle_dist = Normal::new(base_inputs.muzzle_angle, params.angle_std_dev)
1293        .map_err(|e| format!("Invalid angle distribution: {}", e))?;
1294    let bc_dist = Normal::new(base_inputs.bc_value, params.bc_std_dev)
1295        .map_err(|e| format!("Invalid BC distribution: {}", e))?;
1296    let wind_speed_dist = Normal::new(base_wind.speed, params.wind_speed_std_dev)
1297        .map_err(|e| format!("Invalid wind speed distribution: {}", e))?;
1298    let wind_dir_dist =
1299        Normal::new(base_wind.direction, params.wind_speed_std_dev * 0.1) // Small variation in direction
1300            .map_err(|e| format!("Invalid wind direction distribution: {}", e))?;
1301    let azimuth_dist = Normal::new(base_inputs.azimuth_angle, params.azimuth_std_dev)
1302        .map_err(|e| format!("Invalid azimuth distribution: {}", e))?;
1303
1304    // Create distribution for pointing errors (simulates shooter's aiming consistency)
1305    let pointing_error_dist = Normal::new(0.0, params.angle_std_dev * target_distance)
1306        .map_err(|e| format!("Invalid pointing distribution: {}", e))?;
1307
1308    for _ in 0..params.num_simulations {
1309        // Create varied inputs
1310        let mut inputs = base_inputs.clone();
1311        inputs.muzzle_velocity = velocity_dist.sample(&mut rng).max(0.0);
1312        inputs.muzzle_angle = angle_dist.sample(&mut rng);
1313        inputs.bc_value = bc_dist.sample(&mut rng).max(0.01);
1314        inputs.azimuth_angle = azimuth_dist.sample(&mut rng); // Add horizontal variation
1315
1316        // Create varied wind (now based on base wind conditions)
1317        let wind = WindConditions {
1318            speed: wind_speed_dist.sample(&mut rng).abs(),
1319            direction: wind_dir_dist.sample(&mut rng),
1320        };
1321
1322        // Run trajectory
1323        let solver = TrajectorySolver::new(inputs, wind, Default::default());
1324        match solver.solve() {
1325            Ok(result) => {
1326                ranges.push(result.max_range);
1327                impact_velocities.push(result.impact_velocity);
1328
1329                // Interpolate position at target distance (not ground impact)
1330                if let Some(pos_at_target) = result.position_at_range(target_distance) {
1331                    // Calculate deviation from baseline at the SAME target distance
1332                    // X = lateral deviation (windage), Y = vertical deviation (elevation)
1333                    let mut deviation = Vector3::new(
1334                        pos_at_target.x - baseline_at_target.x, // Lateral deviation
1335                        pos_at_target.y - baseline_at_target.y, // Vertical deviation
1336                        0.0, // Z deviation is 0 since we're comparing at same range
1337                    );
1338
1339                    // Add additional pointing error to simulate realistic group sizes
1340                    // This represents the shooter's ability to aim consistently
1341                    let pointing_error_y = pointing_error_dist.sample(&mut rng);
1342                    deviation.y += pointing_error_y;
1343
1344                    impact_positions.push(deviation);
1345                }
1346            }
1347            Err(_) => {
1348                // Skip failed simulations
1349                continue;
1350            }
1351        }
1352    }
1353
1354    if ranges.is_empty() {
1355        return Err("No successful simulations".into());
1356    }
1357
1358    Ok(MonteCarloResults {
1359        ranges,
1360        impact_velocities,
1361        impact_positions,
1362    })
1363}
1364
1365// Calculate zero angle for a target
1366pub fn calculate_zero_angle(
1367    inputs: BallisticInputs,
1368    target_distance: f64,
1369    target_height: f64,
1370) -> Result<f64, BallisticsError> {
1371    calculate_zero_angle_with_conditions(
1372        inputs,
1373        target_distance,
1374        target_height,
1375        WindConditions::default(),
1376        AtmosphericConditions::default(),
1377    )
1378}
1379
1380pub fn calculate_zero_angle_with_conditions(
1381    inputs: BallisticInputs,
1382    target_distance: f64,
1383    target_height: f64,
1384    wind: WindConditions,
1385    atmosphere: AtmosphericConditions,
1386) -> Result<f64, BallisticsError> {
1387    // Helper function to get height at target distance for a given angle
1388    let get_height_at_angle = |angle: f64| -> Result<Option<f64>, BallisticsError> {
1389        let mut test_inputs = inputs.clone();
1390        test_inputs.muzzle_angle = angle;
1391
1392        let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1393        solver.set_max_range(target_distance * 2.0);
1394        solver.set_time_step(0.001);
1395        let result = solver.solve()?;
1396
1397        // Z is downrange in standard ballistics coordinates
1398        for i in 0..result.points.len() {
1399            if result.points[i].position.z >= target_distance {
1400                if i > 0 {
1401                    let p1 = &result.points[i - 1];
1402                    let p2 = &result.points[i];
1403                    let t = (target_distance - p1.position.z) / (p2.position.z - p1.position.z);
1404                    return Ok(Some(p1.position.y + t * (p2.position.y - p1.position.y)));
1405                } else {
1406                    return Ok(Some(result.points[i].position.y));
1407                }
1408            }
1409        }
1410        Ok(None)
1411    };
1412
1413    // Binary search for the angle that hits the target
1414    // Use only positive angles to ensure proper ballistic arc (upward trajectory)
1415    let mut low_angle = 0.0; // radians (horizontal)
1416    let mut high_angle = 0.2; // radians (about 11 degrees)
1417    let tolerance = 0.00001; // radians
1418    let max_iterations = 50;
1419
1420    // MBA-194: Validate bracketing before starting binary search
1421    // Check that the target height is actually between low and high angle trajectories
1422    let low_height = get_height_at_angle(low_angle)?;
1423    let high_height = get_height_at_angle(high_angle)?;
1424
1425    match (low_height, high_height) {
1426        (Some(lh), Some(hh)) => {
1427            let low_error = lh - target_height;
1428            let high_error = hh - target_height;
1429
1430            // For proper bracketing, low angle should undershoot (negative error)
1431            // and high angle should overshoot (positive error)
1432            if low_error > 0.0 && high_error > 0.0 {
1433                // Both angles overshoot - target is too close or height too low
1434                // This shouldn't happen for typical zeroing, but handle gracefully
1435                // Try to find a valid bracket by reducing low_angle (can't go negative)
1436                // Since we can't go below 0, just proceed and let binary search find best
1437            } else if low_error < 0.0 && high_error < 0.0 {
1438                // Both angles undershoot - target is beyond effective range
1439                // Try expanding high_angle up to 45 degrees (0.785 rad)
1440                let mut expanded = false;
1441                for multiplier in [2.0, 3.0, 4.0] {
1442                    let new_high = (high_angle * multiplier).min(0.785);
1443                    if let Ok(Some(h)) = get_height_at_angle(new_high) {
1444                        if h - target_height > 0.0 {
1445                            high_angle = new_high;
1446                            expanded = true;
1447                            break;
1448                        }
1449                    }
1450                    if new_high >= 0.785 {
1451                        break;
1452                    }
1453                }
1454                if !expanded {
1455                    return Err("Cannot find zero angle: target beyond effective range even at maximum angle".into());
1456                }
1457            }
1458            // If signs are opposite, we have valid bracketing - proceed
1459        }
1460        (None, Some(_hh)) => {
1461            // Low angle doesn't reach target, high does - this is fine
1462            // Binary search will increase low_angle until trajectory reaches
1463        }
1464        (Some(_lh), None) => {
1465            // High angle doesn't reach target - shouldn't happen
1466            return Err(
1467                "Cannot find zero angle: high angle trajectory doesn't reach target distance"
1468                    .into(),
1469            );
1470        }
1471        (None, None) => {
1472            // Neither reaches target - target too far
1473            return Err(
1474                "Cannot find zero angle: trajectory cannot reach target distance at any angle"
1475                    .into(),
1476            );
1477        }
1478    }
1479
1480    for _iteration in 0..max_iterations {
1481        let mid_angle = (low_angle + high_angle) / 2.0;
1482
1483        let mut test_inputs = inputs.clone();
1484        test_inputs.muzzle_angle = mid_angle;
1485
1486        let mut solver = TrajectorySolver::new(test_inputs, wind.clone(), atmosphere.clone());
1487        // Make sure we calculate far enough to reach the target
1488        solver.set_max_range(target_distance * 2.0);
1489        solver.set_time_step(0.001);
1490        let result = solver.solve()?;
1491
1492        // Find the height at target distance (Z is downrange)
1493        let mut height_at_target = None;
1494        for i in 0..result.points.len() {
1495            if result.points[i].position.z >= target_distance {
1496                if i > 0 {
1497                    // Linear interpolation
1498                    let p1 = &result.points[i - 1];
1499                    let p2 = &result.points[i];
1500                    let t = (target_distance - p1.position.z) / (p2.position.z - p1.position.z);
1501                    height_at_target = Some(p1.position.y + t * (p2.position.y - p1.position.y));
1502                } else {
1503                    height_at_target = Some(result.points[i].position.y);
1504                }
1505                break;
1506            }
1507        }
1508
1509        match height_at_target {
1510            Some(height) => {
1511                let error = height - target_height;
1512                // MBA-193: Check height error FIRST (primary convergence criterion)
1513                // Height accuracy is what matters for zeroing - angle tolerance is secondary
1514                if error.abs() < 0.001 {
1515                    return Ok(mid_angle);
1516                }
1517
1518                // Only use angle tolerance as convergence criterion if we have
1519                // exhausted angle precision AND height error is still acceptable
1520                // (within 10mm which is reasonable for long range)
1521                if (high_angle - low_angle).abs() < tolerance {
1522                    if error.abs() < 0.01 {
1523                        // Height error within 10mm - acceptable for practical use
1524                        return Ok(mid_angle);
1525                    }
1526                    // Angle converged but height error too large - this shouldn't happen
1527                    // with proper tolerance values, but return best effort
1528                    return Ok(mid_angle);
1529                }
1530
1531                if error > 0.0 {
1532                    high_angle = mid_angle;
1533                } else {
1534                    low_angle = mid_angle;
1535                }
1536            }
1537            None => {
1538                // Trajectory didn't reach target distance, increase angle
1539                low_angle = mid_angle;
1540
1541                // MBA-193: Check angle tolerance for None case too
1542                if (high_angle - low_angle).abs() < tolerance {
1543                    return Err("Trajectory cannot reach target distance - angle converged without valid solution".into());
1544                }
1545            }
1546        }
1547    }
1548
1549    Err("Failed to find zero angle".into())
1550}
1551
1552// Estimate BC from trajectory data
1553pub fn estimate_bc_from_trajectory(
1554    velocity: f64,
1555    mass: f64,
1556    diameter: f64,
1557    points: &[(f64, f64)], // (distance, drop) pairs
1558) -> Result<f64, BallisticsError> {
1559    // Simple BC estimation using least squares
1560    let mut best_bc = 0.5;
1561    let mut best_error = f64::MAX;
1562    let mut found_valid = false;
1563
1564    // Try different BC values
1565    for bc in (100..1000).step_by(10) {
1566        let bc_value = bc as f64 / 1000.0;
1567
1568        let inputs = BallisticInputs {
1569            muzzle_velocity: velocity,
1570            bc_value,
1571            bullet_mass: mass,
1572            bullet_diameter: diameter,
1573            ..Default::default()
1574        };
1575
1576        let mut solver = TrajectorySolver::new(inputs, Default::default(), Default::default());
1577        // Set max range for BC estimation
1578        solver.set_max_range(points.last().map(|(d, _)| *d * 1.5).unwrap_or(1000.0));
1579
1580        let result = match solver.solve() {
1581            Ok(r) => r,
1582            Err(_) => continue, // Skip this BC value if solve fails
1583        };
1584
1585        // Calculate error
1586        let mut total_error = 0.0;
1587        for (target_dist, target_drop) in points {
1588            // Find drop at this distance
1589            let mut calculated_drop = None;
1590            for i in 0..result.points.len() {
1591                if result.points[i].position.z >= *target_dist {
1592                    if i > 0 {
1593                        // Linear interpolation
1594                        let p1 = &result.points[i - 1];
1595                        let p2 = &result.points[i];
1596                        let t = (target_dist - p1.position.z) / (p2.position.z - p1.position.z);
1597                        calculated_drop =
1598                            Some(-(p1.position.y + t * (p2.position.y - p1.position.y)));
1599                    } else {
1600                        calculated_drop = Some(-result.points[i].position.y);
1601                    }
1602                    break;
1603                }
1604            }
1605
1606            if let Some(drop) = calculated_drop {
1607                let error = (drop - target_drop).abs();
1608                total_error += error * error;
1609            }
1610        }
1611
1612        if total_error < best_error {
1613            best_error = total_error;
1614            best_bc = bc_value;
1615            found_valid = true;
1616        }
1617    }
1618
1619    if !found_valid {
1620        return Err(BallisticsError::from("Unable to estimate BC from provided data. Check that drop values are in correct units.".to_string()));
1621    }
1622
1623    Ok(best_bc)
1624}
1625
1626// Helper function to calculate air density
1627fn calculate_air_density(atmosphere: &AtmosphericConditions) -> f64 {
1628    // Simplified air density calculation
1629    // P / (R * T) where R is specific gas constant for dry air
1630    let r_specific = 287.058; // J/(kg·K)
1631    let temperature_k = atmosphere.temperature + 273.15;
1632
1633    // Convert pressure from hPa to Pa
1634    let pressure_pa = atmosphere.pressure * 100.0;
1635
1636    // Basic density calculation
1637    let density = pressure_pa / (r_specific * temperature_k);
1638
1639    // Altitude correction (simplified)
1640    let altitude_factor = (-atmosphere.altitude / 8000.0).exp();
1641
1642    density * altitude_factor
1643}
1644
1645// Add rand dependencies for Monte Carlo
1646use rand;
1647use rand_distr;