Skip to main content

hpr_design/
fins.rs

1//! Fin sets and tube fins: planforms, cross-sections, tabs, and mass properties from geometry.
2//!
3//! **Fin frame.** A fin set's frame has its origin on the body axis at the station of the root
4//! chord's leading edge. Fin `k` of `N` lies in the plane through the axis at roll angle
5//! `φ_k = φ_0 + 2πk/N` from `x_B` toward `y_B`. In a fin's own coordinates, `x` runs aft from the
6//! root leading edge, the span `h` runs outward from the body surface (radius `R_b + h`), and the
7//! thickness coordinate `τ` is normal to the fin plane. Planform definitions follow S. Niskanen,
8//! *OpenRocket technical documentation* v13.05, §3.2.2, pp. 25–29: a trapezoidal fin has root chord
9//! `c_r`, tip chord `c_t` parallel to the body, span `s`, and sweep `x_t`, the axial distance from
10//! the root leading edge to the tip leading edge; an elliptical fin has chord
11//! `c(h) = c_r √(1 − (h/s)²)` centered on the root chord; a freeform fin is a polygon.
12//!
13//! **Mass.** Each fin is a plate whose local thickness varies along each chord with the
14//! cross-section. At span `h`, a chord from `a` to `b` (length `c`) contributes the moments
15//! `M_k = ∫ x^k t(x) dx` and `T = ∫ t(x)³/12 dx`:
16//!
17//! ```text
18//! square:   t(x) = t
19//! rounded:  semicircular leading and trailing edges of radius a_r = min(t, c)/2
20//! airfoil:  t(x) = 10 t P(ξ),  P = 0.2969√ξ − 0.1260ξ − 0.3516ξ² + 0.2843ξ³ − 0.1015ξ⁴
21//! ```
22//!
23//! The airfoil is the NACA four-digit symmetric thickness distribution (I. H. Abbott and A. E.
24//! von Doenhoff, *Theory of Wing Sections*, Dover, 1959, eq. 6.2) with its maximum thickness,
25//! `1.0003 t` at `ξ = 0.2998`, scaled to the fin thickness. OpenRocket's documentation uses the
26//! cross-section only for drag (§3.4.4, pp. 49–50); hpr-design also counts the volume it removes.
27//! The fin's moments about the fin-set frame are then
28//!
29//! ```text
30//! m = ρ ∫ M_0 dh,  ∫ r dm = ρ ∫ (R_b + h) M_0 dh,  ∫ r² dm = ρ ∫ (R_b + h)² M_0 dh,
31//! ∫ x dm = ρ ∫ M_1 dh,  ∫ x² dm = ρ ∫ M_2 dh,  ∫ r x dm = ρ ∫ (R_b + h) M_1 dh,  ∫ τ² dm = ρ ∫ T dh
32//! ```
33//!
34//! and with the fin at `φ = 0` (points at `(r, τ, −x)` in body axes)
35//!
36//! ```text
37//! I_xx = ∫(τ² + x²) dm,  I_yy = ∫(r² + x²) dm,  I_zz = ∫(r² + τ²) dm,  I_xz = ∫ r x dm,  I_xy = I_yz = 0
38//! ```
39//!
40//! about the origin. A tab is a square-section slab below the root (`−h_tab ≤ h ≤ 0`), over the
41//! length it states, which may pass either end of the root ([ADR-309][adr-309], the decision to
42//! weigh a tab as its file states it). The flat
43//! root is taken to sit on the body at radius `R_b`; the sliver between a flat root and the curved
44//! tube, `t²/8R_b` deep, is ignored. On a nose cone or a transition the surface is not level
45//! along the root: `R_b` is the body's radius at the root leading edge, `h` is measured from it,
46//! and a freeform fin's root runs through its root points on the surface (OpenRocket's reading of
47//! a fin on a nose cone, [ADR-166][adr-166]). **Cant** `δ` turns each fin (with its tab) by `δ` about its own
48//! outward span axis through the root mid-chord, right-handed, so a positive cant turns fin 0's
49//! leading edge toward `−y_B`. See `docs/physics/mass.md`.
50//!
51//! **Fillets.** A fillet of radius `r` runs the root chord `c_r` on each face of each fin. Its
52//! section is the region between the fin's mid-plane, the body's circle of radius `R_b`, and a
53//! circle of radius `r` tangent to both: OpenRocket 24.12's reading, which leaves the fin's
54//! thickness out. Its mass and center of mass match OpenRocket's to 1e-15 on nine probe designs
55//! ([ADR-096][adr-096], the decision on fillets). With the fillet circle's center at
56//! `(c, r)`, `c = √(R_b² + 2 R_b r)` and `θ = atan(r / c)`, the section is the triangle
57//! `(0, 0), (c, 0), (c, r)` less the body's sector of angle `θ` and the fillet's of `π/2 − θ`:
58//!
59//! ```text
60//! A = c r / 2 − R_b² θ / 2 − r² (π/2 − θ) / 2
61//! ```
62//!
63//! which tends to `r² (1 − π/4)` on a flat body. Its moments come the same way, and the fillets
64//! are a prism of that section along the root, in the fillet's own material.
65//!
66//! [adr-166]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0166-a-fin-root-that-follows-the-body.md
67//! [adr-096]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-096-fin-fillets-and-an-automatic-radius-inside-a-nose-cone-read-as-openrocket-reads-them-2026-09-28
68//! [adr-309]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0309-a-fin-tab-weighed-as-stated.md
69
70use std::f64::consts::PI;
71
72use hpr_core::quadrature::{Tolerance, integrate};
73use hpr_core::{DMat3, DQuat, DVec3};
74use serde::{Deserialize, Serialize};
75
76use crate::error::DesignError;
77use crate::mass::MassProperties;
78use crate::material::Material;
79use crate::shapes::{Profile, check_dimension};
80
81/// The outline of one fin.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
83#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
84#[non_exhaustive]
85pub enum FinPlanform {
86    /// A trapezoid with its tip chord parallel to the root.
87    Trapezoidal {
88        /// Root chord, m.
89        root_chord_m: f64,
90        /// Tip chord, m (zero for a pointed fin).
91        tip_chord_m: f64,
92        /// Span from the body surface to the tip, m.
93        span_m: f64,
94        /// Axial distance from the root leading edge aft to the tip leading edge, m.
95        sweep_m: f64,
96    },
97    /// Half an ellipse on the root chord.
98    Elliptical {
99        /// Root chord, m.
100        root_chord_m: f64,
101        /// Span, m.
102        span_m: f64,
103    },
104    /// A polygon given as `[x, h]` points from the root leading edge, which must be `[0, 0]`,
105    /// around to the root trailing edge `[c_r, h_r]` with `c_r > 0` and `h_r ≥ 0`, closed along
106    /// the root; `x` runs aft and `h` outward, in meters. On a body tube the root is level,
107    /// `h_r = 0`; on a nose cone or a transition it follows the surface, through `root_m`.
108    Freeform {
109        /// The outline, m.
110        points_m: Vec<[f64; 2]>,
111        /// The root's points between its trailing and leading edges, aft to fore, m: none for a
112        /// straight root. The root is straight between them.
113        #[serde(default, skip_serializing_if = "Vec::is_empty")]
114        root_m: Vec<[f64; 2]>,
115    },
116}
117
118/// The shape of a fin's section along its chord.
119#[derive(
120    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize, schemars::JsonSchema,
121)]
122#[serde(rename_all = "snake_case")]
123#[non_exhaustive]
124pub enum FinCrossSection {
125    /// Constant thickness, square edges.
126    #[default]
127    Square,
128    /// Semicircular leading and trailing edges.
129    Rounded,
130    /// The NACA four-digit symmetric thickness distribution.
131    Airfoil,
132}
133
134/// A rectangular tab below a fin's root, reaching into the body.
135///
136/// The tab is weighed as stated: it may start ahead of the root's leading edge (a negative
137/// offset) or end past its trailing edge, as OpenRocket 24.12 weighs one (it trims only a few
138/// rounding overhangs to the root on loading), so long as it meets the root over some length
139/// ([ADR-309][adr-309]). `.ork` files state tabs that pass the root by rounding, by less than
140/// 0.03 mm, and by design, by more than 0.8 mm.
141///
142/// [adr-309]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0309-a-fin-tab-weighed-as-stated.md
143#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
144#[serde(deny_unknown_fields)]
145pub struct FinTab {
146    /// Depth below the root, m.
147    pub height_m: f64,
148    /// Length along the root, m.
149    pub length_m: f64,
150    /// Distance from the root leading edge aft to the tab's leading edge, m; negative for a tab
151    /// that starts ahead of the root.
152    pub offset_m: f64,
153}
154
155/// Fillets along each fin's root: a concave joint on both faces, running the root chord.
156#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
157#[serde(deny_unknown_fields)]
158pub struct FinFillet {
159    /// Radius of the fillet's concave face, m.
160    pub radius_m: f64,
161    /// Material (bulk).
162    pub material: Material,
163}
164
165/// A set of identical fins spaced evenly around the body.
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
167#[serde(deny_unknown_fields)]
168pub struct FinSet {
169    /// Number of fins, 1 to 64 (`FinSet::MAX_COUNT`).
170    pub count: u32,
171    /// Outline of each fin.
172    pub planform: FinPlanform,
173    /// Maximum thickness, m.
174    pub thickness_m: f64,
175    /// Section shape.
176    #[serde(default)]
177    pub cross_section: FinCrossSection,
178    /// Optional tab below each root.
179    #[serde(default)]
180    pub tab: Option<FinTab>,
181    /// Optional fillets along each root.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub fillet: Option<FinFillet>,
184    /// Cant angle, rad.
185    #[serde(default)]
186    pub cant_rad: f64,
187    /// Roll angle of the first fin from `x_B` toward `y_B`, rad.
188    #[serde(default)]
189    pub base_angle_rad: f64,
190    /// Material (bulk).
191    pub material: Material,
192}
193
194/// Area and centroid of a planform.
195#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
196pub struct PlanformGeometry {
197    /// Area of one fin, m².
198    pub area_m2: f64,
199    /// Centroid, m aft of the root leading edge.
200    pub centroid_x_m: f64,
201    /// Centroid, m outward from the root.
202    pub centroid_span_m: f64,
203}
204
205/// NACA four-digit thickness polynomial `P(ξ)` (Abbott and von Doenhoff, eq. 6.2); the mass code
206/// uses its moments, and the tests integrate it directly.
207#[cfg(test)]
208fn naca_polynomial(xi: f64) -> f64 {
209    0.2969 * xi.sqrt() - 0.1260 * xi - 0.3516 * xi * xi + 0.2843 * xi.powi(3) - 0.1015 * xi.powi(4)
210}
211
212/// `10 ∫₀¹ P dξ`, `10 ∫₀¹ ξ P dξ` and `10 ∫₀¹ ξ² P dξ`, term by term.
213const AIRFOIL_PHI: [f64; 3] = [
214    10.0 * (0.2969 * 2.0 / 3.0 - 0.1260 / 2.0 - 0.3516 / 3.0 + 0.2843 / 4.0 - 0.1015 / 5.0),
215    10.0 * (0.2969 * 2.0 / 5.0 - 0.1260 / 3.0 - 0.3516 / 4.0 + 0.2843 / 5.0 - 0.1015 / 6.0),
216    10.0 * (0.2969 * 2.0 / 7.0 - 0.1260 / 4.0 - 0.3516 / 5.0 + 0.2843 / 6.0 - 0.1015 / 7.0),
217];
218
219/// `1000 ∫₀¹ P³ dξ`, evaluated with mpmath at 30 digits; `airfoil_constants_are_the_integrals`
220/// recomputes it.
221const AIRFOIL_PSI: f64 = 0.472_889_488_894_451_523_708_489_652_762;
222
223/// Chordwise moments `[M_0, M_1, M_2, T]` of a chord from `a` to `b` of thickness `t`.
224fn chord_moments(section: FinCrossSection, a: f64, b: f64, t: f64) -> [f64; 4] {
225    let c = b - a;
226    if c <= 0.0 {
227        return [0.0; 4];
228    }
229    match section {
230        FinCrossSection::Square => [
231            t * c,
232            0.5 * t * (b * b - a * a),
233            t * (b.powi(3) - a.powi(3)) / 3.0,
234            t.powi(3) * c / 12.0,
235        ],
236        FinCrossSection::Airfoil => {
237            let [p0, p1, p2] = AIRFOIL_PHI;
238            [
239                t * c * p0,
240                t * (a * c * p0 + c * c * p1),
241                t * (a * a * c * p0 + 2.0 * a * c * c * p1 + c.powi(3) * p2),
242                t.powi(3) * c * AIRFOIL_PSI / 12.0,
243            ]
244        }
245        FinCrossSection::Rounded => {
246            // A slab of the middle thickness minus what the two rounded edges remove. With
247            // v = a_r − u the depth from the edge's center, the removed thickness is
248            // δ = 2a_r − 2√(a_r² − v²), whose moments from the edge are D_0, D_1, D_2.
249            let mid = t.min(c);
250            let r = 0.5 * mid;
251            let d0 = r * r * (2.0 - PI / 2.0);
252            let d1 = r * d0 - r.powi(3) / 3.0;
253            let d2 = r * r * d0 - PI * r.powi(4) / 8.0;
254            let e0 = 8.0 * r.powi(4) - 1.5 * PI * r.powi(4);
255            let m0 = mid * c - 2.0 * d0;
256            [
257                m0,
258                m0 * 0.5 * (a + b),
259                mid * (b.powi(3) - a.powi(3)) / 3.0
260                    - (a * a * d0 + 2.0 * a * d1 + d2)
261                    - (b * b * d0 - 2.0 * b * d1 + d2),
262                (mid.powi(3) * c - 2.0 * e0) / 12.0,
263            ]
264        }
265    }
266}
267
268impl FinPlanform {
269    /// Root chord, m.
270    pub fn root_chord_m(&self) -> f64 {
271        match self {
272            Self::Trapezoidal { root_chord_m, .. } | Self::Elliptical { root_chord_m, .. } => {
273                *root_chord_m
274            }
275            Self::Freeform { points_m, .. } => points_m.last().map_or(0.0, |p| p[0]),
276        }
277    }
278
279    /// How far aft of the root leading edge the outline reaches, m: the root chord, or the tip's
280    /// trailing edge where it lies further aft (a trapezoid's sweep plus its tip chord), or a
281    /// freeform outline's aft-most point. A fin set placed on a tube's aft end can reach past it
282    /// this way, and the rocket then stands on its fin tips (#1254).
283    pub fn aft_extent_m(&self) -> f64 {
284        match self {
285            Self::Trapezoidal {
286                root_chord_m,
287                tip_chord_m,
288                sweep_m,
289                ..
290            } => root_chord_m.max(sweep_m + tip_chord_m),
291            Self::Elliptical { root_chord_m, .. } => *root_chord_m,
292            Self::Freeform { points_m, root_m } => points_m
293                .iter()
294                .chain(root_m)
295                .fold(self.root_chord_m(), |m, p| m.max(p[0])),
296        }
297    }
298
299    /// Span, m.
300    pub fn span_m(&self) -> f64 {
301        match self {
302            Self::Trapezoidal { span_m, .. } | Self::Elliptical { span_m, .. } => *span_m,
303            Self::Freeform { points_m, root_m } => {
304                points_m.iter().chain(root_m).fold(0.0, |m, p| m.max(p[1]))
305            }
306        }
307    }
308
309    /// Checks dimensions, and that a freeform outline is a simple polygon, nowhere below the root
310    /// leading edge, that starts and ends on the root.
311    ///
312    /// # Errors
313    ///
314    /// [`DesignError::Domain`] or [`DesignError::Geometry`].
315    pub fn validate(&self) -> Result<(), DesignError> {
316        match self {
317            Self::Trapezoidal {
318                root_chord_m,
319                tip_chord_m,
320                span_m,
321                sweep_m,
322            } => {
323                check_dimension("fin root chord", *root_chord_m, false)?;
324                check_dimension("fin tip chord", *tip_chord_m, true)?;
325                check_dimension("fin span", *span_m, false)?;
326                if !sweep_m.is_finite() {
327                    return Err(DesignError::Domain {
328                        what: "fin sweep",
329                        value: *sweep_m,
330                    });
331                }
332            }
333            Self::Elliptical {
334                root_chord_m,
335                span_m,
336            } => {
337                check_dimension("fin root chord", *root_chord_m, false)?;
338                check_dimension("fin span", *span_m, false)?;
339            }
340            Self::Freeform { points_m, root_m } => validate_outline(points_m, root_m)?,
341        }
342        Ok(())
343    }
344
345    /// The chord intervals `(a, b)` at span `h` (m outward from the root), sorted along `x` (m aft
346    /// of the root leading edge), replacing the contents of `out`. A span at or beyond the tip
347    /// gives none. The planform should be valid ([`FinPlanform::validate`]).
348    pub fn chords_at(&self, h: f64, out: &mut Vec<(f64, f64)>) {
349        out.clear();
350        match self {
351            Self::Trapezoidal {
352                root_chord_m,
353                tip_chord_m,
354                span_m,
355                sweep_m,
356            } => {
357                if (0.0..*span_m).contains(&h) {
358                    let f = h / span_m;
359                    let lead = sweep_m * f;
360                    out.push((lead, lead + root_chord_m + (tip_chord_m - root_chord_m) * f));
361                }
362            }
363            Self::Elliptical {
364                root_chord_m,
365                span_m,
366            } => {
367                if (0.0..*span_m).contains(&h) {
368                    let f = h / span_m;
369                    let chord = root_chord_m * (1.0 - f * f).max(0.0).sqrt();
370                    let lead = 0.5 * (root_chord_m - chord);
371                    out.push((lead, lead + chord));
372                }
373            }
374            Self::Freeform { points_m, root_m } => {
375                let mut crossings: Vec<f64> = Vec::new();
376                let polygon = || points_m.iter().chain(root_m);
377                for (&p, &q) in polygon().zip(polygon().cycle().skip(1)) {
378                    let (lo, hi) = (p[1].min(q[1]), p[1].max(q[1]));
379                    if p[1] != q[1] && h >= lo && h < hi {
380                        crossings.push(p[0] + (h - p[1]) * (q[0] - p[0]) / (q[1] - p[1]));
381                    }
382                }
383                crossings.sort_by(f64::total_cmp);
384                let (pairs, _) = crossings.as_chunks::<2>();
385                out.extend(pairs.iter().map(|&[a, b]| (a, b)));
386            }
387        }
388    }
389
390    /// Span stations where the chord intervals change form: 0, the span, and freeform vertices.
391    fn breakpoints(&self) -> Vec<f64> {
392        let mut points = vec![0.0, self.span_m()];
393        if let Self::Freeform { points_m, root_m } = self {
394            points.extend(points_m.iter().chain(root_m).map(|p| p[1]));
395        }
396        points.sort_by(f64::total_cmp);
397        points.dedup();
398        points
399    }
400
401    /// Area and centroid of the planform.
402    ///
403    /// # Errors
404    ///
405    /// As [`FinPlanform::validate`], or [`DesignError::Numerics`] if an integral fails.
406    pub fn geometry(&self) -> Result<PlanformGeometry, DesignError> {
407        self.validate()?;
408        let scale = self.root_chord_m() + self.span_m();
409        let mut chords = Vec::new();
410        let mut total = [0.0; 3];
411        for pair in self.breakpoints().windows(2) {
412            let piece = integrate(
413                |h| {
414                    self.chords_at(h * scale, &mut chords);
415                    chords.iter().fold([0.0; 3], |acc, &(a, b)| {
416                        let (a, b) = (a / scale, b / scale);
417                        [
418                            acc[0] + (b - a),
419                            acc[1] + 0.5 * (b * b - a * a),
420                            acc[2] + h * (b - a),
421                        ]
422                    })
423                },
424                pair[0] / scale,
425                pair[1] / scale,
426                PLATE,
427            )?;
428            for (sum, value) in total.iter_mut().zip(piece.value) {
429                *sum += value;
430            }
431        }
432        let area = total[0] * scale * scale;
433        if area <= 0.0 {
434            return Err(DesignError::Geometry("the fin has no area".to_owned()));
435        }
436        Ok(PlanformGeometry {
437            area_m2: area,
438            centroid_x_m: scale * total[1] / total[0],
439            centroid_span_m: scale * total[2] / total[0],
440        })
441    }
442}
443
444/// Quadrature settings for plate integrands scaled to order one.
445const PLATE: Tolerance = Tolerance {
446    relative: 1e-12,
447    absolute: 1e-16,
448    max_intervals: 4000,
449};
450
451/// Checks a freeform outline and its root points: finite points, at least three in the outline,
452/// the first at the root leading edge and the last aft of it, none below it, the root's points
453/// running fore between the root's ends, positive area, and no two non-adjacent edges touching.
454fn validate_outline(outline: &[[f64; 2]], root: &[[f64; 2]]) -> Result<(), DesignError> {
455    if outline.len() < 3 {
456        return Err(DesignError::Geometry(format!(
457            "a freeform fin needs at least 3 points, got {}",
458            outline.len()
459        )));
460    }
461    let points: Vec<[f64; 2]> = outline.iter().chain(root).copied().collect();
462    for p in &points {
463        for (what, value) in [("freeform fin x", p[0]), ("freeform fin span", p[1])] {
464            if !value.is_finite() {
465                return Err(DesignError::Domain { what, value });
466            }
467        }
468        if p[1] < 0.0 {
469            return Err(DesignError::Domain {
470                what: "freeform fin span",
471                value: p[1],
472            });
473        }
474    }
475    let (first, last) = (outline[0], outline[outline.len() - 1]);
476    if first != [0.0, 0.0] || last[0] <= 0.0 {
477        return Err(DesignError::Geometry(
478            "a freeform fin must start at the root leading edge [0, 0] and end at the root \
479             trailing edge [c, h] with c > 0"
480                .to_owned(),
481        ));
482    }
483    // The root runs fore from the trailing edge to the leading edge, one point after another.
484    let mut aft = last[0];
485    for p in root {
486        if !(p[0] < aft && p[0] > 0.0) {
487            return Err(DesignError::Geometry(format!(
488                "a freeform fin's root points must run fore, strictly between its trailing edge \
489                 at x = {} m and its leading edge. One is at x = {} m",
490                last[0], p[0]
491            )));
492        }
493        aft = p[0];
494    }
495    let points = points.as_slice();
496    let n = points.len();
497    let edge = |i: usize| (points[i], points[(i + 1) % n]);
498    for i in 0..n {
499        for j in (i + 1)..n {
500            // Adjacent edges share a vertex; the closing edge is adjacent to the first.
501            if j == i + 1 || (i == 0 && j == n - 1) {
502                continue;
503            }
504            let (p, q) = edge(i);
505            let (r, s) = edge(j);
506            if segments_touch(p, q, r, s) {
507                return Err(DesignError::Geometry(format!(
508                    "the freeform fin outline crosses itself (edges {i} and {j})"
509                )));
510            }
511        }
512    }
513    let twice_area: f64 = (0..n)
514        .map(|i| {
515            let (p, q) = edge(i);
516            p[0] * q[1] - q[0] * p[1]
517        })
518        .sum();
519    if twice_area == 0.0 {
520        return Err(DesignError::Geometry("the fin has no area".to_owned()));
521    }
522    // From the root leading edge out along the outline and back along the root, a fin above its
523    // root turns clockwise in `[x, h]`: every outline over a level root does. One that turns the
524    // other way runs below its root, inside the body.
525    if twice_area > 0.0 {
526        return Err(DesignError::Geometry(
527            "the freeform fin outline runs below its root".to_owned(),
528        ));
529    }
530    Ok(())
531}
532
533/// Whether the closed segments `pq` and `rs` share a point.
534fn segments_touch(p: [f64; 2], q: [f64; 2], r: [f64; 2], s: [f64; 2]) -> bool {
535    let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| {
536        (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
537    };
538    let within = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| {
539        c[0] >= a[0].min(b[0])
540            && c[0] <= a[0].max(b[0])
541            && c[1] >= a[1].min(b[1])
542            && c[1] <= a[1].max(b[1])
543    };
544    let d1 = cross(r, s, p);
545    let d2 = cross(r, s, q);
546    let d3 = cross(p, q, r);
547    let d4 = cross(p, q, s);
548    if ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0))
549        && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))
550    {
551        return true;
552    }
553    (d1 == 0.0 && within(r, s, p))
554        || (d2 == 0.0 && within(r, s, q))
555        || (d3 == 0.0 && within(p, q, r))
556        || (d4 == 0.0 && within(p, q, s))
557}
558
559/// Volume integrals of a plate per unit density, about the fin-set origin with the fin at roll 0:
560/// `[V, ∫r, ∫r², ∫x, ∫x², ∫rx, ∫τ²]` (each `dV`).
561type PlateIntegrals = [f64; 7];
562
563impl FinSet {
564    /// How far a root's point may stand off the surface of the nose cone or transition it sits
565    /// on, m: a micron, well inside any build tolerance and far outside the rounding of a file's
566    /// seventeen digits.
567    pub const ROOT_ON_SURFACE_M: f64 = 1e-6;
568
569    /// The most planform, as a share of the fin's, that a root's straight pieces may cut off or
570    /// add across a curved surface: 0.1%, a tenth of the 1% to which `cargo xtask ork` holds a
571    /// design's mass to OpenRocket's. On the cockpit of OpenRocket's *Pods--airframes and
572    /// winglets*, OpenRocket's own 20 pieces come to 0.032%, the `.ork` reader's 64 to 0.0031%,
573    /// and one straight piece, the chord, to 11.4% of its area (12.8% more than the fin's).
574    pub const ROOT_SLIVER_SHARE: f64 = 1e-3;
575
576    /// The root's points from leading to trailing edge: its ends, and a freeform fin's root
577    /// points between them.
578    fn root_points(&self) -> Vec<[f64; 2]> {
579        let mut points = vec![[0.0, 0.0]];
580        match &self.planform {
581            FinPlanform::Freeform { points_m, root_m } => {
582                points.extend(root_m.iter().rev());
583                points.extend(points_m.last());
584            }
585            other => points.push([other.root_chord_m(), 0.0]),
586        }
587        points
588    }
589
590    /// Checks that the set can sit on a body tube: its root is level, ending at `h = 0` with no
591    /// root points.
592    ///
593    /// # Errors
594    ///
595    /// [`DesignError::Geometry`] for a root that isn't level.
596    pub fn check_level_root(&self) -> Result<(), DesignError> {
597        if self.root_points().iter().any(|p| p[1] != 0.0) {
598            return Err(DesignError::Geometry(
599                "a fin set on a body tube needs a level root: a freeform outline that ends at \
600                 h = 0, with every root point there too"
601                    .to_owned(),
602            ));
603        }
604        Ok(())
605    }
606
607    /// How the root sits on a nose cone's or transition's surface, with its leading edge `fore_m`
608    /// aft of the body's forward end: the farthest any of its points stands off it, m, and the
609    /// planform its straight pieces cut off or add across the curve, m². A point at `[x, h]` is on
610    /// the surface when `h = r(x_LE + x) − r(x_LE)`. Each piece's sliver is the parabolic segment
611    /// `(2/3) δ Δx`, with `δ` the surface's distance from the piece's midpoint, which is exact to
612    /// leading order in `Δx` for a smooth surface.
613    pub fn root_on_surface(&self, profile: &Profile, fore_m: f64) -> (f64, f64) {
614        let base = profile.radius_m(fore_m);
615        let miss = |[x, h]: [f64; 2]| h - (profile.radius_m(fore_m + x) - base);
616        let points = self.root_points();
617        // NaN-propagating, so a broken profile or point is refused by name below.
618        let off = points
619            .iter()
620            .map(|&p| miss(p).abs())
621            .fold(0.0, |a: f64, m| {
622                if a.is_nan() || m.is_nan() {
623                    f64::NAN
624                } else {
625                    a.max(m)
626                }
627            });
628        let sliver = points
629            .windows(2)
630            .map(|pair| {
631                let middle = [
632                    0.5 * (pair[0][0] + pair[1][0]),
633                    0.5 * (pair[0][1] + pair[1][1]),
634                ];
635                2.0 / 3.0 * miss(middle).abs() * (pair[1][0] - pair[0][0])
636            })
637            .sum();
638        (off, sliver)
639    }
640    /// The radius of a nose cone's or transition's surface at the root leading edge, `fore_m` aft
641    /// of the body's forward end, after checking that the set can sit there: the root within the
642    /// body's length, its points within [`FinSet::ROOT_ON_SURFACE_M`] of the surface, its pieces'
643    /// slivers within [`FinSet::ROOT_SLIVER_SHARE`] of the fin's area
644    /// ([`FinSet::root_on_surface`]), and no tab or fillet, whose models take a body tube. The
645    /// root's height is measured from that radius.
646    ///
647    /// # Errors
648    ///
649    /// [`DesignError::Geometry`] for a set that can't sit on the body as given.
650    pub fn root_radius_on(&self, profile: &Profile, fore_m: f64) -> Result<f64, DesignError> {
651        let length = profile.length_m();
652        let chord = self.planform.root_chord_m();
653        let slack = Self::ROOT_ON_SURFACE_M;
654        if !(fore_m >= -slack && fore_m + chord <= length + slack) {
655            return Err(DesignError::Geometry(format!(
656                "a fin set's root runs from {fore_m} m to {} m along a body {length} m long. On a \
657                 nose cone or a transition it must stay on it",
658                fore_m + chord
659            )));
660        }
661        if self.tab.is_some() || self.fillet.is_some() {
662            return Err(DesignError::Geometry(
663                "a fin set on a nose cone or a transition with a tab or a fillet: their models \
664                 take a body tube"
665                    .to_owned(),
666            ));
667        }
668        let (off, sliver) = self.root_on_surface(profile, fore_m);
669        // A NaN from a broken profile is refused too.
670        if off.is_nan() || off > slack {
671            return Err(DesignError::Geometry(format!(
672                "a fin set's root stands {off} m off the surface of the nose cone or transition it \
673                 sits on, at one of its points"
674            )));
675        }
676        let share = sliver / self.planform.geometry()?.area_m2;
677        if share.is_nan() || share > Self::ROOT_SLIVER_SHARE {
678            return Err(DesignError::Geometry(format!(
679                "a fin set's root cuts across the curved surface it sits on between its points, by \
680                 {:.3}% of the fin's area, more than {}%. Draw it through more points on the \
681                 surface",
682                100.0 * share,
683                100.0 * Self::ROOT_SLIVER_SHARE
684            )));
685        }
686        Ok(profile.radius_m(fore_m))
687    }
688
689    /// The most fins a set may have, the same bound as [`crate::PodSet::MAX_COUNT`].
690    ///
691    /// The set's mass properties build one body per fin and add them up, so a count is an
692    /// allocation and a loop: four billion fins would ask for hundreds of gigabytes and never
693    /// return, where a refusal is an error. 64 is far more than any rocket carries: the most fins
694    /// in one set among the `.ork` designs HPR Sim's checks read is 8 (a one-off count over 78
695    /// designs, not a committed survey), the aerodynamics take
696    /// 1 to 8 (the fin–fin interference factors of the OpenRocket technical documentation 13.05,
697    /// eq. 3.54, from MIL-HDBK-762(MI) p. 5-24, and its tumbling efficiencies, Table 3.4, stop at
698    /// 8), and the `.ork` reader leaves out any part counted more than 64 times. A set of 9 to 64
699    /// fins is weighed; the aerodynamics refuse it with their own error.
700    pub const MAX_COUNT: u32 = 64;
701
702    /// Checks the set's count, dimensions and planform.
703    ///
704    /// # Errors
705    ///
706    /// [`DesignError::Domain`] for no fins or more than [`Self::MAX_COUNT`] (`what` is
707    /// `"fin count (1 to 64)"`, the value the count), a bad dimension, cant or base angle, and
708    /// [`DesignError::Geometry`] for a planform or tab that doesn't close or fit.
709    pub fn validate(&self) -> Result<(), DesignError> {
710        if self.count == 0 || self.count > Self::MAX_COUNT {
711            return Err(DesignError::Domain {
712                what: "fin count (1 to 64)",
713                value: f64::from(self.count),
714            });
715        }
716        self.planform.validate()?;
717        check_dimension("fin thickness", self.thickness_m, false)?;
718        for (what, value) in [
719            ("fin cant", self.cant_rad),
720            ("fin base angle", self.base_angle_rad),
721        ] {
722            if !value.is_finite() {
723                return Err(DesignError::Domain { what, value });
724            }
725        }
726        if let Some(fillet) = &self.fillet {
727            check_dimension("fin fillet radius", fillet.radius_m, true)?;
728        }
729        if let Some(tab) = self.tab {
730            check_dimension("fin tab height", tab.height_m, false)?;
731            check_dimension("fin tab length", tab.length_m, false)?;
732            if !tab.offset_m.is_finite() {
733                return Err(DesignError::Domain {
734                    what: "fin tab offset",
735                    value: tab.offset_m,
736                });
737            }
738            // A tab past either end of the root is weighed as stated (ADR-309); one that shares
739            // no length with the root holds to nothing.
740            let root = self.planform.root_chord_m();
741            if tab.offset_m >= root || tab.offset_m + tab.length_m <= 0.0 {
742                return Err(DesignError::Geometry(format!(
743                    "a fin tab must meet its fin's root chord, from 0 to {root} m, over some length"
744                )));
745            }
746        }
747        Ok(())
748    }
749
750    /// The planform integrals of one fin, without its tab.
751    fn fin_integrals(&self, body_radius_m: f64) -> Result<PlateIntegrals, DesignError> {
752        let scale = self.planform.root_chord_m() + self.planform.span_m();
753        let rb = body_radius_m / scale;
754        let t = self.thickness_m / scale;
755        let mut chords = Vec::new();
756        let mut total = [0.0; 7];
757        for pair in self.planform.breakpoints().windows(2) {
758            let piece = integrate(
759                |h| {
760                    self.planform.chords_at(h * scale, &mut chords);
761                    let mut m = [0.0; 4];
762                    for &(a, b) in &chords {
763                        let c = chord_moments(self.cross_section, a / scale, b / scale, t);
764                        for k in 0..4 {
765                            m[k] += c[k];
766                        }
767                    }
768                    let r = rb + h;
769                    [m[0], r * m[0], r * r * m[0], m[1], m[2], r * m[1], m[3]]
770                },
771                pair[0] / scale,
772                pair[1] / scale,
773                PLATE,
774            )?;
775            for (sum, value) in total.iter_mut().zip(piece.value) {
776                *sum += value;
777            }
778        }
779        // Undo the scaling: lengths to the powers 3, 4, 5, 4, 5, 5, 5.
780        let powers = [3, 4, 5, 4, 5, 5, 5];
781        Ok(std::array::from_fn(|k| total[k] * scale.powi(powers[k])))
782    }
783
784    /// The integrals of the tab slab `offset ≤ x ≤ offset + length`, `−height ≤ h ≤ 0`.
785    fn tab_integrals(&self, body_radius_m: f64) -> PlateIntegrals {
786        let Some(tab) = self.tab else {
787            return [0.0; 7];
788        };
789        let t = self.thickness_m;
790        let (x0, x1) = (tab.offset_m, tab.offset_m + tab.length_m);
791        let (r0, r1) = (body_radius_m - tab.height_m, body_radius_m);
792        let (h, l) = (tab.height_m, tab.length_m);
793        let r_first = 0.5 * (r1 * r1 - r0 * r0);
794        let x_first = 0.5 * (x1 * x1 - x0 * x0);
795        [
796            t * l * h,
797            t * l * r_first,
798            t * l * (r1.powi(3) - r0.powi(3)) / 3.0,
799            t * h * x_first,
800            t * h * (x1.powi(3) - x0.powi(3)) / 3.0,
801            t * x_first * r_first,
802            t.powi(3) / 12.0 * l * h,
803        ]
804    }
805
806    /// Mass properties of one fin (and its tab) at roll angle 0 and no cant, in the fin-set
807    /// frame, on a body of radius `body_radius_m`.
808    ///
809    /// # Errors
810    ///
811    /// As [`FinSet::validate`], plus [`DesignError::Domain`] for a negative body radius or a
812    /// fillet more than [`FILLET_RATIO_MAX`] times the body radius, [`DesignError::Numerics`] if
813    /// an integral fails, and [`MassProperties::validate`]'s errors for a result that isn't
814    /// finite (a tab too long for its moments to fit in an `f64`).
815    pub fn single_fin(&self, body_radius_m: f64) -> Result<MassProperties, DesignError> {
816        self.validate()?;
817        check_dimension("fin body radius", body_radius_m, true)?;
818        if let Some(tab) = self.tab
819            && tab.height_m > body_radius_m
820        {
821            return Err(DesignError::Geometry(format!(
822                "a fin tab must reach no deeper than the body radius ({body_radius_m} m)"
823            )));
824        }
825        let density = self.material.bulk_kg_m3("fin set")?;
826        let fin = self.fin_integrals(body_radius_m)?;
827        let tab = self.tab_integrals(body_radius_m);
828        let [v, r1, r2, x1, x2, rx, tau2] = std::array::from_fn(|k| fin[k] + tab[k]);
829        if v <= 0.0 {
830            return Err(DesignError::Geometry("the fin has no volume".to_owned()));
831        }
832        let mass = density * v;
833        // Points sit at (r, τ, −x): I_xz = −∫ x_B z_B dm = ∫ r x dm.
834        let about_origin = DMat3::from_cols(
835            DVec3::new(tau2 + x2, 0.0, rx),
836            DVec3::new(0.0, r2 + x2, 0.0),
837            DVec3::new(rx, 0.0, r2 + tau2),
838        ) * density;
839        let cg = DVec3::new(r1 / v, 0.0, -x1 / v);
840        let at_origin = MassProperties {
841            mass_kg: mass,
842            cg_m: cg,
843            inertia_kg_m2: DMat3::ZERO,
844        };
845        // Move the tensor from the origin to the center: I_cg = I_o − m(|c|²E − c cᵀ).
846        let inertia = about_origin - at_origin.inertia_about(DVec3::ZERO);
847        let plate = MassProperties {
848            inertia_kg_m2: inertia,
849            ..at_origin
850        };
851        let fin = match self.fillets(body_radius_m)? {
852            Some(fillets) => MassProperties::combine([&plate, &fillets]),
853            None => plate,
854        };
855        let fin = if self.cant_rad == 0.0 {
856            fin
857        } else {
858            let pivot = DVec3::new(body_radius_m, 0.0, -0.5 * self.planform.root_chord_m());
859            fin.translated(-pivot)
860                .rotated(DQuat::from_rotation_x(self.cant_rad))
861                .translated(pivot)
862        };
863        // A tab is held to no length by its root (ADR-309), so one of a length near f64's range
864        // overflows its moments: refuse a result that isn't finite rather than return it.
865        fin.validate()?;
866        Ok(fin)
867    }
868
869    /// Mass properties of the two fillets along one fin's root, at roll angle 0 and no cant, in
870    /// the fin-set frame; `None` for a fin with no fillets or fillets of no radius. The pair is a
871    /// prism of length `c_r` whose section is [`fillet_section`] on each side of the fin's plane,
872    /// so with `A`, `S_x`, `S_xx`, `S_yy` one side's area and moments about the body axis:
873    ///
874    /// ```text
875    /// m = 2ρA c_r,  I_xx = 2ρ(S_yy c_r + A c_r³/3),  I_yy = 2ρ(S_xx c_r + A c_r³/3),
876    /// I_zz = 2ρ(S_xx + S_yy) c_r,  I_xz = ρ S_x c_r²
877    /// ```
878    ///
879    /// about the origin, then moved to the center, `(S_x/A, 0, −c_r/2)`.
880    fn fillets(&self, body_radius_m: f64) -> Result<Option<MassProperties>, DesignError> {
881        let Some(fillet) = self.fillet.as_ref().filter(|f| f.radius_m > 0.0) else {
882            return Ok(None);
883        };
884        let density = fillet.material.bulk_kg_m3("fin fillet")?;
885        // No body, no fillet: the section is none ([`fillet_section`]).
886        if body_radius_m == 0.0 {
887            return Ok(None);
888        }
889        // The section is a triangle less two sectors, and far from real fillets the difference
890        // loses digits to cancellation. At the bounds below it keeps 10 (a millionth of the
891        // body's radius: 8.6e-11 off 60-digit arithmetic) and 12 (a thousand times: 7.6e-13).
892        // A thinner fillet weighs under 1e-12 of the body's radius squared per meter of root:
893        // none. A wider one is refused, not weighed on digits that are noise.
894        let ratio = fillet.radius_m / body_radius_m;
895        if ratio < 1e-6 {
896            return Ok(None);
897        }
898        if ratio > FILLET_RATIO_MAX {
899            return Err(DesignError::Domain {
900                what: "fin fillet radius over the body radius (at most 1000)",
901                value: ratio,
902            });
903        }
904        let [area, sx, sxx, syy] = fillet_section(body_radius_m, fillet.radius_m);
905        // Invariant between the bounds above: the section is positive and finite there.
906        if !(area > 0.0 && [sx, sxx, syy].iter().all(|v| v.is_finite())) {
907            return Err(DesignError::Domain {
908                what: "fin fillet section area",
909                value: area,
910            });
911        }
912        let l = self.planform.root_chord_m();
913        let mass = 2.0 * density * area * l;
914        if mass == 0.0 {
915            return Ok(None);
916        }
917        let ixz = density * sx * l * l;
918        let about_origin = DMat3::from_cols(
919            DVec3::new(2.0 * density * (syy * l + area * l.powi(3) / 3.0), 0.0, ixz),
920            DVec3::new(0.0, 2.0 * density * (sxx * l + area * l.powi(3) / 3.0), 0.0),
921            DVec3::new(ixz, 0.0, 2.0 * density * (sxx + syy) * l),
922        );
923        let at_origin = MassProperties {
924            mass_kg: mass,
925            cg_m: DVec3::new(sx / area, 0.0, -0.5 * l),
926            inertia_kg_m2: DMat3::ZERO,
927        };
928        Ok(Some(MassProperties {
929            inertia_kg_m2: about_origin - at_origin.inertia_about(DVec3::ZERO),
930            ..at_origin
931        }))
932    }
933
934    /// Mass properties of the whole set in its frame, on a body of radius `body_radius_m`.
935    ///
936    /// # Errors
937    ///
938    /// As [`FinSet::single_fin`].
939    pub fn mass_properties(&self, body_radius_m: f64) -> Result<MassProperties, DesignError> {
940        let fin = self.single_fin(body_radius_m)?;
941        let fins: Vec<MassProperties> = (0..self.count)
942            .map(|k| {
943                fin.rolled(self.base_angle_rad + 2.0 * PI * f64::from(k) / f64::from(self.count))
944            })
945            .collect();
946        Ok(MassProperties::combine(&fins))
947    }
948}
949
950/// The widest fin fillet weighed, as a multiple of the body radius ([`FinSet::single_fin`]).
951pub const FILLET_RATIO_MAX: f64 = 1e3;
952
953/// One fillet's section on the `+y` side of a fin in the plane `y = 0`, with `x` outward along
954/// the fin: its area and moments `[A, S_x, S_xx, S_yy]` about the body axis (`S_x = ∫ x dA`,
955/// `S_xx = ∫ x² dA`, `S_yy = ∫ y² dA`), m², m³, m⁴, m⁴. The section is the triangle
956/// `(0, 0), (c, 0), (c, r)` less two circular sectors, the body's about the axis from `0` to `θ`
957/// and the fillet's about `(c, r)` from `θ − π` to `−π/2` (module docs). A body of no radius
958/// gives a section of none.
959pub(crate) fn fillet_section(body_radius_m: f64, radius_m: f64) -> [f64; 4] {
960    let (rb, r) = (body_radius_m, radius_m);
961    let c = (rb * rb + 2.0 * rb * r).sqrt();
962    let theta = r.atan2(c);
963    // The triangle: vertices (0, 0), (c, 0), (c, r).
964    let triangle_area = 0.5 * c * r;
965    let triangle = [
966        triangle_area,
967        triangle_area * 2.0 * c / 3.0,
968        triangle_area * c * c / 2.0,
969        triangle_area * r * r / 6.0,
970    ];
971    let body = sector([0.0, 0.0], rb, 0.0, theta);
972    let joint = sector([c, r], r, theta - PI, -0.5 * PI);
973    std::array::from_fn(|k| triangle[k] - body[k] - joint[k])
974}
975
976/// A circular sector about `center`, of radius `rho`, from angle `from` to `to` (`to ≥ from`):
977/// `[A, S_x, S_xx, S_yy]` about the origin. With `Δ = to − from` and `σ = to + from`, the moments
978/// about the center are `ρ³/3 · 2 sin(Δ/2) [cos(σ/2), sin(σ/2)]` and `ρ⁴/8 · (Δ ± sin Δ cos σ)`,
979/// the second written as `(Δ − sin Δ) + sin Δ (1 ± cos σ)` so that the body's thin sector, whose
980/// `Δ` and `σ` are both small, loses no digits to cancellation.
981fn sector([x0, y0]: [f64; 2], rho: f64, from: f64, to: f64) -> [f64; 4] {
982    let (span, sum) = (to - from, to + from);
983    let area = 0.5 * rho * rho * span;
984    let chord = 2.0 * (0.5 * span).sin() * rho.powi(3) / 3.0;
985    let (sx, sy) = (chord * (0.5 * sum).cos(), chord * (0.5 * sum).sin());
986    let (lean, sine) = (span_less_sine(span), span.sin());
987    let (sxx, syy) = (
988        rho.powi(4) / 8.0 * (lean + sine * 2.0 * (0.5 * sum).cos().powi(2)),
989        rho.powi(4) / 8.0 * (lean + sine * 2.0 * (0.5 * sum).sin().powi(2)),
990    );
991    [
992        area,
993        sx + x0 * area,
994        sxx + 2.0 * x0 * sx + x0 * x0 * area,
995        syy + 2.0 * y0 * sy + y0 * y0 * area,
996    ]
997}
998
999/// `x − sin x`, by its Taylor series below `x = 0.25`, where the difference would cancel: the
1000/// terms through `x¹⁵` leave a remainder under 1e-18 of the sum.
1001fn span_less_sine(x: f64) -> f64 {
1002    if x.abs() >= 0.25 {
1003        return x - x.sin();
1004    }
1005    // x³/3! − x⁵/5! + …, each term the last times −x²/((2k)(2k+1)).
1006    let mut term = x.powi(3) / 6.0;
1007    let mut sum = 0.0;
1008    for k in 2..=8 {
1009        sum += term;
1010        term *= -x * x / f64::from((2 * k) * (2 * k + 1));
1011    }
1012    sum
1013}
1014
1015/// Tube fins: open tubes parallel to the body, touching it, spaced evenly around it.
1016#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1017#[serde(deny_unknown_fields)]
1018pub struct TubeFinSet {
1019    /// Number of tubes, 1 to 64 (`TubeFinSet::MAX_COUNT`).
1020    pub count: u32,
1021    /// Length, m.
1022    pub length_m: f64,
1023    /// Outer radius, m.
1024    pub outer_radius_m: f64,
1025    /// Wall thickness, m.
1026    pub thickness_m: f64,
1027    /// Roll angle of the first tube's axis from `x_B` toward `y_B`, rad.
1028    #[serde(default)]
1029    pub base_angle_rad: f64,
1030    /// Material (bulk).
1031    pub material: Material,
1032}
1033
1034impl TubeFinSet {
1035    /// The most tubes a set may have: as [`FinSet::MAX_COUNT`], a bound on the bodies its mass
1036    /// properties build one by one, far above any rocket's (the most tubes in one set among the
1037    /// `.ork` designs read is 6, a one-off count over 78 designs, not a committed survey).
1038    pub const MAX_COUNT: u32 = 64;
1039
1040    /// The outer radius of `count` tubes that close the ring around a body of radius
1041    /// `body_radius_m`, each touching the body and its two neighbors, which is the radius
1042    /// OpenRocket 24.12 gives a tube fin set written `auto` ([ADR-098][adr-098]).
1043    ///
1044    /// The axes of `N` tubes of radius `r` sit on a circle of radius `R + r`, `2π/N` apart, so
1045    /// neighboring axes are a chord `2(R + r) sin(π/N)` apart. Touching means that chord is `2r`:
1046    ///
1047    /// `r = R sin(π/N) / (1 − sin(π/N))`.
1048    ///
1049    /// For one or two tubes `sin(π/N)` is 0 or 1 and no finite ring closes; OpenRocket 24.12 gives
1050    /// those the body's radius, measured on its probes on 20 and 50 mm bodies, and so does this;
1051    /// so does a count of none, which [`Self::mass_properties`] refuses. On a 50 mm body, six
1052    /// tubes are 50 mm (`sin(π/6) = 1/2`), four are 120.7 mm and eight are 31.0 mm.
1053    ///
1054    /// [adr-098]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-098-a-tube-fin-sets-automatic-radius-read-as-openrocket-reads-it-2026-09-28
1055    pub fn closing_radius_m(body_radius_m: f64, count: u32) -> f64 {
1056        if count < 3 {
1057            return body_radius_m;
1058        }
1059        let s = (PI / f64::from(count)).sin();
1060        body_radius_m * s / (1.0 - s)
1061    }
1062
1063    /// Mass properties in the set's frame (origin on the body axis at the tubes' forward end), on
1064    /// a body of radius `body_radius_m`. Each tube is a hollow cylinder,
1065    /// `I_a = m(R² + r²)/2` and `I_t = m((R² + r²)/4 + L²/12)`, with its axis at `R_b + R`.
1066    ///
1067    /// # Errors
1068    ///
1069    /// [`DesignError::Domain`] for a bad dimension, or a count of none or more than
1070    /// [`Self::MAX_COUNT`] (`what` is `"tube fin count (1 to 64)"`), [`DesignError::Geometry`] for
1071    /// a wall thicker than the radius, and material errors.
1072    pub fn mass_properties(&self, body_radius_m: f64) -> Result<MassProperties, DesignError> {
1073        if self.count == 0 || self.count > Self::MAX_COUNT {
1074            return Err(DesignError::Domain {
1075                what: "tube fin count (1 to 64)",
1076                value: f64::from(self.count),
1077            });
1078        }
1079        check_dimension("body radius", body_radius_m, true)?;
1080        if !self.base_angle_rad.is_finite() {
1081            return Err(DesignError::Domain {
1082                what: "tube fin base angle",
1083                value: self.base_angle_rad,
1084            });
1085        }
1086        let density = self.material.bulk_kg_m3("tube fin set")?;
1087        let tube = crate::parts::hollow_cylinder(
1088            "tube fin",
1089            density,
1090            self.length_m,
1091            self.outer_radius_m,
1092            self.thickness_m,
1093        )?;
1094        let one = tube.translated(DVec3::new(body_radius_m + self.outer_radius_m, 0.0, 0.0));
1095        let tubes: Vec<MassProperties> = (0..self.count)
1096            .map(|k| {
1097                one.rolled(self.base_angle_rad + 2.0 * PI * f64::from(k) / f64::from(self.count))
1098            })
1099            .collect();
1100        Ok(MassProperties::combine(&tubes))
1101    }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106    use super::*;
1107    use hpr_core::quadrature::integrate_scalar;
1108
1109    fn close(got: f64, want: f64, rel: f64, what: &str) {
1110        let err = if want == 0.0 {
1111            got.abs()
1112        } else {
1113            ((got - want) / want).abs()
1114        };
1115        assert!(err <= rel, "{what}: {got} vs {want} (relative {err:e})");
1116    }
1117
1118    fn mat_close(a: DMat3, b: DMat3, rel: f64, what: &str) {
1119        let scale = b.to_cols_array().iter().fold(0.0f64, |m, v| m.max(v.abs()));
1120        let diff = (a - b)
1121            .to_cols_array()
1122            .iter()
1123            .fold(0.0f64, |m, v| m.max(v.abs()));
1124        assert!(diff <= rel * scale, "{what}: {a:?}\nvs\n{b:?}");
1125    }
1126
1127    fn ply() -> Material {
1128        Material::bulk("plywood", 630.0)
1129    }
1130
1131    fn rectangle(chord: f64, span: f64) -> FinPlanform {
1132        FinPlanform::Trapezoidal {
1133            root_chord_m: chord,
1134            tip_chord_m: chord,
1135            span_m: span,
1136            sweep_m: 0.0,
1137        }
1138    }
1139
1140    fn set(count: u32, planform: FinPlanform, thickness: f64) -> FinSet {
1141        FinSet {
1142            count,
1143            planform,
1144            thickness_m: thickness,
1145            cross_section: FinCrossSection::Square,
1146            tab: None,
1147            fillet: None,
1148            cant_rad: 0.0,
1149            base_angle_rad: 0.0,
1150            material: ply(),
1151        }
1152    }
1153
1154    #[test]
1155    fn airfoil_constants_are_the_integrals() {
1156        // With ξ = u², dξ = 2u du, and the integrands are polynomials in u.
1157        let tol = Tolerance::default();
1158        let p = naca_polynomial;
1159        for (k, want) in AIRFOIL_PHI.iter().enumerate() {
1160            let power = i32::try_from(2 * k).unwrap();
1161            let got = 10.0
1162                * integrate_scalar(|u| u.powi(power) * p(u * u) * 2.0 * u, 0.0, 1.0, tol).unwrap();
1163            close(got, *want, 1e-14, "phi");
1164        }
1165        let psi = 1000.0 * integrate_scalar(|u| p(u * u).powi(3) * 2.0 * u, 0.0, 1.0, tol).unwrap();
1166        close(psi, AIRFOIL_PSI, 1e-14, "psi");
1167    }
1168
1169    #[test]
1170    fn chord_moments_match_quadrature_of_each_section() {
1171        // The references ask for the tightest tolerance the quadrature allows (50 ε relative).
1172        let tol = Tolerance {
1173            relative: 0.0,
1174            absolute: 0.0,
1175            max_intervals: 4000,
1176        };
1177        let t: f64 = 0.004;
1178        // (a, b) wider than the thickness, and a sliver narrower than it (a circle of diameter c).
1179        for (a, b) in [(0.02, 0.17), (0.05, 0.053)] {
1180            let c: f64 = b - a;
1181            let rounded = |x: f64| {
1182                let mid = t.min(c);
1183                let r = 0.5 * mid;
1184                let u = (x - a).min(b - x);
1185                if u >= r {
1186                    mid
1187                } else {
1188                    2.0 * (r * r - (r - u).powi(2)).max(0.0).sqrt()
1189                }
1190            };
1191            let airfoil = |x: f64| 10.0 * t * naca_polynomial((x - a) / c);
1192            let square = |_x: f64| t;
1193            let sections: [(FinCrossSection, &dyn Fn(f64) -> f64); 3] = [
1194                (FinCrossSection::Square, &square),
1195                (FinCrossSection::Rounded, &rounded),
1196                (FinCrossSection::Airfoil, &airfoil),
1197            ];
1198            // Exact references: split where the edges meet the flat, and substitute x = a + v²
1199            // (and x = b − v²) at the ends, where the thickness grows like a square root.
1200            let edge = 0.5 * t.min(c);
1201            let reference = |f: &dyn Fn(f64) -> f64| -> f64 {
1202                let fore = integrate_scalar(|v| f(a + v * v) * 2.0 * v, 0.0, edge.sqrt(), tol);
1203                let aft = integrate_scalar(|v| f(b - v * v) * 2.0 * v, 0.0, edge.sqrt(), tol);
1204                let middle = integrate_scalar(f, a + edge, b - edge, tol);
1205                fore.unwrap() + aft.unwrap() + middle.unwrap()
1206            };
1207            for (section, thickness) in sections {
1208                let got = chord_moments(section, a, b, t);
1209                for (k, &moment) in got.iter().take(3).enumerate() {
1210                    let power = i32::try_from(k).unwrap();
1211                    let want = reference(&|x: f64| x.powi(power) * thickness(x));
1212                    close(
1213                        moment,
1214                        want,
1215                        1e-13,
1216                        &format!("{section:?} M{k} on [{a}, {b}]"),
1217                    );
1218                }
1219                let want = reference(&|x: f64| thickness(x).powi(3) / 12.0);
1220                close(got[3], want, 1e-13, &format!("{section:?} T on [{a}, {b}]"));
1221            }
1222        }
1223        // The rounded section of a wide chord loses (1 − π/4) t² of area.
1224        let m = chord_moments(FinCrossSection::Rounded, 0.0, 0.1, t);
1225        close(
1226            m[0],
1227            0.1 * t - (1.0 - PI / 4.0) * t * t,
1228            1e-14,
1229            "rounded area",
1230        );
1231    }
1232
1233    #[test]
1234    fn the_aft_extent_is_the_outline_s_aft_most_point() {
1235        // #1254: a fin reaches aft of its root chord where its tip's trailing edge lies further
1236        // aft, by sweep plus tip chord; a fin swept forward, or a short tip, reaches the root's
1237        // trailing edge.
1238        let trapezoid = |root: f64, tip: f64, sweep: f64| FinPlanform::Trapezoidal {
1239            root_chord_m: root,
1240            tip_chord_m: tip,
1241            span_m: 0.1,
1242            sweep_m: sweep,
1243        };
1244        assert_eq!(trapezoid(0.2, 0.1, 0.15).aft_extent_m(), 0.15 + 0.1);
1245        assert_eq!(trapezoid(0.2, 0.1, 0.05).aft_extent_m(), 0.2);
1246        assert_eq!(trapezoid(0.2, 0.1, -0.05).aft_extent_m(), 0.2);
1247        let elliptical = FinPlanform::Elliptical {
1248            root_chord_m: 0.2,
1249            span_m: 0.1,
1250        };
1251        assert_eq!(elliptical.aft_extent_m(), 0.2);
1252        // A freeform fin raked back past its root, and one whose outline stays within it.
1253        let raked = FinPlanform::Freeform {
1254            points_m: vec![[0.0, 0.0], [0.18, 0.1], [0.26, 0.1], [0.2, 0.0]],
1255            root_m: Vec::new(),
1256        };
1257        raked.validate().unwrap();
1258        assert_eq!(raked.aft_extent_m(), 0.26);
1259        let swept = FinPlanform::Freeform {
1260            points_m: vec![[0.0, 0.0], [0.1, 0.1], [0.15, 0.1], [0.2, 0.0]],
1261            root_m: Vec::new(),
1262        };
1263        swept.validate().unwrap();
1264        assert_eq!(swept.aft_extent_m(), swept.root_chord_m());
1265    }
1266
1267    #[test]
1268    fn planform_areas_and_centroids_are_the_closed_forms() {
1269        let (cr, ct, s, xt) = (0.15, 0.06, 0.1, 0.07);
1270        let trapezoid = FinPlanform::Trapezoidal {
1271            root_chord_m: cr,
1272            tip_chord_m: ct,
1273            span_m: s,
1274            sweep_m: xt,
1275        };
1276        let g = trapezoid.geometry().unwrap();
1277        close(g.area_m2, 0.5 * s * (cr + ct), 1e-13, "trapezoid area");
1278        close(
1279            g.centroid_x_m,
1280            (xt * (cr + 2.0 * ct) + cr * cr + cr * ct + ct * ct) / (3.0 * (cr + ct)),
1281            1e-13,
1282            "trapezoid centroid x",
1283        );
1284        close(
1285            g.centroid_span_m,
1286            s * (cr + 2.0 * ct) / (3.0 * (cr + ct)),
1287            1e-13,
1288            "trapezoid centroid h",
1289        );
1290        // The same outline as a freeform polygon.
1291        let freeform = FinPlanform::Freeform {
1292            points_m: vec![[0.0, 0.0], [xt, s], [xt + ct, s], [cr, 0.0]],
1293            root_m: Vec::new(),
1294        };
1295        let f = freeform.geometry().unwrap();
1296        close(f.area_m2, g.area_m2, 1e-13, "freeform area");
1297        close(f.centroid_x_m, g.centroid_x_m, 1e-13, "freeform centroid x");
1298        close(
1299            f.centroid_span_m,
1300            g.centroid_span_m,
1301            1e-13,
1302            "freeform centroid h",
1303        );
1304        // Half ellipse: area π c_r s / 4, centroid at mid-chord and 4s/3π out.
1305        let e = FinPlanform::Elliptical {
1306            root_chord_m: cr,
1307            span_m: s,
1308        }
1309        .geometry()
1310        .unwrap();
1311        close(e.area_m2, PI * cr * s / 4.0, 1e-12, "ellipse area");
1312        close(e.centroid_x_m, cr / 2.0, 1e-12, "ellipse centroid x");
1313        close(
1314            e.centroid_span_m,
1315            4.0 * s / (3.0 * PI),
1316            1e-12,
1317            "ellipse centroid h",
1318        );
1319    }
1320
1321    #[test]
1322    fn a_rectangular_fin_set_matches_box_inertia_by_hand() {
1323        let (c, s, t, rb, rho) = (0.12, 0.08, 0.003, 0.04, 630.0);
1324        let m = rho * c * s * t;
1325        let d = rb + s / 2.0;
1326        // One fin: a box with s along x, t along y, c along z, centered at (d, 0, −c/2).
1327        let one = set(1, rectangle(c, s), t).single_fin(rb).unwrap();
1328        close(one.mass_kg, m, 1e-13, "mass");
1329        assert!((one.cg_m - DVec3::new(d, 0.0, -c / 2.0)).length() < 1e-15);
1330        let box_inertia = DMat3::from_diagonal(DVec3::new(
1331            m * (t * t + c * c) / 12.0,
1332            m * (s * s + c * c) / 12.0,
1333            m * (s * s + t * t) / 12.0,
1334        ));
1335        mat_close(one.inertia_kg_m2, box_inertia, 1e-12, "one fin");
1336        // Four fins: two along ±x and two along ±y.
1337        let four = set(4, rectangle(c, s), t).mass_properties(rb).unwrap();
1338        close(four.mass_kg, 4.0 * m, 1e-13, "four fins");
1339        assert!(four.cg_m.truncate().length() < 1e-15);
1340        let transverse =
1341            2.0 * m * (t * t + c * c) / 12.0 + 2.0 * (m * (s * s + c * c) / 12.0 + m * d * d);
1342        let axial = 4.0 * (m * (s * s + t * t) / 12.0 + m * d * d);
1343        mat_close(
1344            four.inertia_kg_m2,
1345            DMat3::from_diagonal(DVec3::new(transverse, transverse, axial)),
1346            1e-12,
1347            "four fins",
1348        );
1349        // Three fins are isotropic across the axis too; two are not.
1350        let three = set(3, rectangle(c, s), t)
1351            .mass_properties(rb)
1352            .unwrap()
1353            .inertia_kg_m2;
1354        close(
1355            three.x_axis.x,
1356            three.y_axis.y,
1357            1e-12,
1358            "three fins isotropic",
1359        );
1360        assert!(three.y_axis.x.abs() < 1e-12 * three.x_axis.x);
1361        let two = set(2, rectangle(c, s), t)
1362            .mass_properties(rb)
1363            .unwrap()
1364            .inertia_kg_m2;
1365        assert!((two.x_axis.x - two.y_axis.y).abs() > 1e-4 * two.y_axis.y);
1366
1367        // Roots on the axis, as on a pod of no length (M1.13b2): the same boxes, `d = s/2` out.
1368        let d = s / 2.0;
1369        let on_axis = set(4, rectangle(c, s), t).mass_properties(0.0).unwrap();
1370        let transverse =
1371            2.0 * m * (t * t + c * c) / 12.0 + 2.0 * (m * (s * s + c * c) / 12.0 + m * d * d);
1372        let axial = 4.0 * (m * (s * s + t * t) / 12.0 + m * d * d);
1373        mat_close(
1374            on_axis.inertia_kg_m2,
1375            DMat3::from_diagonal(DVec3::new(transverse, transverse, axial)),
1376            1e-12,
1377            "four fins from the axis",
1378        );
1379    }
1380
1381    #[test]
1382    fn cant_turns_the_fin_about_its_span_axis() {
1383        let (c, s, t, rb, rho) = (0.12, 0.08, 0.003, 0.04, 630.0);
1384        let m = rho * c * s * t;
1385        // Canted 90°, the chord lies along y: a box with s along x, c along y, t along z, whose
1386        // center stays at the pivot's station because the pivot is the root mid-chord.
1387        let mut fins = set(1, rectangle(c, s), t);
1388        fins.cant_rad = PI / 2.0;
1389        let turned = fins.single_fin(rb).unwrap();
1390        assert!((turned.cg_m - DVec3::new(rb + s / 2.0, 0.0, -c / 2.0)).length() < 1e-15);
1391        let expected = DMat3::from_diagonal(DVec3::new(
1392            m * (c * c + t * t) / 12.0,
1393            m * (s * s + t * t) / 12.0,
1394            m * (s * s + c * c) / 12.0,
1395        ));
1396        mat_close(turned.inertia_kg_m2, expected, 1e-12, "canted 90°");
1397        // A small cant only couples x and... keeps mass and center and the trace.
1398        fins.cant_rad = 0.05;
1399        let small = fins.single_fin(rb).unwrap();
1400        let flat = set(1, rectangle(c, s), t).single_fin(rb).unwrap();
1401        close(small.mass_kg, flat.mass_kg, 1e-15, "mass");
1402        let trace = |i: DMat3| i.x_axis.x + i.y_axis.y + i.z_axis.z;
1403        close(
1404            trace(small.inertia_kg_m2),
1405            trace(flat.inertia_kg_m2),
1406            1e-12,
1407            "trace",
1408        );
1409    }
1410
1411    #[test]
1412    fn positive_cant_turns_the_leading_edge_toward_negative_y() {
1413        // A swept fin's centroid lies aft of the root mid-chord, so turning it by δ about the span
1414        // axis through the mid-chord moves the centroid to y = (x̄ − c_r/2) sin δ and
1415        // z = −c_r/2 − (x̄ − c_r/2) cos δ; the leading edge (x = 0) goes to y = −(c_r/2) sin δ.
1416        let (cr, ct, s, xt) = (0.15, 0.05, 0.1, 0.09);
1417        let planform = FinPlanform::Trapezoidal {
1418            root_chord_m: cr,
1419            tip_chord_m: ct,
1420            span_m: s,
1421            sweep_m: xt,
1422        };
1423        let centroid = planform.geometry().unwrap().centroid_x_m;
1424        assert!(centroid > cr / 2.0);
1425        let mut fins = set(1, planform, 0.003);
1426        let delta: f64 = 0.2;
1427        fins.cant_rad = delta;
1428        let fin = fins.single_fin(0.04).unwrap();
1429        close(
1430            fin.cg_m.y,
1431            (centroid - cr / 2.0) * delta.sin(),
1432            1e-12,
1433            "centroid y",
1434        );
1435        close(
1436            fin.cg_m.z,
1437            -cr / 2.0 - (centroid - cr / 2.0) * delta.cos(),
1438            1e-12,
1439            "centroid z",
1440        );
1441        assert!(fin.cg_m.y > 0.0);
1442        let leading_edge = DQuat::from_rotation_x(delta) * DVec3::new(0.04, 0.0, cr / 2.0);
1443        assert!(leading_edge.y < 0.0);
1444    }
1445
1446    #[test]
1447    fn a_tab_must_meet_the_root_and_fit_the_body() {
1448        // ADR-309: a tab is weighed as stated wherever it meets the root over some length, as
1449        // OpenRocket 24.12 weighs one; one that meets it nowhere, or only at an end, holds to
1450        // nothing. Along the root is checked without a body; the depth needs one.
1451        let mut fins = set(3, rectangle(0.1, 0.05), 0.003);
1452        let tab = |length_m: f64, offset_m: f64| {
1453            Some(FinTab {
1454                height_m: 0.01,
1455                length_m,
1456                offset_m,
1457            })
1458        };
1459        let refusal = |fins: &FinSet| match fins.validate() {
1460            Err(DesignError::Geometry(why)) => why.contains("must meet its fin's root chord"),
1461            _ => false,
1462        };
1463        // Each side of each end, at the bound: touching an end or past it is refused, a
1464        // nanometer onto the root is weighed.
1465        for (length_m, offset_m, meets) in [
1466            (0.02, 0.1, false),
1467            (0.02, 0.1 + 1e-9, false),
1468            (0.02, 0.1 - 1e-9, true),
1469            (0.02, -0.02, false),
1470            (0.02, -0.02 - 1e-9, false),
1471            (0.02 + 1e-9, -0.02, true),
1472            // Past the trailing edge by 10 mm, ahead of the leading edge by 10 mm, and both.
1473            (0.08, 0.03, true),
1474            (0.02, -0.01, true),
1475            (0.12, -0.01, true),
1476        ] {
1477            fins.tab = tab(length_m, offset_m);
1478            assert_eq!(refusal(&fins), !meets, "{:?}", fins.tab);
1479            assert_eq!(fins.mass_properties(0.03).is_ok(), meets, "{:?}", fins.tab);
1480        }
1481        fins.tab = Some(FinTab {
1482            height_m: 0.05,
1483            length_m: 0.02,
1484            offset_m: 0.0,
1485        });
1486        assert!(
1487            matches!(fins.mass_properties(0.03), Err(DesignError::Geometry(why)) if why.contains("no deeper than the body radius"))
1488        );
1489        fins.tab = Some(FinTab {
1490            height_m: 0.03,
1491            length_m: 0.1,
1492            offset_m: 0.0,
1493        });
1494        fins.mass_properties(0.03).unwrap();
1495    }
1496
1497    #[test]
1498    fn a_tab_past_the_root_is_weighed_as_its_whole_slab() {
1499        // A tab adds its whole slab to one fin, wherever it sits along the root (0.1 m here):
1500        // past the trailing edge, ahead of the leading edge, past both, or inside. The slab is a
1501        // box, r from R_b − h to R_b, τ ±t/2 and x from o to o + l, with points at (r, τ, −x), so
1502        // about its own center I = m diag(t² + l², h² + l², h² + t²)/12, and about the origin
1503        // I_o = I_c + m(|c|²E − c cᵀ) with c = (R_b − h/2, 0, −(o + l/2)). Comparing the
1504        // tensors about the origin pins every moment, I_xz's sign included (ρ = 630 kg/m³).
1505        let (t, h, rb) = (0.003, 0.01, 0.03);
1506        let about_origin = |m: &MassProperties| {
1507            let c = m.cg_m;
1508            m.inertia_kg_m2
1509                + (DMat3::IDENTITY * c.length_squared()
1510                    - DMat3::from_cols(c * c.x, c * c.y, c * c.z))
1511                    * m.mass_kg
1512        };
1513        let bare = set(3, rectangle(0.1, 0.05), t);
1514        let without = bare.single_fin(rb).unwrap();
1515        for (l, o) in [(0.08, 0.03), (0.02, -0.01), (0.12, -0.01), (0.04, 0.03)] {
1516            let mut tabbed = bare.clone();
1517            tabbed.tab = Some(FinTab {
1518                height_m: h,
1519                length_m: l,
1520                offset_m: o,
1521            });
1522            let with = tabbed.single_fin(rb).unwrap();
1523            let slab = 630.0 * t * l * h;
1524            assert!(
1525                ((with.mass_kg - without.mass_kg) - slab).abs() < 1e-12 * slab,
1526                "{l} {o}"
1527            );
1528            let z = (with.cg_m.z * with.mass_kg - without.cg_m.z * without.mass_kg) / slab;
1529            assert!((z + (o + 0.5 * l)).abs() < 1e-9, "{l} {o}: {z}");
1530            let c = DVec3::new(rb - 0.5 * h, 0.0, -(o + 0.5 * l));
1531            let own = DMat3::from_diagonal(DVec3::new(t * t + l * l, h * h + l * l, h * h + t * t))
1532                * (slab / 12.0);
1533            let expected = own
1534                + (DMat3::IDENTITY * c.length_squared()
1535                    - DMat3::from_cols(c * c.x, c * c.y, c * c.z))
1536                    * slab;
1537            let got = about_origin(&with) - about_origin(&without);
1538            let scale = slab * (rb * rb + (o + l).powi(2));
1539            for (g, e) in got.to_cols_array().iter().zip(expected.to_cols_array()) {
1540                assert!(
1541                    (g - e).abs() < 1e-9 * scale,
1542                    "{l} {o}: {got:?} against {expected:?}"
1543                );
1544            }
1545        }
1546        // The set of three adds three slabs, its mass ρ t l h a fin.
1547        let mut tabbed = set(3, rectangle(0.1, 0.05), t);
1548        tabbed.tab = Some(FinTab {
1549            height_m: h,
1550            length_m: 0.08,
1551            offset_m: 0.03,
1552        });
1553        let added =
1554            tabbed.mass_properties(rb).unwrap().mass_kg - bare.mass_properties(rb).unwrap().mass_kg;
1555        let slab = 3.0 * 630.0 * t * 0.08 * h;
1556        assert!((added - slab).abs() < 1e-12 * slab, "{added}");
1557    }
1558
1559    #[test]
1560    fn a_tab_too_long_for_its_moments_is_refused() {
1561        // A tab 1e103 m long has a finite mass but an x³ moment past f64's range; the fin's
1562        // result is refused for its inertia, not returned with an infinite or NaN entry.
1563        let mut fins = set(3, rectangle(0.1, 0.05), 0.003);
1564        fins.tab = Some(FinTab {
1565            height_m: 0.01,
1566            length_m: 1e103,
1567            offset_m: 0.0,
1568        });
1569        assert!(
1570            matches!(fins.single_fin(0.03), Err(DesignError::UnphysicalInertia(why)) if why.contains("non-finite")),
1571            "{:?}",
1572            fins.single_fin(0.03)
1573        );
1574    }
1575
1576    #[test]
1577    fn a_swept_fin_has_the_parallel_axis_product_of_inertia() {
1578        // A single trapezoidal fin: I_xz about the origin is ∫ r x dm, so about the center it is
1579        // ∫ r x dm − m r̄ x̄ (with z = −x, I_xz = −∫ x_B z_B dm). Check against direct quadrature of
1580        // the planform.
1581        let (cr, ct, s, xt, t, rb, rho) = (0.15, 0.05, 0.1, 0.09, 0.004, 0.05, 1800.0);
1582        let planform = FinPlanform::Trapezoidal {
1583            root_chord_m: cr,
1584            tip_chord_m: ct,
1585            span_m: s,
1586            sweep_m: xt,
1587        };
1588        let mut fins = set(1, planform, t);
1589        fins.material = Material::bulk("G10", rho);
1590        let fin = fins.single_fin(rb).unwrap();
1591        let tol = Tolerance::default();
1592        let lead = |h: f64| xt * h / s;
1593        let chord = |h: f64| cr + (ct - cr) * h / s;
1594        let area = integrate_scalar(chord, 0.0, s, tol).unwrap();
1595        let mx = integrate_scalar(|h| chord(h) * (lead(h) + chord(h) / 2.0), 0.0, s, tol).unwrap();
1596        let mr = integrate_scalar(|h| chord(h) * (rb + h), 0.0, s, tol).unwrap();
1597        let mrx = integrate_scalar(
1598            |h| (rb + h) * chord(h) * (lead(h) + chord(h) / 2.0),
1599            0.0,
1600            s,
1601            tol,
1602        )
1603        .unwrap();
1604        let m = rho * t * area;
1605        close(fin.mass_kg, m, 1e-13, "mass");
1606        let product = rho * t * mrx - m * (mr / area) * (mx / area);
1607        close(fin.inertia_kg_m2.z_axis.x, product, 1e-11, "I_xz");
1608        close(fin.inertia_kg_m2.x_axis.z, product, 1e-11, "I_zx");
1609    }
1610
1611    #[test]
1612    fn a_closing_ring_of_tubes_touches_the_body_and_its_neighbors() {
1613        let body = 0.05;
1614        for count in 3..=12 {
1615            let r = TubeFinSet::closing_radius_m(body, count);
1616            assert!(r > 0.0 && r.is_finite(), "{count}: {r}");
1617            // Neighboring axes, on the circle of radius R + r, are 2r apart: the tubes touch.
1618            let step = 2.0 * PI / f64::from(count);
1619            let (a, b) = (
1620                DVec3::new(body + r, 0.0, 0.0),
1621                DVec3::new((body + r) * step.cos(), (body + r) * step.sin(), 0.0),
1622            );
1623            close(a.distance(b), 2.0 * r, 1e-14, "neighbors touch");
1624        }
1625        // Six tubes are as wide as the body; four much wider, eight narrower.
1626        close(TubeFinSet::closing_radius_m(body, 6), body, 1e-15, "six");
1627        close(
1628            TubeFinSet::closing_radius_m(body, 4),
1629            body * (1.0 + 2f64.sqrt()),
1630            1e-15,
1631            "four",
1632        );
1633        // No finite ring closes with one or two: the body's radius, as OpenRocket 24.12 gives.
1634        assert_eq!(TubeFinSet::closing_radius_m(body, 1), body);
1635        assert_eq!(TubeFinSet::closing_radius_m(body, 2), body);
1636    }
1637
1638    #[test]
1639    fn tube_fins_are_hollow_cylinders_around_the_body() {
1640        let tubes = TubeFinSet {
1641            count: 6,
1642            length_m: 0.1,
1643            outer_radius_m: 0.012,
1644            thickness_m: 0.001,
1645            base_angle_rad: 0.0,
1646            material: Material::bulk("cardboard", 790.0),
1647        };
1648        let rb = 0.02;
1649        let g = tubes.mass_properties(rb).unwrap();
1650        let (ro, ri) = (0.012, 0.011);
1651        let m1 = 790.0 * PI * (ro * ro - ri * ri) * 0.1;
1652        close(g.mass_kg, 6.0 * m1, 1e-13, "mass");
1653        let d = rb + ro;
1654        let axial = 6.0 * (0.5 * m1 * (ro * ro + ri * ri) + m1 * d * d);
1655        close(g.inertia_kg_m2.z_axis.z, axial, 1e-13, "axial");
1656        let transverse = 6.0 * m1 * ((ro * ro + ri * ri) / 4.0 + 0.01 / 12.0) + 3.0 * m1 * d * d;
1657        close(g.inertia_kg_m2.x_axis.x, transverse, 1e-12, "transverse");
1658        close(g.cg_m.z, -0.05, 1e-15, "center");
1659    }
1660
1661    /// OpenRocket's *Pods--airframes and winglets* example's cockpit: one balsa fin, 6.985 mm
1662    /// thick, a triangle on its tangent ogive's last 50 mm, its root through `pieces` straight
1663    /// pieces on the surface. Returns the set and its root leading edge's station on the nose.
1664    fn cockpit(pieces: u32) -> (FinSet, Profile, f64) {
1665        let nose = Profile::nose(
1666            crate::NoseShape::Ogive { radius_ratio: 1.0 },
1667            0.136525,
1668            0.0168275,
1669        )
1670        .unwrap();
1671        let (chord, fore) = (0.05, 0.136525 - 0.05);
1672        let base = nose.radius_m(fore);
1673        let rise = |x: f64| nose.radius_m(fore + x) - base;
1674        let root_m = (1..pieces)
1675            .rev()
1676            .map(|i| {
1677                let x = chord * f64::from(i) / f64::from(pieces);
1678                [x, rise(x)]
1679            })
1680            .collect();
1681        let planform = FinPlanform::Freeform {
1682            points_m: vec![
1683                [0.0, 0.0],
1684                [0.009347826086956524, 0.006956521739130436],
1685                [chord, 0.0022276567072510058],
1686            ],
1687            root_m,
1688        };
1689        let mut set = set(1, planform, 0.006985);
1690        set.material = Material::bulk("balsa", 170.0);
1691        (set, nose, fore)
1692    }
1693
1694    /// M4.5g4 (ADR-166): a fin's root along a nose cone is read as OpenRocket 24.12 reads it.
1695    /// OpenRocket draws the cockpit's root through 21 points, 2.5 mm apart: through the same
1696    /// points, hpr's area, mass and center of mass are OpenRocket's (its `getPlanformArea`,
1697    /// `getMass` and `getComponentCG`, to the six digits the oracle printed). hpr's own 64
1698    /// pieces sit closer to the curve, which bulges out of each chord: 2.9e-4 less area than
1699    /// OpenRocket's 20, and 3.1e-5 more than the curve itself.
1700    #[test]
1701    fn a_root_along_a_nose_cone_is_openrockets() {
1702        let (set, nose, fore) = cockpit(20);
1703        let radius = set.root_radius_on(&nose, fore).unwrap();
1704        close(
1705            radius,
1706            0.0145998,
1707            1e-5,
1708            "body radius at the root leading edge",
1709        );
1710        let g = set.planform.geometry().unwrap();
1711        close(g.area_m2, 1.449544e-4, 1e-6, "OpenRocket's planform area");
1712        let m = set.mass_properties(radius).unwrap();
1713        close(m.mass_kg, 1.72126e-4, 1e-5, "OpenRocket's mass");
1714        // Fin 0 at roll 0: its points at (r, τ, −x) about the root leading edge on the axis.
1715        close(
1716            -m.cg_m.z,
1717            0.0191163,
1718            1e-5,
1719            "OpenRocket's center of mass, aft",
1720        );
1721        close(m.cg_m.x, 0.017882, 1e-5, "OpenRocket's center of mass, out");
1722        let fine = |pieces| cockpit(pieces).0.planform.geometry().unwrap().area_m2;
1723        let (ours, curve) = (fine(64), fine(1024));
1724        assert!(
1725            ours < g.area_m2 && curve < ours,
1726            "{curve} < {ours} < {}",
1727            g.area_m2
1728        );
1729        close(ours, g.area_m2, 3.0e-4, "64 pieces against OpenRocket's 20");
1730        close(ours, curve, 3.5e-5, "64 pieces against the curve");
1731        // The slivers ROOT_SLIVER_SHARE's doc quotes, and the chord refused.
1732        let share = |pieces| {
1733            let (set, nose, fore) = cockpit(pieces);
1734            set.root_on_surface(&nose, fore).1 / set.planform.geometry().unwrap().area_m2
1735        };
1736        for (pieces, want) in [(20, 3.2e-4), (64, 3.1e-5), (1, 0.114)] {
1737            close(share(pieces), want, 0.1, "sliver share");
1738        }
1739        let (chord, nose, fore) = cockpit(1);
1740        let err = chord.root_radius_on(&nose, fore).unwrap_err();
1741        assert!(
1742            matches!(&err, DesignError::Geometry(m) if m.contains("cuts across")),
1743            "{err}"
1744        );
1745        // The span is the outline's highest point above the root leading edge.
1746        close(set.planform.span_m(), 0.006956521739130436, 1e-15, "span");
1747    }
1748
1749    /// M4.5g4 (ADR-166): a fin set sits on a nose cone or a transition only with its root on the
1750    /// surface, within a micron, along the body and with no tab or fillet; each refusal is named.
1751    #[test]
1752    fn a_root_off_the_surface_is_refused_by_name() {
1753        // A straight cone's surface is straight: an outline that ends on it needs no root points.
1754        let cone =
1755            Profile::transition(crate::NoseShape::Conical {}, 0.2, 0.02, 0.04, false).unwrap();
1756        let rise = 0.02 / 0.2 * 0.05;
1757        let on_cone = |end_h: f64| {
1758            set(
1759                3,
1760                FinPlanform::Freeform {
1761                    points_m: vec![[0.0, 0.0], [0.03, 0.04], [0.05, end_h]],
1762                    root_m: Vec::new(),
1763                },
1764                0.003,
1765            )
1766        };
1767        close(
1768            on_cone(rise).root_radius_on(&cone, 0.1).unwrap(),
1769            0.03,
1770            1e-14,
1771            "radius at x = 0.1 m",
1772        );
1773        let says = |set: FinSet, fore: f64, what: &str| {
1774            let err = set.root_radius_on(&cone, fore).unwrap_err();
1775            assert!(
1776                matches!(&err, DesignError::Geometry(m) if m.contains(what)),
1777                "{what}: {err}"
1778            );
1779        };
1780        // Just inside and just outside the micron.
1781        assert!(on_cone(rise + 0.9e-6).root_radius_on(&cone, 0.1).is_ok());
1782        says(on_cone(rise + 1.1e-6), 0.1, "stands");
1783        says(on_cone(rise - 1.1e-6), 0.1, "stands");
1784        // A level root on a cone stands off it at its trailing edge.
1785        says(set(3, rectangle(0.05, 0.04), 0.003), 0.1, "stands");
1786        // Along the body, a micron's slack at either end.
1787        says(on_cone(rise), -2e-6, "must stay on it");
1788        says(on_cone(rise), 0.15 + 2e-6, "must stay on it");
1789        assert!(on_cone(rise).root_radius_on(&cone, 0.15).is_ok());
1790        let mut tabbed = on_cone(rise);
1791        tabbed.tab = Some(FinTab {
1792            height_m: 0.005,
1793            length_m: 0.02,
1794            offset_m: 0.01,
1795        });
1796        says(tabbed, 0.1, "tab or a fillet");
1797        let mut filleted = on_cone(rise);
1798        filleted.fillet = Some(FinFillet {
1799            radius_m: 0.005,
1800            material: ply(),
1801        });
1802        says(filleted, 0.1, "tab or a fillet");
1803    }
1804
1805    #[test]
1806    fn bad_outlines_and_dimensions_are_rejected() {
1807        let bowtie = FinPlanform::Freeform {
1808            points_m: vec![[0.0, 0.0], [0.1, 0.1], [0.0, 0.1], [0.1, 0.0]],
1809            root_m: Vec::new(),
1810        };
1811        assert!(matches!(bowtie.validate(), Err(DesignError::Geometry(_))));
1812        let below = FinPlanform::Freeform {
1813            points_m: vec![[0.0, 0.0], [0.05, -0.01], [0.1, 0.0]],
1814            root_m: Vec::new(),
1815        };
1816        assert!(below.validate().is_err());
1817        // An outline that ends above the root leading edge has a root that rises: a planform, but
1818        // not one a body tube holds (ADR-166); the tree refuses it there (`tree.rs`'s tests).
1819        let open = FinPlanform::Freeform {
1820            points_m: vec![[0.0, 0.0], [0.05, 0.05], [0.1, 0.02]],
1821            root_m: Vec::new(),
1822        };
1823        assert!(open.validate().is_ok());
1824        let err = set(1, open, 0.003).check_level_root().unwrap_err();
1825        assert!(
1826            matches!(&err, DesignError::Geometry(m) if m.contains("needs a level root")),
1827            "{err}"
1828        );
1829        // Root points run fore, strictly between the root's ends, and stay at or above its
1830        // leading edge.
1831        let outline = vec![[0.0, 0.0], [0.05, 0.05], [0.1, 0.02]];
1832        let with_root = |root_m: Vec<[f64; 2]>| FinPlanform::Freeform {
1833            points_m: outline.clone(),
1834            root_m,
1835        };
1836        assert!(
1837            with_root(vec![[0.07, 0.012], [0.03, 0.004]])
1838                .validate()
1839                .is_ok()
1840        );
1841        for (root, says) in [
1842            (vec![[0.03, 0.004], [0.07, 0.012]], "must run fore"),
1843            (vec![[0.1, 0.02]], "must run fore"),
1844            (vec![[0.12, 0.02]], "must run fore"),
1845            (vec![[0.0, 0.0]], "must run fore"),
1846            (vec![[0.05, 0.06]], "runs below its root"),
1847            (vec![[0.07, 0.04], [0.03, 0.004]], "crosses itself"),
1848        ] {
1849            let err = with_root(root.clone()).validate().unwrap_err();
1850            assert!(
1851                matches!(&err, DesignError::Geometry(m) if m.contains(says)),
1852                "{root:?}: {err}"
1853            );
1854        }
1855        assert!(matches!(
1856            with_root(vec![[0.05, -0.001]]).validate(),
1857            Err(DesignError::Domain {
1858                what: "freeform fin span",
1859                ..
1860            })
1861        ));
1862        // The root leading edge is the origin, and the outline runs forward to aft.
1863        let shifted = FinPlanform::Freeform {
1864            points_m: vec![[0.03, 0.0], [0.08, 0.05], [0.13, 0.0]],
1865            root_m: Vec::new(),
1866        };
1867        assert!(shifted.validate().is_err());
1868        let backwards = FinPlanform::Freeform {
1869            points_m: vec![[0.0, 0.0], [-0.05, 0.05], [-0.1, 0.0]],
1870            root_m: Vec::new(),
1871        };
1872        assert!(backwards.validate().is_err());
1873        assert!(
1874            set(0, rectangle(0.1, 0.1), 0.003)
1875                .mass_properties(0.03)
1876                .is_err()
1877        );
1878        assert!(
1879            set(3, rectangle(0.1, 0.1), 0.0)
1880                .mass_properties(0.03)
1881                .is_err()
1882        );
1883        let mut fabric = set(3, rectangle(0.1, 0.1), 0.003);
1884        fabric.material = Material::surface("ripstop", 0.04);
1885        assert!(matches!(
1886            fabric.mass_properties(0.03),
1887            Err(DesignError::MaterialKind { .. })
1888        ));
1889    }
1890
1891    /// `[A, S_x, S_xx, S_yy]` of one fillet's section by quadrature, column by column: from the
1892    /// fillet circle's tangent point on the body out to the body's radius, the section runs from
1893    /// the body's circle up to the fillet's; beyond, from the fin's plane up to the fillet's. The
1894    /// body's circle is integrated in `x = R_b − v²`, which takes out its vertical tangent.
1895    fn fillet_section_by_quadrature(rb: f64, r: f64) -> [f64; 4] {
1896        let tol = Tolerance {
1897            relative: 1e-12,
1898            absolute: 1e-24,
1899            ..Tolerance::default()
1900        };
1901        let c = (rb * rb + 2.0 * rb * r).sqrt();
1902        let joint = |x: f64| r - (r * r - (x - c) * (x - c)).max(0.0).sqrt();
1903        let body = |x: f64| (rb * rb - x * x).max(0.0).sqrt();
1904        let moments = |bottom: f64, top: f64, x: f64| {
1905            [
1906                top - bottom,
1907                x * (top - bottom),
1908                x * x * (top - bottom),
1909                (top.powi(3) - bottom.powi(3)) / 3.0,
1910            ]
1911        };
1912        let near = integrate(
1913            |v| {
1914                let x = rb - v * v;
1915                moments(body(x), joint(x), x).map(|m| m * 2.0 * v)
1916            },
1917            0.0,
1918            (rb - c * rb / (rb + r)).sqrt(),
1919            tol,
1920        )
1921        .unwrap();
1922        let far = integrate(|x| moments(0.0, joint(x), x), rb, c, tol).unwrap();
1923        std::array::from_fn(|k| near.value[k] + far.value[k])
1924    }
1925
1926    #[test]
1927    fn fillet_section_is_its_region_by_quadrature() {
1928        for (rb, r) in [
1929            (0.05, 0.005),
1930            (0.05, 0.01),
1931            (0.05, 0.03),
1932            (0.1, 0.001),
1933            (0.02, 0.05),
1934        ] {
1935            let got = fillet_section(rb, r);
1936            let want = fillet_section_by_quadrature(rb, r);
1937            for (k, what) in ["A", "S_x", "S_xx", "S_yy"].into_iter().enumerate() {
1938                close(got[k], want[k], 1e-11, what);
1939            }
1940        }
1941        // No body, no fillet.
1942        assert_eq!(fillet_section(0.0, 0.01)[0], 0.0);
1943        // The series meets the difference where it hands over.
1944        let x: f64 = 0.25;
1945        close(
1946            span_less_sine(x.next_down()),
1947            x - x.sin(),
1948            1e-13,
1949            "x − sin x",
1950        );
1951        close(
1952            span_less_sine(1e-3),
1953            1e-9 / 6.0 - 1e-15 / 120.0 + 1e-21 / 5040.0,
1954            1e-15,
1955            "x − sin x",
1956        );
1957    }
1958
1959    #[test]
1960    fn a_fillet_on_a_flat_body_is_a_square_less_a_quarter_circle() {
1961        // The curvature's share is of order `r/R_b`, 1e-8 here.
1962        let r = 0.01;
1963        close(
1964            fillet_section(1e6, r)[0],
1965            r * r * (1.0 - PI / 4.0),
1966            1e-6,
1967            "flat",
1968        );
1969    }
1970
1971    /// The worked example in `docs/physics/mass.md`: a 5 mm fillet on a 30 mm tube is 4.253 mm²
1972    /// (the triangle 86.603 mm² less sectors of 64.506 and 17.843 mm²), and six of them along a
1973    /// 100 mm root in cardboard, 680 kg/m³, weigh 1.735 g.
1974    #[test]
1975    fn the_worked_fillet_example_is_the_docs() {
1976        let [a, ..] = fillet_section(0.030, 0.005);
1977        assert!((a * 1e6 - 4.253).abs() < 5e-4, "{}", a * 1e6);
1978        let planform = FinPlanform::Trapezoidal {
1979            root_chord_m: 0.1,
1980            tip_chord_m: 0.05,
1981            span_m: 0.05,
1982            sweep_m: 0.05,
1983        };
1984        let bare = set(3, planform.clone(), 0.003);
1985        let mut filleted = set(3, planform, 0.003);
1986        filleted.fillet = Some(FinFillet {
1987            radius_m: 0.005,
1988            material: Material::bulk("cardboard", 680.0),
1989        });
1990        let mass_g = (filleted.mass_properties(0.030).unwrap().mass_kg
1991            - bare.mass_properties(0.030).unwrap().mass_kg)
1992            * 1e3;
1993        assert!((mass_g - 1.735).abs() < 5e-4, "{mass_g}");
1994    }
1995
1996    /// Far from real fillets the section's closed form cancels away: a fillet more than
1997    /// [`FILLET_RATIO_MAX`] times the body radius is refused, not weighed on noise; one under a
1998    /// millionth of it, or on a body of no radius, weighs nothing.
1999    #[test]
2000    fn a_fillet_far_from_the_body_s_size_is_refused_or_none() {
2001        let planform = FinPlanform::Trapezoidal {
2002            root_chord_m: 0.1,
2003            tip_chord_m: 0.05,
2004            span_m: 0.05,
2005            sweep_m: 0.05,
2006        };
2007        let filleted = |radius_m: f64| {
2008            let mut fins = set(3, planform.clone(), 0.003);
2009            fins.fillet = Some(FinFillet {
2010                radius_m,
2011                material: Material::bulk("epoxy", 1200.0),
2012            });
2013            fins
2014        };
2015        let bare = set(3, planform.clone(), 0.003);
2016        let rb = 0.05;
2017        let widest = FILLET_RATIO_MAX * rb;
2018        for radius_m in [widest * (1.0 + 1e-12), 1e10, 1e12, 1e100] {
2019            let error = filleted(radius_m).single_fin(rb).unwrap_err();
2020            assert!(
2021                matches!(error, DesignError::Domain { what, value }
2022                    if what.starts_with("fin fillet radius") && value == radius_m / rb),
2023                "{radius_m}: {error:?}"
2024            );
2025        }
2026        let mass = |fins: &FinSet, rb: f64| fins.single_fin(rb).unwrap().mass_kg;
2027        assert!(mass(&filleted(widest), rb) > mass(&bare, rb));
2028        assert!(mass(&filleted(1e-6 * rb), rb) > mass(&bare, rb));
2029        for (radius_m, body_m) in [(1e-6 * rb * (1.0 - 1e-12), rb), (1e-20, rb), (0.005, 0.0)] {
2030            assert_eq!(
2031                mass(&filleted(radius_m), body_m),
2032                mass(&bare, body_m),
2033                "{radius_m} on {body_m}"
2034            );
2035        }
2036        // A fillet of a weightless material weighs nothing, and is no error.
2037        let mut fins = set(3, planform, 0.003);
2038        fins.fillet = Some(FinFillet {
2039            radius_m: 0.005,
2040            material: Material::bulk("air", 0.0),
2041        });
2042        assert_eq!(
2043            fins.single_fin(0.05).unwrap().mass_kg,
2044            set(3, fins.planform.clone(), 0.003)
2045                .single_fin(0.05)
2046                .unwrap()
2047                .mass_kg
2048        );
2049    }
2050
2051    #[test]
2052    fn fillets_are_a_prism_of_their_section_along_the_root() {
2053        // Moments by quadrature, assembled by the equations in `FinSet::fillets`' docs.
2054        let (rb, r, rho) = (0.05, 0.005, 1200.0);
2055        let planform = FinPlanform::Trapezoidal {
2056            root_chord_m: 0.1,
2057            tip_chord_m: 0.05,
2058            span_m: 0.05,
2059            sweep_m: 0.05,
2060        };
2061        let mut fins = set(3, planform, 0.003);
2062        let bare = fins.single_fin(rb).unwrap();
2063        fins.fillet = Some(FinFillet {
2064            radius_m: r,
2065            material: Material::bulk("epoxy", rho),
2066        });
2067        let with = fins.single_fin(rb).unwrap();
2068        let pair = with.without_part(&bare);
2069        let [a, sx, sxx, syy] = fillet_section_by_quadrature(rb, r);
2070        let l = 0.1;
2071        close(pair.mass_kg, 2.0 * rho * a * l, 1e-10, "mass");
2072        assert!((pair.cg_m - DVec3::new(sx / a, 0.0, -0.5 * l)).length() < 1e-12);
2073        let about_origin = with.inertia_about(DVec3::ZERO) - bare.inertia_about(DVec3::ZERO);
2074        let want = DMat3::from_cols(
2075            DVec3::new(
2076                2.0 * rho * (syy * l + a * l.powi(3) / 3.0),
2077                0.0,
2078                rho * sx * l * l,
2079            ),
2080            DVec3::new(0.0, 2.0 * rho * (sxx * l + a * l.powi(3) / 3.0), 0.0),
2081            DVec3::new(rho * sx * l * l, 0.0, 2.0 * rho * (sxx + syy) * l),
2082        );
2083        mat_close(about_origin, want, 1e-9, "fillets about the origin");
2084        // A fillet of no radius is none, and a negative one is refused.
2085        fins.fillet = Some(FinFillet {
2086            radius_m: 0.0,
2087            material: Material::bulk("epoxy", rho),
2088        });
2089        assert_eq!(fins.single_fin(rb).unwrap(), bare);
2090        fins.fillet = Some(FinFillet {
2091            radius_m: -0.001,
2092            material: Material::bulk("epoxy", rho),
2093        });
2094        assert!(matches!(
2095            fins.single_fin(rb),
2096            Err(DesignError::Domain {
2097                what: "fin fillet radius",
2098                ..
2099            })
2100        ));
2101    }
2102
2103    /// A fin set's count is 1 to [`FinSet::MAX_COUNT`]: none and one over are refused by the
2104    /// count check itself (its `what` and the count), so four billion fins are an error rather
2105    /// than a loop that never returns; the bound itself is weighed, as 64 fins of one fin each.
2106    #[test]
2107    fn a_fin_count_over_the_bound_is_refused_and_the_bound_is_weighed() {
2108        let rb = 0.028;
2109        let planform = FinPlanform::Trapezoidal {
2110            root_chord_m: 0.05,
2111            tip_chord_m: 0.02,
2112            span_m: 0.03,
2113            sweep_m: 0.02,
2114        };
2115        for count in [0, FinSet::MAX_COUNT + 1, 4_000_000_000, u32::MAX] {
2116            let fins = set(count, planform.clone(), 0.003);
2117            for result in [fins.validate(), fins.mass_properties(rb).map(|_| ())] {
2118                match result {
2119                    Err(DesignError::Domain { what, value }) => {
2120                        assert_eq!(what, "fin count (1 to 64)", "{count}");
2121                        assert_eq!(value, f64::from(count), "{count}");
2122                    }
2123                    other => panic!("{count} fins: {other:?}"),
2124                }
2125            }
2126        }
2127        let most = set(FinSet::MAX_COUNT, planform.clone(), 0.003);
2128        most.validate().unwrap();
2129        let one = set(1, planform, 0.003).mass_properties(rb).unwrap();
2130        let all = most.mass_properties(rb).unwrap();
2131        close(all.mass_kg, 64.0 * one.mass_kg, 1e-13, "64 fins' mass");
2132        // Evenly spaced, the fins' center lies on the axis.
2133        assert!(
2134            all.cg_m.x.abs() < 1e-15 && all.cg_m.y.abs() < 1e-15,
2135            "{:?}",
2136            all.cg_m
2137        );
2138    }
2139
2140    /// A tube fin set's count is 1 to [`TubeFinSet::MAX_COUNT`], refused by the count check
2141    /// itself above it, and weighed at it.
2142    #[test]
2143    fn a_tube_fin_count_over_the_bound_is_refused_and_the_bound_is_weighed() {
2144        let tubes = |count| TubeFinSet {
2145            count,
2146            length_m: 0.1,
2147            outer_radius_m: 0.012,
2148            thickness_m: 0.001,
2149            base_angle_rad: 0.0,
2150            material: Material::bulk("cardboard", 790.0),
2151        };
2152        for count in [0, TubeFinSet::MAX_COUNT + 1, 4_000_000_000, u32::MAX] {
2153            match tubes(count).mass_properties(0.02) {
2154                Err(DesignError::Domain { what, value }) => {
2155                    assert_eq!(what, "tube fin count (1 to 64)", "{count}");
2156                    assert_eq!(value, f64::from(count), "{count}");
2157                }
2158                other => panic!("{count} tubes: {other:?}"),
2159            }
2160        }
2161        let one = tubes(1).mass_properties(0.02).unwrap();
2162        let all = tubes(TubeFinSet::MAX_COUNT).mass_properties(0.02).unwrap();
2163        close(all.mass_kg, 64.0 * one.mass_kg, 1e-13, "64 tubes' mass");
2164    }
2165}