1use crate::cli_api::{
22 AtmosphericConditions, BallisticInputs, BallisticsError, TrajectoryPoint, TrajectorySolver,
23 WindConditions,
24};
25use std::fmt;
26
27pub const MIL_PER_UNIT_RATIO: f64 = 1000.0;
29pub const MOA_PER_UNIT_RATIO: f64 = 3438.0;
32
33const RANGE_TOLERANCE_M: f64 = 0.1;
35const MAX_ITERATIONS: u32 = 10;
37
38#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct LeadComponents {
41 pub lead_m: f64,
43 pub lead_mil: f64,
45 pub lead_moa: f64,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct LeadSolution {
52 pub time_of_flight_s: f64,
54 pub lead_m: f64,
56 pub lead_mil: f64,
58 pub lead_moa: f64,
60 pub corrected_range_m: f64,
62 pub iterations: u32,
64}
65
66#[derive(Debug)]
68pub enum LeadError {
69 InvalidInput(String),
71 TargetOvertakesShooter { corrected_range_m: f64 },
74 Convergence { iterations: u32, residual_m: f64 },
78 BeyondSolvedSpan {
82 corrected_range_m: f64,
83 solved_span_m: f64,
84 },
85 Solver(BallisticsError),
87}
88
89impl fmt::Display for LeadError {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 match self {
92 LeadError::InvalidInput(msg) => write!(f, "invalid lead input: {msg}"),
93 LeadError::TargetOvertakesShooter { corrected_range_m } => write!(
94 f,
95 "target reaches the shooter before intercept (corrected range {corrected_range_m:.1} m)"
96 ),
97 LeadError::Convergence { iterations, residual_m } => write!(
98 f,
99 "intercept range failed to converge after {iterations} iterations (residual {residual_m:.2} m)"
100 ),
101 LeadError::BeyondSolvedSpan { corrected_range_m, solved_span_m } => write!(
102 f,
103 "intercept range {corrected_range_m:.1} m lies beyond the solved trajectory span ({solved_span_m:.1} m)"
104 ),
105 LeadError::Solver(e) => write!(f, "trajectory solve failed: {e}"),
106 }
107 }
108}
109
110impl std::error::Error for LeadError {
111 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
112 match self {
113 Self::Solver(error) => Some(error),
114 _ => None,
115 }
116 }
117}
118
119impl From<BallisticsError> for LeadError {
120 fn from(e: BallisticsError) -> Self {
121 LeadError::Solver(e)
122 }
123}
124
125fn velocity_components(speed_mps: f64, angle_deg: f64) -> (f64, f64) {
128 let a = angle_deg.to_radians();
129 (speed_mps * a.cos(), speed_mps * a.sin())
130}
131
132pub fn lead_from_tof(speed_mps: f64, angle_deg: f64, tof_s: f64, range_m: f64) -> LeadComponents {
136 let (_, v_lateral) = velocity_components(speed_mps, angle_deg);
137 let lead_m = v_lateral * tof_s;
138 let ratio = if range_m < 1.0 { 0.0 } else { lead_m / range_m };
139 LeadComponents {
140 lead_m,
141 lead_mil: ratio * MIL_PER_UNIT_RATIO,
142 lead_moa: ratio * MOA_PER_UNIT_RATIO,
143 }
144}
145
146pub fn mover_ring(target_speed_mps: f64, time_s: f64, downrange_m: f64) -> (f64, Option<f64>) {
165 let ring_m = target_speed_mps * time_s;
166 let ring_mil = if downrange_m > 0.0 {
167 Some(ring_m / downrange_m * MIL_PER_UNIT_RATIO)
168 } else {
169 None
170 };
171 (ring_m, ring_mil)
172}
173
174fn tof_at(points: &[TrajectoryPoint], x_m: f64) -> Option<f64> {
178 if points.is_empty() || x_m < 0.0 {
179 return None;
180 }
181 if x_m <= points[0].position.x {
182 return Some(points[0].time);
183 }
184 for w in points.windows(2) {
185 let (p1, p2) = (&w[0], &w[1]);
186 if p2.position.x >= x_m {
187 let dx = p2.position.x - p1.position.x;
188 let t = if dx.abs() < 1e-12 {
189 0.0
190 } else {
191 (x_m - p1.position.x) / dx
192 };
193 return Some(p1.time + t * (p2.time - p1.time));
194 }
195 }
196 None
197}
198
199pub fn calculate_lead(
209 inputs: BallisticInputs,
210 wind: WindConditions,
211 atmo: AtmosphericConditions,
212 speed_mps: f64,
213 angle_deg: f64,
214 range_m: f64,
215) -> Result<LeadSolution, LeadError> {
216 calculate_lead_with_station_presence(
217 inputs,
218 wind,
219 atmo,
220 speed_mps,
221 angle_deg,
222 range_m,
223 crate::atmosphere::StationAtmospherePresence::NEITHER,
224 )
225}
226
227pub fn calculate_lead_with_station_presence(
232 inputs: BallisticInputs,
233 wind: WindConditions,
234 atmo: AtmosphericConditions,
235 speed_mps: f64,
236 angle_deg: f64,
237 range_m: f64,
238 station_presence: crate::atmosphere::StationAtmospherePresence,
239) -> Result<LeadSolution, LeadError> {
240 if !speed_mps.is_finite() || speed_mps < 0.0 {
241 return Err(LeadError::InvalidInput(format!(
242 "target speed must be finite and non-negative, got {speed_mps}"
243 )));
244 }
245 if !angle_deg.is_finite() {
246 return Err(LeadError::InvalidInput(format!(
247 "target angle must be finite, got {angle_deg}"
248 )));
249 }
250 if !range_m.is_finite() || range_m <= 0.0 {
251 return Err(LeadError::InvalidInput(format!(
252 "range must be finite and positive, got {range_m}"
253 )));
254 }
255
256 let (v_radial, _) = velocity_components(speed_mps, angle_deg);
257
258 let max_range = range_m + (v_radial.max(0.0) * 6.0).max(20.0);
261 let mut solver =
262 TrajectorySolver::new_with_station_presence(inputs, wind, atmo, station_presence);
263 solver.set_max_range(max_range);
264 let result = solver.solve()?;
265 let points = &result.points;
266
267 let solved_span_m = points.last().map(|p| p.position.x).unwrap_or(0.0);
270 let beyond_solved = move |r: f64| LeadError::BeyondSolvedSpan {
271 corrected_range_m: r,
272 solved_span_m,
273 };
274
275 let mut corrected = range_m;
282 let mut iterations = 0u32;
283 if v_radial.abs() > 1e-9 && speed_mps > 0.0 {
284 loop {
285 let tof = tof_at(points, corrected).ok_or_else(|| beyond_solved(corrected))?;
286 let next = range_m + v_radial * tof;
287 if next <= 0.0 {
288 return Err(LeadError::TargetOvertakesShooter {
289 corrected_range_m: next,
290 });
291 }
292 let residual = (next - corrected).abs();
293 iterations += 1;
294 corrected = next;
295 if residual < RANGE_TOLERANCE_M {
296 break;
297 }
298 if iterations >= MAX_ITERATIONS {
299 return Err(LeadError::Convergence {
300 iterations,
301 residual_m: residual,
302 });
303 }
304 }
305 }
306
307 let tof = tof_at(points, corrected).ok_or_else(|| beyond_solved(corrected))?;
308 let components = lead_from_tof(speed_mps, angle_deg, tof, corrected);
309 Ok(LeadSolution {
310 time_of_flight_s: tof,
311 lead_m: components.lead_m,
312 lead_mil: components.lead_mil,
313 lead_moa: components.lead_moa,
314 corrected_range_m: corrected,
315 iterations,
316 })
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322 use crate::{AtmosphericConditions, BallisticInputs, DragModel, WindConditions};
323
324 fn base_inputs() -> BallisticInputs {
325 BallisticInputs {
326 muzzle_velocity: 800.0,
327 bc_value: 0.5,
328 bc_type: DragModel::G7,
329 bullet_mass: 0.0109,
330 bullet_diameter: 0.00782,
331 bullet_length: 0.0309,
332 sight_height: 0.05,
333 use_rk4: true,
334 ..BallisticInputs::default()
335 }
336 }
337
338 #[test]
339 fn lead_from_tof_perpendicular_is_speed_times_tof() {
340 let c = lead_from_tof(3.0, 90.0, 0.5, 300.0);
341 assert!((c.lead_m - 1.5).abs() < 1e-12);
342 assert!((c.lead_mil - 1.5 / 300.0 * 1000.0).abs() < 1e-12);
343 assert!((c.lead_moa - 1.5 / 300.0 * 3438.0).abs() < 1e-12);
344 }
345
346 #[test]
347 fn moa_mil_ratio_is_exactly_3_438() {
348 let c = lead_from_tof(5.0, 90.0, 0.7, 400.0);
349 assert!((c.lead_moa / c.lead_mil - 3.438).abs() < 1e-12);
350 }
351
352 #[test]
353 fn pure_radial_motion_has_zero_lead() {
354 for angle in [0.0, 180.0] {
355 let c = lead_from_tof(10.0, angle, 0.5, 300.0);
356 assert!(c.lead_m.abs() < 1e-9, "angle {angle} must give zero lead");
357 }
358 }
359
360 #[test]
361 fn right_to_left_lead_is_negative() {
362 let c = lead_from_tof(3.0, 270.0, 0.5, 300.0);
363 assert!(
364 c.lead_m < 0.0,
365 "270 deg = target moving left => negative (hold left)"
366 );
367 }
368
369 #[test]
370 fn zero_speed_gives_zero_lead_solution() {
371 let s = calculate_lead(
372 base_inputs(),
373 WindConditions::default(),
374 AtmosphericConditions::default(),
375 0.0,
376 90.0,
377 300.0,
378 )
379 .expect("zero speed must solve");
380 assert_eq!(s.lead_m, 0.0);
381 assert_eq!(s.lead_mil, 0.0);
382 assert!((s.corrected_range_m - 300.0).abs() < 1e-9);
383 }
384
385 #[test]
386 fn outbound_45_converges_fast_and_grows_range() {
387 let s = calculate_lead(
388 base_inputs(),
389 WindConditions::default(),
390 AtmosphericConditions::default(),
391 15.0,
392 45.0,
393 600.0,
394 )
395 .expect("outbound must converge");
396 assert!(s.iterations < 10, "iterations {}", s.iterations);
397 assert!(
398 s.corrected_range_m > 600.0,
399 "outbound target => longer intercept"
400 );
401 }
403
404 #[test]
405 fn inbound_gives_shorter_corrected_range() {
406 let s = calculate_lead(
407 base_inputs(),
408 WindConditions::default(),
409 AtmosphericConditions::default(),
410 15.0,
411 180.0,
412 600.0,
413 )
414 .expect("inbound must converge");
415 assert!(s.corrected_range_m < 600.0);
416 assert!(s.lead_m.abs() < 1e-9, "pure inbound has no lateral lead");
417 }
418
419 #[test]
420 fn over_closing_target_is_a_typed_error() {
421 let r = calculate_lead(
423 base_inputs(),
424 WindConditions::default(),
425 AtmosphericConditions::default(),
426 2000.0,
427 180.0,
428 600.0,
429 );
430 match r {
431 Err(LeadError::TargetOvertakesShooter { .. }) | Err(LeadError::Convergence { .. }) => {}
432 other => panic!("expected typed overtake/convergence error, got {other:?}"),
433 }
434 }
435
436 #[test]
437 fn invalid_inputs_are_rejected() {
438 let bad = |speed: f64, angle: f64, range: f64| {
439 calculate_lead(
440 base_inputs(),
441 WindConditions::default(),
442 AtmosphericConditions::default(),
443 speed,
444 angle,
445 range,
446 )
447 };
448 assert!(matches!(
449 bad(f64::NAN, 90.0, 300.0),
450 Err(LeadError::InvalidInput(_))
451 ));
452 assert!(matches!(
453 bad(-1.0, 90.0, 300.0),
454 Err(LeadError::InvalidInput(_))
455 ));
456 assert!(matches!(
457 bad(3.0, f64::INFINITY, 300.0),
458 Err(LeadError::InvalidInput(_))
459 ));
460 assert!(matches!(
461 bad(3.0, 90.0, 0.0),
462 Err(LeadError::InvalidInput(_))
463 ));
464 }
465}