Skip to main content

ballistics_engine/
fast_trajectory.rs

1//! Fast trajectory solver for longer ranges.
2//!
3//! This is a Rust implementation of the fast fixed-step trajectory solver
4//! that provides significant performance improvements for long-range calculations.
5
6use crate::{
7    atmosphere::{calculate_air_density_cimp, get_local_atmosphere_humid, AtmoSock},
8    bc_estimation::velocity_segment_bc,
9    constants::{G_ACCEL_MPS2, MPS_TO_FPS, STANDARD_AIR_DENSITY},
10    drag::get_drag_coefficient,
11    wind::WindSock,
12    DragModel, InternalBallisticInputs as BallisticInputs,
13};
14use nalgebra::Vector3;
15
16/// Fast solution container matching Python implementation
17#[derive(Debug, Clone)]
18pub struct FastSolution {
19    /// Time points
20    pub t: Vec<f64>,
21    /// State vectors at each time point [6 x n_points]
22    pub y: Vec<Vec<f64>>,
23    /// Event times [target_hit, max_ord, ground_hit]
24    pub t_events: [Vec<f64>; 3],
25    /// Whether integration succeeded
26    pub success: bool,
27}
28
29impl FastSolution {
30    /// Interpolate solution at time t
31    pub fn sol(&self, t_query: &[f64]) -> Vec<Vec<f64>> {
32        let mut result = vec![vec![0.0; t_query.len()]; 6];
33
34        for (i, &tq) in t_query.iter().enumerate() {
35            // Find the right interval using binary search
36            // Use unwrap_or to safely handle NaN values by treating them as greater
37            let idx = match self
38                .t
39                .binary_search_by(|&t| t.partial_cmp(&tq).unwrap_or(std::cmp::Ordering::Greater))
40            {
41                Ok(idx) => idx,
42                Err(idx) => idx,
43            };
44
45            if idx == 0 {
46                // Before first point
47                for (result_component, source_component) in result.iter_mut().zip(&self.y) {
48                    result_component[i] = source_component[0];
49                }
50            } else if idx >= self.t.len() {
51                // After last point
52                for (result_component, source_component) in result.iter_mut().zip(&self.y) {
53                    result_component[i] = source_component[self.t.len() - 1];
54                }
55            } else {
56                // Linear interpolation
57                let t0 = self.t[idx - 1];
58                let t1 = self.t[idx];
59                let span = t1 - t0;
60
61                for (result_component, source_component) in result.iter_mut().zip(&self.y) {
62                    let y0 = source_component[idx - 1];
63                    let y1 = source_component[idx];
64                    result_component[i] = if span.abs() < f64::EPSILON {
65                        y1
66                    } else {
67                        let frac = (tq - t0) / span;
68                        y0 + frac * (y1 - y0)
69                    };
70                }
71            }
72        }
73
74        result
75    }
76
77    /// Convert from row-major to column-major format for compatibility
78    pub fn from_trajectory_data(
79        times: Vec<f64>,
80        states: Vec<[f64; 6]>,
81        t_events: [Vec<f64>; 3],
82    ) -> Self {
83        let n_points = times.len();
84        let mut y = vec![vec![0.0; n_points]; 6];
85
86        for (i, state) in states.iter().enumerate() {
87            for j in 0..6 {
88                y[j][i] = state[j];
89            }
90        }
91
92        FastSolution {
93            t: times,
94            y,
95            t_events,
96            success: true,
97        }
98    }
99
100    /// A clearly-failed solution carrying only the launch state, with `success = false`.
101    /// Used when inputs are too degenerate to integrate (e.g. non-physical atmosphere),
102    /// so callers see `success = false` instead of a stub trajectory reported as success.
103    fn degenerate(initial_state: &[f64; 6]) -> Self {
104        let mut y = vec![Vec::new(); 6];
105        for (j, slot) in y.iter_mut().enumerate() {
106            slot.push(initial_state[j]);
107        }
108        FastSolution {
109            t: vec![0.0],
110            y,
111            t_events: [Vec::new(), Vec::new(), Vec::new()],
112            success: false,
113        }
114    }
115}
116
117fn direct_atmosphere_values(atmo_params: (f64, f64, f64, f64)) -> Option<(f64, f64)> {
118    let (a, b, c, d) = atmo_params;
119    (a.is_finite() && b.is_finite() && c == 0.0 && d == 0.0 && a > 0.0 && a < 2.0 && b > 200.0)
120        .then_some((a, b))
121}
122
123fn stability_atmosphere_params(atmo_params: (f64, f64, f64, f64)) -> (f64, f64, f64, f64) {
124    if let Some((air_density, _)) = direct_atmosphere_values(atmo_params) {
125        // compute_stability_coefficient consumes standard-mode temperature/pressure, whose
126        // Miller correction is rho_ref/rho. At the 15 C reference temperature, scaling pressure
127        // by rho/rho_ref supplies that exact correction without misreading sound speed as temp.
128        (0.0, 15.0, 1013.25 * air_density / STANDARD_AIR_DENSITY, 1.0)
129    } else {
130        atmo_params
131    }
132}
133
134const MAX_STANDARD_DENSITY_RATIO: f64 = 2.0;
135
136/// True if `atmo_params` can yield a finite, positive air density. `atmo_params` has TWO
137/// modes that `compute_derivatives` distinguishes:
138///   * **Standard**: `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` —
139///     positive station pressure. Slot 3 is a density RATIO, not humidity, despite the
140///     `humidity` field it lands in via `build_inputs`. A nonpositive ratio means "not supplied"
141///     and falls back to `1.0`; a supplied ratio must be below `2.0`.
142///   * **Direct**: `(air_density, speed_of_sound, 0.0, 0.0)` — slots 2 and 3 are `0.0`
143///     sentinels, with a real density (< 2.0 kg/m³) and speed of sound (> 200 m/s).
144///
145/// A pressure <= 0 that ISN'T the direct-mode sentinel, an overlarge supplied density ratio, or
146/// any non-finite value would yield a non-physical atmosphere, so it is rejected. (Earlier this
147/// guard also rejected legitimate direct-mode input; the direct-mode allowance below fixes that.)
148fn atmo_is_physical(atmo_params: (f64, f64, f64, f64)) -> bool {
149    let (a, b, c, d) = atmo_params;
150    if !(a.is_finite() && b.is_finite() && c.is_finite() && d.is_finite()) {
151        return false;
152    }
153    // Direct-atmosphere mode: (density, speed_of_sound, 0, 0). Constants mirror
154    // derivatives.rs (MAX_REALISTIC_DENSITY = 2.0 kg/m³, MIN_REALISTIC_SPEED_OF_SOUND = 200 m/s).
155    // Standard mode: positive station pressure (hPa), plus either the documented missing-ratio
156    // sentinel or a supplied ratio below the physical ceiling.
157    direct_atmosphere_values(atmo_params).is_some() || (c > 0.0 && d < MAX_STANDARD_DENSITY_RATIO)
158}
159
160#[derive(Debug, Clone, Copy)]
161enum FastAtmosphere {
162    Direct {
163        air_density: f64,
164        speed_of_sound: f64,
165    },
166    Standard {
167        base_density: f64,
168    },
169}
170
171/// Fast trajectory integration parameters
172pub struct FastIntegrationParams {
173    pub horiz: f64,
174    pub vert: f64,
175    pub initial_state: [f64; 6],
176    pub t_span: (f64, f64),
177    /// Dual-mode atmosphere tuple. Standard mode is
178    /// `(base_alt_m, base_temp_c, base_pressure_hPa, base_density_ratio)` (slot 3 is a density
179    /// RATIO, not humidity; nonpositive means "not supplied" and falls back to `1.0`, while a
180    /// supplied ratio must be below `2.0`). Direct mode is
181    /// `(air_density, speed_of_sound, 0.0, 0.0)`.
182    pub atmo_params: (f64, f64, f64, f64),
183    /// MBA-1137: optional downrange-segmented atmosphere. When `Some`, the per-substep drag
184    /// density samples the base (station-referenced) T/P/H for the zone at the current downrange
185    /// distance before applying the altitude lapse. `None` (default) keeps the single-station
186    /// base and — combined with the MBA-1137 density-freeze fix — varies density with altitude only.
187    pub atmo_sock: Option<AtmoSock>,
188}
189
190/// Aerodynamic-jump vertical launch-angle offset (radians) for the fast-integrate path.
191///
192/// Bryan Litz's crosswind estimator (`Y = 0.01*Sg - 0.0024*L + 0.032` MOA/mph) fed by the
193/// engine's Miller Sg. The fast path receives a prebuilt initial velocity (no muzzle angle),
194/// so the caller rotates that velocity by this offset. Returns 0 when the feature is off or
195/// the inputs are degenerate. Crosswind is taken from `wind_speed`/`wind_angle`
196/// (BallisticInputs convention: 0 = headwind, +PI/2 = from the right). MBA-959, EXPERIMENTAL.
197pub fn aerodynamic_jump_launch_offset_rad(
198    inputs: &BallisticInputs,
199    atmo_params: (f64, f64, f64, f64),
200) -> f64 {
201    let crosswind_from_right_mps = inputs.wind_speed * inputs.wind_angle.sin();
202    aerodynamic_jump_launch_offset_for_crosswind_rad(inputs, atmo_params, crosswind_from_right_mps)
203}
204
205fn aerodynamic_jump_launch_offset_for_crosswind_rad(
206    inputs: &BallisticInputs,
207    atmo_params: (f64, f64, f64, f64),
208    crosswind_from_right_mps: f64,
209) -> f64 {
210    if !inputs.enable_aerodynamic_jump {
211        return 0.0;
212    }
213    let diameter = inputs.bullet_diameter;
214    if !(inputs.twist_rate.is_finite()
215        && inputs.twist_rate != 0.0
216        && diameter.is_finite()
217        && diameter > 0.0
218        && inputs.bullet_length.is_finite()
219        && inputs.bullet_length > 0.0
220        && inputs.muzzle_velocity.is_finite())
221    {
222        return 0.0;
223    }
224    let stability_atmo = stability_atmosphere_params(atmo_params);
225    let sg = crate::stability::compute_stability_coefficient(inputs, stability_atmo);
226    if !(sg.is_finite() && sg > 0.0) {
227        return 0.0;
228    }
229    let length_cal = inputs.bullet_length / diameter;
230    const MS_TO_MPH: f64 = 2.236_936_292_054_4;
231    let crosswind_from_right_mph = crosswind_from_right_mps * MS_TO_MPH;
232    let vertical_moa = crate::aerodynamic_jump::litz_crosswind_jump_moa(
233        sg,
234        length_cal,
235        crosswind_from_right_mph,
236        inputs.is_twist_right,
237    );
238    if !vertical_moa.is_finite() {
239        return 0.0;
240    }
241    const MOA_PER_RAD: f64 = 3437.7467707849;
242    vertical_moa / MOA_PER_RAD
243}
244
245/// Rotate a McCoy-frame state's velocity (indices 3..6) by `theta_rad` in the vertical
246/// (downrange–vertical) plane, preserving speed and horizontal heading. Positive = up.
247fn rotate_launch_velocity(state: &mut [f64; 6], theta_rad: f64) {
248    let (vx, vy, vz) = (state[3], state[4], state[5]);
249    let speed = (vx * vx + vy * vy + vz * vz).sqrt();
250    if speed <= 0.0 {
251        return;
252    }
253    let h = (vx * vx + vz * vz).sqrt(); // horizontal (downrange+lateral) speed
254    let new_elev = vy.atan2(h) + theta_rad;
255    state[4] = speed * new_elev.sin();
256    let new_h = speed * new_elev.cos();
257    let scale = if h > 1e-12 { new_h / h } else { 0.0 };
258    state[3] = vx * scale;
259    state[5] = vz * scale;
260}
261
262fn launch_state_with_aerodynamic_jump(
263    inputs: &BallisticInputs,
264    atmo_params: (f64, f64, f64, f64),
265    segmented_crosswind_from_right_mps: Option<f64>,
266    mut initial_state: [f64; 6],
267) -> [f64; 6] {
268    let offset = match segmented_crosswind_from_right_mps {
269        Some(crosswind) => {
270            aerodynamic_jump_launch_offset_for_crosswind_rad(inputs, atmo_params, crosswind)
271        }
272        None => aerodynamic_jump_launch_offset_rad(inputs, atmo_params),
273    };
274    if offset != 0.0 {
275        rotate_launch_velocity(&mut initial_state, offset);
276    }
277    initial_state
278}
279
280/// Fast fixed-step integration for longer trajectories
281pub fn fast_integrate(
282    inputs: &BallisticInputs,
283    wind_sock: &WindSock,
284    params: FastIntegrationParams,
285) -> FastSolution {
286    // Malformed wind or a degenerate atmosphere would otherwise silently stub or poison the run.
287    if wind_sock.validate_segments().is_err() || !atmo_is_physical(params.atmo_params) {
288        return FastSolution::degenerate(&params.initial_state);
289    }
290    let mut effective_inputs = inputs.clone();
291    // MBA-1415: this is a public entry point that external bindings call directly, bypassing
292    // TrajectorySolver::new. It must therefore carry every input-conditioning step itself, or a
293    // caller setting a conditioned field gets no error and no effect. Idempotent, so inputs that
294    // already passed through a solver are unaffected.
295    effective_inputs.normalize_for_solve();
296    if params.atmo_params.2 > 0.0 {
297        effective_inputs.altitude = params.atmo_params.0;
298        effective_inputs.temperature = params.atmo_params.1;
299        effective_inputs.pressure = params.atmo_params.2;
300        effective_inputs.humidity = params.atmo_params.3;
301    }
302    let inputs = &effective_inputs;
303    // Extract parameters
304    let _mass_kg = inputs.bullet_mass; // SI (kg)
305    let bc = inputs.bc_value;
306    let drag_model = &inputs.bc_type;
307
308    // Check for BC segments
309    let has_bc_segments =
310        inputs.bc_segments.is_some() && !inputs.bc_segments.as_ref().unwrap().is_empty();
311    let has_bc_segments_data =
312        inputs.bc_segments_data.is_some() && !inputs.bc_segments_data.as_ref().unwrap().is_empty();
313
314    // Time step - adjust based on distance
315    let dt = if params.horiz > 200.0 {
316        0.001
317    } else if params.horiz > 100.0 {
318        0.0005
319    } else {
320        0.0001
321    };
322
323    // MBA-959: aerodynamic jump perturbs the prebuilt launch velocity vertically (this path is
324    // handed an initial_state, not a muzzle angle). A no-op returning the original when disabled.
325    let segmented_crosswind_from_right_mps = if inputs.enable_aerodynamic_jump {
326        wind_sock.muzzle_crosswind_from_right_mps()
327    } else {
328        None
329    };
330    let initial_state = launch_state_with_aerodynamic_jump(
331        inputs,
332        params.atmo_params,
333        segmented_crosswind_from_right_mps,
334        params.initial_state,
335    );
336    let vx = initial_state[3]; // horizontal (downrange) velocity
337
338    // MBA-1145: decouple the integration-loop ceiling from the pre-allocation heuristic.
339    // Previously t_max = min(4*horiz/vx, t_span.1) bounded BOTH the Vec sizing AND the loop
340    // itself, so the 4x-horiz/vx estimate doubled as the loop cap. That estimate is only a
341    // heuristic — extreme high-drag or high-launch-angle shots exceed it, and the loop then
342    // terminated BEFORE hit_target/hit_ground, silently truncating the trajectory tail (Monte
343    // Carlo reported impact metrics short of the real range). The loop already breaks on
344    // hit_target (pos.x >= horiz) and hit_ground (pos.y <= ground_threshold), and any real
345    // trajectory descends below the ground threshold within a few seconds of apex, so the loop
346    // bound's only job is a runaway safety ceiling: use the full t_span.1 (default 30 s). The
347    // 4x estimate is retained ONLY to size the pre-allocation (keeps the small-allocation fast
348    // path for short shots); the Vec grows for the rare long run because the loop bound is n_steps.
349    let n_steps = ((params.t_span.1 / dt) as usize) + 1;
350    let est_steps = if vx > 1e-6 && params.horiz > 0.0 {
351        (((4.0 * params.horiz / vx) / dt) as usize) + 1
352    } else {
353        n_steps
354    };
355    let cap = est_steps.min(n_steps);
356    let mut times = Vec::with_capacity(cap);
357    let mut states = Vec::with_capacity(cap);
358
359    // Initial state (with the aerodynamic-jump launch perturbation applied above)
360    times.push(0.0);
361    states.push(initial_state);
362
363    // Direct mode supplies a fixed density and speed of sound. Standard mode supplies station
364    // conditions plus base_ratio; its local density/sound speed are lapsed at every substep.
365    // Guard a missing standard-mode ratio by falling back to sea-level density (MBA-1157 owns
366    // stricter validation of that separate contract).
367    let atmosphere =
368        if let Some((air_density, speed_of_sound)) = direct_atmosphere_values(params.atmo_params) {
369            FastAtmosphere::Direct {
370                air_density,
371                speed_of_sound,
372            }
373        } else {
374            let base_density = if params.atmo_params.3 > 0.0 {
375                params.atmo_params.3 * 1.225
376            } else {
377                1.225
378            };
379            FastAtmosphere::Standard { base_density }
380        };
381
382    // MBA-1137: borrow the optional downrange-segmented atmosphere once (queried 4x per step).
383    let atmo_sock = params.atmo_sock.as_ref();
384
385    // Hoist invariants out of compute_derivatives (called 4x per step). Both the drag-model name
386    // and the projectile shape depend only on inputs, not on state/mach, so computing them per
387    // call wasted an allocation + heuristic every k1..k4. Mirrors cli_api.rs exactly.
388
389    // Drag-model name as a borrowed &'static str. DragModel's Display goes via Debug, which
390    // heap-allocates a String on every call; this match is bit-identical (Display == Debug ==
391    // variant name) with no per-step allocation.
392    let drag_model_str: &str = match drag_model {
393        DragModel::G1 => "G1",
394        DragModel::G2 => "G2",
395        DragModel::G5 => "G5",
396        DragModel::G6 => "G6",
397        DragModel::G7 => "G7",
398        DragModel::G8 => "G8",
399        DragModel::GI => "GI",
400        DragModel::GS => "GS",
401        DragModel::RA4 => "RA4",
402    };
403
404    // SI fallbacks for caliber/weight (SI-only MC callers may leave the imperial fields 0).
405    let caliber_in = if inputs.caliber_inches > 0.0 {
406        inputs.caliber_inches
407    } else {
408        inputs.bullet_diameter / 0.0254
409    };
410    let weight_gr = if inputs.weight_grains > 0.0 {
411        inputs.weight_grains
412    } else {
413        inputs.bullet_mass / crate::constants::GRAINS_TO_KG
414    };
415
416    // Projectile shape for transonic corrections (MBA-949: shared resolver — bullet_model name
417    // first, then the caliber/weight/drag-model heuristic).
418    let projectile_shape = crate::transonic_drag::resolve_projectile_shape(
419        inputs.bullet_model.as_deref(),
420        caliber_in,
421        weight_gr,
422        drag_model_str,
423    );
424
425    // Coriolis omega (Earth rotation), hoisted (invariant over the flight). MBA-957:
426    // fast_integrate — the Monte Carlo / Python-binding path — previously applied NO Coriolis.
427    // First project into level downrange/up/lateral axes: azimuth 0 = North; omega.Z is NEGATIVE
428    // (Omega.East = -Omega cos(lat) sin(az)). The derivative kernel then projects this vector into
429    // the inclined shot frame and applies the physical -2 Omega x v.
430    let omega_vector = match inputs.latitude {
431        Some(latitude) if inputs.enable_coriolis => {
432            let omega_earth = 7.2921159e-5_f64; // rad/s
433            let lat = latitude.to_radians();
434            let az = inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
435            Some(Vector3::new(
436                omega_earth * lat.cos() * az.cos(),  // X: downrange
437                omega_earth * lat.sin(),             // Y: vertical
438                -omega_earth * lat.cos() * az.sin(), // Z: lateral (corrected sign)
439            ))
440        }
441        _ => None,
442    };
443    // Parse the string model once; the derivative kernel is called four times per RK4 step.
444    let wind_shear_model = if inputs.enable_wind_shear {
445        let model = crate::wind_shear::boundary_layer_model_from_name(&inputs.wind_shear_model);
446        (model != crate::wind_shear::WindShearModel::None).then_some(model)
447    } else {
448        None
449    };
450
451    // Integration loop
452    let mut hit_target = false;
453    let mut hit_ground = false;
454    let mut max_ord_time = None;
455    let mut max_ord_y = 0.0;
456    let ground_threshold = inputs.ground_threshold;
457
458    // RK4 integration
459    for i in 0..n_steps - 1 {
460        let t = i as f64 * dt;
461        let state = states[i];
462
463        let pos = Vector3::new(state[0], state[1], state[2]);
464        let _vel = Vector3::new(state[3], state[4], state[5]);
465
466        // Check termination conditions (X is downrange, McCoy)
467        if pos.x >= params.horiz {
468            hit_target = true;
469            break;
470        }
471
472        if pos.y <= ground_threshold {
473            hit_ground = true;
474            break;
475        }
476
477        // Track maximum ordinate
478        if pos.y > max_ord_y {
479            max_ord_y = pos.y;
480            max_ord_time = Some(t);
481        }
482
483        // RK4 step
484        let k1 = compute_derivatives(
485            &state,
486            inputs,
487            wind_sock,
488            atmosphere,
489            drag_model,
490            projectile_shape,
491            bc,
492            has_bc_segments,
493            has_bc_segments_data,
494            omega_vector,
495            wind_shear_model,
496            atmo_sock,
497        );
498
499        let mut state2 = state;
500        for j in 0..6 {
501            state2[j] = state[j] + 0.5 * dt * k1[j];
502        }
503        let k2 = compute_derivatives(
504            &state2,
505            inputs,
506            wind_sock,
507            atmosphere,
508            drag_model,
509            projectile_shape,
510            bc,
511            has_bc_segments,
512            has_bc_segments_data,
513            omega_vector,
514            wind_shear_model,
515            atmo_sock,
516        );
517
518        let mut state3 = state;
519        for j in 0..6 {
520            state3[j] = state[j] + 0.5 * dt * k2[j];
521        }
522        let k3 = compute_derivatives(
523            &state3,
524            inputs,
525            wind_sock,
526            atmosphere,
527            drag_model,
528            projectile_shape,
529            bc,
530            has_bc_segments,
531            has_bc_segments_data,
532            omega_vector,
533            wind_shear_model,
534            atmo_sock,
535        );
536
537        let mut state4 = state;
538        for j in 0..6 {
539            state4[j] = state[j] + dt * k3[j];
540        }
541        let k4 = compute_derivatives(
542            &state4,
543            inputs,
544            wind_sock,
545            atmosphere,
546            drag_model,
547            projectile_shape,
548            bc,
549            has_bc_segments,
550            has_bc_segments_data,
551            omega_vector,
552            wind_shear_model,
553            atmo_sock,
554        );
555
556        // Update state
557        let mut new_state = state;
558        for j in 0..6 {
559            new_state[j] = state[j] + dt * (k1[j] + 2.0 * k2[j] + 2.0 * k3[j] + k4[j]) / 6.0;
560        }
561
562        if state[0] < params.horiz && new_state[0] >= params.horiz {
563            // Keep every terminal metric on the requested target plane. The former top-of-loop
564            // check retained this full-step endpoint, biasing time, drop, and velocity past it.
565            let alpha = (params.horiz - state[0]) / (new_state[0] - state[0]);
566            let mut target_state = state;
567            for j in 0..6 {
568                target_state[j] = state[j] + alpha * (new_state[j] - state[j]);
569            }
570            target_state[0] = params.horiz;
571            times.push(t + alpha * dt);
572            states.push(target_state);
573            hit_target = true;
574            break;
575        }
576
577        times.push(t + dt);
578        states.push(new_state);
579    }
580
581    // Create event arrays
582    let t_events = [
583        if hit_target {
584            vec![*times.last().unwrap()]
585        } else {
586            vec![]
587        },
588        if let Some(t) = max_ord_time {
589            vec![t]
590        } else {
591            vec![]
592        },
593        if hit_ground {
594            vec![*times.last().unwrap()]
595        } else {
596            vec![]
597        },
598    ];
599
600    // MBA-1134 (rank 10) — regression fix: apply the canonical empirical Litz drift as a
601    // post-process to the lateral (McCoy Z) here too. The derivatives kernel no longer
602    // integrates spin drift, and this plain fast_integrate is the single-shot fast path
603    // (solve_trajectory_rust / the API), so without this it would carry NO spin drift and
604    // twist direction would have no effect (the Magnus term is also suppressed when
605    // use_enhanced_spin_drift is set). Mirrors fast_integrate_with_segments,
606    // cli_api::apply_spin_drift and the Monte-Carlo path so all solver families agree; uses
607    // the SAME muzzle Sg (spin_drift::effective_sg_from_inputs).
608    if inputs.use_enhanced_spin_drift {
609        // Standard-mode atmo_params is (base_alt, temp_c, press_hpa, ratio); direct mode
610        // (density, sound, 0, 0) carries no explicit temp/pressure, so fall back to sea-level
611        // standard (the Sg density correction is a no-op there).
612        let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
613            (params.atmo_params.1, params.atmo_params.2)
614        } else {
615            (15.0, 1013.25)
616        };
617        let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
618        for (t, state) in times.iter().zip(states.iter_mut()) {
619            if *t > 0.0 {
620                state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
621            }
622        }
623    }
624
625    FastSolution::from_trajectory_data(times, states, t_events)
626}
627
628fn fast_magnus_acceleration(
629    inputs: &BallisticInputs,
630    air_velocity: Vector3<f64>,
631    air_density: f64,
632    mach: f64,
633    gravity_acceleration: Vector3<f64>,
634) -> Vector3<f64> {
635    if !inputs.enable_magnus
636        || inputs.use_enhanced_spin_drift
637        || inputs.bullet_diameter <= 0.0
638        || inputs.twist_rate <= 0.0
639        || inputs.bullet_mass <= 0.0
640    {
641        return Vector3::zeros();
642    }
643
644    let speed_air = air_velocity.norm();
645    let diameter_m = inputs.bullet_diameter;
646    let (spin_rate_rad_s, spin_param) = crate::spin_drift::calculate_magnus_spin_state(
647        inputs.muzzle_velocity,
648        speed_air,
649        inputs.twist_rate,
650        diameter_m,
651    );
652    let d_in = if inputs.caliber_inches > 0.0 {
653        inputs.caliber_inches
654    } else {
655        diameter_m / 0.0254
656    };
657    let m_gr = if inputs.weight_grains > 0.0 {
658        inputs.weight_grains
659    } else {
660        inputs.bullet_mass / crate::constants::GRAINS_TO_KG
661    };
662    let l_in = if inputs.bullet_length > 0.0 {
663        inputs.bullet_length / 0.0254
664    } else {
665        let estimated = crate::stability::estimate_bullet_length_m(diameter_m, inputs.bullet_mass);
666        if estimated > 0.0 {
667            estimated / 0.0254
668        } else {
669            4.5 * d_in.max(1e-9)
670        }
671    };
672    let sg = crate::spin_drift::calculate_dynamic_stability(
673        m_gr,
674        speed_air,
675        spin_rate_rad_s,
676        d_in,
677        l_in,
678        air_density,
679    );
680    let (yaw_rad, _) = crate::spin_drift::calculate_yaw_of_repose(
681        sg,
682        speed_air,
683        spin_rate_rad_s,
684        0.0,
685        0.0,
686        air_density,
687        d_in,
688        l_in,
689        m_gr,
690        mach,
691        "match",
692        false,
693    );
694    let area = std::f64::consts::PI * (diameter_m / 2.0).powi(2);
695    let c_np = crate::derivatives::calculate_magnus_moment_coefficient(mach);
696    let force = 0.5 * air_density * speed_air.powi(2) * area * c_np * spin_param * yaw_rad.sin();
697    if force <= 1e-12 {
698        return Vector3::zeros();
699    }
700
701    crate::derivatives::yaw_of_repose_magnus_direction(
702        air_velocity,
703        gravity_acceleration,
704        inputs.is_twist_right,
705    )
706    .map_or_else(Vector3::zeros, |direction| {
707        (force / inputs.bullet_mass) * direction
708    })
709}
710
711fn interpolated_vertical_apex(
712    previous_time: f64,
713    previous: &[f64; 6],
714    current_time: f64,
715    current: &[f64; 6],
716) -> Option<(f64, [f64; 6])> {
717    let dt = current_time - previous_time;
718    let previous_vy = previous[4];
719    let current_vy = current[4];
720    if !dt.is_finite()
721        || dt <= 0.0
722        || !previous_vy.is_finite()
723        || !current_vy.is_finite()
724        || previous_vy <= 0.0
725        || current_vy > 0.0
726    {
727        return None;
728    }
729
730    let denominator = previous_vy - current_vy;
731    if !denominator.is_finite() || denominator <= 0.0 {
732        return None;
733    }
734    let alpha = previous_vy / denominator;
735    // An exact endpoint root is already retained as the current saved point. Only synthesize a
736    // strictly interior point so the solution remains ordered without duplicate event times.
737    if !alpha.is_finite() || !(0.0..1.0).contains(&alpha) {
738        return None;
739    }
740
741    let mut apex = [0.0; 6];
742    for component in 0..6 {
743        apex[component] = previous[component] + alpha * (current[component] - previous[component]);
744    }
745
746    // Cubic Hermite interpolation uses each endpoint's position and velocity, avoiding the
747    // chord-height bias that linear interpolation has around a stationary point.
748    let alpha2 = alpha * alpha;
749    let alpha3 = alpha2 * alpha;
750    let h00 = 2.0 * alpha3 - 3.0 * alpha2 + 1.0;
751    let h10 = alpha3 - 2.0 * alpha2 + alpha;
752    let h01 = -2.0 * alpha3 + 3.0 * alpha2;
753    let h11 = alpha3 - alpha2;
754    for axis in 0..3 {
755        apex[axis] = h00 * previous[axis]
756            + h10 * dt * previous[axis + 3]
757            + h01 * current[axis]
758            + h11 * dt * current[axis + 3];
759    }
760    apex[4] = 0.0;
761
762    apex.iter()
763        .all(|component| component.is_finite())
764        .then_some((previous_time + alpha * dt, apex))
765}
766
767/// Compute derivatives for the state vector
768#[allow(clippy::too_many_arguments)]
769fn compute_derivatives(
770    state: &[f64; 6],
771    inputs: &BallisticInputs,
772    wind_sock: &WindSock,
773    atmosphere: FastAtmosphere,
774    drag_model: &DragModel,
775    projectile_shape: crate::transonic_drag::ProjectileShape,
776    bc: f64,
777    has_bc_segments: bool,
778    has_bc_segments_data: bool,
779    omega: Option<Vector3<f64>>,
780    wind_shear_model: Option<crate::wind_shear::WindShearModel>,
781    // MBA-1137: optional downrange-segmented atmosphere (zone base swapped by pos.x before lapse).
782    atmo_sock: Option<&AtmoSock>,
783) -> [f64; 6] {
784    let pos = Vector3::new(state[0], state[1], state[2]);
785    let vel = Vector3::new(state[3], state[4], state[5]);
786
787    // Resolve the cached downrange wind in level axes, then apply boundary-layer shear using
788    // height gained above launch. Site elevation is MSL and intentionally does not enter shear.
789    let level_wind = wind_sock.vector_for_range_stateless(pos.x);
790    let level_wind = if let Some(model) = wind_shear_model {
791        let height_rel_launch =
792            crate::atmosphere::shot_frame_altitude(0.0, pos.x, pos.y, inputs.shooting_angle);
793        crate::wind_shear::apply_boundary_layer_shear(level_wind, height_rel_launch, model)
794    } else {
795        level_wind
796    };
797    let wind_vector =
798        crate::derivatives::level_vector_to_shot_frame(level_wind, inputs.shooting_angle);
799
800    // Velocity relative to air
801    let vel_adjusted = vel - wind_vector;
802    let v_mag = vel_adjusted.norm();
803
804    // Gravity acceleration vector, rotated into the shot-aligned frame by shooting_angle
805    // (uphill/downhill inclined fire), matching cli_api::TrajectorySolver::gravity_acceleration.
806    let theta = inputs.shooting_angle;
807    let accel_gravity = Vector3::new(
808        -G_ACCEL_MPS2 * theta.sin(),
809        -G_ACCEL_MPS2 * theta.cos(),
810        0.0,
811    );
812
813    // Calculate acceleration
814    let mut accel = if v_mag < 1e-6 {
815        accel_gravity
816    } else {
817        // Calculate drag
818        let v_fps = v_mag * MPS_TO_FPS;
819
820        // Resolve LOCAL density and speed of sound. Direct mode uses its supplied fixed values;
821        // standard mode evaluates the substep altitude with the lapse-rate pipeline.
822        // `inputs.temperature`/`inputs.pressure` are the standard-mode base (station) T/P set by
823        // fast_integrate from atmo_params; `base_density` is the station-altitude density, so
824        // `base_density / 1.225` recovers the station base_ratio the lapse pipeline expects.
825        //
826        // MBA-1137 (density-freeze fix): previously ONLY the speed of sound was taken from this
827        // call and `density_scale` used the flight-constant `base_density`, so the fast/MC path
828        // held density frozen for the whole flight (density did NOT vary with altitude — a latent
829        // bug the cli_api/derivatives paths already avoid). Now the LOCAL density is used for
830        // `density_scale` below, so the fast path varies density with altitude too.
831        //
832        // MBA-1137 (zones): when a downrange-segmented atmosphere is present, swap the BASE
833        // (station-referenced) temp/pressure/ratio for the zone at the current downrange distance
834        // (pos.x), recomputing the zone base_ratio via CIPM, BEFORE the altitude lapse — so
835        // downrange-zone selection and the world-vertical lapse compose without double-counting.
836        // `None` keeps the single-station base.
837        //
838        // Humidity is NOT plumbed to this call site: on the fast path (fast_integrate) the
839        // `humidity` FIELD is overwritten with atmo_params.3 (the density RATIO), so
840        // `inputs.humidity` is not a real RH — pass 0.0 (dry) rather than fabricate.
841        let (local_density, speed_of_sound) = match atmosphere {
842            FastAtmosphere::Direct {
843                air_density,
844                speed_of_sound,
845            } => (air_density, speed_of_sound),
846            FastAtmosphere::Standard { base_density } => {
847                let altitude = crate::atmosphere::shot_frame_altitude(
848                    inputs.altitude,
849                    pos.x,
850                    pos.y,
851                    inputs.shooting_angle,
852                );
853                let (base_temp_c, base_press_hpa, base_ratio) = match atmo_sock {
854                    Some(sock) => {
855                        let (zt, zp, zh) = sock.atmo_for_range(pos.x);
856                        (zt, zp, calculate_air_density_cimp(zt, zp, zh) / 1.225)
857                    }
858                    None => (inputs.temperature, inputs.pressure, base_density / 1.225),
859                };
860                get_local_atmosphere_humid(
861                    altitude,
862                    inputs.altitude, // base_alt approximation
863                    base_temp_c,
864                    base_press_hpa,
865                    base_ratio,
866                    0.0, // humidity not available here (see note above)
867                )
868            }
869        };
870        let mach = v_mag / speed_of_sound;
871
872        // Get BC value (potentially from segments)
873        let bc_current = match (
874            inputs.bc_segments_data.as_ref(),
875            inputs.bc_segments.as_ref(),
876        ) {
877            (Some(segments_data), _) if inputs.use_bc_segments && has_bc_segments_data => {
878                velocity_segment_bc(v_fps, segments_data, bc)
879            }
880            (_, Some(segments)) if has_bc_segments => {
881                crate::derivatives::interpolated_bc(mach, segments, Some(inputs))
882            }
883            _ => bc,
884        };
885        // Guard bc_value == 0 (allowed on FFI/WASM/public MC surfaces): the division below
886        // would be Inf -> NaN. Mirrors cli_api's effective_bc.max(1e-6); inert for valid BCs.
887        let bc_current = bc_current.max(1e-6);
888
889        // Apply the transonic drag-rise correction once (mirrors derivatives.rs / cli_api) so
890        // the Monte Carlo / fast path doesn't under-predict drag near Mach 1. The projectile
891        // shape is invariant for the whole integration, so it is hoisted into fast_integrate and
892        // passed in rather than recomputed per call. wave_drag=false: the G1/G7 tables already
893        // embed the rise.
894        // MBA-940: a user-supplied custom drag table is the final Cd, used as-is (no G-model
895        // lookup, transonic, or form-factor correction — the curve already encodes the true drag).
896        // Its Cd is the projectile's ACTUAL drag coefficient, so the retardation denominator
897        // must be the sectional density (lb/in²), not a BC: Cd_own / SD == Cd_ref / BC
898        // (see BallisticInputs::custom_drag_denominator).
899        let (drag_factor, retard_denom) = if let Some(ref table) = inputs.custom_drag_table {
900            (
901                // MBA-1357: cd_scale is a single whole-curve drag multiplier applied here, at
902                // the Cd lookup site. The Mach-keyed DSF table (truing_dsf.rs) is a SEPARATE,
903                // drop-only post-processing correction applied to a solved TrajectoryResult's
904                // points after integration finishes — it never touches this drag computation.
905                table.interpolate(mach) * inputs.cd_scale,
906                inputs.custom_drag_denominator(bc_current),
907            )
908        } else {
909            let base_cd = get_drag_coefficient(mach, drag_model);
910            let cd =
911                crate::transonic_drag::transonic_correction(mach, base_cd, projectile_shape, false);
912            (cd, bc_current)
913        };
914
915        // Calculate drag acceleration using proper ballistics formula
916        let cd_to_retard = crate::constants::CD_TO_RETARD;
917        let standard_factor = drag_factor * cd_to_retard;
918        // MBA-1137: use the LOCAL (per-substep) density, not the frozen flight-constant
919        // `base_density`, so drag varies with altitude AND downrange zone.
920        let density_scale = local_density / 1.225;
921
922        // Drag acceleration in ft/s^2
923        let a_drag_ft_s2 = (v_fps * v_fps) * standard_factor * density_scale / retard_denom;
924
925        // Convert to m/s^2 and apply to velocity vector
926        let a_drag_m_s2 = a_drag_ft_s2 * 0.3048; // ft/s^2 to m/s^2
927        let accel_drag = -a_drag_m_s2 * (vel_adjusted / v_mag);
928
929        // The Litz post-process owns the gyroscopic effect whenever it is enabled. Otherwise,
930        // honor the explicit Magnus flag with the same dynamic-Sg/yaw model as sibling solvers.
931        let accel_magnus =
932            fast_magnus_acceleration(inputs, vel_adjusted, local_density, mach, accel_gravity);
933
934        // Total acceleration
935        accel_drag + accel_gravity + accel_magnus
936    };
937
938    // Coriolis (Earth rotation), MBA-957. Omega arrives in level downrange/up/lateral axes;
939    // project it into the inclined shot frame before applying the physical -2 Omega x v.
940    if let Some(omega) = omega {
941        let omega = crate::derivatives::level_vector_to_shot_frame(omega, inputs.shooting_angle);
942        accel += -2.0 * omega.cross(&vel);
943    }
944
945    // Return derivatives [vx, vy, vz, ax, ay, az]
946    [vel.x, vel.y, vel.z, accel.x, accel.y, accel.z]
947}
948
949/// Fast integration with explicit wind segments using RK45
950/// MBA-155: Upstreamed from ballistics_rust
951pub fn fast_integrate_with_segments(
952    inputs: &BallisticInputs,
953    wind_segments: Vec<crate::wind::WindSegment>,
954    params: FastIntegrationParams,
955) -> FastSolution {
956    // Use the RK45 implementation from trajectory_integration module
957    use crate::trajectory_integration::{integrate_trajectory, TrajectoryParams};
958
959    // Malformed wind or a degenerate atmosphere would otherwise silently stub or poison the run.
960    if crate::wind::validate_wind_segments(&wind_segments).is_err()
961        || !atmo_is_physical(params.atmo_params)
962    {
963        return FastSolution::degenerate(&params.initial_state);
964    }
965
966    // MBA-1415: like plain fast_integrate, this is a public entry point external bindings call
967    // directly, so it must apply every input-conditioning step rather than relying on
968    // TrajectorySolver::new. Shadowing `inputs` here means every read below — mass, bc_value,
969    // drag model, the launch state — sees the conditioned values, with no site left to miss.
970    // Idempotent, so inputs that already passed through a solver are unaffected.
971    let mut normalized_inputs = inputs.clone();
972    normalized_inputs.normalize_for_solve();
973    let inputs = &normalized_inputs;
974
975    // Match plain fast_integrate: this entry point also receives a prebuilt launch state, so
976    // apply the experimental aerodynamic-jump angle exactly once before the low-level integrator.
977    let segmented_crosswind_from_right_mps =
978        if inputs.enable_aerodynamic_jump && !wind_segments.is_empty() {
979            WindSock::new(wind_segments.clone()).muzzle_crosswind_from_right_mps()
980        } else {
981            None
982        };
983    let initial_state = launch_state_with_aerodynamic_jump(
984        inputs,
985        params.atmo_params,
986        segmented_crosswind_from_right_mps,
987        params.initial_state,
988    );
989
990    // Extract parameters
991    let mass_kg = inputs.bullet_mass; // SI (kg)
992    let bc = inputs.bc_value;
993    let drag_model = inputs.bc_type;
994
995    // Coriolis omega — gated on enable_coriolis (+ a latitude), INDEPENDENT of
996    // spin-drift/Magnus. A caller can now request Coriolis-only (enable_coriolis=true
997    // with enable_advanced_effects=false) instead of being forced to enable all three.
998    let omega_vector = if inputs.enable_coriolis && inputs.latitude.is_some() {
999        // Calculate omega based on latitude and shot azimuth
1000        // First project Earth's rotation into level downrange/up/lateral axes based on azimuth;
1001        // the derivative kernel handles the additional inclined-shot projection.
1002        // azimuth_angle: 0 = North, pi/2 = East
1003        let omega_earth = 7.2921159e-5; // rad/s
1004        let lat_rad = inputs.latitude.unwrap_or(0.0).to_radians();
1005        let azimuth = inputs.shot_azimuth; // compass bearing (0=N), NOT the aiming offset
1006        Some(Vector3::new(
1007            omega_earth * lat_rad.cos() * azimuth.cos(), // X: downrange component
1008            omega_earth * lat_rad.sin(),                 // Y: vertical component
1009            -omega_earth * lat_rad.cos() * azimuth.sin(), // Z: lateral (MBA-957: corrected sign)
1010        ))
1011    } else {
1012        None
1013    };
1014
1015    // Set up trajectory parameters
1016    let traj_params = TrajectoryParams {
1017        mass_kg,
1018        bc,
1019        drag_model,
1020        wind_segments,
1021        atmos_params: params.atmo_params,
1022        omega_vector,
1023        enable_spin_drift: inputs.use_enhanced_spin_drift,
1024        enable_magnus: inputs.enable_magnus,
1025        enable_coriolis: inputs.enable_coriolis,
1026        target_distance_m: params.horiz,
1027        enable_wind_shear: inputs.enable_wind_shear,
1028        wind_shear_model: inputs.wind_shear_model.clone(),
1029        shooter_altitude_m: inputs.altitude,
1030        is_twist_right: inputs.is_twist_right,
1031        shooting_angle: inputs.shooting_angle,
1032        // MBA-717: carry the real bullet geometry so spin-drift / Magnus use it.
1033        bullet_diameter: inputs.bullet_diameter,
1034        bullet_length: inputs.bullet_length,
1035        twist_rate: inputs.twist_rate,
1036        cd_scale: inputs.cd_scale,
1037        custom_drag_table: inputs.custom_drag_table.clone(),
1038        bc_segments: inputs.bc_segments.clone(),
1039        use_bc_segments: inputs.use_bc_segments,
1040        // MBA-954: keep the historical -1000.0 here (behavior-preserving for this binding path);
1041        // threading inputs.ground_threshold would change the default ground plane for existing
1042        // callers. Direct TrajectoryParams constructors can now configure it.
1043        ground_threshold: -1000.0,
1044        // MBA-1137: forward the downrange-segmented atmosphere to the RK45 derivatives path.
1045        atmo_sock: params.atmo_sock,
1046    };
1047
1048    // Use RK45 adaptive integration
1049    let trajectory = integrate_trajectory(
1050        initial_state,
1051        params.t_span,
1052        traj_params,
1053        "RK45", // Use RK45 implementation
1054        1e-6,   // tolerance
1055        0.01,   // max_step
1056    );
1057
1058    // Convert trajectory to FastSolution format
1059    let n_points = trajectory.len();
1060    let mut times = Vec::with_capacity(n_points + 1);
1061    let mut states = Vec::with_capacity(n_points + 1);
1062
1063    let mut target_hit_time: Option<f64> = None;
1064    let mut ground_hit_time: Option<f64> = None;
1065    let mut max_ord_time = None;
1066    let mut max_ord_y = 0.0;
1067
1068    for (t, state_vec) in trajectory {
1069        // Convert Vector6 to array
1070        let state = [
1071            state_vec[0],
1072            state_vec[1],
1073            state_vec[2],
1074            state_vec[3],
1075            state_vec[4],
1076            state_vec[5],
1077        ];
1078
1079        // Check termination conditions
1080        // McCoy: state[0]=downrange, state[1]=vertical, state[2]=lateral
1081
1082        // The RK45 integrator intentionally returns only ~50 range-spaced states. Use vertical
1083        // velocity to recover an apex between adjacent saves, and retain the synthetic point so
1084        // FastSolution::sol(max_ord_time) returns its Hermite-interpolated height rather than the
1085        // lower straight chord between coarse samples.
1086        if let Some((&previous_time, &previous_state)) = times.last().zip(states.last()) {
1087            if let Some((apex_time, apex_state)) =
1088                interpolated_vertical_apex(previous_time, &previous_state, t, &state)
1089            {
1090                if apex_state[1] > max_ord_y {
1091                    max_ord_y = apex_state[1];
1092                    max_ord_time = Some(apex_time);
1093                }
1094                times.push(apex_time);
1095                states.push(apex_state);
1096            }
1097        }
1098
1099        // Record FIRST time target is hit
1100        if target_hit_time.is_none() && state[0] >= params.horiz {
1101            target_hit_time = Some(t);
1102        }
1103
1104        // Record ground hit
1105        if ground_hit_time.is_none() && state[1] <= inputs.ground_threshold {
1106            ground_hit_time = Some(t);
1107        }
1108
1109        // Track maximum ordinate
1110        if state[1] > max_ord_y {
1111            max_ord_y = state[1];
1112            max_ord_time = Some(t);
1113        }
1114
1115        times.push(t);
1116        states.push(state);
1117    }
1118
1119    // Create event arrays
1120    let t_events = [
1121        if let Some(t) = target_hit_time {
1122            vec![t]
1123        } else {
1124            vec![]
1125        },
1126        if let Some(t) = max_ord_time {
1127            vec![t]
1128        } else {
1129            vec![]
1130        },
1131        if let Some(t) = ground_hit_time {
1132            vec![t]
1133        } else {
1134            vec![]
1135        },
1136    ];
1137
1138    // MBA-1134 (rank 10): the derivatives kernel no longer integrates spin drift, so apply the
1139    // canonical empirical Litz drift as a post-process to the lateral (McCoy Z) of every point at
1140    // its time of flight — matching cli_api::apply_spin_drift and the Monte-Carlo path so all three
1141    // solver families agree. Uses the SAME muzzle Sg (spin_drift::effective_sg_from_inputs).
1142    if inputs.use_enhanced_spin_drift {
1143        // Standard-mode atmo_params is (base_alt, temp_c, press_hpa, ratio); direct mode
1144        // (density, sound, 0, 0) carries no explicit temp/pressure, so fall back to sea-level
1145        // standard (the Sg density correction is a no-op there).
1146        let (sd_temp_c, sd_press_hpa) = if params.atmo_params.2 > 0.0 {
1147            (params.atmo_params.1, params.atmo_params.2)
1148        } else {
1149            (15.0, 1013.25)
1150        };
1151        let sg = crate::spin_drift::effective_sg_from_inputs(inputs, sd_temp_c, sd_press_hpa);
1152        for (t, state) in times.iter().zip(states.iter_mut()) {
1153            if *t > 0.0 {
1154                state[2] += crate::spin_drift::litz_drift_meters(sg, *t, inputs.is_twist_right);
1155            }
1156        }
1157    }
1158
1159    FastSolution::from_trajectory_data(times, states, t_events)
1160}
1161
1162#[cfg(test)]
1163mod tests {
1164    use super::*;
1165    use crate::BCSegmentData;
1166
1167    fn expected_shot_frame_vector(level: Vector3<f64>, angle: f64) -> Vector3<f64> {
1168        let (sin_angle, cos_angle) = angle.sin_cos();
1169        Vector3::new(
1170            level.x * cos_angle + level.y * sin_angle,
1171            -level.x * sin_angle + level.y * cos_angle,
1172            level.z,
1173        )
1174    }
1175
1176    #[test]
1177    fn measured_bc_fast_drag_ignores_name_based_form_factor_flag() {
1178        let derivatives_with_flag = |use_form_factor| {
1179            let inputs = BallisticInputs {
1180                bc_value: 0.462,
1181                bc_type: DragModel::G1,
1182                bullet_model: Some("168gr SMK Match".to_string()),
1183                use_form_factor,
1184                temperature: 15.0,
1185                pressure: 1013.25,
1186                ..BallisticInputs::default()
1187            };
1188
1189            compute_derivatives(
1190                &[0.0, 0.0, 0.0, 600.0, 0.0, 0.0],
1191                &inputs,
1192                &WindSock::new(vec![]),
1193                FastAtmosphere::Standard {
1194                    base_density: 1.225,
1195                },
1196                &inputs.bc_type,
1197                crate::transonic_drag::ProjectileShape::Spitzer,
1198                inputs.bc_value,
1199                false,
1200                false,
1201                None,
1202                None,
1203                None,
1204            )
1205        };
1206
1207        let baseline = derivatives_with_flag(false);
1208        let flagged = derivatives_with_flag(true);
1209
1210        for component in 3..6 {
1211            assert_eq!(
1212                flagged[component].to_bits(),
1213                baseline[component].to_bits(),
1214                "published BC already encodes form factor: component {component}, baseline={} flagged={}",
1215                baseline[component],
1216                flagged[component]
1217            );
1218        }
1219    }
1220
1221    #[test]
1222    fn velocity_bc_data_requires_opt_in_in_plain_fast_kernel() {
1223        let acceleration = |inputs: &BallisticInputs| {
1224            let has_mach_segments = inputs
1225                .bc_segments
1226                .as_ref()
1227                .is_some_and(|segments| !segments.is_empty());
1228            let has_velocity_segments = inputs
1229                .bc_segments_data
1230                .as_ref()
1231                .is_some_and(|segments| !segments.is_empty());
1232            compute_derivatives(
1233                &[0.0, 0.0, 0.0, 600.0, 0.0, 0.0],
1234                inputs,
1235                &WindSock::new(vec![]),
1236                FastAtmosphere::Standard {
1237                    base_density: 1.225,
1238                },
1239                &inputs.bc_type,
1240                crate::transonic_drag::ProjectileShape::Spitzer,
1241                inputs.bc_value,
1242                has_mach_segments,
1243                has_velocity_segments,
1244                None,
1245                None,
1246                None,
1247            )
1248        };
1249
1250        let scalar_inputs = BallisticInputs {
1251            bc_value: 0.5,
1252            bc_type: DragModel::G7,
1253            temperature: 15.0,
1254            pressure: 1013.25,
1255            ..BallisticInputs::default()
1256        };
1257        let mut disabled_inputs = scalar_inputs.clone();
1258        disabled_inputs.bc_segments_data = Some(vec![BCSegmentData {
1259            velocity_min: 0.0,
1260            velocity_max: 4_000.0,
1261            bc_value: 0.46,
1262        }]);
1263        disabled_inputs.use_bc_segments = false;
1264        let mut enabled_inputs = disabled_inputs.clone();
1265        enabled_inputs.use_bc_segments = true;
1266        let mut mach_only_inputs = scalar_inputs.clone();
1267        mach_only_inputs.bc_segments = Some(vec![(0.0, 0.4), (3.0, 0.4)]);
1268        let mut disabled_with_both = mach_only_inputs.clone();
1269        disabled_with_both.bc_segments_data = disabled_inputs.bc_segments_data.clone();
1270
1271        let scalar = acceleration(&scalar_inputs);
1272        let disabled = acceleration(&disabled_inputs);
1273        let enabled = acceleration(&enabled_inputs);
1274        let mach_only = acceleration(&mach_only_inputs);
1275        let disabled_with_both = acceleration(&disabled_with_both);
1276
1277        assert_eq!(
1278            disabled[3].to_bits(),
1279            scalar[3].to_bits(),
1280            "a populated velocity table must not change drag while use_bc_segments is false"
1281        );
1282        assert!(
1283            enabled[3] < disabled[3] - 1.0,
1284            "enabling the lower BC table must increase drag: disabled ax={} enabled ax={}",
1285            disabled[3],
1286            enabled[3]
1287        );
1288        assert_eq!(
1289            disabled_with_both[3].to_bits(),
1290            mach_only[3].to_bits(),
1291            "disabling velocity data must fall through to an explicit Mach table"
1292        );
1293    }
1294
1295    #[test]
1296    fn inclined_positions_at_same_world_altitude_have_same_fast_acceleration() {
1297        let angle = std::f64::consts::FRAC_PI_6;
1298        let inputs = BallisticInputs {
1299            altitude: 100.0,
1300            temperature: 15.0,
1301            pressure: 1013.25,
1302            shooting_angle: angle,
1303            ..BallisticInputs::default()
1304        };
1305        let wind_sock = WindSock::new(vec![]);
1306        let atmosphere = FastAtmosphere::Standard {
1307            base_density: 1.225,
1308        };
1309        let state_along_slant = [1_000.0, 0.0, 0.0, 600.0, 0.0, 0.0];
1310        let state_across_slant = [0.0, 500.0 / angle.cos(), 0.0, 600.0, 0.0, 0.0];
1311
1312        let a = compute_derivatives(
1313            &state_along_slant,
1314            &inputs,
1315            &wind_sock,
1316            atmosphere,
1317            &inputs.bc_type,
1318            crate::transonic_drag::ProjectileShape::Spitzer,
1319            inputs.bc_value,
1320            false,
1321            false,
1322            None,
1323            None,
1324            None,
1325        );
1326        let b = compute_derivatives(
1327            &state_across_slant,
1328            &inputs,
1329            &wind_sock,
1330            atmosphere,
1331            &inputs.bc_type,
1332            crate::transonic_drag::ProjectileShape::Spitzer,
1333            inputs.bc_value,
1334            false,
1335            false,
1336            None,
1337            None,
1338            None,
1339        );
1340
1341        for component in 3..6 {
1342            assert!(
1343                (a[component] - b[component]).abs() < 1e-10,
1344                "fast derivative component {component} differs at equal world altitude: {} vs {}",
1345                a[component],
1346                b[component]
1347            );
1348        }
1349    }
1350
1351    #[test]
1352    fn inclined_headwind_is_rotated_into_solver_frame() {
1353        let angle = std::f64::consts::FRAC_PI_6;
1354        let inputs = BallisticInputs {
1355            shooting_angle: angle,
1356            ..BallisticInputs::default()
1357        };
1358        let speed_mps = 360.0 * (1000.0 / 3600.0);
1359        let level_headwind = Vector3::new(-speed_mps, 0.0, 0.0);
1360        let velocity = expected_shot_frame_vector(level_headwind, angle);
1361        let state = [0.0, 0.0, 0.0, velocity.x, velocity.y, velocity.z];
1362        let actual = compute_derivatives(
1363            &state,
1364            &inputs,
1365            &WindSock::new(vec![crate::wind::WindSegment::new(360.0, 0.0, 1000.0)]),
1366            FastAtmosphere::Direct {
1367                air_density: 1.225,
1368                speed_of_sound: 340.0,
1369            },
1370            &inputs.bc_type,
1371            crate::transonic_drag::ProjectileShape::Spitzer,
1372            inputs.bc_value,
1373            false,
1374            false,
1375            None,
1376            None,
1377            None,
1378        );
1379        let expected = Vector3::new(
1380            -G_ACCEL_MPS2 * angle.sin(),
1381            -G_ACCEL_MPS2 * angle.cos(),
1382            0.0,
1383        );
1384
1385        assert!(
1386            (Vector3::new(actual[3], actual[4], actual[5]) - expected).norm() < 1e-12,
1387            "co-moving horizontal wind must leave only shot-frame gravity: {actual:?}"
1388        );
1389    }
1390
1391    #[test]
1392    fn plain_fast_kernel_applies_power_law_wind_shear() {
1393        let state = [500.0, 100.0, 0.0, 700.0, 0.0, 0.0];
1394        let run = |enable_wind_shear: bool, model: &str, wind_speed_kmh: f64| {
1395            let inputs = BallisticInputs {
1396                bc_value: 0.5,
1397                bc_type: DragModel::G7,
1398                enable_wind_shear,
1399                wind_shear_model: model.to_string(),
1400                ..BallisticInputs::default()
1401            };
1402            let wind_shear_model = enable_wind_shear
1403                .then(|| crate::wind_shear::boundary_layer_model_from_name(model))
1404                .filter(|model| *model != crate::wind_shear::WindShearModel::None);
1405            compute_derivatives(
1406                &state,
1407                &inputs,
1408                &WindSock::new(vec![crate::wind::WindSegment::new(
1409                    wind_speed_kmh,
1410                    90.0,
1411                    2_000.0,
1412                )]),
1413                FastAtmosphere::Direct {
1414                    air_density: 1.225,
1415                    speed_of_sound: 340.0,
1416                },
1417                &inputs.bc_type,
1418                crate::transonic_drag::ProjectileShape::Spitzer,
1419                inputs.bc_value,
1420                false,
1421                false,
1422                None,
1423                wind_shear_model,
1424                None,
1425            )
1426        };
1427
1428        let uniform = run(false, "power_law", 36.0);
1429        let model_none = run(true, "none", 36.0);
1430        assert_eq!(model_none, uniform, "model=none must preserve uniform wind");
1431
1432        let sheared = run(true, "power_law", 36.0);
1433        assert!(
1434            sheared[5] < uniform[5],
1435            "stronger aloft crosswind must increase leftward acceleration: uniform={}, shear={}",
1436            uniform[5],
1437            sheared[5]
1438        );
1439
1440        let ratio = crate::wind_shear::boundary_layer_speed_ratio(
1441            state[1],
1442            crate::wind_shear::WindShearModel::PowerLaw,
1443        );
1444        let equivalent_uniform = run(false, "none", 36.0 * ratio);
1445        for component in 3..6 {
1446            assert!(
1447                (sheared[component] - equivalent_uniform[component]).abs() < 1e-12,
1448                "shear component {component} must equal base wind scaled by {ratio}: shear={}, expected={}",
1449                sheared[component],
1450                equivalent_uniform[component]
1451            );
1452        }
1453    }
1454
1455    #[test]
1456    fn plain_fast_path_wind_shear_changes_high_arc_drift() {
1457        let run = |enable_wind_shear: bool, model: &str| {
1458            let inputs = BallisticInputs {
1459                muzzle_velocity: 800.0,
1460                bc_value: 0.5,
1461                bc_type: DragModel::G7,
1462                bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
1463                bullet_diameter: 0.308 * 0.0254,
1464                enable_wind_shear,
1465                wind_shear_model: model.to_string(),
1466                ground_threshold: -100.0,
1467                ..BallisticInputs::default()
1468            };
1469            let elevation = 0.12_f64;
1470            let solution = fast_integrate(
1471                &inputs,
1472                &WindSock::new(vec![crate::wind::WindSegment::new(36.0, 90.0, 2_000.0)]),
1473                FastIntegrationParams {
1474                    horiz: 1_000.0,
1475                    vert: 0.0,
1476                    initial_state: [
1477                        0.0,
1478                        0.0,
1479                        0.0,
1480                        inputs.muzzle_velocity * elevation.cos(),
1481                        inputs.muzzle_velocity * elevation.sin(),
1482                        0.0,
1483                    ],
1484                    t_span: (0.0, 5.0),
1485                    atmo_params: (0.0, 15.0, 1013.25, 1.0),
1486                    atmo_sock: None,
1487                },
1488            );
1489            let last = solution.t.len() - 1;
1490            assert_eq!(solution.y[0][last].to_bits(), 1_000.0_f64.to_bits());
1491            solution.y[2][last]
1492        };
1493
1494        let uniform = run(false, "power_law");
1495        let model_none = run(true, "none");
1496        assert_eq!(model_none.to_bits(), uniform.to_bits());
1497        let sheared = run(true, "power_law");
1498        assert!(
1499            sheared.abs() > uniform.abs() + 0.01,
1500            "aloft shear must increase drift magnitude: uniform={uniform}, shear={sheared}"
1501        );
1502    }
1503
1504    #[test]
1505    fn inclined_coriolis_is_rotated_into_solver_frame() {
1506        let angle = std::f64::consts::FRAC_PI_6;
1507        let inputs = BallisticInputs {
1508            shooting_angle: angle,
1509            ..BallisticInputs::default()
1510        };
1511        let velocity = Vector3::new(600.0, 20.0, 5.0);
1512        let state = [0.0, 0.0, 0.0, velocity.x, velocity.y, velocity.z];
1513        let level_omega = Vector3::new(3.0e-5, 6.0e-5, -2.0e-5);
1514        let run = |omega| {
1515            compute_derivatives(
1516                &state,
1517                &inputs,
1518                &WindSock::new(vec![]),
1519                FastAtmosphere::Direct {
1520                    air_density: 1.225,
1521                    speed_of_sound: 340.0,
1522                },
1523                &inputs.bc_type,
1524                crate::transonic_drag::ProjectileShape::Spitzer,
1525                inputs.bc_value,
1526                false,
1527                false,
1528                omega,
1529                None,
1530                None,
1531            )
1532        };
1533        let baseline = run(None);
1534        let with_coriolis = run(Some(level_omega));
1535        let actual = Vector3::new(
1536            with_coriolis[3] - baseline[3],
1537            with_coriolis[4] - baseline[4],
1538            with_coriolis[5] - baseline[5],
1539        );
1540        let expected = -2.0 * expected_shot_frame_vector(level_omega, angle).cross(&velocity);
1541
1542        assert!(
1543            (actual - expected).norm() < 1e-12,
1544            "inclined Coriolis mismatch: actual={actual:?}, expected={expected:?}"
1545        );
1546    }
1547
1548    #[test]
1549    fn test_fast_solution_interpolation() {
1550        let times = vec![0.0, 1.0, 2.0];
1551        let states = vec![
1552            [0.0, 0.0, 0.0, 100.0, 50.0, 0.0],
1553            [100.0, 45.0, 0.0, 99.0, 40.0, 0.0],
1554            [198.0, 80.0, 0.0, 98.0, 30.0, 0.0],
1555        ];
1556
1557        let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
1558
1559        // Test interpolation at t=1.5
1560        let result = solution.sol(&[1.5]);
1561
1562        assert!((result[0][0] - 149.0).abs() < 1e-10); // x position
1563        assert!((result[1][0] - 62.5).abs() < 1e-10); // y position
1564        assert!((result[3][0] - 98.5).abs() < 1e-10); // vx velocity
1565    }
1566
1567    #[test]
1568    fn test_bc_from_velocity_segments() {
1569        let segments = vec![
1570            BCSegmentData {
1571                velocity_min: 0.0,
1572                velocity_max: 1000.0,
1573                bc_value: 0.5,
1574            },
1575            BCSegmentData {
1576                velocity_min: 1000.0,
1577                velocity_max: 2000.0,
1578                bc_value: 0.52,
1579            },
1580            BCSegmentData {
1581                velocity_min: 2000.0,
1582                velocity_max: 3000.0,
1583                bc_value: 0.55,
1584            },
1585        ];
1586
1587        // MBA-1404: every one of these query points is >25 fps (half the 50 fps-capped
1588        // margin on all three 1000 fps-wide bands) away from the nearest boundary/coverage
1589        // edge, so none of them fall inside a smoothstep blend window -- values are
1590        // unchanged from the pre-MBA-1404 step behavior.
1591        assert_eq!(velocity_segment_bc(500.0, &segments, 0.5), 0.5);
1592        assert_eq!(velocity_segment_bc(1500.0, &segments, 0.5), 0.52);
1593        assert_eq!(velocity_segment_bc(2500.0, &segments, 0.5), 0.55);
1594
1595        // Test edge cases
1596        assert_eq!(velocity_segment_bc(-100.0, &segments, 0.5), 0.5); // Below min
1597        assert_eq!(velocity_segment_bc(3500.0, &segments, 0.5), 0.55); // Above max
1598    }
1599
1600    #[test]
1601    fn test_fast_solution_interpolation_edge_cases() {
1602        let times = vec![0.0, 1.0, 2.0, 3.0];
1603        let states = vec![
1604            [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1605            [800.0, 40.0, 100.0, 750.0, 30.0, 0.0],
1606            [1550.0, 60.0, 200.0, 700.0, 10.0, 0.0],
1607            [2250.0, 50.0, 300.0, 650.0, -10.0, 0.0],
1608        ];
1609
1610        let solution = FastSolution::from_trajectory_data(times, states, [vec![], vec![], vec![]]);
1611
1612        // Test interpolation before first point
1613        let result_before = solution.sol(&[-0.5]);
1614        assert!((result_before[0][0] - 0.0).abs() < 1e-10); // Should clamp to first
1615
1616        // Test interpolation after last point
1617        let result_after = solution.sol(&[5.0]);
1618        assert!((result_after[0][0] - 2250.0).abs() < 1e-10); // Should clamp to last
1619
1620        // Test interpolation at exact points
1621        let result_exact = solution.sol(&[1.0]);
1622        assert!((result_exact[0][0] - 800.0).abs() < 1e-10);
1623
1624        // Test multiple query points
1625        let result_multi = solution.sol(&[0.5, 1.5, 2.5]);
1626        assert_eq!(result_multi[0].len(), 3);
1627    }
1628
1629    #[test]
1630    fn test_fast_solution_from_trajectory_data() {
1631        let times = vec![0.0, 0.5, 1.0];
1632        let states = vec![
1633            [0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
1634            [10.0, 11.0, 12.0, 13.0, 14.0, 15.0],
1635            [20.0, 21.0, 22.0, 23.0, 24.0, 25.0],
1636        ];
1637        let t_events = [vec![1.0], vec![0.5], vec![]];
1638
1639        let solution = FastSolution::from_trajectory_data(times.clone(), states, t_events);
1640
1641        // Check that data is stored correctly
1642        assert_eq!(solution.t, times);
1643        assert_eq!(solution.y.len(), 6); // 6 state components
1644        assert_eq!(solution.y[0].len(), 3); // 3 time points
1645        assert!(solution.success);
1646
1647        // Verify column-major storage
1648        assert_eq!(solution.y[0][0], 0.0); // x at t=0
1649        assert_eq!(solution.y[1][0], 1.0); // y at t=0
1650        assert_eq!(solution.y[0][2], 20.0); // x at t=1.0
1651    }
1652
1653    #[test]
1654    fn test_bc_segments_boundary_conditions() {
1655        // Test with single segment
1656        // MBA-1404: a single-segment table has no adjacent band to blend against, so this
1657        // stays byte-identical to the pre-MBA-1404 step/clamp lookup everywhere.
1658        let single_segment = vec![BCSegmentData {
1659            velocity_min: 1000.0,
1660            velocity_max: 2000.0,
1661            bc_value: 0.5,
1662        }];
1663
1664        assert_eq!(velocity_segment_bc(500.0, &single_segment, 0.5), 0.5); // Below
1665        assert_eq!(velocity_segment_bc(1500.0, &single_segment, 0.5), 0.5); // In range
1666        assert_eq!(velocity_segment_bc(2500.0, &single_segment, 0.5), 0.5); // Above
1667
1668        // Test with exact boundary values
1669        // Half-open bands make a shared boundary belong to the band that starts there.
1670        // A ends at 999, B starts at 1000: a 1 fps interior gap falls back to bc=0.7.
1671        let segments = vec![
1672            BCSegmentData {
1673                velocity_min: 0.0,
1674                velocity_max: 999.0, // Exclusive upper bound to avoid overlap
1675                bc_value: 0.45,
1676            },
1677            BCSegmentData {
1678                velocity_min: 1000.0,
1679                velocity_max: 2000.0,
1680                bc_value: 0.50,
1681            },
1682        ];
1683
1684        // MBA-1404: the 1 fps gap caps both of its edges' margins to
1685        // min(50, 0.25*1) = 0.25 fps (half-margin 0.125 fps either side of 999 and 1000).
1686        // v=1000.0 is now the gap-entry boundary's exact center (t=0.5): it blends halfway
1687        // between the gap's fallback (0.7) and band B (0.50) instead of hard-stepping to
1688        // band B alone. This is a deliberate, exact-value update -- not a loosened
1689        // tolerance -- and would fail against the old step behavior (0.50).
1690        assert_eq!(velocity_segment_bc(1000.0, &segments, 0.7), 0.6); // At second segment start (blended)
1691                                                                      // v=0.0 is the coverage-entry boundary's center, but that edge is a no-op blend:
1692                                                                      // the clamp below band A returns the same value band A itself would, so this stays
1693                                                                      // exactly flat and is unchanged from before MBA-1404.
1694        assert_eq!(velocity_segment_bc(0.0, &segments, 0.7), 0.45); // At min (coverage edge: still flat, no jump to smooth)
1695                                                                    // v=998.999 is inside the gap-exit boundary's [998.875, 999.125] margin window
1696                                                                    // (t=0.496), partway through the smoothstep blend from band A (0.45) toward the
1697                                                                    // gap's fallback (0.7).
1698        assert_eq!(
1699            velocity_segment_bc(998.999, &segments, 0.7),
1700            0.5735000320000354
1701        ); // Just below exclusive max (blending toward the gap)
1702           // v=999.0 is the gap-exit boundary's exact center (t=0.5): halfway between band A
1703           // (0.45) and the fallback (0.7), not the old hard fallback value (0.7) alone.
1704        assert_eq!(velocity_segment_bc(999.0, &segments, 0.7), 0.575); // Gap starts at exclusive max (blended)
1705    }
1706
1707    #[test]
1708    fn velocity_segment_gaps_and_clamps_do_not_depend_on_order() {
1709        let fallback_bc = 0.73;
1710        let ascending_with_gap = vec![
1711            BCSegmentData {
1712                velocity_min: 0.0,
1713                velocity_max: 999.0,
1714                bc_value: 0.6,
1715            },
1716            BCSegmentData {
1717                velocity_min: 1000.0,
1718                velocity_max: 2000.0,
1719                bc_value: 0.8,
1720            },
1721        ];
1722        // MBA-1404: v=999.5 is dead center of the 1 fps gap, 0.5 fps from each edge --
1723        // comfortably outside either edge's +/-0.125 fps blend margin (min(50, 0.25*1)) --
1724        // so this stays exactly the fallback, unchanged from before MBA-1404.
1725        assert_eq!(
1726            velocity_segment_bc(999.5, &ascending_with_gap, fallback_bc),
1727            fallback_bc,
1728            "coverage gaps must use the projectile's base BC"
1729        );
1730
1731        let mut descending = ascending_with_gap.clone();
1732        descending.reverse();
1733        // MBA-1404: -100/2500 are far outside the +/-25 fps coverage-entry/exit margins
1734        // (min(50, 0.25*999) and min(50, 0.25*1000)), so these clamps are unchanged too.
1735        assert_eq!(
1736            velocity_segment_bc(-100.0, &descending, fallback_bc),
1737            0.6,
1738            "below coverage must clamp to the lowest-velocity band"
1739        );
1740        assert_eq!(
1741            velocity_segment_bc(2500.0, &descending, fallback_bc),
1742            0.8,
1743            "above coverage must clamp to the highest-velocity band"
1744        );
1745    }
1746
1747    #[test]
1748    fn test_bc_segments_empty_fallback() {
1749        let empty_segments: Vec<BCSegmentData> = vec![];
1750
1751        // MBA-1404: an empty table has no adjacent bands to blend against, so this stays
1752        // byte-identical to the pre-MBA-1404 behavior (always the fallback).
1753        // With empty segments, should return fallback value
1754        let result = velocity_segment_bc(1500.0, &empty_segments, 0.73);
1755        assert_eq!(result, 0.73); // Caller-provided fallback value
1756    }
1757
1758    #[test]
1759    fn test_fast_integration_params() {
1760        // Verify FastIntegrationParams struct can be constructed
1761        let params = FastIntegrationParams {
1762            horiz: 1000.0,
1763            vert: 0.0,
1764            initial_state: [0.0, 0.0, 0.0, 800.0, 50.0, 0.0], // McCoy: vx=downrange
1765            t_span: (0.0, 5.0),
1766            atmo_params: (0.0, 15.0, 1013.25, 1.0),
1767            atmo_sock: None,
1768        };
1769
1770        assert_eq!(params.horiz, 1000.0);
1771        assert_eq!(params.t_span.0, 0.0);
1772        assert_eq!(params.t_span.1, 5.0);
1773        assert_eq!(params.initial_state[3], 800.0); // vx (downrange, McCoy)
1774    }
1775
1776    #[test]
1777    fn test_fast_solution_event_arrays() {
1778        let times = vec![0.0, 1.0, 2.0];
1779        let states = vec![
1780            [0.0, 0.0, 0.0, 800.0, 50.0, 0.0],
1781            [800.0, 40.0, 500.0, 750.0, 30.0, 0.0],
1782            [1500.0, 20.0, 1000.0, 700.0, 10.0, 0.0],
1783        ];
1784
1785        // Create solution with events
1786        let t_events = [
1787            vec![2.0], // target_hit at t=2
1788            vec![0.5], // max_ord at t=0.5
1789            vec![],    // no ground_hit
1790        ];
1791
1792        let solution = FastSolution::from_trajectory_data(times, states, t_events);
1793
1794        assert_eq!(solution.t_events[0], vec![2.0]); // Target hit
1795        assert_eq!(solution.t_events[1], vec![0.5]); // Max ordinate
1796        assert!(solution.t_events[2].is_empty()); // No ground hit
1797    }
1798
1799    #[test]
1800    fn segmented_fast_path_interpolates_max_ordinate_between_saved_points() {
1801        let expected_apex_time = 5.105_f64;
1802        let downrange_velocity = 100.0_f64;
1803        let vertical_velocity = G_ACCEL_MPS2 * expected_apex_time;
1804        let inputs = BallisticInputs {
1805            muzzle_velocity: downrange_velocity.hypot(vertical_velocity),
1806            bc_value: 0.5,
1807            bc_type: DragModel::G7,
1808            use_enhanced_spin_drift: false,
1809            ..BallisticInputs::default()
1810        };
1811        let solution = fast_integrate_with_segments(
1812            &inputs,
1813            vec![],
1814            FastIntegrationParams {
1815                horiz: 1_000.0,
1816                vert: 0.0,
1817                initial_state: [0.0, 0.0, 0.0, downrange_velocity, vertical_velocity, 0.0],
1818                t_span: (0.0, 12.0),
1819                // Negligible density makes this an analytic constant-gravity arc while retaining
1820                // the valid direct-atmosphere sentinel.
1821                atmo_params: (1e-12, 340.0, 0.0, 0.0),
1822                atmo_sock: None,
1823            },
1824        );
1825
1826        assert!(solution.success);
1827        assert_eq!(solution.t_events[1].len(), 1);
1828        let reported_time = solution.t_events[1][0];
1829        assert!(
1830            (reported_time - expected_apex_time).abs() < 0.006,
1831            "max-ordinate time must be interpolated between coarse saves: reported={reported_time} expected={expected_apex_time}"
1832        );
1833        let event_index = solution
1834            .t
1835            .iter()
1836            .position(|time| time.to_bits() == reported_time.to_bits())
1837            .expect("the interpolated apex must be retained in the solution");
1838        assert_eq!(solution.y[4][event_index].to_bits(), 0.0_f64.to_bits());
1839
1840        let expected_height = vertical_velocity * expected_apex_time
1841            - 0.5 * G_ACCEL_MPS2 * expected_apex_time.powi(2);
1842        let event_state = solution.sol(&[reported_time]);
1843        assert!(
1844            (event_state[1][0] - expected_height).abs() < 2e-4,
1845            "max-ordinate state must preserve the interpolated apex height: reported={} expected={expected_height}",
1846            event_state[1][0]
1847        );
1848    }
1849
1850    #[test]
1851    fn plain_fast_path_interpolates_the_target_crossing() {
1852        let target = 500.123456789;
1853        let initial_state = [0.0, 0.0, 0.25, 800.0, 12.0, -2.5];
1854        let inputs = BallisticInputs {
1855            muzzle_velocity: 800.0,
1856            bc_value: 0.5,
1857            bc_type: DragModel::G7,
1858            ground_threshold: -100.0,
1859            use_enhanced_spin_drift: false,
1860            ..BallisticInputs::default()
1861        };
1862        let run = |horiz| {
1863            fast_integrate(
1864                &inputs,
1865                &WindSock::new(vec![]),
1866                FastIntegrationParams {
1867                    horiz,
1868                    vert: 0.0,
1869                    initial_state,
1870                    t_span: (0.0, 2.0),
1871                    atmo_params: (0.0, 15.0, 1013.25, 1.0),
1872                    atmo_sock: None,
1873                },
1874            )
1875        };
1876
1877        // A longer run retains the two full RK4 samples bracketing the requested target.
1878        let reference = run(target + 2.0);
1879        let left = reference.y[0]
1880            .windows(2)
1881            .position(|x| x[0] < target && x[1] > target)
1882            .expect("reference trajectory must bracket target");
1883        let right = left + 1;
1884        let alpha =
1885            (target - reference.y[0][left]) / (reference.y[0][right] - reference.y[0][left]);
1886
1887        let solution = run(target);
1888        let last = solution.t.len() - 1;
1889        assert_eq!(solution.y[0][last].to_bits(), target.to_bits());
1890        let expected_time = reference.t[left] + alpha * (reference.t[right] - reference.t[left]);
1891        assert!((solution.t[last] - expected_time).abs() < 1e-12);
1892        assert_eq!(solution.t_events[0], vec![solution.t[last]]);
1893
1894        for component in 0..6 {
1895            assert_eq!(solution.y[component].len(), solution.t.len());
1896            let expected = reference.y[component][left]
1897                + alpha * (reference.y[component][right] - reference.y[component][left]);
1898            assert!(
1899                (solution.y[component][last] - expected).abs() < 1e-9,
1900                "component {component} is not at the crossing: actual={}, expected={expected}",
1901                solution.y[component][last]
1902            );
1903        }
1904    }
1905
1906    #[test]
1907    fn fast_path_coriolis_uses_shot_direction() {
1908        // Regression: fast_integrate_with_segments (the path the Python binding uses)
1909        // built its Coriolis omega from azimuth_angle (the aiming offset, always ~0)
1910        // instead of shot_azimuth, so east and west shots came out identical. After the
1911        // fix they must differ with the correct Eotvos sign (east lifted, higher).
1912        use std::f64::consts::FRAC_PI_2;
1913        // Returns (final_downrange, final_vertical) for a shot fired along `shot_az`.
1914        fn final_xy(shot_az: f64) -> (f64, f64) {
1915            let inputs = BallisticInputs {
1916                muzzle_velocity: 800.0,
1917                bc_value: 0.5,
1918                bc_type: DragModel::G7,
1919                enable_advanced_effects: true, // gates the omega vector
1920                enable_coriolis: true,
1921                latitude: Some(45.0),
1922                shot_azimuth: shot_az,
1923                ..BallisticInputs::default()
1924            };
1925            let v = 800.0_f64;
1926            let elev = 0.02_f64;
1927            let params = FastIntegrationParams {
1928                horiz: 1000.0,
1929                vert: 0.0,
1930                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1931                t_span: (0.0, 5.0),
1932                atmo_params: (0.0, 15.0, 1013.25, 1.0),
1933                atmo_sock: None,
1934            };
1935            let sol = fast_integrate_with_segments(&inputs, vec![], params);
1936            let n = sol.y[0].len();
1937            (sol.y[0][n - 1], sol.y[1][n - 1])
1938        }
1939        let (ex, ey) = final_xy(FRAC_PI_2); // east
1940        let (wx, wy) = final_xy(3.0 * FRAC_PI_2); // west
1941                                                  // Both shots cover essentially the same downrange (Coriolis barely affects x),
1942                                                  // so comparing the final vertical is apples-to-apples.
1943        assert!(
1944            (ex - wx).abs() < 0.5,
1945            "east/west downrange should be ~equal (ex={ex:.4}, wx={wx:.4})"
1946        );
1947        // Pre-fix the fast path was North-locked, making these byte-identical. The Eotvos
1948        // term now lifts the east shot above the west shot.
1949        assert!(
1950            ey > wy,
1951            "fast-path east ({ey:.6}) must be higher than west ({wy:.6}) (Eotvos)"
1952        );
1953        assert!(
1954            (ey - wy) > 1e-5,
1955            "fast-path E-W vertical separation ({:.8} m) should be non-zero (the pre-fix bug was exact equality)",
1956            ey - wy
1957        );
1958    }
1959
1960    #[test]
1961    fn fast_path_coriolis_independent_of_advanced_effects() {
1962        // Coriolis is now gated on enable_coriolis (+ latitude), NOT enable_advanced_effects.
1963        // So a caller can request Coriolis-only without being forced to enable spin/Magnus.
1964        use std::f64::consts::FRAC_PI_2;
1965        fn final_y(coriolis: bool, shot_az: f64) -> f64 {
1966            let inputs = BallisticInputs {
1967                muzzle_velocity: 800.0,
1968                bc_value: 0.5,
1969                bc_type: DragModel::G7,
1970                enable_coriolis: coriolis,
1971                enable_advanced_effects: false, // explicitly OFF — Coriolis must still work
1972                latitude: Some(45.0),
1973                shot_azimuth: shot_az,
1974                ..BallisticInputs::default()
1975            };
1976            let v = 800.0_f64;
1977            let elev = 0.02_f64;
1978            let params = FastIntegrationParams {
1979                horiz: 1000.0,
1980                vert: 0.0,
1981                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
1982                t_span: (0.0, 5.0),
1983                atmo_params: (0.0, 15.0, 1013.25, 1.0),
1984                atmo_sock: None,
1985            };
1986            let sol = fast_integrate_with_segments(&inputs, vec![], params);
1987            let n = sol.y[0].len();
1988            sol.y[1][n - 1]
1989        }
1990        // enable_coriolis=true with advanced effects OFF: directional Coriolis still applies.
1991        let e = final_y(true, FRAC_PI_2);
1992        let w = final_y(true, 3.0 * FRAC_PI_2);
1993        assert!(
1994            e > w && (e - w) > 1e-5,
1995            "Coriolis-only (no advanced effects) must still be directional: E={e} W={w}"
1996        );
1997        // enable_coriolis=false: no Coriolis at all, east == west.
1998        let e2 = final_y(false, FRAC_PI_2);
1999        let w2 = final_y(false, 3.0 * FRAC_PI_2);
2000        assert!(
2001            (e2 - w2).abs() < 1e-9,
2002            "with enable_coriolis=false, east/west must be identical: E={e2} W={w2}"
2003        );
2004    }
2005
2006    #[test]
2007    fn fast_path_rejects_degenerate_atmosphere() {
2008        let inputs = BallisticInputs {
2009            muzzle_velocity: 800.0,
2010            bc_value: 0.5,
2011            bc_type: DragModel::G7,
2012            ..BallisticInputs::default()
2013        };
2014        let v = 800.0_f64;
2015        let e = 0.02_f64;
2016        let mk = |atmo: (f64, f64, f64, f64)| FastIntegrationParams {
2017            horiz: 500.0,
2018            vert: 0.0,
2019            initial_state: [0.0, 0.0, 0.0, v * e.cos(), v * e.sin(), 0.0],
2020            t_span: (0.0, 5.0),
2021            atmo_params: atmo,
2022            atmo_sock: None,
2023        };
2024        // pressure <= 0 -> fail loudly (success=false) instead of a 1-point stub as success.
2025        let zero_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 0.0, 1.0)));
2026        assert!(
2027            !zero_p.success,
2028            "pressure=0 atmosphere must yield success=false"
2029        );
2030        // non-finite pressure -> also rejected.
2031        let nan_p = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, f64::NAN, 1.0)));
2032        assert!(!nan_p.success, "NaN pressure must yield success=false");
2033        // A supplied density ratio must imply a physically plausible density in both wrappers.
2034        let segmented_too_dense =
2035            fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 50.0)));
2036        let plain_too_dense = fast_integrate(
2037            &inputs,
2038            &WindSock::new(vec![]),
2039            mk((0.0, 15.0, 1013.25, 50.0)),
2040        );
2041        assert!(
2042            !segmented_too_dense.success && !plain_too_dense.success,
2043            "ratio=50 atmosphere must fail in both wrappers: segmented={}, plain={}",
2044            segmented_too_dense.success,
2045            plain_too_dense.success
2046        );
2047        // realistic atmosphere -> success.
2048        let good = fast_integrate_with_segments(&inputs, vec![], mk((0.0, 15.0, 1013.25, 1.0)));
2049        assert!(good.success, "realistic atmosphere must yield success=true");
2050        // Direct-atmosphere mode (density, speed_of_sound, 0, 0) is legitimate and must NOT
2051        // be rejected by the guard (regression: 0.21.2 rejected it via the pressure<=0 check).
2052        let direct = fast_integrate_with_segments(&inputs, vec![], mk((1.225, 340.0, 0.0, 0.0)));
2053        assert!(
2054            direct.success,
2055            "direct-atmosphere mode (pressure=0 sentinel) must yield success=true"
2056        );
2057    }
2058
2059    #[test]
2060    fn fast_paths_reject_invalid_wind_segments() {
2061        let inputs = BallisticInputs {
2062            muzzle_velocity: 800.0,
2063            bc_value: 0.5,
2064            bc_type: DragModel::G7,
2065            ..BallisticInputs::default()
2066        };
2067        let mk = || FastIntegrationParams {
2068            horiz: 100.0,
2069            vert: 0.0,
2070            initial_state: [0.0, 0.0, 0.0, 800.0, 0.0, 0.0],
2071            t_span: (0.0, 5.0),
2072            atmo_params: (0.0, 15.0, 1013.25, 1.0),
2073            atmo_sock: None,
2074        };
2075        let invalid = crate::wind::WindSegment::new(10.0, 90.0, f64::NAN);
2076
2077        let plain = fast_integrate(&inputs, &WindSock::new(vec![invalid]), mk());
2078        let segmented = fast_integrate_with_segments(&inputs, vec![invalid], mk());
2079
2080        assert!(
2081            !plain.success && !segmented.success,
2082            "invalid segmented wind must fail in both fast wrappers: plain={}, segmented={}",
2083            plain.success,
2084            segmented.success
2085        );
2086    }
2087
2088    #[test]
2089    fn plain_fast_path_honors_direct_atmosphere_values() {
2090        fn final_speed(muzzle_velocity: f64, atmo_params: (f64, f64, f64, f64)) -> f64 {
2091            let inputs = BallisticInputs {
2092                muzzle_velocity,
2093                bc_value: 0.5,
2094                bc_type: DragModel::G7,
2095                ground_threshold: -100.0,
2096                ..BallisticInputs::default()
2097            };
2098
2099            let wind_sock = WindSock::new(vec![]);
2100            let solution = fast_integrate(
2101                &inputs,
2102                &wind_sock,
2103                FastIntegrationParams {
2104                    horiz: 10_000.0,
2105                    vert: 0.0,
2106                    initial_state: [0.0, 0.0, 0.0, muzzle_velocity, 0.0, 0.0],
2107                    t_span: (0.0, 0.2),
2108                    atmo_params,
2109                    atmo_sock: None,
2110                },
2111            );
2112            assert!(solution.success);
2113
2114            let last = solution.y[0].len() - 1;
2115            (solution.y[3][last].powi(2)
2116                + solution.y[4][last].powi(2)
2117                + solution.y[5][last].powi(2))
2118            .sqrt()
2119        }
2120
2121        let thin_air = final_speed(800.0, (0.905, 340.0, 0.0, 0.0));
2122        let dense_air = final_speed(800.0, (1.225, 340.0, 0.0, 0.0));
2123        assert!(
2124            thin_air > dense_air,
2125            "lower supplied density must retain more velocity: thin={thin_air}, dense={dense_air}"
2126        );
2127
2128        let low_sound_speed = final_speed(340.0, (1.0, 300.0, 0.0, 0.0));
2129        let high_sound_speed = final_speed(340.0, (1.0, 400.0, 0.0, 0.0));
2130        assert!(
2131            (low_sound_speed - high_sound_speed).abs() > 1e-6,
2132            "supplied sound speed must affect Mach-dependent drag"
2133        );
2134    }
2135
2136    #[test]
2137    fn segmented_fast_path_nonpositive_density_ratio_uses_standard_fallback() {
2138        fn terminal_velocity(base_ratio: f64) -> f64 {
2139            let inputs = BallisticInputs {
2140                muzzle_velocity: 800.0,
2141                bc_value: 0.5,
2142                bc_type: DragModel::G7,
2143                ground_threshold: -100.0,
2144                ..BallisticInputs::default()
2145            };
2146
2147            let solution = fast_integrate_with_segments(
2148                &inputs,
2149                vec![],
2150                FastIntegrationParams {
2151                    horiz: 500.0,
2152                    vert: 0.0,
2153                    initial_state: [0.0, 0.0, 0.0, 800.0, 0.0, 0.0],
2154                    t_span: (0.0, 5.0),
2155                    atmo_params: (0.0, 15.0, 1013.25, base_ratio),
2156                    atmo_sock: None,
2157                },
2158            );
2159            assert!(solution.success);
2160
2161            let last = solution.y[3].len() - 1;
2162            solution.y[3][last]
2163        }
2164
2165        let explicit_sea_level = terminal_velocity(1.0);
2166        for base_ratio in [0.0, -1.0] {
2167            let missing_ratio = terminal_velocity(base_ratio);
2168            assert!(
2169                missing_ratio < 800.0,
2170                "missing density ratio must not create a vacuum trajectory: {missing_ratio}"
2171            );
2172            assert!((missing_ratio - explicit_sea_level).abs() < 1e-9);
2173        }
2174    }
2175
2176    #[test]
2177    fn fast_path_carries_real_bullet_geometry() {
2178        // MBA-717: build_inputs hardcoded diameter=.308 / length=1.24in / twist=10 because
2179        // TrajectoryParams didn't carry them. They're now plumbed through, so the BallisticInputs
2180        // the derivatives see reflect the real bullet (caliber gates the Magnus block at
2181        // bullet_diameter > 0.0). Guard against regressing back to the hardcoded values: a
2182        // zero-diameter input must reach the derivatives as zero (Magnus skipped), whereas the
2183        // old code would have forced .308 regardless. We assert the run still completes and the
2184        // two geometries don't crash — the data path is exercised end-to-end.
2185        let run = |diameter: f64, twist: f64| {
2186            let inputs = BallisticInputs {
2187                muzzle_velocity: 800.0,
2188                bc_value: 0.5,
2189                bc_type: DragModel::G7,
2190                bullet_diameter: diameter,
2191                bullet_length: 0.0318,
2192                twist_rate: twist,
2193                enable_advanced_effects: true,
2194                enable_magnus: true,
2195                ..BallisticInputs::default()
2196            };
2197            let v = 800.0_f64;
2198            let elev = 0.02_f64;
2199            let params = FastIntegrationParams {
2200                horiz: 1000.0,
2201                vert: 0.0,
2202                initial_state: [0.0, 0.0, 0.0, v * elev.cos(), v * elev.sin(), 0.0],
2203                t_span: (0.0, 5.0),
2204                atmo_params: (0.0, 15.0, 1013.25, 1.0),
2205                atmo_sock: None,
2206            };
2207            fast_integrate_with_segments(&inputs, vec![], params)
2208        };
2209        // Both a real .224 and a real .338 produce a valid trajectory (geometry is honored, not
2210        // overridden by a hardcoded .308). Regression sentinel for the plumbing.
2211        assert!(run(0.00569, 7.0).success, ".224 geometry must solve");
2212        assert!(run(0.00858, 10.0).success, ".338 geometry must solve");
2213    }
2214
2215    #[test]
2216    fn segmented_fast_spin_flags_do_not_depend_on_advanced_umbrella() {
2217        fn endpoint(
2218            enable_advanced_effects: bool,
2219            enable_magnus: bool,
2220            use_enhanced_spin_drift: bool,
2221        ) -> Vector3<f64> {
2222            let inputs = BallisticInputs {
2223                muzzle_velocity: 823.0,
2224                bullet_mass: 168.0 * crate::constants::GRAINS_TO_KG,
2225                bullet_diameter: 0.308 * 0.0254,
2226                bullet_length: 1.215 * 0.0254,
2227                caliber_inches: 0.308,
2228                weight_grains: 168.0,
2229                bc_value: 0.475,
2230                bc_type: DragModel::G1,
2231                twist_rate: 12.0,
2232                is_twist_right: true,
2233                enable_advanced_effects,
2234                enable_magnus,
2235                use_enhanced_spin_drift,
2236                ..BallisticInputs::default()
2237            };
2238            let elevation = 0.02_f64;
2239            let solution = fast_integrate_with_segments(
2240                &inputs,
2241                vec![],
2242                FastIntegrationParams {
2243                    horiz: 1_000.0,
2244                    vert: 0.0,
2245                    initial_state: [
2246                        0.0,
2247                        0.0,
2248                        0.0,
2249                        inputs.muzzle_velocity * elevation.cos(),
2250                        inputs.muzzle_velocity * elevation.sin(),
2251                        0.0,
2252                    ],
2253                    t_span: (0.0, 5.0),
2254                    atmo_params: (0.0, 15.0, 1013.25, 1.0),
2255                    atmo_sock: None,
2256                },
2257            );
2258            assert!(solution.success);
2259            let last = solution.t.len() - 1;
2260            Vector3::new(
2261                solution.y[0][last],
2262                solution.y[1][last],
2263                solution.y[2][last],
2264            )
2265        }
2266
2267        let baseline = endpoint(false, false, false);
2268        let magnus_without_umbrella = endpoint(false, true, false);
2269        let magnus_with_umbrella = endpoint(true, true, false);
2270        assert!(
2271            (magnus_without_umbrella - baseline).norm() > 1e-5,
2272            "test shot must produce a measurable Magnus displacement"
2273        );
2274        assert!(
2275            (magnus_with_umbrella - magnus_without_umbrella).norm() < 1e-12,
2276            "the legacy umbrella must not suppress explicitly enabled Magnus: without={magnus_without_umbrella:?} with={magnus_with_umbrella:?}"
2277        );
2278
2279        let litz_only = endpoint(false, false, true);
2280        let litz_without_umbrella = endpoint(false, true, true);
2281        let litz_with_umbrella = endpoint(true, true, true);
2282        assert!(
2283            (litz_without_umbrella - litz_only).norm() < 1e-12,
2284            "Litz mode must suppress explicitly enabled Magnus: litz={litz_only:?} both={litz_without_umbrella:?}"
2285        );
2286        assert!(
2287            (litz_with_umbrella - litz_without_umbrella).norm() < 1e-12,
2288            "the legacy umbrella must not change Magnus suppression in Litz mode: without={litz_without_umbrella:?} with={litz_with_umbrella:?}"
2289        );
2290    }
2291
2292    /// MBA-1356: cd_scale — this module's custom-deck interpolation site.
2293    fn deck_test_inputs(cd_scale: f64) -> BallisticInputs {
2294        BallisticInputs {
2295            bullet_mass: 0.0106,
2296            bullet_diameter: 0.00782,
2297            muzzle_velocity: 850.0,
2298            custom_drag_table: Some(crate::drag::DragTable::new(
2299                vec![0.5, 1.0, 2.0, 3.0],
2300                vec![0.23, 0.40, 0.30, 0.26],
2301            )),
2302            cd_scale,
2303            temperature: 15.0,
2304            pressure: 1013.25,
2305            ..BallisticInputs::default()
2306        }
2307    }
2308
2309    fn deck_accel_x(cd_scale: f64) -> f64 {
2310        let inputs = deck_test_inputs(cd_scale);
2311        compute_derivatives(
2312            &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2313            &inputs,
2314            &WindSock::new(vec![]),
2315            FastAtmosphere::Standard {
2316                base_density: 1.225,
2317            },
2318            &inputs.bc_type,
2319            crate::transonic_drag::ProjectileShape::Spitzer,
2320            inputs.bc_value,
2321            false,
2322            false,
2323            None,
2324            None,
2325            None,
2326        )[3]
2327    }
2328
2329    #[test]
2330    fn cd_scale_default_is_one_and_absent_matches_explicit() {
2331        assert_eq!(BallisticInputs::default().cd_scale, 1.0);
2332
2333        let omitted_inputs = BallisticInputs {
2334            bullet_mass: 0.0106,
2335            bullet_diameter: 0.00782,
2336            muzzle_velocity: 850.0,
2337            custom_drag_table: Some(crate::drag::DragTable::new(
2338                vec![0.5, 1.0, 2.0, 3.0],
2339                vec![0.23, 0.40, 0.30, 0.26],
2340            )),
2341            temperature: 15.0,
2342            pressure: 1013.25,
2343            ..BallisticInputs::default()
2344        };
2345        assert_eq!(omitted_inputs.cd_scale, 1.0);
2346
2347        let a_omitted = compute_derivatives(
2348            &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2349            &omitted_inputs,
2350            &WindSock::new(vec![]),
2351            FastAtmosphere::Standard {
2352                base_density: 1.225,
2353            },
2354            &omitted_inputs.bc_type,
2355            crate::transonic_drag::ProjectileShape::Spitzer,
2356            omitted_inputs.bc_value,
2357            false,
2358            false,
2359            None,
2360            None,
2361            None,
2362        )[3];
2363        let a_explicit = deck_accel_x(1.0);
2364        assert_eq!(
2365            a_omitted.to_bits(),
2366            a_explicit.to_bits(),
2367            "omitted cd_scale (Default) must be bit-identical to an explicit 1.0"
2368        );
2369    }
2370
2371    /// (b) Scale-direction test, fast_trajectory path: cd_scale=1.10 must add more drag
2372    /// (a more negative x-acceleration) than 1.0; 0.90 must add less.
2373    #[test]
2374    fn cd_scale_direction_on_fast_trajectory_kernel() {
2375        let baseline = deck_accel_x(1.0);
2376        let scaled_up = deck_accel_x(1.10);
2377        let scaled_down = deck_accel_x(0.90);
2378
2379        assert!(
2380            scaled_up < baseline,
2381            "cd_scale=1.10 must increase drag deceleration (more negative ax): \
2382             base={baseline} up={scaled_up}"
2383        );
2384        assert!(
2385            scaled_down > baseline,
2386            "cd_scale=0.90 must decrease drag deceleration (less negative ax): \
2387             base={baseline} down={scaled_down}"
2388        );
2389    }
2390
2391    /// cd_scale must be inert on the standard G-model/BC path (no custom_drag_table).
2392    #[test]
2393    fn cd_scale_is_inert_without_a_custom_drag_table() {
2394        let make = |cd_scale: f64| BallisticInputs {
2395            bc_value: 0.5,
2396            bc_type: DragModel::G1,
2397            temperature: 15.0,
2398            pressure: 1013.25,
2399            cd_scale,
2400            ..BallisticInputs::default()
2401        };
2402        let accel = |cd_scale: f64| {
2403            let inputs = make(cd_scale);
2404            compute_derivatives(
2405                &[0.0, 0.0, 0.0, 700.0, 0.0, 0.0],
2406                &inputs,
2407                &WindSock::new(vec![]),
2408                FastAtmosphere::Standard {
2409                    base_density: 1.225,
2410                },
2411                &inputs.bc_type,
2412                crate::transonic_drag::ProjectileShape::Spitzer,
2413                inputs.bc_value,
2414                false,
2415                false,
2416                None,
2417                None,
2418                None,
2419            )[3]
2420        };
2421        assert_eq!(
2422            accel(1.0).to_bits(),
2423            accel(1.5).to_bits(),
2424            "cd_scale must not affect the G-model/BC drag path"
2425        );
2426    }
2427}