Skip to main content

rockets_engine/
geometry.rs

1//! Geometry-to-aerodynamics: a subsonic Barrowman subset for slender model
2//! rockets (nose cone + body tube + trapezoidal fins), implemented against the
3//! OpenRocket technical documentation and its `FinSetCalc`/`BarrowmanCalculator`
4//! sources. CP comes from the component moment sum; drag is friction + base +
5//! conical nose pressure. Supersonic values are clamped to the Mach-1 results.
6//!
7//! Not covered (deliberately): supersonic wave drag, boat-tails/transitions,
8//! elliptical or free-form fins, and induced drag from angle of attack (use
9//! `with_body_lift`'s `induced_k` table if you have a better estimate).
10
11use crate::{Error, Result};
12
13/// Nose-cone families supported by the subset.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum NoseShape {
16    /// Straight conical nose.
17    Conical,
18    /// Tangent ogive nose.
19    Ogive,
20    /// Half-ellipsoid nose.
21    Elliptical,
22    /// Power-series parabolic nose (exponent 0.5).
23    Parabolic,
24}
25
26impl std::str::FromStr for NoseShape {
27    type Err = Error;
28
29    fn from_str(s: &str) -> Result<Self> {
30        match s {
31            "conical" | "cone" => Ok(Self::Conical),
32            "ogive" => Ok(Self::Ogive),
33            "elliptical" | "ellipse" => Ok(Self::Elliptical),
34            "parabolic" => Ok(Self::Parabolic),
35            _ => Err(Error::invalid(
36                "nose shape",
37                "conical, ogive, elliptical or parabolic",
38            )),
39        }
40    }
41}
42
43impl NoseShape {
44    /// CP location as a fraction of nose length, from the volume/area relation
45    /// XB = L − V/A_base. Ogive uses the standard tangent-ogive value.
46    fn cp_fraction(self) -> f64 {
47        match self {
48            Self::Conical => 2.0 / 3.0,
49            Self::Ogive => 0.466,
50            Self::Elliptical => 1.0 / 3.0,
51            Self::Parabolic => 0.5,
52        }
53    }
54
55    /// Pressure-drag coefficient at subsonic speeds. Conical noses use
56    /// 0.8·sin²(φ) with the half-angle φ = atan(r/L); streamlined shapes are
57    /// taken as zero, the usual Barrowman approximation.
58    fn pressure_cd(self, length_m: f64, diameter_m: f64) -> f64 {
59        match self {
60            Self::Conical => {
61                let r = diameter_m / 2.0;
62                let sin_phi = r / (r * r + length_m * length_m).sqrt();
63                0.8 * sin_phi * sin_phi
64            }
65            _ => 0.0,
66        }
67    }
68
69    /// Lateral (wetted) area. Conical uses the exact slant area; the others
70    /// approximate the cylinder at the base diameter.
71    fn lateral_area(self, length_m: f64, diameter_m: f64) -> f64 {
72        let r = diameter_m / 2.0;
73        match self {
74            Self::Conical => std::f64::consts::PI * r * (r * r + length_m * length_m).sqrt(),
75            _ => std::f64::consts::PI * diameter_m * length_m,
76        }
77    }
78}
79
80/// A nose cone with length and base diameter, in metres.
81#[derive(Debug, Clone, Copy)]
82pub struct NoseCone {
83    /// Shape family.
84    pub shape: NoseShape,
85    /// Nose length in metres.
86    pub length_m: f64,
87    /// Base diameter in metres.
88    pub diameter_m: f64,
89}
90
91/// The cylindrical body tube behind the nose.
92#[derive(Debug, Clone, Copy)]
93pub struct BodyTube {
94    /// Tube length in metres.
95    pub length_m: f64,
96    /// Tube diameter in metres.
97    pub diameter_m: f64,
98}
99
100/// Identical trapezoidal fins at the aft end of the tube. `leading_sweep_m` is
101/// the horizontal offset of the tip leading edge from the root leading edge.
102#[derive(Debug, Clone, Copy)]
103pub struct TrapezoidalFins {
104    /// Number of identical fins.
105    pub count: u32,
106    /// Root chord length in metres.
107    pub root_chord_m: f64,
108    /// Tip chord length in metres.
109    pub tip_chord_m: f64,
110    /// Fin semispan in metres (body surface to tip).
111    pub span_m: f64,
112    /// Horizontal offset of the tip leading edge from the root leading edge.
113    pub leading_sweep_m: f64,
114    /// Fin thickness in metres.
115    pub thickness_m: f64,
116}
117
118/// The complete slender geometry.
119#[derive(Debug, Clone, Copy)]
120pub struct RocketGeometry {
121    /// Nose cone.
122    pub nose: NoseCone,
123    /// Cylindrical body tube.
124    pub tube: BodyTube,
125    /// Aft trapezoidal fin set.
126    pub fins: TrapezoidalFins,
127    /// Roughness height in metres (default 20 µm, painted surface).
128    pub roughness_m: f64,
129}
130
131impl RocketGeometry {
132    /// Build with the default painted-surface roughness (20 µm).
133    pub fn new(nose: NoseCone, tube: BodyTube, fins: TrapezoidalFins) -> Self {
134        Self {
135            nose,
136            tube,
137            fins,
138            roughness_m: 20e-6,
139        }
140    }
141
142    /// Set the roughness height in metres.
143    pub fn with_roughness(mut self, roughness_m: f64) -> Self {
144        self.roughness_m = roughness_m;
145        self
146    }
147
148    /// Total aerodynamic length (nose + tube).
149    pub fn total_length_m(&self) -> f64 {
150        self.nose.length_m + self.tube.length_m
151    }
152
153    /// Largest body diameter (nose base or tube).
154    pub fn max_diameter_m(&self) -> f64 {
155        self.nose.diameter_m.max(self.tube.diameter_m)
156    }
157
158    /// Reference area, π/4·d² of the largest diameter.
159    pub fn ref_area_m2(&self) -> f64 {
160        std::f64::consts::FRAC_PI_4 * self.max_diameter_m().powi(2)
161    }
162
163    fn fin_area(&self) -> f64 {
164        self.fins.span_m * (self.fins.root_chord_m + self.fins.tip_chord_m) / 2.0
165    }
166
167    /// Mean aerodynamic chord of one fin (trapezoid formula).
168    fn mac(&self) -> f64 {
169        let (cr, ct) = (self.fins.root_chord_m, self.fins.tip_chord_m);
170        (2.0 / 3.0) * (cr + ct - cr * ct / (cr + ct))
171    }
172
173    /// Fin CP measured from the fin's root leading edge: xMAC_LE + MAC/4.
174    fn fin_cp(&self) -> f64 {
175        let (cr, ct, s, m) = (
176            self.fins.root_chord_m,
177            self.fins.tip_chord_m,
178            self.fins.span_m,
179            self.fins.leading_sweep_m,
180        );
181        let y_mac = (s / 3.0) * (cr + 2.0 * ct) / (cr + ct);
182        let x_mac_le = m * y_mac / s;
183        x_mac_le + 0.25 * self.mac()
184    }
185
186    fn midchord_cos(&self) -> f64 {
187        let (cr, ct, s, m) = (
188            self.fins.root_chord_m,
189            self.fins.tip_chord_m,
190            self.fins.span_m,
191            self.fins.leading_sweep_m,
192        );
193        let gamma = ((m + ct / 2.0 - cr / 2.0) / s).atan();
194        gamma.cos()
195    }
196
197    /// Normal-force slope of one fin, divided by the reference area.
198    /// OpenRocket's subsonic Diederich simplification.
199    fn fin_cna1(&self, mach: f64) -> f64 {
200        let span = self.fins.span_m;
201        let area = self.fin_area();
202        let cos = self.midchord_cos();
203        if area <= 0.0 || span <= 0.0 || cos <= 0.0 {
204            return 0.0;
205        }
206        let ratio = (span * span) / (area * cos);
207        2.0 * std::f64::consts::PI * span * span
208            / (1.0 + (1.0 + (1.0 - mach * mach) * ratio * ratio).sqrt())
209            / self.ref_area_m2()
210    }
211
212    /// Body-interference factor (1 + tau) with tau = r/(span + r).
213    fn interference_tau(&self) -> f64 {
214        let r = self.max_diameter_m() / 2.0;
215        r / (self.fins.span_m + r)
216    }
217
218    fn fin_count_factor(&self) -> f64 {
219        match self.fins.count {
220            5 => 0.948,
221            6 => 0.913,
222            7 => 0.854,
223            8 => 0.810,
224            n if n >= 9 => 0.75,
225            _ => 1.0,
226        }
227    }
228
229    /// Total fin-set normal-force slope for this Mach number.
230    ///
231    /// The Diederich `fin_cna1` is the slope of a fin *pair* (a wing of
232    /// semispan `span`), so a set of `n` fins contributes `n/2` pairs,
233    /// with fin-body carryover (1 + tau) and a many-fin interference
234    /// reduction. This matches OpenRocket's `FinSetCalc` convention,
235    /// verified against its BarrowmanCalculatorTest Alpha III values.
236    fn fin_set_cna(&self, mach: f64) -> f64 {
237        self.fin_cna1(mach)
238            * (1.0 + self.interference_tau())
239            * self.fin_count_factor()
240            * (self.fins.count as f64 / 2.0)
241    }
242
243    /// Fin CP measured from the nose tip (fin trailing edge at body end).
244    fn fin_cp_abs(&self) -> f64 {
245        self.total_length_m() - self.fins.root_chord_m + self.fin_cp()
246    }
247
248    /// Nose radius profile r(x) with x measured from the tip.
249    fn nose_radius(&self, x: f64) -> f64 {
250        let l = self.nose.length_m;
251        let r = self.nose.diameter_m / 2.0;
252        let t = (x / l).clamp(0.0, 1.0);
253        match self.nose.shape {
254            NoseShape::Conical => r * t,
255            NoseShape::Elliptical => r * (1.0 - (1.0 - t).powi(2)).sqrt(),
256            NoseShape::Parabolic => r * t * (2.0 - t),
257            NoseShape::Ogive => {
258                let rho = (r * r + l * l) / (2.0 * r);
259                (rho * rho - (l - x).powi(2)).max(0.0).sqrt() - (rho - r)
260            }
261        }
262    }
263
264    /// Solid-nose CG (from the tip) and pitch inertia per unit mass about
265    /// that CG, from numerical integration of the radius profile.
266    fn nose_volume_properties(&self) -> (f64, f64) {
267        const N: usize = 1024;
268        let l = self.nose.length_m;
269        let dx = l / N as f64;
270        let mut volume = 0.0; // ∫ r² dx (up to the density·π factor)
271        let mut moment = 0.0; // ∫ x r² dx
272        for i in 0..N {
273            let x = (i as f64 + 0.5) * dx;
274            let r2 = self.nose_radius(x).powi(2);
275            volume += r2 * dx;
276            moment += x * r2 * dx;
277        }
278        let cg = moment / volume;
279        let mut inertia = 0.0; // ∫ r² (r²/4 + (x−cg)²) dx
280        for i in 0..N {
281            let x = (i as f64 + 0.5) * dx;
282            let r2 = self.nose_radius(x).powi(2);
283            inertia += r2 * (r2 / 4.0 + (x - cg).powi(2)) * dx;
284        }
285        (cg, inertia / volume)
286    }
287
288    /// Fin planform centroid, measured from the root leading edge.
289    fn fin_planform_cg(&self) -> f64 {
290        let (cr, ct, m) = (
291            self.fins.root_chord_m,
292            self.fins.tip_chord_m,
293            self.fins.leading_sweep_m,
294        );
295        (cr * cr + cr * ct + ct * ct + m * (cr + 2.0 * ct)) / (3.0 * (cr + ct))
296    }
297
298    /// Fin centroid height above the body surface.
299    fn fin_radial_cg(&self) -> f64 {
300        let (cr, ct, s) = (
301            self.fins.root_chord_m,
302            self.fins.tip_chord_m,
303            self.fins.span_m,
304        );
305        s * (cr + 2.0 * ct) / (3.0 * (cr + ct))
306    }
307
308    /// Combine component masses with the geometry's component CGs into a
309    /// dry CG and a pitch-inertia estimate about that CG.
310    ///
311    /// The nose is a solid of revolution (numerically integrated), the
312    /// tube a thin-walled cylinder, and the fins and optional motor casing
313    /// point masses; evenly spaced fins add n/2 · m · (r_body + y_cg)² for
314    /// their radial offset. `casing` is (mass_kg, CG from the nose tip).
315    pub fn mass_properties(
316        &self,
317        nose_kg: f64,
318        tube_kg: f64,
319        fins_kg: f64,
320        casing: Option<(f64, f64)>,
321    ) -> MassProperties {
322        assert!(
323            nose_kg >= 0.0 && tube_kg >= 0.0 && fins_kg >= 0.0,
324            "component masses must be non-negative"
325        );
326        let (nose_cg, nose_inertia) = self.nose_volume_properties();
327        let tube_cg = self.nose.length_m + self.tube.length_m / 2.0;
328        let fin_cg = self.total_length_m() - self.fins.root_chord_m + self.fin_planform_cg();
329        let mut parts: Vec<(f64, f64, f64)> = vec![
330            (nose_kg, nose_cg, nose_kg * nose_inertia),
331            (
332                tube_kg,
333                tube_cg,
334                tube_kg * (self.tube.length_m.powi(2) / 12.0 + self.tube.diameter_m.powi(2) / 8.0),
335            ),
336            (fins_kg, fin_cg, 0.0),
337        ];
338        if let Some((kg, cg)) = casing {
339            parts.push((kg, cg, 0.0));
340        }
341        let total: f64 = parts.iter().map(|p| p.0).sum();
342        assert!(total > 0.0, "component masses must sum to a positive mass");
343        let cg: f64 = parts.iter().map(|p| p.0 * p.1).sum::<f64>() / total;
344        let mut inertia: f64 = parts.iter().map(|p| p.2 + p.0 * (p.1 - cg).powi(2)).sum();
345        inertia += fins_kg * (self.tube.diameter_m / 2.0 + self.fin_radial_cg()).powi(2) / 2.0;
346        MassProperties {
347            dry_mass_kg: total,
348            dry_cg_m: cg,
349            pitch_inertia_kg_m2: inertia,
350        }
351    }
352
353    /// Total CP from the component moment sum (nose + fin set).
354    fn total_cp(&self, mach: f64) -> f64 {
355        let nose_cna = 2.0;
356        let fin_cna = self.fin_set_cna(mach);
357        (nose_cna * self.nose.length_m * self.nose.shape.cp_fraction()
358            + fin_cna * self.fin_cp_abs())
359            / (nose_cna + fin_cna)
360    }
361
362    #[cfg(test)]
363    fn nose_cp(&self) -> f64 {
364        self.nose.length_m * self.nose.shape.cp_fraction()
365    }
366
367    fn base_cd(mach: f64) -> f64 {
368        if mach <= 1.0 {
369            0.12 + 0.13 * mach * mach
370        } else {
371            0.25 / mach
372        }
373    }
374
375    fn friction_cd(&self, mach: f64, sound_mps: f64) -> f64 {
376        let length = self.total_length_m();
377        let velocity = mach * sound_mps;
378        let reynolds = velocity * length / 1.5e-5;
379        let rough_ratio = self.roughness_m / length;
380        let cf_turbulent = if reynolds < 1.0e4 {
381            1.48e-2
382        } else {
383            1.0 / (1.5 * reynolds.ln() - 5.6).powi(2)
384        };
385        let cf_rough = 0.032 * rough_ratio.powf(0.2);
386        // Fully turbulent: take the larger of the smooth and roughness-limited
387        // coefficients, then the subsonic compressibility correction.
388        let cf = cf_turbulent.max(cf_rough) * (1.0 - 0.1 * mach * mach);
389        let r = self.max_diameter_m() / 2.0;
390        let fineness = length / r;
391        let correction = 1.0 + 1.0 / (2.0 * fineness);
392        let body_wet = self
393            .nose
394            .shape
395            .lateral_area(self.nose.length_m, self.nose.diameter_m)
396            + std::f64::consts::PI * self.tube.diameter_m * self.tube.length_m;
397        let fin_wet = 2.0 * self.fins.count as f64 * self.fin_area();
398        let thickness_factor = 1.0 + 2.0 * self.fins.thickness_m / self.mac();
399        cf * (correction * body_wet + thickness_factor * fin_wet) / self.ref_area_m2()
400    }
401
402    /// Full analysis. Mach samples at 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, and 3.0;
403    /// the last point simply repeats the Mach-1 values (subsonic clamp).
404    pub fn analyze(&self) -> AeroAnalysis {
405        self.validate();
406        let machs: [f64; 7] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 3.0];
407        let mut cd_vs_mach = Vec::new();
408        let mut cna_vs_mach = Vec::new();
409        let mut cp_vs_mach = Vec::new();
410        let mut induced_k_vs_mach = Vec::new();
411        for &m in &machs {
412            let effective = m.min(1.0);
413            cd_vs_mach.push((
414                m,
415                Self::base_cd(effective)
416                    + self
417                        .nose
418                        .shape
419                        .pressure_cd(self.nose.length_m, self.nose.diameter_m)
420                    + self.friction_cd(effective, 340.0),
421            ));
422            let fin_cna = self.fin_set_cna(effective);
423            cna_vs_mach.push((m, 2.0 + fin_cna));
424            cp_vs_mach.push((m, self.total_cp(effective)));
425            // Induced drag is not part of the Barrowman model; leave zero.
426            induced_k_vs_mach.push((m, 0.0));
427        }
428        AeroAnalysis {
429            cd_vs_mach,
430            cna_vs_mach,
431            cp_vs_mach,
432            induced_k_vs_mach,
433            ref_area_m2: self.ref_area_m2(),
434            total_length_m: self.total_length_m(),
435            max_diameter_m: self.max_diameter_m(),
436        }
437    }
438
439    fn validate(&self) {
440        assert!(self.nose.length_m > 0.0 && self.tube.length_m > 0.0);
441        assert!(self.nose.diameter_m > 0.0 && self.tube.diameter_m > 0.0);
442        assert!(self.fins.count > 0);
443        assert!(self.fins.span_m > 0.0);
444        assert!(self.fins.root_chord_m > 0.0 && self.fins.tip_chord_m > 0.0);
445        assert!(self.fins.thickness_m > 0.0);
446    }
447}
448
449/// Parse the compact geometry spec used by the CLI:
450/// `nose=shape:length:diameter,tube=length:diameter,fins=count:root:tip:span:sweep:thickness`.
451/// The fin thickness is optional (default 2 mm). Lengths are in metres.
452pub fn parse_geometry(spec: &str) -> Result<RocketGeometry> {
453    let mut nose = None;
454    let mut tube = None;
455    let mut fins = None;
456    for item in spec.split(',') {
457        let (key, val) = item
458            .split_once('=')
459            .ok_or_else(|| Error::invalid("geometry", "expected key=value items"))?;
460        let parts: Vec<&str> = val.split(':').collect();
461        let number = |i: usize| -> Result<f64> {
462            parts
463                .get(i)
464                .ok_or_else(|| Error::invalid("geometry", "missing numeric field"))?
465                .parse()
466                .map_err(|_| Error::invalid("geometry", "non-numeric field"))
467        };
468        match key {
469            "nose" => {
470                if parts.len() != 3 {
471                    return Err(Error::invalid("nose", "expected shape:length:diameter"));
472                }
473                let shape = parts[0].parse::<NoseShape>()?;
474                nose = Some(NoseCone {
475                    shape,
476                    length_m: number(1)?,
477                    diameter_m: number(2)?,
478                });
479            }
480            "tube" => {
481                if parts.len() != 2 {
482                    return Err(Error::invalid("tube", "expected length:diameter"));
483                }
484                tube = Some(BodyTube {
485                    length_m: number(0)?,
486                    diameter_m: number(1)?,
487                });
488            }
489            "fins" => {
490                if !(5..=6).contains(&parts.len()) {
491                    return Err(Error::invalid(
492                        "fins",
493                        "expected count:root:tip:span:sweep[:thickness]",
494                    ));
495                }
496                let count: u32 = parts[0]
497                    .parse()
498                    .map_err(|_| Error::invalid("fin count", "must be an integer"))?;
499                fins = Some(TrapezoidalFins {
500                    count,
501                    root_chord_m: number(1)?,
502                    tip_chord_m: number(2)?,
503                    span_m: number(3)?,
504                    leading_sweep_m: number(4)?,
505                    thickness_m: if parts.len() == 6 { number(5)? } else { 0.002 },
506                });
507            }
508            other => {
509                return Err(Error::invalid(
510                    "geometry key",
511                    match other {
512                        "nose" | "tube" | "fins" => unreachable!(),
513                        _ => "must be nose, tube or fins",
514                    },
515                ))
516            }
517        }
518    }
519    Ok(RocketGeometry::new(
520        nose.ok_or_else(|| Error::invalid("geometry", "nose is required"))?,
521        tube.ok_or_else(|| Error::invalid("geometry", "tube is required"))?,
522        fins.ok_or_else(|| Error::invalid("geometry", "fins are required"))?,
523    ))
524}
525
526/// Dry-mass breakdown estimated from geometry and component masses by
527/// [`RocketGeometry::mass_properties`].
528#[derive(Debug, Clone, Copy)]
529pub struct MassProperties {
530    /// Sum of the component masses (structure plus motor casing).
531    pub dry_mass_kg: f64,
532    /// Dry centre of gravity, metres aft of the nose tip.
533    pub dry_cg_m: f64,
534    /// Pitch inertia about the dry CG, kg·m².
535    pub pitch_inertia_kg_m2: f64,
536}
537
538/// The curves and reference quantities produced by [`RocketGeometry::analyze`].
539#[derive(Debug, Clone)]
540pub struct AeroAnalysis {
541    /// Axial drag coefficient vs Mach (subsonic, clamped above Mach 1).
542    pub cd_vs_mach: Vec<(f64, f64)>,
543    /// Normal-force coefficient slope per radian vs Mach (nose + fin set).
544    pub cna_vs_mach: Vec<(f64, f64)>,
545    /// Centre of pressure, metres aft of the nose tip, vs Mach.
546    pub cp_vs_mach: Vec<(f64, f64)>,
547    /// Induced-drag factor per radian² vs Mach (zero: not in the Barrowman model).
548    pub induced_k_vs_mach: Vec<(f64, f64)>,
549    /// Reference area, π/4·d² of the largest diameter.
550    pub ref_area_m2: f64,
551    /// Total aerodynamic length (nose + tube).
552    pub total_length_m: f64,
553    /// Largest body diameter.
554    pub max_diameter_m: f64,
555}
556
557#[cfg(feature = "ballistics")]
558impl AeroAnalysis {
559    /// Bundle the analysis with the remaining airframe parameters.
560    pub fn airframe(
561        &self,
562        cg_dry_m: f64,
563        cg_prop_m: f64,
564        pitch_inertia_kg_m2: f64,
565        recovery_cd_area_m2: f64,
566    ) -> crate::Airframe {
567        crate::Airframe {
568            diameter_m: self.max_diameter_m,
569            cd_vs_mach: self.cd_vs_mach.clone(),
570            cna_vs_mach: self.cna_vs_mach.clone(),
571            cp_vs_mach: self.cp_vs_mach.clone(),
572            cg_dry_m,
573            cg_prop_m,
574            pitch_inertia_kg_m2,
575            induced_k_vs_mach: self.induced_k_vs_mach.clone(),
576            recovery_cd_area_m2,
577        }
578    }
579
580    /// Drag + atmosphere + body lift for this geometry in the given wind.
581    pub fn forces(&self, wind_mps: crate::Vec3) -> Result<crate::ballistics::BallisticForces> {
582        crate::ballistics::BallisticForces::new(
583            self.max_diameter_m,
584            self.cd_vs_mach.clone(),
585            crate::ballistics::Atmosphere::default(),
586            wind_mps,
587        )?
588        .with_body_lift(self.cna_vs_mach.clone(), self.induced_k_vs_mach.clone())
589    }
590
591    /// Weathercock parameters for this geometry.
592    pub fn weathercock_params(
593        &self,
594        cg_dry_m: f64,
595        cg_prop_m: f64,
596        pitch_inertia_kg_m2: f64,
597    ) -> Result<crate::WeathercockParams> {
598        crate::WeathercockParams::new(
599            self.cna_vs_mach.clone(),
600            self.cp_vs_mach.clone(),
601            cg_dry_m,
602            cg_prop_m,
603            self.max_diameter_m,
604            pitch_inertia_kg_m2,
605            0.2,
606        )
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613
614    fn example() -> RocketGeometry {
615        RocketGeometry::new(
616            NoseCone {
617                shape: NoseShape::Conical,
618                length_m: 0.1,
619                diameter_m: 0.024,
620            },
621            BodyTube {
622                length_m: 0.4,
623                diameter_m: 0.024,
624            },
625            TrapezoidalFins {
626                count: 3,
627                root_chord_m: 0.05,
628                tip_chord_m: 0.03,
629                span_m: 0.04,
630                leading_sweep_m: 0.02,
631                thickness_m: 0.002,
632            },
633        )
634    }
635
636    #[test]
637    fn nose_cp_fractions_match_barrowman() {
638        assert_eq!(NoseShape::Conical.cp_fraction(), 2.0 / 3.0);
639        assert_eq!(NoseShape::Ogive.cp_fraction(), 0.466);
640        assert_eq!(NoseShape::Elliptical.cp_fraction(), 1.0 / 3.0);
641        assert_eq!(NoseShape::Parabolic.cp_fraction(), 0.5);
642    }
643
644    #[test]
645    fn conical_pressure_drag_uses_half_angle() {
646        let cd = NoseShape::Conical.pressure_cd(0.1, 0.024);
647        let sin_phi = 0.012 / (0.012_f64.powi(2) + 0.1_f64.powi(2)).sqrt();
648        assert!((cd - 0.8 * sin_phi * sin_phi).abs() < 1e-12);
649        assert_eq!(NoseShape::Ogive.pressure_cd(0.1, 0.024), 0.0);
650    }
651
652    #[test]
653    fn fin_cp_matches_the_trapezoid_formula() {
654        let geo = example();
655        // Independently: MAC = (2/3)(cr+ct - cr*ct/(cr+ct)), yMAC = s(cr+2ct)/(3(cr+ct)).
656        let mac = (2.0 / 3.0) * (0.05 + 0.03 - 0.05 * 0.03 / 0.08);
657        let y_mac = (0.04 / 3.0) * (0.05 + 2.0 * 0.03) / 0.08;
658        let expected = 0.02 * y_mac / 0.04 + 0.25 * mac;
659        assert!((geo.fin_cp() - expected).abs() < 1e-12, "{}", geo.fin_cp());
660    }
661
662    #[test]
663    fn conical_nose_volume_properties_match_the_solid_cone() {
664        let geo = example(); // conical nose, L = 0.1, R = 0.012
665        let (cg, inertia) = geo.nose_volume_properties();
666        assert!((cg - 0.75 * 0.1).abs() < 1e-6, "cg {cg}");
667        let expected = 3.0 * 0.012_f64.powi(2) / 20.0 + 3.0 * 0.1_f64.powi(2) / 80.0;
668        assert!(
669            (inertia - expected).abs() / expected < 1e-4,
670            "inertia {inertia} expected {expected}"
671        );
672    }
673
674    #[test]
675    fn fin_centroid_matches_polygon_limits() {
676        let geo = example();
677        // Rectangle limit (m = 0, ct = cr): centroid at cr/2, height s/2.
678        let rectangular = RocketGeometry::new(
679            geo.nose,
680            geo.tube,
681            TrapezoidalFins {
682                count: 3,
683                root_chord_m: 0.05,
684                tip_chord_m: 0.05,
685                span_m: 0.04,
686                leading_sweep_m: 0.0,
687                thickness_m: 0.002,
688            },
689        );
690        assert!((rectangular.fin_planform_cg() - 0.025).abs() < 1e-12);
691        assert!((rectangular.fin_radial_cg() - 0.02).abs() < 1e-12);
692        // Triangle limit (ct = 0): (cr + m)/3 from the leading edge, s/3 up.
693        let triangular = RocketGeometry::new(
694            geo.nose,
695            geo.tube,
696            TrapezoidalFins {
697                count: 3,
698                root_chord_m: 0.06,
699                tip_chord_m: 0.0,
700                span_m: 0.03,
701                leading_sweep_m: 0.03,
702                thickness_m: 0.002,
703            },
704        );
705        assert!((triangular.fin_planform_cg() - (0.06 + 0.03) / 3.0).abs() < 1e-12);
706        assert!((triangular.fin_radial_cg() - 0.01).abs() < 1e-12);
707    }
708
709    #[test]
710    fn mass_properties_are_consistent() {
711        let geo = example();
712        let props = geo.mass_properties(0.012, 0.020, 0.006, None);
713        assert!((props.dry_mass_kg - 0.038).abs() < 1e-12);
714        // CG is the mass-weighted component mean, inside the airframe.
715        let (nose_cg, _) = geo.nose_volume_properties();
716        let tube_cg = geo.nose.length_m + geo.tube.length_m / 2.0;
717        let fin_cg = geo.total_length_m() - geo.fins.root_chord_m + geo.fin_planform_cg();
718        let expected_cg = (0.012 * nose_cg + 0.020 * tube_cg + 0.006 * fin_cg) / 0.038;
719        assert!((props.dry_cg_m - expected_cg).abs() < 1e-12);
720        assert!(props.dry_cg_m > 0.0 && props.dry_cg_m < geo.total_length_m());
721        assert!(props.pitch_inertia_kg_m2 > 0.0);
722        // A casing at the aft end moves the CG aft and adds inertia.
723        let with_casing = geo.mass_properties(0.012, 0.020, 0.006, Some((0.02, 0.32)));
724        assert!(with_casing.dry_cg_m > props.dry_cg_m);
725        assert!(with_casing.pitch_inertia_kg_m2 > props.pitch_inertia_kg_m2);
726        assert!((with_casing.dry_mass_kg - 0.058).abs() < 1e-12);
727        // A heavier nose moves the CG forward.
728        let heavy_nose = geo.mass_properties(0.024, 0.020, 0.006, None);
729        assert!(heavy_nose.dry_cg_m < props.dry_cg_m);
730    }
731
732    #[test]
733    fn mass_properties_single_component_is_exact() {
734        let geo = example();
735        let props = geo.mass_properties(0.0, 0.05, 0.0, None);
736        // Only the tube: CG at its midpoint, inertia its thin-cylinder value.
737        let tube_cg = geo.nose.length_m + geo.tube.length_m / 2.0;
738        assert!((props.dry_cg_m - tube_cg).abs() < 1e-12);
739        let expected =
740            0.05 * (geo.tube.length_m.powi(2) / 12.0 + geo.tube.diameter_m.powi(2) / 8.0);
741        assert!(
742            (props.pitch_inertia_kg_m2 - expected).abs() / expected < 1e-12,
743            "{} vs {expected}",
744            props.pitch_inertia_kg_m2
745        );
746    }
747
748    #[test]
749    fn fin_set_cna_matches_diederich() {
750        let geo = example();
751        // Fin pair: 2π·span²/(1+sqrt(1+(span²/(A·cosΓ))²)) / Aref, then
752        // (N/2)·(1+tau) — the Diederich value is a wing (two fins).
753        let area = geo.fin_area();
754        let cos = geo.midchord_cos();
755        let ratio = geo.fins.span_m * geo.fins.span_m / (area * cos);
756        let one = 2.0 * std::f64::consts::PI * geo.fins.span_m * geo.fins.span_m
757            / (1.0 + (1.0 + ratio * ratio).sqrt())
758            / geo.ref_area_m2();
759        let expected = 1.5 * one * (1.0 + geo.interference_tau());
760        let actual = geo.fin_set_cna(0.0);
761        assert!(
762            (actual - expected).abs() / expected < 1e-9,
763            "actual {actual} expected {expected}"
764        );
765        // And the classic closed form 4N(s/d)²/(1+sqrt(1+(2l/(cr+ct))²))·K.
766        let d = geo.max_diameter_m();
767        let classic = 4.0 * 3.0 * (geo.fins.span_m / d).powi(2)
768            / (1.0 + (1.0_f64 + 1.0_f64).sqrt())
769            * (1.0 + geo.interference_tau());
770        assert!(
771            (actual - classic).abs() / classic < 0.02,
772            "actual {actual} classic {classic}"
773        );
774    }
775
776    #[test]
777    fn total_cp_is_the_moment_sum() {
778        let geo = example();
779        let fin_cna = geo.fin_set_cna(0.0);
780        let expected = (2.0 * geo.nose_cp() + fin_cna * geo.fin_cp_abs()) / (2.0 + fin_cna);
781        assert!((geo.total_cp(0.0) - expected).abs() < 1e-12);
782        // CP must sit aft of the nose CP (fins pull it back).
783        assert!(geo.total_cp(0.0) > geo.nose_cp());
784    }
785
786    #[test]
787    fn base_cd_matches_openrocket() {
788        assert_eq!(RocketGeometry::base_cd(0.0), 0.12);
789        assert_eq!(RocketGeometry::base_cd(1.0), 0.25);
790        assert_eq!(RocketGeometry::base_cd(2.0), 0.125);
791    }
792
793    #[test]
794    fn analysis_produces_finite_curves_and_roughness_costs_drag() {
795        let geo = example();
796        let analysis = geo.analyze();
797        for &(m, cd) in &analysis.cd_vs_mach {
798            assert!(cd.is_finite() && cd > 0.0, "mach {m} cd {cd}");
799        }
800        for &(m, cp) in &analysis.cp_vs_mach {
801            assert!(cp.is_finite() && cp > 0.0, "mach {m} cp {cp}");
802        }
803        let smooth = geo.with_roughness(1e-6).analyze();
804        let rough = geo.with_roughness(500e-6).analyze();
805        assert!(rough.cd_vs_mach[2].1 > smooth.cd_vs_mach[2].1);
806    }
807}