1use crate::InternalBallisticInputs as BallisticInputs;
2
3pub fn compute_stability_coefficient(
15 inputs: &BallisticInputs,
16 atmo_params: (f64, f64, f64, f64),
17) -> f64 {
18 if inputs.twist_rate == 0.0 || inputs.bullet_length == 0.0 || inputs.bullet_diameter == 0.0 {
20 return 0.0;
21 }
22
23 const MILLER_CONST: f64 = 30.0;
25 const TEMP_REF_K: f64 = 288.15; const PRESS_REF_HPA: f64 = 1013.25;
27
28 let twist_rate_m = inputs.twist_rate.abs() * 0.0254; let twist_calibers = twist_rate_m / inputs.bullet_diameter;
32 let length_calibers = inputs.bullet_length / inputs.bullet_diameter;
33
34 let mass_grains = inputs.bullet_mass / 0.00006479891; let diameter_inches = inputs.bullet_diameter / 0.0254; let mass_term = MILLER_CONST * mass_grains;
40 let geom_term = twist_calibers.powi(2)
41 * diameter_inches.powi(3)
42 * length_calibers
43 * (1.0 + length_calibers.powi(2));
44
45 if geom_term == 0.0 {
46 return 0.0;
47 }
48
49 let (_, temp_c, current_press_hpa, _) = atmo_params;
51 let temp_k = temp_c + 273.15;
52
53 let density_correction = (temp_k / TEMP_REF_K) * (PRESS_REF_HPA / current_press_hpa);
56
57 let velocity_correction = miller_velocity_correction(inputs.muzzle_velocity);
59
60 (mass_term / geom_term) * velocity_correction * density_correction
63}
64
65pub const BULLET_LENGTH_RHO_EFF_KG_M3: f64 = 7600.0;
72
73const MIN_LENGTH_CALIBERS: f64 = 1.2;
77const MAX_LENGTH_CALIBERS: f64 = 6.5;
78
79pub const DEFAULT_TWIST_SG_TARGET: f64 = 2.0;
87
88const GRAINS_PER_KG: f64 = 1.0 / 0.00006479891;
89const METERS_PER_INCH: f64 = 0.0254;
90const MPS_TO_FPS: f64 = 3.28084;
91const MILLER_VEL_REF_FPS: f64 = 2800.0;
92
93pub(crate) fn miller_velocity_correction(muzzle_velocity_mps: f64) -> f64 {
98 (muzzle_velocity_mps * MPS_TO_FPS / MILLER_VEL_REF_FPS).powf(1.0 / 3.0)
99}
100
101pub fn estimate_bullet_length_m(diameter_m: f64, mass_kg: f64) -> f64 {
115 if mass_kg <= 0.0 || diameter_m <= 0.0 || !mass_kg.is_finite() || !diameter_m.is_finite() {
116 return 0.0;
117 }
118
119 let frontal_area = std::f64::consts::FRAC_PI_4 * diameter_m * diameter_m;
120 let raw_length = mass_kg / (BULLET_LENGTH_RHO_EFF_KG_M3 * frontal_area);
121
122 let length_calibers = (raw_length / diameter_m).clamp(MIN_LENGTH_CALIBERS, MAX_LENGTH_CALIBERS);
124 length_calibers * diameter_m
125}
126
127pub fn default_twist_inches(diameter_m: f64, mass_kg: f64, muzzle_velocity_mps: f64) -> f64 {
159 const FALLBACK_TWIST_IN: f64 = 12.0;
160
161 if diameter_m <= 0.0
162 || mass_kg <= 0.0
163 || muzzle_velocity_mps <= 0.0
164 || !diameter_m.is_finite()
165 || !mass_kg.is_finite()
166 || !muzzle_velocity_mps.is_finite()
167 {
168 return FALLBACK_TWIST_IN;
169 }
170
171 let length_m = estimate_bullet_length_m(diameter_m, mass_kg);
172 if length_m <= 0.0 {
173 return FALLBACK_TWIST_IN;
174 }
175
176 let d_in = diameter_m / METERS_PER_INCH;
177 let m_gr = mass_kg * GRAINS_PER_KG;
178 let l_cal = length_m / diameter_m;
179 let velocity_correction = miller_velocity_correction(muzzle_velocity_mps);
180
181 let geom = d_in.powi(3) * l_cal * (1.0 + l_cal * l_cal);
182 let denom = DEFAULT_TWIST_SG_TARGET * geom;
183 if denom <= 0.0 {
184 return FALLBACK_TWIST_IN;
185 }
186
187 let t_cal_sq = 30.0 * m_gr * velocity_correction / denom;
188 if !t_cal_sq.is_finite() || t_cal_sq <= 0.0 {
189 return FALLBACK_TWIST_IN;
190 }
191
192 let twist_in = t_cal_sq.sqrt() * d_in;
193 if twist_in.is_finite() && twist_in > 0.0 {
194 twist_in
195 } else {
196 FALLBACK_TWIST_IN
197 }
198}
199
200#[cfg(any(target_arch = "wasm32", test))]
203pub(crate) fn resolve_twist_inches(
204 explicit_twist_inches: Option<f64>,
205 diameter_m: f64,
206 mass_kg: f64,
207 muzzle_velocity_mps: f64,
208) -> f64 {
209 explicit_twist_inches
210 .unwrap_or_else(|| default_twist_inches(diameter_m, mass_kg, muzzle_velocity_mps))
211}
212
213pub fn compute_spin_drift(
224 time_s: f64,
225 stability: f64,
226 twist_rate: f64,
227 is_twist_right: bool,
228) -> f64 {
229 compute_spin_drift_with_decay(time_s, stability, twist_rate, is_twist_right, None)
230}
231
232pub fn compute_spin_drift_with_decay(
238 time_s: f64,
239 stability: f64,
240 twist_rate: f64,
241 is_twist_right: bool,
242 decay_factor: Option<f64>, ) -> f64 {
244 if stability == 0.0 || time_s <= 0.0 || twist_rate == 0.0 {
245 return 0.0;
246 }
247
248 let sign = if is_twist_right { 1.0 } else { -1.0 };
249
250 let scaling_factor = 1.25;
253 let base_drift = sign * scaling_factor * (stability + 1.2) * time_s.powf(1.83);
254
255 let effective_drift = if let Some(decay) = decay_factor {
257 base_drift * decay.max(0.0).min(1.0)
258 } else {
259 base_drift
260 };
261
262 effective_drift * 0.0254
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 fn create_test_inputs() -> BallisticInputs {
271 BallisticInputs {
272 muzzle_velocity: 823.0, bc_value: 0.5,
274 bullet_mass: 0.0109, bullet_diameter: 0.00782, bullet_length: 0.033, twist_rate: 10.0,
278 ..Default::default()
279 }
280 }
281
282 #[test]
283 fn test_compute_stability_coefficient() {
284 let inputs = create_test_inputs();
285 let atmo_params = (0.0, 15.0, 1013.25, 1.0); let stability = compute_stability_coefficient(&inputs, atmo_params);
288
289 println!("Computed stability: {}", stability);
291
292 assert!(stability > 0.0);
294 assert!(stability < 10.0); assert!(stability > 1.0);
298 assert!(stability < 3.0);
299 }
300
301 #[test]
302 fn test_compute_stability_coefficient_zero_cases() {
303 let mut inputs = create_test_inputs();
304 let atmo_params = (0.0, 15.0, 1013.25, 1.0);
305
306 inputs.twist_rate = 0.0;
308 assert_eq!(compute_stability_coefficient(&inputs, atmo_params), 0.0);
309
310 inputs = create_test_inputs();
312 inputs.bullet_length = 0.0;
313 assert_eq!(compute_stability_coefficient(&inputs, atmo_params), 0.0);
314
315 inputs = create_test_inputs();
317 inputs.bullet_diameter = 0.0;
318 assert_eq!(compute_stability_coefficient(&inputs, atmo_params), 0.0);
319 }
320
321 #[test]
322 fn test_compute_stability_coefficient_atmospheric_effects() {
323 let inputs = create_test_inputs();
324
325 let standard_atmo = (0.0, 15.0, 1013.25, 1.0);
327 let standard_stability = compute_stability_coefficient(&inputs, standard_atmo);
328
329 let high_alt_atmo = (3000.0, 5.0, 900.0, 1.0);
331 let high_alt_stability = compute_stability_coefficient(&inputs, high_alt_atmo);
332
333 assert!(high_alt_stability > standard_stability);
335
336 let hot_atmo = (0.0, 35.0, 1013.25, 1.0);
338 let hot_stability = compute_stability_coefficient(&inputs, hot_atmo);
339
340 assert!(hot_stability > standard_stability);
342 }
343
344 #[test]
345 fn test_compute_spin_drift() {
346 let time_s = 1.5;
347 let stability = 2.0;
348 let twist_rate = 10.0;
349
350 let drift_right = compute_spin_drift(time_s, stability, twist_rate, true);
352 assert!(drift_right > 0.0); let drift_left = compute_spin_drift(time_s, stability, twist_rate, false);
356 assert!(drift_left < 0.0); assert!((drift_left + drift_right).abs() < 1e-10); assert!(drift_right.abs() < 0.25); }
362
363 #[test]
364 fn test_compute_spin_drift_zero_cases() {
365 assert_eq!(compute_spin_drift(1.5, 0.0, 10.0, true), 0.0);
367
368 assert_eq!(compute_spin_drift(0.0, 2.0, 10.0, true), 0.0);
370
371 assert_eq!(compute_spin_drift(-1.0, 2.0, 10.0, true), 0.0);
373
374 assert_eq!(compute_spin_drift(1.5, 2.0, 0.0, true), 0.0);
376 }
377
378 const GR_TO_KG: f64 = 0.00006479891;
381 const IN_TO_M: f64 = 0.0254;
382
383 fn len_in(diameter_in: f64, mass_gr: f64) -> f64 {
384 estimate_bullet_length_m(diameter_in * IN_TO_M, mass_gr * GR_TO_KG) / IN_TO_M
385 }
386
387 fn twist_in(diameter_in: f64, mass_gr: f64, v_fps: f64) -> f64 {
388 default_twist_inches(diameter_in * IN_TO_M, mass_gr * GR_TO_KG, v_fps * 0.3048)
389 }
390
391 #[test]
392 fn test_estimate_bullet_length_reference_bullets() {
393 let cases = [
395 (0.308, 175.0, 1.24, 0.06), (0.224, 77.0, 0.99, 0.06), (0.338, 300.0, 1.74, 0.06), (0.224, 55.0, 0.72, 0.05), (0.510, 750.0, 1.90, 0.08), ];
401 for (d, m, expected, tol) in cases {
402 let got = len_in(d, m);
403 assert!(
404 (got - expected).abs() < tol,
405 ".{d}/{m}gr length: expected ~{expected}\", got {got:.4}\" (L/d {:.2})",
406 got / d
407 );
408 }
409 }
410
411 #[test]
412 fn test_estimate_bullet_length_preserves_handgun_geometry() {
413 for (diameter_in, mass_gr, expected_ratio) in [
416 (0.355, 115.0, 1.702_847_900_515), (0.451, 230.0, 1.660_968_083_966), (0.355, 90.0, 1.332_663_574_316), ] {
420 let diameter_m = diameter_in * IN_TO_M;
421 let mass_kg = mass_gr * GR_TO_KG;
422 let frontal_area = std::f64::consts::FRAC_PI_4 * diameter_m * diameter_m;
423 let model_ratio = mass_kg / (BULLET_LENGTH_RHO_EFF_KG_M3 * frontal_area) / diameter_m;
424 let estimated_ratio = estimate_bullet_length_m(diameter_m, mass_kg) / diameter_m;
425
426 assert!((estimated_ratio - model_ratio).abs() < 1e-12);
427 assert!((estimated_ratio - expected_ratio).abs() < 1e-12);
428 }
429 }
430
431 #[test]
432 fn test_estimate_bullet_length_degenerate_inputs() {
433 assert_eq!(estimate_bullet_length_m(0.00782, 0.0), 0.0);
434 assert_eq!(estimate_bullet_length_m(0.00782, -1.0), 0.0);
435 assert_eq!(estimate_bullet_length_m(0.0, 0.011), 0.0);
436 assert_eq!(estimate_bullet_length_m(-0.1, 0.011), 0.0);
437 assert_eq!(estimate_bullet_length_m(f64::NAN, 0.011), 0.0);
438 }
439
440 #[test]
441 fn test_estimate_bullet_length_clamps_ld_ratio() {
442 const EXPECTED_MIN: f64 = 1.2;
443 const EXPECTED_MAX: f64 = 6.5;
444
445 let diameter_m = 0.355 * IN_TO_M;
446 for raw_ratio in [1.19_f64, 1.20, 1.21, 6.49, 6.50, 6.51] {
447 let mass_kg = raw_ratio
448 * BULLET_LENGTH_RHO_EFF_KG_M3
449 * std::f64::consts::FRAC_PI_4
450 * diameter_m.powi(3);
451 let actual_ratio = estimate_bullet_length_m(diameter_m, mass_kg) / diameter_m;
452 let expected_ratio = raw_ratio.clamp(EXPECTED_MIN, EXPECTED_MAX);
453
454 assert!(
455 (actual_ratio - expected_ratio).abs() < 1e-12,
456 "raw L/d {raw_ratio}: expected {expected_ratio}, got {actual_ratio}"
457 );
458 }
459 }
460
461 #[test]
462 fn test_default_twist_reference_bullets() {
463 let cases = [
466 (0.308, 175.0, 2600.0, 11.2, 1.2), (0.224, 55.0, 3240.0, 10.1, 1.5), (0.224, 77.0, 2750.0, 7.2, 1.2), (0.264, 140.0, 2700.0, 7.7, 1.2), ];
471 for (d, m, v, expected, tol) in cases {
472 let got = twist_in(d, m, v);
473 assert!(got > 0.0, ".{d}/{m}gr twist must be positive, got {got}");
474 assert!(
475 (got - expected).abs() < tol,
476 ".{d}/{m}gr twist: expected ~1:{expected}\", got 1:{got:.2}\"",
477 );
478 }
479 }
480
481 #[test]
482 fn test_default_twist_yields_target_sg() {
483 let d_m = 0.308 * IN_TO_M;
486 let m_kg = 175.0 * GR_TO_KG;
487 let v_mps = 2600.0 * 0.3048;
488 let twist = default_twist_inches(d_m, m_kg, v_mps);
489 let inputs = BallisticInputs {
490 muzzle_velocity: v_mps,
491 bullet_mass: m_kg,
492 bullet_diameter: d_m,
493 bullet_length: estimate_bullet_length_m(d_m, m_kg),
494 twist_rate: twist,
495 ..Default::default()
496 };
497 let sg = compute_stability_coefficient(&inputs, (0.0, 15.0, 1013.25, 1.0));
498 assert!(
499 (sg - DEFAULT_TWIST_SG_TARGET).abs() < 0.02,
500 "expected Sg ~{DEFAULT_TWIST_SG_TARGET}, got {sg}"
501 );
502 }
503
504 #[test]
505 fn test_default_twist_degenerate_inputs_fall_back() {
506 assert_eq!(default_twist_inches(0.0, 0.011, 800.0), 12.0);
507 assert_eq!(default_twist_inches(0.00782, 0.0, 800.0), 12.0);
508 assert_eq!(default_twist_inches(0.00782, 0.011, 0.0), 12.0);
509 assert_eq!(default_twist_inches(f64::NAN, 0.011, 800.0), 12.0);
510 }
511
512 #[test]
513 fn test_resolve_twist_preserves_explicit_or_uses_miller_default() {
514 let diameter_m = 0.224 * IN_TO_M;
515 let mass_kg = 77.0 * GR_TO_KG;
516 let velocity_mps = 2750.0 * 0.3048;
517 let expected_default = default_twist_inches(diameter_m, mass_kg, velocity_mps);
518
519 assert_eq!(
520 resolve_twist_inches(Some(9.5), diameter_m, mass_kg, velocity_mps).to_bits(),
521 9.5_f64.to_bits()
522 );
523 assert_eq!(
524 resolve_twist_inches(None, diameter_m, mass_kg, velocity_mps).to_bits(),
525 expected_default.to_bits()
526 );
527 assert_ne!(expected_default.to_bits(), 12.0_f64.to_bits());
528
529 let metric_default = resolve_twist_inches(
530 None,
531 5.6896 * 0.001,
532 4.98951607 * 0.001,
533 838.2,
534 );
535 assert!((metric_default - expected_default).abs() < 1e-12);
536 }
537
538 #[test]
539 fn test_heavier_bullet_needs_faster_twist() {
540 let light = twist_in(0.224, 55.0, 2900.0);
542 let heavy = twist_in(0.224, 77.0, 2900.0);
543 assert!(heavy < light, "77gr twist {heavy} should be faster than 55gr {light}");
544 }
545
546 #[test]
547 fn test_print_reference_estimates() {
548 println!("\n=== MBA-1135 estimate_bullet_length_m ===");
550 for (d, m) in [
551 (0.308, 175.0),
552 (0.224, 77.0),
553 (0.338, 300.0),
554 (0.224, 55.0),
555 (0.510, 750.0),
556 (0.264, 140.0),
557 ] {
558 let l = len_in(d, m);
559 println!(".{d}/{m}gr -> {l:.4}\" (L/d {:.3})", l / d);
560 }
561 println!("\n=== MBA-1135 default_twist_inches (SG=1.5 vs 2.0) ===");
562 for (d, m, v) in [
563 (0.308, 175.0, 2600.0),
564 (0.224, 55.0, 3240.0),
565 (0.224, 77.0, 2750.0),
566 (0.264, 140.0, 2700.0),
567 ] {
568 let t20 = twist_in(d, m, v);
570 let t15 = t20 * (DEFAULT_TWIST_SG_TARGET / 1.5_f64).sqrt();
571 println!(".{d}/{m}gr @ {v}fps -> SG1.5: 1:{t15:.2}\" SG2.0: 1:{t20:.2}\"");
572 }
573 println!();
574 }
575
576 #[test]
577 fn test_compute_spin_drift_scaling() {
578 let stability = 2.0;
579 let twist_rate = 10.0;
580
581 let drift_1s = compute_spin_drift(1.0, stability, twist_rate, true);
583 let drift_2s = compute_spin_drift(2.0, stability, twist_rate, true);
584
585 assert!(drift_2s > drift_1s);
587
588 let drift_low_stability = compute_spin_drift(1.5, 1.0, twist_rate, true);
590 let drift_high_stability = compute_spin_drift(1.5, 3.0, twist_rate, true);
591
592 assert!(drift_high_stability > drift_low_stability);
594 }
595}