Skip to main content

hpr_design/
tree.rs

1//! The design tree: a rocket of stages, each a stack of body components from the nose aft with
2//! parts attached to them, and how the tree resolves into placed parts and the rocket's structural
3//! mass properties.
4//!
5//! **Stations and the body origin.** A *station* `s` is a distance aft of the nose tip, the way
6//! design files state positions. The body frame's origin is the nose tip (`z_ref = 0` in
7//! `docs/physics/frames.md`), so station `s` is body `z = −s`. A part's own frame has its origin at
8//! its forward end ([`crate::mass`]), so a part whose forward end is at station `s` is translated by
9//! `(0, 0, −s)`.
10//!
11//! **Body components** (nose cones, body tubes and transitions) are the stages' component lists.
12//! They stack: each starts where the one before it ends, through every stage, from `s = 0`.
13//! Shoulders don't count toward the stack.
14//!
15//! **Parallel stages** ([`ParallelStage`]) don't stack: a stage strapped beside a body tube of an
16//! axial stage, such as a set of boosters, is laid out as a pod set on that tube ([`PodSet`]), its
17//! body components each pod's stack, while its parts and their mass stay its own stage's, so a
18//! separation after the stage it hangs on drops it (the decision record on parallel stages,
19//! [ADR-171][adr-171]).
20//!
21//! **Attached parts** are children of a component, placed along it by a [`Position`]. Fins, tube
22//! fins, launch lugs and rail buttons attach to the outside of a body tube and take its outer
23//! radius. Inner tubes, centering rings, mass components and recovery parts go inside a body
24//! component or an inner tube. Only inner tubes have children of their own. Radial offsets are
25//! always measured from the body axis.
26//!
27//! **Automatic radii** ([`AutoDimension`]) are taken from neighbors and parents when the tree
28//! resolves; a stored value for an automatic dimension is ignored.
29//!
30//! **Mass.** A component's own mass properties come from its part's geometry, placed. Overrides
31//! ([`Overrides`]) replace them, or the component together with everything attached to it; a
32//! stage's overrides replace the whole stage. Overrides nested deeper apply first. Motors are never
33//! part of the structure ([`crate::config`]).
34//!
35//! See `docs/physics/design.md` and the decision record on the design tree, [ADR-007][adr-007].
36//!
37//! [adr-007]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-007-design-tree-stations-placement-automatic-radii-overrides-motors-and-checks-2026-09-17
38//! [adr-171]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-171-a-parallel-stage-is-a-pod-set-that-separates-2026-10-05
39
40use std::collections::{BTreeMap, BTreeSet};
41
42use hpr_core::{DMat3, DVec3};
43use serde::{Deserialize, Serialize};
44
45use crate::config::{Configuration, MotorMount};
46use crate::error::DesignError;
47use crate::finish::Finish;
48use crate::fins::{FinSet, TubeFinSet};
49use crate::mass::{MassProperties, Placement};
50use crate::parts::{
51    BodyTube, CenteringRing, InnerTube, LaunchLug, MassComponent, NoseCone, Packing, Parachute,
52    PodSet, RailButton, ShockCord, Streamer, Transition,
53};
54use crate::shapes::check_dimension;
55use crate::solids::Wall;
56
57/// Slack when comparing lengths that should agree, m: far below any build tolerance and far above
58/// the round-off in stations summed from millimeter inputs.
59pub const LENGTH_TOLERANCE_M: f64 = 1e-9;
60
61/// A rocket design: its stages, how its reference diameter is chosen, and its motor
62/// configurations.
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
64#[serde(deny_unknown_fields)]
65pub struct Rocket {
66    /// Name.
67    #[serde(default)]
68    pub name: String,
69    /// Stages from the nose aft. The first holds the nose cone. A parallel stage comes after the
70    /// stage it hangs on ([`Stage::parallel`]).
71    pub stages: Vec<Stage>,
72    /// How the reference diameter is chosen.
73    #[serde(default)]
74    pub reference_diameter: ReferenceDiameter,
75    /// Motor configurations.
76    #[serde(default)]
77    pub configurations: Vec<Configuration>,
78}
79
80/// A stage: body components stacked from its forward end aft, on the airframe's axis or, for a
81/// parallel stage, along each of its pods.
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
83#[serde(deny_unknown_fields)]
84pub struct Stage {
85    /// Unique id.
86    pub id: String,
87    /// Name.
88    #[serde(default)]
89    pub name: String,
90    /// Body components (nose cones, body tubes, transitions), forward to aft.
91    pub components: Vec<Component>,
92    /// Overrides for the whole stage without its motors, applied after every override inside it. A
93    /// center-of-mass override is measured aft of the stage's forward end.
94    #[serde(
95        default,
96        skip_serializing_if = "Overrides::is_empty",
97        deserialize_with = "object_only"
98    )]
99    pub overrides: Overrides,
100    /// How `overrides` set the stage's inertia ([`StageOverrideRule`]): by rescaling and moving
101    /// the stage as one body, as `hpr-design` does by default, or with its parts left in place,
102    /// as OpenRocket 24.12 weighs a single stage.
103    #[serde(default, skip_serializing_if = "StageOverrideRule::is_rescaled")]
104    pub override_rule: StageOverrideRule,
105    /// Mass the stage carries beyond what its parts weigh ([`AddedMass`]): a point mass, added to
106    /// the parts before `overrides` apply. A parallel stage's sits among its pods. A stage a
107    /// parallel stage hangs on can carry one at a station, unless that parallel stage is one pod
108    /// off the axis, and can't carry one with no station ([`Rocket::layout`]).
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub added_mass: Option<AddedMass>,
111    /// A drag coefficient stated for the stage ([`DragOverride`]): added to the rocket's drag, or,
112    /// covering its children, in place of everything in the stage.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub drag_override: Option<DragOverride>,
115    /// Where the stage hangs beside the airframe, for a parallel stage; `None` for a stage on the
116    /// axis, which stacks.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub parallel: Option<ParallelStage>,
119}
120
121/// Where a parallel stage hangs: beside a body tube of an earlier axial stage, as a set of pods.
122///
123/// A parallel stage, such as a pair of strap-on boosters, is laid out exactly as a pod set on that
124/// tube would be ([`PodSet`]): its body components are each pod's stack, repeated `pods.count`
125/// times around the axis, and they take their normal force and drag once per pod. What differs is
126/// whose they are: the stage's parts, mass and motors are its own stage's, not the tube's, so a
127/// separation after the stage it hangs on drops the pods while the airframe flies on. See the
128/// design page's *Parallel stages* section (`docs/physics/design.md`) and the decision record on
129/// parallel stages, [ADR-171][adr-171].
130///
131/// [adr-171]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-171-a-parallel-stage-is-a-pod-set-that-separates-2026-10-05
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
133#[serde(deny_unknown_fields)]
134pub struct ParallelStage {
135    /// The id of the body tube it hangs on: a body component of an earlier stage on the axis.
136    pub on: String,
137    /// Where along that tube the pods sit, as an attached part's position; measured from the
138    /// tube, never after a sibling ([`Position::After`] is refused).
139    pub position: Position,
140    /// How many pods, how far from the axis, and at what roll angle.
141    pub pods: PodSet,
142}
143
144/// Reads a struct from an object only. serde's derived reader also takes a struct from an array
145/// of its fields in order, so `"overrides": []` would read as no overrides and be dropped on
146/// writing, while the schema refuses it (issue #253); the format reader's array check can't see
147/// a key the written document leaves out.
148fn object_only<'de, D, T>(deserializer: D) -> Result<T, D::Error>
149where
150    D: serde::Deserializer<'de>,
151    T: Deserialize<'de>,
152{
153    struct ObjectOnly<T>(std::marker::PhantomData<T>);
154    impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for ObjectOnly<T> {
155        type Value = T;
156        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
157            formatter.write_str("an object")
158        }
159        fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
160            T::deserialize(serde::de::value::MapAccessDeserializer::new(map))
161        }
162    }
163    deserializer.deserialize_map(ObjectOnly(std::marker::PhantomData))
164}
165
166/// A node of the design tree: a part, where it sits, and what hangs off it.
167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
168#[serde(deny_unknown_fields)]
169pub struct Component {
170    /// Unique id.
171    pub id: String,
172    /// Name.
173    #[serde(default)]
174    pub name: String,
175    /// The part, with its geometry and material.
176    pub part: Part,
177    /// Where an attached part sits along its parent. Body components (a stage's own list) have
178    /// none: they stack.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub position: Option<Position>,
181    /// Dimensions taken from neighbors or the parent instead of the part's stored values.
182    #[serde(default, skip_serializing_if = "Vec::is_empty")]
183    pub auto: Vec<AutoDimension>,
184    /// Makes a body tube or an inner tube a motor mount.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub motor_mount: Option<MotorMount>,
187    /// The outer surface's finish, for skin friction; `None` means [`Finish::default`]. Parts
188    /// inside the body ignore it.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub finish: Option<Finish>,
191    /// Mass, center-of-mass and inertia overrides.
192    #[serde(
193        default,
194        skip_serializing_if = "Overrides::is_empty",
195        deserialize_with = "object_only"
196    )]
197    pub overrides: Overrides,
198    /// Whether the overrides replace this component together with everything attached to it
199    /// (`true`), or this component alone (`false`).
200    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
201    pub overrides_include_children: bool,
202    /// A drag coefficient stated in place of the drag the component's geometry gives
203    /// ([`DragOverride`]).
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub drag_override: Option<DragOverride>,
206    /// Attached parts, or a pod set's body components.
207    #[serde(default, skip_serializing_if = "Vec::is_empty")]
208    pub children: Vec<Component>,
209}
210
211impl Component {
212    /// The axial extent used to place the component, m: [`Part::length_m`], but for a pod set the
213    /// sum of its body components' lengths, which stack along the pod.
214    pub fn length_m(&self) -> f64 {
215        match self.part {
216            // A fold from +0: an empty sum of floats is −0.
217            Part::PodSet(_) => self
218                .children
219                .iter()
220                .fold(0.0, |length, c| length + c.part.length_m()),
221            _ => self.part.length_m(),
222        }
223    }
224}
225
226/// A part in the tree. Serialized as an object with one key, the part's kind.
227#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
228#[serde(rename_all = "snake_case")]
229#[non_exhaustive]
230pub enum Part {
231    /// A nose cone (body component).
232    NoseCone(NoseCone),
233    /// A body tube (body component).
234    BodyTube(BodyTube),
235    /// A transition (body component).
236    Transition(Transition),
237    /// An inner tube (internal): a coupler, motor mount tube or engine block.
238    InnerTube(InnerTube),
239    /// A centering ring or bulkhead (internal).
240    CenteringRing(CenteringRing),
241    /// A fin set (external, on a body tube). Its axial extent is the root chord.
242    FinSet(FinSet),
243    /// Tube fins (external, on a body tube).
244    TubeFinSet(TubeFinSet),
245    /// Launch lugs (external, on a body tube). The extent covers the whole row.
246    LaunchLug(LaunchLug),
247    /// Rail buttons (external, on a body tube). The extent covers the whole row.
248    RailButton(RailButton),
249    /// Pods (external, on a body tube). Its children are the pod's body components, which stack
250    /// along the pod's axis; its extent is theirs ([`Component::length_m`]).
251    PodSet(PodSet),
252    /// A mass component (internal).
253    MassComponent(MassComponent),
254    /// A parachute (internal).
255    Parachute(Parachute),
256    /// A streamer (internal).
257    Streamer(Streamer),
258    /// A shock cord (internal).
259    ShockCord(ShockCord),
260}
261
262/// Where a part belongs in the tree.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264enum Role {
265    /// A stage's stacked component.
266    Body,
267    /// On the outside of a body tube.
268    External,
269    /// Inside a body component or an inner tube.
270    Internal,
271}
272
273impl Part {
274    /// The part's kind, as serialized.
275    pub fn kind_name(&self) -> &'static str {
276        match self {
277            Self::NoseCone(_) => "nose_cone",
278            Self::BodyTube(_) => "body_tube",
279            Self::Transition(_) => "transition",
280            Self::InnerTube(_) => "inner_tube",
281            Self::CenteringRing(_) => "centering_ring",
282            Self::FinSet(_) => "fin_set",
283            Self::TubeFinSet(_) => "tube_fin_set",
284            Self::LaunchLug(_) => "launch_lug",
285            Self::RailButton(_) => "rail_button",
286            Self::PodSet(_) => "pod_set",
287            Self::MassComponent(_) => "mass_component",
288            Self::Parachute(_) => "parachute",
289            Self::Streamer(_) => "streamer",
290            Self::ShockCord(_) => "shock_cord",
291        }
292    }
293
294    fn role(&self) -> Role {
295        match self {
296            Self::NoseCone(_) | Self::BodyTube(_) | Self::Transition(_) => Role::Body,
297            Self::FinSet(_)
298            | Self::TubeFinSet(_)
299            | Self::LaunchLug(_)
300            | Self::RailButton(_)
301            | Self::PodSet(_) => Role::External,
302            Self::InnerTube(_)
303            | Self::CenteringRing(_)
304            | Self::MassComponent(_)
305            | Self::Parachute(_)
306            | Self::Streamer(_)
307            | Self::ShockCord(_) => Role::Internal,
308        }
309    }
310
311    /// Whether this is a body component: a nose cone, body tube or transition.
312    pub fn is_body(&self) -> bool {
313        self.role() == Role::Body
314    }
315
316    /// Whether this attaches to the outside of a body tube: fins, tube fins, lugs, rail buttons,
317    /// pods.
318    pub fn is_external(&self) -> bool {
319        self.role() == Role::External
320    }
321
322    /// The axial extent used to place the part, m: a body component's length without shoulders, a
323    /// fin set's root chord, a row of lugs or buttons from the first one's forward end to the last
324    /// one's aft end, and a packed part's packed length. A pod set's extent is its pods' body
325    /// components, which the part alone doesn't hold, so here it is 0: see
326    /// [`Component::length_m`].
327    pub fn length_m(&self) -> f64 {
328        let row =
329            |count: u32, one: f64, spacing: f64| one + spacing * f64::from(count.saturating_sub(1));
330        match self {
331            Self::NoseCone(p) => p.length_m,
332            Self::BodyTube(p) => p.length_m,
333            Self::Transition(p) => p.length_m,
334            Self::InnerTube(p) => p.length_m,
335            Self::CenteringRing(p) => p.length_m,
336            Self::FinSet(p) => p.planform.root_chord_m(),
337            Self::TubeFinSet(p) => p.length_m,
338            Self::LaunchLug(p) => row(p.count, p.length_m, p.spacing_m),
339            Self::RailButton(p) => row(p.count, p.outer_diameter_m, p.spacing_m),
340            Self::PodSet(_) => 0.0,
341            Self::MassComponent(p) => p.packing.length_m,
342            Self::Parachute(p) => p.packing.length_m,
343            Self::Streamer(p) => p.packing.length_m,
344            Self::ShockCord(p) => p.packing.length_m,
345        }
346    }
347
348    /// How a mass object or recovery part is packed, or `None` for a part that is not packed.
349    pub fn packing(&self) -> Option<&Packing> {
350        match self {
351            Self::MassComponent(p) => Some(&p.packing),
352            Self::Parachute(p) => Some(&p.packing),
353            Self::Streamer(p) => Some(&p.packing),
354            Self::ShockCord(p) => Some(&p.packing),
355            _ => None,
356        }
357    }
358
359    /// A body component's outer radius at its forward end, m (zero at a nose tip).
360    pub fn fore_radius_m(&self) -> Option<f64> {
361        match self {
362            Self::NoseCone(_) => Some(0.0),
363            Self::BodyTube(p) => Some(p.outer_radius_m),
364            Self::Transition(p) => Some(p.fore_radius_m),
365            _ => None,
366        }
367    }
368
369    /// A body component's outer radius at its aft end, m.
370    pub fn aft_radius_m(&self) -> Option<f64> {
371        match self {
372            Self::NoseCone(p) => Some(p.base_radius_m),
373            Self::BodyTube(p) => Some(p.outer_radius_m),
374            Self::Transition(p) => Some(p.aft_radius_m),
375            _ => None,
376        }
377    }
378
379    /// A body component's largest outer radius anywhere along it, m.
380    ///
381    /// # Errors
382    ///
383    /// Profile errors for a nose cone or transition.
384    pub fn max_radius_m(&self) -> Result<Option<f64>, DesignError> {
385        Ok(match self {
386            Self::NoseCone(p) => Some(p.profile()?.max_radius_m()),
387            Self::BodyTube(p) => Some(p.outer_radius_m),
388            Self::Transition(p) => Some(p.profile()?.max_radius_m()),
389            _ => None,
390        })
391    }
392
393    /// The inside radius of a body tube or inner tube, m: where internal parts fit.
394    pub fn inner_radius_m(&self) -> Option<f64> {
395        match self {
396            Self::BodyTube(p) => Some(p.outer_radius_m - p.thickness_m),
397            Self::InnerTube(p) => Some(p.outer_radius_m - p.thickness_m),
398            _ => None,
399        }
400    }
401
402    /// Where the part's own axis crosses the `x`–`y` plane, `[x, y]` in body axes, m: an inner
403    /// tube's or packed part's radial offset turned by its angle, and the body axis for every
404    /// other part.
405    pub fn axis_offset_m(&self) -> [f64; 2] {
406        let turned = |r: f64, angle: f64| [r * angle.cos(), r * angle.sin()];
407        match self {
408            Self::InnerTube(p) => turned(p.radial_offset_m, p.angle_rad),
409            Self::MassComponent(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
410            Self::Parachute(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
411            Self::Streamer(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
412            Self::ShockCord(p) => turned(p.packing.radial_offset_m, p.packing.angle_rad),
413            _ => [0.0, 0.0],
414        }
415    }
416
417    /// An internal part's outer radius about its own axis, m: an inner tube's or ring's outer
418    /// radius, or a packed part's packed radius.
419    pub fn outer_radius_about_axis_m(&self) -> Option<f64> {
420        match self {
421            Self::InnerTube(p) => Some(p.outer_radius_m),
422            Self::CenteringRing(p) => Some(p.outer_radius_m),
423            Self::MassComponent(p) => Some(p.packing.radius_m),
424            Self::Parachute(p) => Some(p.packing.radius_m),
425            Self::Streamer(p) => Some(p.packing.radius_m),
426            Self::ShockCord(p) => Some(p.packing.radius_m),
427            _ => None,
428        }
429    }
430
431    /// How far an internal part reaches from `axis` (`[x, y]` in body axes, m): the distance
432    /// between the two axes plus the part's outer radius, for the farthest tube of a cluster.
433    pub fn reach_from_m(&self, axis: [f64; 2]) -> Option<f64> {
434        let [x, y] = self.axis_offset_m();
435        let tubes = match self {
436            Self::InnerTube(tube) if !tube.cluster_m.is_empty() => tube.cluster_m.as_slice(),
437            _ => &[[0.0, 0.0]],
438        };
439        self.outer_radius_about_axis_m().map(|r| {
440            tubes
441                .iter()
442                .map(|&[u, v]| (x + u - axis[0]).hypot(y + v - axis[1]) + r)
443                .fold(f64::NEG_INFINITY, f64::max)
444        })
445    }
446
447    /// Mass properties in the part's own frame. External attachments need the radius of the body
448    /// they sit on.
449    ///
450    /// # Errors
451    ///
452    /// The part's own geometry, material and numerical errors, and [`DesignError::Geometry`] when
453    /// an external attachment has no body radius.
454    pub fn mass_properties(
455        &self,
456        body_radius_m: Option<f64>,
457    ) -> Result<MassProperties, DesignError> {
458        let body = || {
459            body_radius_m.ok_or_else(|| {
460                DesignError::Geometry(format!(
461                    "a {} needs the radius of the body it sits on",
462                    self.kind_name()
463                ))
464            })
465        };
466        match self {
467            Self::NoseCone(p) => p.mass_properties(),
468            Self::BodyTube(p) => p.mass_properties(),
469            Self::Transition(p) => p.mass_properties(),
470            Self::InnerTube(p) => p.mass_properties(),
471            Self::CenteringRing(p) => p.mass_properties(),
472            Self::FinSet(p) => p.mass_properties(body()?),
473            Self::TubeFinSet(p) => p.mass_properties(body()?),
474            Self::LaunchLug(p) => p.mass_properties(body()?),
475            Self::RailButton(p) => p.mass_properties(body()?),
476            Self::PodSet(p) => p.pods().map(|_| MassProperties::ZERO),
477            Self::MassComponent(p) => p.mass_properties(),
478            Self::Parachute(p) => p.mass_properties(),
479            Self::Streamer(p) => p.mass_properties(),
480            Self::ShockCord(p) => p.mass_properties(),
481        }
482    }
483}
484
485/// Where an attached part sits along its parent. Offsets are positive aft.
486#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
487#[serde(tag = "from", rename_all = "snake_case", deny_unknown_fields)]
488pub enum Position {
489    /// The part's forward end is `aft_offset_m` aft of the parent's forward end.
490    Top {
491        /// Offset, m.
492        #[serde(default)]
493        aft_offset_m: f64,
494    },
495    /// The part's middle is `aft_offset_m` aft of the parent's middle.
496    Middle {
497        /// Offset, m.
498        #[serde(default)]
499        aft_offset_m: f64,
500    },
501    /// The part's aft end is `aft_offset_m` aft of the parent's aft end.
502    Bottom {
503        /// Offset, m.
504        #[serde(default)]
505        aft_offset_m: f64,
506    },
507    /// The part's forward end is `aft_offset_m` aft of the previous sibling's aft end, or of the
508    /// parent's forward end for the first child.
509    After {
510        /// Offset, m.
511        #[serde(default)]
512        aft_offset_m: f64,
513    },
514    /// The part's forward end is at station `station_m`, measured aft of the nose tip.
515    Absolute {
516        /// Station, m.
517        station_m: f64,
518    },
519}
520
521/// A dimension resolved from the tree instead of stored in the part.
522#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
523#[serde(rename_all = "snake_case")]
524#[non_exhaustive]
525pub enum AutoDimension {
526    /// A nose cone's base radius: the next body component's forward radius.
527    BaseRadius,
528    /// A body tube's outer radius: the previous body component's aft radius, or, when that can't
529    /// be resolved, the next one's forward radius. A centering ring's or inner tube's outer
530    /// radius: its parent's inner radius, which is how a coupler or an engine block fills the tube
531    /// it sits in; inside a hollow nose cone or transition, the parent's outer radius at the
532    /// narrower end of the part less the parent's wall, and never below zero, as OpenRocket 24.12
533    /// reads it ([ADR-096][adr-096]). An inner tube whose resolved radius is less than its wall
534    /// is laid out solid (its wall is cut to its radius), as OpenRocket weighs it; a stated radius
535    /// with too thick a wall is still refused. A tube fin set's outer radius: the radius at which
536    /// its tubes close the ring around the body tube they sit on,
537    /// [`TubeFinSet::closing_radius_m`](crate::TubeFinSet::closing_radius_m), its wall cut to that
538    /// radius when thicker, as OpenRocket 24.12 reads it ([ADR-098][adr-098]).
539    ///
540    /// [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
541    /// [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
542    OuterRadius,
543    /// A transition's forward radius: the previous body component's aft radius.
544    ForeRadius,
545    /// A transition's aft radius: the next body component's forward radius.
546    AftRadius,
547    /// A nose cone's shoulder outer radius: the inner radius of the body tube behind it.
548    ShoulderRadius,
549    /// A transition's forward shoulder outer radius: the inner radius of the body tube ahead of it.
550    ForeShoulderRadius,
551    /// A transition's aft shoulder outer radius: the inner radius of the body tube behind it.
552    AftShoulderRadius,
553    /// A centering ring's inner radius: the outer radius of the widest on-axis inner tube among
554    /// its siblings that overlaps it along the axis, or zero when none does.
555    InnerRadius,
556    /// A mass component's or recovery part's packed radius: its parent's inner radius less the
557    /// part's radial offset.
558    PackedRadius,
559}
560
561impl AutoDimension {
562    /// The dimension's name, as serialized.
563    pub fn name(self) -> &'static str {
564        match self {
565            Self::BaseRadius => "base_radius",
566            Self::OuterRadius => "outer_radius",
567            Self::ForeRadius => "fore_radius",
568            Self::AftRadius => "aft_radius",
569            Self::ShoulderRadius => "shoulder_radius",
570            Self::ForeShoulderRadius => "fore_shoulder_radius",
571            Self::AftShoulderRadius => "aft_shoulder_radius",
572            Self::InnerRadius => "inner_radius",
573            Self::PackedRadius => "packed_radius",
574        }
575    }
576
577    fn applies_to(self, part: &Part) -> bool {
578        use AutoDimension as A;
579        matches!(
580            (self, part),
581            (A::BaseRadius | A::ShoulderRadius, Part::NoseCone(_))
582                | (
583                    A::OuterRadius,
584                    Part::BodyTube(_)
585                        | Part::CenteringRing(_)
586                        | Part::InnerTube(_)
587                        | Part::TubeFinSet(_)
588                )
589                | (
590                    A::ForeRadius | A::AftRadius | A::ForeShoulderRadius | A::AftShoulderRadius,
591                    Part::Transition(_)
592                )
593                | (A::InnerRadius, Part::CenteringRing(_))
594                | (
595                    A::PackedRadius,
596                    Part::MassComponent(_)
597                        | Part::Parachute(_)
598                        | Part::Streamer(_)
599                        | Part::ShockCord(_)
600                )
601        )
602    }
603}
604
605/// Values that replace the mass properties computed from geometry. Each applies in turn:
606///
607/// 1. **Mass** `m′`: the body is rescaled, `I′ = I m′/m`, keeping its center and shape. A body with
608///    no mass becomes a point mass at its center, but for a packed part in a layout (a mass
609///    component, parachute, streamer or shock cord), which takes `m′` as a solid cylinder of its
610///    packing, as OpenRocket 24.12 does ([ADR-063][adr-063]).
611/// 2. **Center of mass**: the center moves along the axis to `cg_aft_m` aft of the component's
612///    forward end (a stage's, for a stage), with or without its children, and off the axis to
613///    `cg_xy_m` when given (otherwise it keeps its offset); the tensor about the center is
614///    unchanged.
615/// 3. **Inertia**: the tensor about the (new) center is replaced.
616///
617/// [adr-063]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-063-packed-parts-read-and-weighed-as-openrocket-packs-them-2026-09-21
618#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
619#[serde(deny_unknown_fields)]
620pub struct Overrides {
621    /// Mass, kg.
622    #[serde(default, skip_serializing_if = "Option::is_none")]
623    pub mass_kg: Option<f64>,
624    /// Center of mass, m aft of the forward end of the component (or the stage).
625    #[serde(default, skip_serializing_if = "Option::is_none")]
626    pub cg_aft_m: Option<f64>,
627    /// Center of mass off the axis, `[x, y]` in body axes, m. For a part inside a cluster's tube or
628    /// a pod, it is measured in that one copy as written (a pod on the body's axis), and the copies
629    /// carry it to each place.
630    #[serde(default, skip_serializing_if = "Option::is_none")]
631    pub cg_xy_m: Option<[f64; 2]>,
632    /// Inertia tensor about the center of mass. For a part inside a cluster's tube or a pod, it is
633    /// in that one copy's axes as written, and turns with each pod.
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub inertia: Option<InertiaOverride>,
636}
637
638/// A drag coefficient stated in place of the one a component's geometry gives: OpenRocket's
639/// drag-coefficient override (`<overridecd>`, `<overridesubcomponentscd>`), as OpenRocket 24.12
640/// flies it, measured on probe designs (`validation/oracles/openrocket/drag_override.py`,
641/// [ADR-167][adr-167]):
642///
643/// - The coefficient is on the rocket's reference area and is the same at every Mach number.
644/// - It replaces all the component's own zero-lift drag: skin friction, pressure drag and the
645///   base drag of its aft face, whether that is the rocket's base or a step down to the part
646///   behind it. A step up at its fore end is its own face, and goes too.
647/// - It counts once per instance: per fin of a fin set, per lug or button of a set.
648/// - On a tube fin set, a pod set or a part in a pod, or covering a pod set, it was not measured,
649///   and `hpr-aero` refuses it by name.
650/// - With `include_children`, the parts attached to the component have no drag of their own.
651/// - On a part inside the body (an inner tube, a ring, a mass) it does nothing, as such a part
652///   has no drag.
653/// - On a stage, it is added to the rocket's drag; with `include_children`, it replaces the
654///   drag of everything in the stage.
655///
656/// [adr-167]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0167-a-part-s-drag-override-as-openrocket-flies-it.md
657#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
658#[serde(deny_unknown_fields)]
659pub struct DragOverride {
660    /// The zero-lift drag coefficient, on the rocket's reference area, per instance. Zero is a
661    /// value: no drag at all.
662    pub coefficient: f64,
663    /// Whether the parts attached to the component (or everything in the stage) lose their own
664    /// drag too.
665    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
666    pub include_children: bool,
667}
668
669/// An inertia tensor about the center of mass in body axes, kg·m². The off-diagonal entries are
670/// the tensor's, `I_xy = −∫ x y dm` ([`crate::mass`]); they default to zero.
671#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
672#[serde(deny_unknown_fields)]
673pub struct InertiaOverride {
674    /// `I_xx`, kg·m².
675    pub xx_kg_m2: f64,
676    /// `I_yy`, kg·m².
677    pub yy_kg_m2: f64,
678    /// `I_zz`, about the rocket's axis, kg·m².
679    pub zz_kg_m2: f64,
680    /// `I_xy`, kg·m².
681    #[serde(default)]
682    pub xy_kg_m2: f64,
683    /// `I_xz`, kg·m².
684    #[serde(default)]
685    pub xz_kg_m2: f64,
686    /// `I_yz`, kg·m².
687    #[serde(default)]
688    pub yz_kg_m2: f64,
689}
690
691impl InertiaOverride {
692    /// A tensor symmetric about the body axis: `diag(I_t, I_t, I_a)`.
693    pub fn axisymmetric(axial_kg_m2: f64, transverse_kg_m2: f64) -> Self {
694        Self {
695            xx_kg_m2: transverse_kg_m2,
696            yy_kg_m2: transverse_kg_m2,
697            zz_kg_m2: axial_kg_m2,
698            xy_kg_m2: 0.0,
699            xz_kg_m2: 0.0,
700            yz_kg_m2: 0.0,
701        }
702    }
703
704    /// The tensor.
705    pub fn tensor(&self) -> DMat3 {
706        DMat3::from_cols(
707            DVec3::new(self.xx_kg_m2, self.xy_kg_m2, self.xz_kg_m2),
708            DVec3::new(self.xy_kg_m2, self.yy_kg_m2, self.yz_kg_m2),
709            DVec3::new(self.xz_kg_m2, self.yz_kg_m2, self.zz_kg_m2),
710        )
711    }
712}
713
714impl Overrides {
715    /// Whether the center of mass is overridden, along the axis or off it.
716    pub fn sets_center(&self) -> bool {
717        self.cg_aft_m.is_some() || self.cg_xy_m.is_some()
718    }
719
720    /// Whether the center of mass is moved along the axis (`cg_aft_m`).
721    pub fn sets_axial_center(&self) -> bool {
722        self.cg_aft_m.is_some()
723    }
724
725    /// Whether nothing is overridden.
726    pub fn is_empty(&self) -> bool {
727        self.mass_kg.is_none()
728            && self.cg_aft_m.is_none()
729            && self.cg_xy_m.is_none()
730            && self.inertia.is_none()
731    }
732
733    /// Applies the overrides to `mass`, measuring a center-of-mass override from station
734    /// `fore_station_m`.
735    ///
736    /// # Errors
737    ///
738    /// [`DesignError::Domain`] for a negative or non-finite mass or a non-finite center, and
739    /// [`DesignError::UnphysicalInertia`] when the result is not a real body
740    /// ([`MassProperties::validate`]).
741    pub fn apply(
742        &self,
743        mass: MassProperties,
744        fore_station_m: f64,
745    ) -> Result<MassProperties, DesignError> {
746        if self.is_empty() {
747            return Ok(mass);
748        }
749        let mut out = mass;
750        if let Some(m) = self.mass_kg {
751            check_dimension("mass override (kg)", m, true)?;
752            out = if out.mass_kg > 0.0 {
753                out.scaled(m / out.mass_kg)
754            } else {
755                MassProperties::point(m, out.cg_m)
756            };
757        }
758        if let Some(aft) = self.cg_aft_m {
759            if !aft.is_finite() {
760                return Err(DesignError::Domain {
761                    what: "center-of-mass override (m)",
762                    value: aft,
763                });
764            }
765            out.cg_m.z = -(fore_station_m + aft);
766        }
767        if let Some([x, y]) = self.cg_xy_m {
768            for value in [x, y] {
769                if !value.is_finite() {
770                    return Err(DesignError::Domain {
771                        what: "off-axis center-of-mass override (m)",
772                        value,
773                    });
774                }
775            }
776            out.cg_m.x = x;
777            out.cg_m.y = y;
778        }
779        if let Some(inertia) = self.inertia {
780            out.inertia_kg_m2 = inertia.tensor();
781        }
782        out.validate()?;
783        Ok(out)
784    }
785
786    /// Applies the overrides to a stage with its parts left where they are
787    /// ([`StageOverrideRule::PartsInPlace`]), measuring a center-of-mass override from station
788    /// `fore_station_m`. `whole` is the stage before its overrides; `placed` is the part of it
789    /// that has a place of its own, `whole` but for a mass that sits wherever the stage's center
790    /// is (an [`AddedMass`] with no station).
791    ///
792    /// The mass and the center are what [`apply`](Self::apply) gives `whole`. The tensor about
793    /// that center `c` is `placed`'s about it, by the parallel-axis theorem, with `placed`'s mass
794    /// `m_p` and center `x_p`: `I = I_p + m_p ((d·d) 1 − d dᵀ)`, `d = x_p − c`. The rest of the
795    /// mass, and whatever mass a mass override adds or takes away, sits at `c` and adds nothing
796    /// to it. A stated inertia replaces the tensor, and a mass of zero leaves none.
797    ///
798    /// # Errors
799    ///
800    /// As [`apply`](Self::apply).
801    pub(crate) fn apply_with_parts_in_place(
802        &self,
803        whole: MassProperties,
804        placed: MassProperties,
805        fore_station_m: f64,
806    ) -> Result<MassProperties, DesignError> {
807        let mut out = self.apply(whole, fore_station_m)?;
808        if self.inertia.is_none() {
809            out.inertia_kg_m2 = if out.mass_kg > 0.0 {
810                placed.inertia_about(out.cg_m)
811            } else {
812                DMat3::ZERO
813            };
814            out.validate()?;
815        }
816        Ok(out)
817    }
818}
819
820/// How a stage's [`Overrides`] set its inertia. Both rules give the stage the overrides' mass and
821/// center; they differ in where the stage's parts are taken to be, and so in the inertia.
822///
823/// With the parts' mass `m_p`, center `x_p` and inertia `I_p` about it, a mass override `m′` and
824/// a center override `c`, an [`AddedMass`] at a station counted among the parts (one with no
825/// station is too under `Rescaled`, and sits at `c` under `PartsInPlace`):
826///
827/// | | Rescaled | Parts in place |
828/// |---|---|---|
829/// | mass override alone | `I_p m′/m_p` | `I_p` |
830/// | center override alone | `I_p` | `I_p + m_p ((d·d) 1 − d dᵀ)`, `d = x_p − c` |
831/// | both | `I_p m′/m_p` | `I_p + m_p ((d·d) 1 − d dᵀ)` |
832///
833/// An inertia override replaces the tensor under either rule. The two agree on a stage with no
834/// override and on an override that changes neither the mass nor the center.
835///
836/// Neither rule is measured on a flying rocket: a stage's overrides say what it weighs and where
837/// it balances, not where the mass the parts don't account for sits. `Rescaled` puts it where the
838/// parts' mass is; `PartsInPlace` puts it at the stage's center and leaves each part where the
839/// design puts it. The decision record that added the second rule weighs the two
840/// ([ADR-340][adr-340]).
841///
842/// [adr-340]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0340-a-stage-s-overrides-leave-its-parts-in-place-as-openrocket-weighs-them.md
843#[derive(
844    Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
845)]
846#[serde(rename_all = "snake_case")]
847#[non_exhaustive]
848pub enum StageOverrideRule {
849    /// The stage's parts, with its added mass, are one body the overrides rescale and move
850    /// ([`Overrides::apply`]): a mass override scales the inertia with the mass, and a center
851    /// override moves the body whole, its inertia about its center unchanged. The default, and
852    /// `hpr-design`'s rule for a part's overrides too ([ADR-061][adr-061]).
853    ///
854    /// [adr-061]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0061-what-a-ork-leaves-unsaid-read-as-openrocket.md
855    #[default]
856    Rescaled,
857    /// The parts stay where the design puts them (`Overrides::apply_with_parts_in_place`): the
858    /// stage's inertia is its parts' about the stage's center, and the mass a mass override adds
859    /// or takes away sits at that center. This is how OpenRocket 24.12 weighs a single stage's
860    /// overrides that cover its parts, measured on probe designs (`validation/oracles/openrocket/`);
861    /// on the lower of two stages OpenRocket's sum is below the parts' inertia about the stage's
862    /// center. The `.ork` reader gives it to every stage with such an override, on the axis
863    /// ([ADR-340][adr-340]) or parallel, whose pods OpenRocket leaves in place the same way
864    /// ([the record that measured a parallel stage][adr-341]).
865    ///
866    /// [adr-340]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0340-a-stage-s-overrides-leave-its-parts-in-place-as-openrocket-weighs-them.md
867    /// [adr-341]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0341-m2-3d8-in-five-a-parallel-stage-s-added-mass-first.md
868    PartsInPlace,
869}
870
871impl StageOverrideRule {
872    /// Whether this is the default rule, [`Rescaled`](Self::Rescaled).
873    pub fn is_rescaled(&self) -> bool {
874        *self == Self::Rescaled
875    }
876
877    /// A stage whose parts weigh `parts`, with `added_mass` added to them and then `overrides`
878    /// applied by this rule, stations measured from the stage's forward end `fore_station_m`.
879    ///
880    /// # Errors
881    ///
882    /// As [`AddedMass::add_to`] and [`Overrides::apply`].
883    pub fn weigh(
884        self,
885        parts: MassProperties,
886        added_mass: Option<AddedMass>,
887        overrides: &Overrides,
888        fore_station_m: f64,
889    ) -> Result<MassProperties, DesignError> {
890        let whole = match added_mass {
891            Some(added) => added.add_to(parts, fore_station_m)?,
892            None => parts,
893        };
894        if overrides.is_empty() {
895            return Ok(whole);
896        }
897        match self {
898            Self::Rescaled => overrides.apply(whole, fore_station_m),
899            Self::PartsInPlace => {
900                // An added mass at a station has a place of its own; one with none sits at the
901                // stage's center, wherever the overrides put it, as OpenRocket 24.12 has it
902                // beside a center override that covers the parts (ADR-340).
903                let placed = match added_mass {
904                    Some(added) if added.cg_aft_m.is_some() => whole,
905                    _ => parts,
906                };
907                overrides.apply_with_parts_in_place(whole, placed, fore_station_m)
908            }
909        }
910    }
911}
912
913/// Mass a stage carries beyond what its parts weigh, such as glue and paint weighed on the
914/// finished rocket: a point mass added to the stage's parts, motors not counted.
915///
916/// With parts of mass `m_p` whose center of mass is at station `x_p`, and an added mass `m_a`:
917///
918/// - **No station** (`cg_aft_m` is `None`): the point sits at the parts' center of mass. The stage
919///   weighs `m_p + m_a`; its center and its inertia about that center are the parts'.
920/// - **A station** `s` aft of the stage's forward end `x_0`: the point sits at `x_a = x_0 + s`
921///   along the axis, as far off the axis as the parts' center of mass is: on it when that center
922///   is, as on any rocket that is the same all the way round, and when the parts weigh nothing.
923///   The stage weighs `m_p + m_a`, its center is at
924///   `(m_p x_p + m_a x_a) / (m_p + m_a)`, and its inertia about that center is the parts' and the
925///   point's by the parallel-axis theorem ([`MassProperties::combine`]).
926///
927/// The stage's [`Overrides`] apply afterward, to the parts and the added mass together.
928///
929/// This is how OpenRocket 24.12 weighs a stage's mass override that doesn't cover the stage's
930/// parts (`<overridesubcomponentsmass>false</overridesubcomponentsmass>`, or no flag written). Its
931/// user guide says such a value "is added to the calculated value" ([Overrides and Surface
932/// Finish][guide]); where the mass goes is measured on probe designs, which hold this rule's mass,
933/// center and inertia to OpenRocket's structure ([the decision record][adr-335]): at the center of the stage's
934/// own parts, or at the stage's center of gravity override when that doesn't cover the parts
935/// either. A motor aboard doesn't move it in OpenRocket, and a [`Layout`] holds no motor.
936///
937/// **A parallel stage's** added mass is one point for the whole set of pods, not one for each:
938/// with no station at the pods' center, and with one that far aft of the parallel stage's
939/// forward end, as far off the axis as the pods' center is. That is OpenRocket 24.12's too,
940/// measured with three boosters and with one ([the decision record][adr-341]).
941///
942/// **The stage a parallel stage hangs on** can carry an added mass at a station: a point among
943/// that stage's own parts. [`Rocket::layout`] refuses one there with no station, and one at a
944/// station beside a parallel stage of one pod off the axis. OpenRocket weighs such a stage with
945/// what hangs on it. With no station its point sits at the center of the stage and its pods
946/// together, and moves when the pods drop. At a station beside one pod off the axis it sits as
947/// far off the axis as that center, and on the axis once the pod is gone. A stage here is one
948/// body that keeps its center.
949///
950/// An added mass of zero changes nothing. One above zero with no station, on a stage whose parts
951/// weigh nothing, has no place to sit, and [`Rocket::layout`] refuses it.
952///
953/// [guide]: https://openrocket.readthedocs.io/en/latest/user_guide/overrides_and_surface_finish.html
954/// [adr-335]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0335-a-stage-s-added-mass-as-openrocket-weighs-it.md
955/// [adr-341]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0341-m2-3d8-in-five-a-parallel-stage-s-added-mass-first.md
956#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
957#[serde(deny_unknown_fields)]
958pub struct AddedMass {
959    /// The mass added, kg.
960    pub mass_kg: f64,
961    /// How far aft of the stage's forward end it sits, m, as far off the axis as the center of
962    /// mass of the stage's parts is: on the axis when that center is. `None` puts it at that
963    /// center.
964    #[serde(default, skip_serializing_if = "Option::is_none")]
965    pub cg_aft_m: Option<f64>,
966}
967
968impl AddedMass {
969    /// `parts` with this mass added, a station measured from `fore_station_m`.
970    ///
971    /// # Errors
972    ///
973    /// [`DesignError::Domain`] for a negative or non-finite mass, a non-finite station, or a mass
974    /// with no station added to parts that weigh nothing.
975    pub fn add_to(
976        &self,
977        parts: MassProperties,
978        fore_station_m: f64,
979    ) -> Result<MassProperties, DesignError> {
980        check_dimension("added mass (kg)", self.mass_kg, true)?;
981        if let Some(aft) = self.cg_aft_m
982            && !aft.is_finite()
983        {
984            return Err(DesignError::Domain {
985                what: "added mass's station (m)",
986                value: aft,
987            });
988        }
989        if self.mass_kg == 0.0 {
990            return Ok(parts);
991        }
992        let at = match self.cg_aft_m {
993            // The station moves the point along the axis only, as a stage's center override
994            // does ([`Overrides::apply`]): it stays as far off the axis as the parts' center is,
995            // which is where OpenRocket 24.12 has it on a stage with one pod (ADR-335).
996            Some(aft) if parts.mass_kg > 0.0 => {
997                DVec3::new(parts.cg_m.x, parts.cg_m.y, -(fore_station_m + aft))
998            }
999            Some(aft) => DVec3::new(0.0, 0.0, -(fore_station_m + aft)),
1000            // Weightless parts have no center of mass for the point to sit at. (`combine` gives
1001            // them the average of their places, which is no one's reading of where glue goes.)
1002            None if parts.mass_kg > 0.0 => parts.cg_m,
1003            None => {
1004                return Err(DesignError::Domain {
1005                    what: "added mass with no station, on parts that weigh nothing (kg)",
1006                    value: self.mass_kg,
1007                });
1008            }
1009        };
1010        let out = MassProperties::combine(&[parts, MassProperties::point(self.mass_kg, at)]);
1011        out.validate()?;
1012        Ok(out)
1013    }
1014}
1015
1016/// How the reference diameter (for aerodynamic coefficients) is chosen.
1017#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
1018#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1019#[non_exhaustive]
1020pub enum ReferenceDiameter {
1021    /// The widest body component (nose cone, body tube or transition) in any stage. Internal
1022    /// parts, shoulders, fins, tube fins, lugs and rail buttons don't count.
1023    Maximum {},
1024    /// The base of the first nose cone.
1025    NoseBase {},
1026    /// A given diameter.
1027    Custom {
1028        /// Diameter, m.
1029        diameter_m: f64,
1030    },
1031}
1032
1033impl Default for ReferenceDiameter {
1034    fn default() -> Self {
1035        Self::Maximum {}
1036    }
1037}
1038
1039/// A component resolved into place.
1040#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1041pub struct PlacedComponent {
1042    /// The component's id.
1043    pub id: String,
1044    /// Index of its stage in [`Layout::stages`].
1045    pub stage: usize,
1046    /// Index of its parent in [`Layout::components`]; `None` for a body component of the airframe
1047    /// (a pod's body components have their pod set as parent).
1048    pub parent: Option<usize>,
1049    /// The part with every automatic dimension filled in.
1050    pub part: Part,
1051    /// Station of its forward end (the start of its axial extent), m aft of the nose tip.
1052    pub fore_station_m: f64,
1053    /// Axial extent ([`Component::length_m`]: a pod set's is its pod's), m.
1054    pub length_m: f64,
1055    /// The outer surface's finish ([`Component::finish`], with the default filled in).
1056    #[serde(default)]
1057    pub finish: Finish,
1058    /// For an external attachment, the radius of the body tube it sits on, m.
1059    pub body_radius_m: Option<f64>,
1060    /// Its motor mount, if it is one.
1061    pub motor_mount: Option<MotorMount>,
1062    /// Its own mass properties in body axes, after overrides that cover it alone.
1063    pub own: MassProperties,
1064    /// It with everything attached to it, after every override that applies within.
1065    pub with_children: MassProperties,
1066    /// Whether its own overrides move its center of mass along the axis (`cg_aft_m`). Written
1067    /// before the move to US spelling as `centre_overridden`, which is still read and never written.
1068    #[serde(default, alias = "centre_overridden")]
1069    pub center_overridden: bool,
1070    /// Where the copies of it sit, each a [`Placement`] of it from where it is written: one
1071    /// [`Placement::HERE`] for a part in no cluster or pod, one per tube for a part inside a
1072    /// clustered inner tube ([`InnerTube::cluster_m`](crate::InnerTube::cluster_m)), and one per
1073    /// pod, turned with it, for a part in a pod ([`PodSet::pods`]); nested, every combination.
1074    /// [`Self::own`] and [`Self::with_children`] count every copy. A clustered tube's own tubes are
1075    /// its part's. An empty list is no copy: the part weighs nothing and a motor in it is not
1076    /// placed.
1077    #[serde(default = "one_copy")]
1078    pub copies: Vec<Placement>,
1079    /// The drag coefficient the component states ([`Component::drag_override`]).
1080    #[serde(default, skip_serializing_if = "Option::is_none")]
1081    pub drag_override: Option<DragOverride>,
1082}
1083
1084/// One copy, where it is written.
1085fn one_copy() -> Vec<Placement> {
1086    vec![Placement::HERE]
1087}
1088
1089impl PlacedComponent {
1090    /// Station of the aft end of its axial extent, m.
1091    pub fn aft_station_m(&self) -> f64 {
1092        self.fore_station_m + self.length_m
1093    }
1094
1095    /// Where the copies of what it holds sit, from where that is written: for a clustered inner
1096    /// tube, every tube of every copy of it; for a pod set, every pod of every copy of it; for any
1097    /// other part, its own copies. A motor in a clustered mount, or in a pod, is one motor per
1098    /// place.
1099    ///
1100    /// # Errors
1101    ///
1102    /// [`DesignError::Domain`] for a cluster offset that is not finite, or a pod set's errors from
1103    /// [`PodSet::pods`].
1104    pub fn contents_copies(&self) -> Result<Vec<Placement>, DesignError> {
1105        let repeats = repeats(&self.part)?;
1106        Ok(self
1107            .copies
1108            .iter()
1109            .flat_map(|copy| repeats.iter().map(move |inner| copy.after(inner)))
1110            .collect())
1111    }
1112}
1113
1114/// Where what `part` holds is repeated, from where one copy of `part` is written: a cluster's
1115/// tubes, a pod set's pods, and one place for any other part.
1116fn repeats(part: &Part) -> Result<Vec<Placement>, DesignError> {
1117    match part {
1118        Part::InnerTube(tube) => Ok(tube.tubes_m()?.into_iter().map(Placement::moved).collect()),
1119        Part::PodSet(pods) => pods.pods(),
1120        _ => Ok(one_copy()),
1121    }
1122}
1123
1124/// A stage resolved into place.
1125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1126pub struct PlacedStage {
1127    /// The stage's id.
1128    pub id: String,
1129    /// Station of its forward end, m.
1130    pub fore_station_m: f64,
1131    /// Station of its aft end, m.
1132    pub aft_station_m: f64,
1133    /// Its mass properties in body axes, without motors, after its added mass and its overrides.
1134    pub mass: MassProperties,
1135    /// Whether the stage's own overrides move its center of mass along the axis (`cg_aft_m`), or
1136    /// its added mass sits at a station ([`AddedMass::cg_aft_m`]).
1137    /// Written before the move to US spelling as `centre_overridden`, which is still read and never written.
1138    #[serde(default, alias = "centre_overridden")]
1139    pub center_overridden: bool,
1140    /// The drag coefficient the stage states ([`Stage::drag_override`]).
1141    #[serde(default, skip_serializing_if = "Option::is_none")]
1142    pub drag_override: Option<DragOverride>,
1143    /// For a parallel stage ([`Stage::parallel`]), the index of the stage whose body tube it hangs
1144    /// on; `None` for a stage on the axis. Its stations are its pods'.
1145    #[serde(default, skip_serializing_if = "Option::is_none")]
1146    pub hung_on: Option<usize>,
1147}
1148
1149/// Each stage's masses before its overrides, as [`Rocket::layout`] combines them, and where it
1150/// starts and ends: what a layout's stages are made from.
1151#[derive(Debug, Clone, PartialEq)]
1152pub(crate) struct StageMasses {
1153    /// Each stage's top-level components' masses, with their children, fore to aft.
1154    masses: Vec<Vec<MassProperties>>,
1155    /// Each stage's fore and aft stations, m.
1156    ends: Vec<Option<(f64, f64)>>,
1157    /// The rocket's length, m.
1158    length_m: f64,
1159}
1160
1161/// A design resolved into placed parts, with its structural mass properties (no motors).
1162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1163pub struct Layout {
1164    /// Every component, depth first: each body component followed by its attached parts.
1165    pub components: Vec<PlacedComponent>,
1166    /// The stages, forward to aft.
1167    pub stages: Vec<PlacedStage>,
1168    /// Length from the nose tip to the aft end of the airframe's last body component, m. Pods that
1169    /// run past it don't count.
1170    pub length_m: f64,
1171    /// Reference diameter, m.
1172    pub reference_diameter_m: f64,
1173    /// Every stage together, without motors.
1174    pub structure: MassProperties,
1175}
1176
1177impl Layout {
1178    /// The component with id `id`, and its index.
1179    pub fn find(&self, id: &str) -> Option<(usize, &PlacedComponent)> {
1180        self.components.iter().enumerate().find(|(_, c)| c.id == id)
1181    }
1182
1183    /// The airframe's body components, forward to aft: not a pod's.
1184    pub fn body(&self) -> impl Iterator<Item = &PlacedComponent> {
1185        self.components.iter().filter(|c| c.parent.is_none())
1186    }
1187
1188    /// The index of the pod set that component `index` is in, if any: the nearest pod set among
1189    /// its parents, never the component itself. The walk takes at most one step per component,
1190    /// so a layout whose parents loop, which [`Layout`]'s own builder never makes, ends it.
1191    pub fn pod_set_of(&self, index: usize) -> Option<usize> {
1192        let mut parent = self.components.get(index)?.parent;
1193        for _ in 0..self.components.len() {
1194            let at = parent?;
1195            let component = self.components.get(at)?;
1196            if matches!(component.part, Part::PodSet(_)) {
1197                return Some(at);
1198            }
1199            parent = component.parent;
1200        }
1201        None
1202    }
1203
1204    /// The pod sets that hold a motor mount, as [`Self::pod_set_of`] finds a mount's, each once, in
1205    /// the order their first mount comes in the layout. A motor's place in this list says which
1206    /// pod set's bases take its area under power.
1207    pub fn motor_pod_sets(&self) -> Vec<usize> {
1208        let mut sets = Vec::new();
1209        for (index, component) in self.components.iter().enumerate() {
1210            if component.motor_mount.is_none() {
1211                continue;
1212            }
1213            if let Some(set) = self.pod_set_of(index)
1214                && !sets.contains(&set)
1215            {
1216                sets.push(set);
1217            }
1218        }
1219        sets
1220    }
1221
1222    /// Reference area `π d²/4`, m².
1223    pub fn reference_area_m2(&self) -> f64 {
1224        0.25 * std::f64::consts::PI * self.reference_diameter_m * self.reference_diameter_m
1225    }
1226}
1227
1228/// An automatic body radius that has nothing to take: where it is, and which radius
1229/// ([`Rocket::unresolvable_body_radii`]).
1230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1231pub struct UnresolvableRadius {
1232    /// Index of the component's stage in [`Rocket::stages`].
1233    pub stage: usize,
1234    /// Index of the component in that stage's [`Stage::components`].
1235    pub component: usize,
1236    /// The component's id.
1237    pub id: String,
1238    /// Which of its radii: [`AutoDimension::BaseRadius`], [`AutoDimension::OuterRadius`],
1239    /// [`AutoDimension::ForeRadius`] or [`AutoDimension::AftRadius`].
1240    pub dimension: AutoDimension,
1241}
1242
1243impl Rocket {
1244    /// Resolves the tree: checks its structure, fills in automatic dimensions, places every part,
1245    /// and computes the mass properties with overrides.
1246    ///
1247    /// # Errors
1248    ///
1249    /// - [`DesignError::DuplicateId`] for an empty or repeated stage or component id.
1250    /// - [`DesignError::Tree`] for a rocket with no stages, an empty stage, a part in the wrong
1251    ///   place (an attached part in a stage's list, a body component attached anywhere but in a pod
1252    ///   set, anything else in a pod set, fins or pods on anything but a body tube, a pod set in a
1253    ///   pod, children under anything but a body component, inner tube or pod set), a pod set with
1254    ///   an override that doesn't cover its pods, an added mass on the stage a parallel stage
1255    ///   hangs on that has no station or sits beside one pod off the axis, a missing or
1256    ///   unexpected position, an automatic dimension that doesn't apply or can't be resolved, or a
1257    ///   motor mount on anything but a body tube or inner tube.
1258    /// - [`DesignError::Domain`] for a pod set of no pods or more than [`PodSet::MAX_COUNT`], a
1259    ///   radial offset or angle out of range, or a body component of no length in a stage.
1260    /// - Any part's geometry, material or numerical error, a custom finish's negative or
1261    ///   non-finite roughness, and override errors.
1262    pub fn layout(&self) -> Result<Layout, DesignError> {
1263        let (components, masses) = self.placed_components()?;
1264        self.staged_layout(components, &masses)
1265    }
1266
1267    /// The body components placed, with their children, and each stage's masses before its
1268    /// overrides: all of [`Rocket::layout`] but the stages.
1269    pub(crate) fn placed_components(
1270        &self,
1271    ) -> Result<(Vec<PlacedComponent>, StageMasses), DesignError> {
1272        if self.stages.is_empty() {
1273            return Err(DesignError::Tree {
1274                id: self.name.clone(),
1275                message: "a rocket needs at least one stage".to_owned(),
1276            });
1277        }
1278        let mut ids = BTreeSet::new();
1279        for stage in &self.stages {
1280            if stage.components.is_empty() {
1281                return Err(tree(&stage.id, "a stage needs at least one body component"));
1282            }
1283            if stage.parallel.is_some() {
1284                // Checked below as the pod set it is laid out as, under the stage's own id.
1285                continue;
1286            }
1287            unique(&mut ids, &stage.id)?;
1288            for component in &stage.components {
1289                check_node(&mut ids, component, None, 0, false)?;
1290            }
1291        }
1292        let mut hung = Hung::default();
1293        for ((k, stage), carrier) in self.stages.iter().enumerate().zip(self.carriers()?) {
1294            let (Some(parallel), Some(carrier)) = (&stage.parallel, carrier) else {
1295                continue;
1296            };
1297            let on = &self.stages[carrier.stage].components[carrier.component];
1298            if matches!(parallel.position, Position::After { .. }) {
1299                return Err(tree(
1300                    &stage.id,
1301                    "a parallel stage is placed along the tube it hangs on, not after a sibling",
1302                ));
1303            }
1304            // A parallel stage's own added mass sits among its pods, and an added mass at a
1305            // station on the stage it hangs on sits at that station, whatever hangs there
1306            // ([`AddedMass`]). One with no station on the stage it hangs on has no fixed place:
1307            // OpenRocket 24.12 puts it at the center of that stage with what hangs on it, which
1308            // moves when the parallel stage drops (ADR-341).
1309            // An added mass of zero changes nothing, wherever it would sit.
1310            if let Some(added) = self.stages[carrier.stage]
1311                .added_mass
1312                .filter(|added| added.mass_kg != 0.0)
1313            {
1314                if added.cg_aft_m.is_none() {
1315                    return Err(tree(
1316                        &stage.id,
1317                        format!(
1318                            "a parallel stage hangs on `{}`, whose stage carries an added mass \
1319                             with no station. Where that mass sits once the parallel stage \
1320                             drops isn't modeled",
1321                            on.id
1322                        ),
1323                    ));
1324                }
1325                // One pod alone pulls the center off the axis, and OpenRocket 24.12 then puts
1326                // the added mass as far off the axis as the stage's center is with the pod
1327                // hanging on it, not with the stage's own parts alone (ADR-341).
1328                if parallel.pods.count == 1 && parallel.pods.radial_offset_m != 0.0 {
1329                    return Err(tree(
1330                        &stage.id,
1331                        format!(
1332                            "a parallel stage of one pod off the axis hangs on `{}`, whose stage \
1333                             carries an added mass. How far off the axis that mass sits once \
1334                             the parallel stage drops isn't modeled",
1335                            on.id
1336                        ),
1337                    ));
1338                }
1339            }
1340            // A mass override that covers what the tube holds, or the whole stage it is in, doesn't
1341            // say whether it covers the parallel stage too: OpenRocket's tree holds the stage
1342            // under the tube (ADR-171). OpenRocket 24.12 takes a stage's covering override as
1343            // the rocket's while the parallel stage hangs there and as the stage's once it is
1344            // gone (ADR-341), which one body for each stage can't give. No probe has measured a
1345            // tube's covering override there.
1346            if !self.stages[carrier.stage].overrides.is_empty()
1347                || (on.overrides_include_children && !on.overrides.is_empty())
1348            {
1349                return Err(tree(
1350                    &stage.id,
1351                    format!(
1352                        "a parallel stage hangs on `{}`, under a mass override that covers what \
1353                         the tube or its stage holds. That override doesn't say whether it covers \
1354                         the parallel stage",
1355                        on.id
1356                    ),
1357                ));
1358            }
1359            let pods = parallel_pods(stage, parallel);
1360            check_node(&mut ids, &pods, Some(&on.part), 1, false)?;
1361            hung.stages
1362                .entry(on.id.clone())
1363                .or_default()
1364                .push((k, pods));
1365        }
1366
1367        let nodes: Vec<(usize, &Component)> = self
1368            .stages
1369            .iter()
1370            .enumerate()
1371            .filter(|(_, stage)| stage.parallel.is_none())
1372            .flat_map(|(k, stage)| stage.components.iter().map(move |c| (k, c)))
1373            .collect();
1374        let mut parts: Vec<Part> = nodes.iter().map(|(_, c)| c.part.clone()).collect();
1375        let autos: Vec<&[AutoDimension]> = nodes.iter().map(|(_, c)| c.auto.as_slice()).collect();
1376        let ids: Vec<&str> = nodes.iter().map(|(_, c)| c.id.as_str()).collect();
1377        resolve_body_radii(&mut parts, &autos, &ids)?;
1378        resolve_shoulders(&mut parts, &autos, &ids)?;
1379
1380        let mut components = Vec::new();
1381        let mut stage_masses: Vec<Vec<MassProperties>> = vec![Vec::new(); self.stages.len()];
1382        let mut stage_ends: Vec<Option<(f64, f64)>> = vec![None; self.stages.len()];
1383        let mut station = 0.0;
1384        for ((stage, node), part) in nodes.iter().zip(parts) {
1385            let length = part.length_m();
1386            check_dimension("body component length", length, false)
1387                .map_err(|e| within(&node.id, e))?;
1388            let placed = place(&part, None, station, &node.id)?;
1389            let index = components.len();
1390            components.push(PlacedComponent {
1391                id: node.id.clone(),
1392                stage: *stage,
1393                parent: None,
1394                part,
1395                fore_station_m: station,
1396                length_m: length,
1397                finish: node.finish.unwrap_or_default(),
1398                body_radius_m: None,
1399                motor_mount: node.motor_mount,
1400                own: placed,
1401                with_children: placed,
1402                center_overridden: node.overrides.sets_axial_center(),
1403                copies: one_copy(),
1404                drag_override: node.drag_override,
1405            });
1406            let with_children = finish(&mut components, index, node, &mut hung)?;
1407            stage_masses[*stage].push(with_children);
1408            let ends = stage_ends[*stage].get_or_insert((station, station));
1409            ends.1 = station + length;
1410            station += length;
1411        }
1412        for (k, mass, ends) in hung.placed {
1413            stage_masses[k].push(mass);
1414            stage_ends[k] = Some(ends);
1415        }
1416        Ok((
1417            components,
1418            StageMasses {
1419                masses: stage_masses,
1420                ends: stage_ends,
1421                length_m: station,
1422            },
1423        ))
1424    }
1425
1426    /// The layout of `components`, placed by [`Rocket::placed_components`] from this design or
1427    /// from one with the same stage components, with this design's stage overrides applied to
1428    /// `masses`: the rest of [`Rocket::layout`].
1429    pub(crate) fn staged_layout(
1430        &self,
1431        components: Vec<PlacedComponent>,
1432        masses: &StageMasses,
1433    ) -> Result<Layout, DesignError> {
1434        let mut stages = Vec::with_capacity(self.stages.len());
1435        let carriers = self.carriers()?;
1436        for ((stage, masses), ends) in self.stages.iter().zip(&masses.masses).zip(&masses.ends) {
1437            let (fore, aft) = ends.unwrap_or((0.0, 0.0));
1438            let parts = MassProperties::combine(masses);
1439            let mass = stage
1440                .override_rule
1441                .weigh(parts, stage.added_mass, &stage.overrides, fore)
1442                .map_err(|e| within(&stage.id, e))?;
1443            let hung_on = carriers[stages.len()].map(|carrier| carrier.stage);
1444            stages.push(PlacedStage {
1445                id: stage.id.clone(),
1446                fore_station_m: fore,
1447                aft_station_m: aft,
1448                mass,
1449                center_overridden: stage.overrides.sets_axial_center()
1450                    || stage
1451                        .added_mass
1452                        .is_some_and(|added| added.cg_aft_m.is_some()),
1453                drag_override: stage.drag_override,
1454                hung_on,
1455            });
1456        }
1457        let structure = MassProperties::combine(stages.iter().map(|s| &s.mass));
1458        let reference_diameter_m = self.reference_diameter_m(&components)?;
1459        Ok(Layout {
1460            components,
1461            stages,
1462            length_m: masses.length_m,
1463            reference_diameter_m,
1464            structure,
1465        })
1466    }
1467
1468    /// The automatic body radii that [`layout`](Self::layout) cannot resolve, forward to aft.
1469    ///
1470    /// These are the radii on a chain of automatic radii with no fixed radius anywhere along it:
1471    /// a nose cone whose base looks back at a tube that looks forward at it, or a stage of tubes
1472    /// that all say "automatic". Neighbors are followed by the rule each [`AutoDimension`]
1473    /// documents. `layout` refuses a design for which this list is not empty; what such a radius
1474    /// should be is not in the design, so an importer that knows its source program's convention
1475    /// fills them in first ([`fill_unresolvable_body_radii`](Self::fill_unresolvable_body_radii)).
1476    ///
1477    /// A parallel stage's body components are not listed: they take their radii from one another,
1478    /// as a pod's do, and `layout` refuses one it can't resolve.
1479    ///
1480    /// Only the body components' own radii are listed. An automatic shoulder with no body tube
1481    /// beside it, or an automatic dimension a part does not have, is refused by `layout` with its
1482    /// own error instead.
1483    pub fn unresolvable_body_radii(&self) -> Vec<UnresolvableRadius> {
1484        let nodes: Vec<(usize, usize, &Component)> = self
1485            .stages
1486            .iter()
1487            .enumerate()
1488            .filter(|(_, stage)| stage.parallel.is_none())
1489            .flat_map(|(k, stage)| {
1490                stage
1491                    .components
1492                    .iter()
1493                    .enumerate()
1494                    .map(move |(i, c)| (k, i, c))
1495            })
1496            .collect();
1497        let parts: Vec<&Part> = nodes.iter().map(|(_, _, c)| &c.part).collect();
1498        let autos: Vec<&[AutoDimension]> =
1499            nodes.iter().map(|(_, _, c)| c.auto.as_slice()).collect();
1500        let (fore, aft) = sweep_body_radii(&parts, &autos);
1501        let mut unresolvable = Vec::new();
1502        for (n, &(stage, component, node)) in nodes.iter().enumerate() {
1503            let mut add = |dimension| {
1504                unresolvable.push(UnresolvableRadius {
1505                    stage,
1506                    component,
1507                    id: node.id.clone(),
1508                    dimension,
1509                });
1510            };
1511            match node.part {
1512                Part::NoseCone(_) if aft[n].is_none() => add(AutoDimension::BaseRadius),
1513                Part::BodyTube(_) if aft[n].is_none() => add(AutoDimension::OuterRadius),
1514                Part::Transition(_) => {
1515                    if fore[n].is_none() {
1516                        add(AutoDimension::ForeRadius);
1517                    }
1518                    if aft[n].is_none() {
1519                        add(AutoDimension::AftRadius);
1520                    }
1521                }
1522                _ => {}
1523            }
1524        }
1525        unresolvable
1526    }
1527
1528    /// Gives every radius [`unresolvable_body_radii`](Self::unresolvable_body_radii) lists the
1529    /// fixed radius `radius_m`, drops its automatic mark, and returns what it filled.
1530    ///
1531    /// Every radius on such a chain is listed, so the whole chain takes the one radius. Radii the
1532    /// neighbor rule could already reach are left as they are and resolve as before. The design
1533    /// no longer records that the filled radii were automatic, which is the point: it now says
1534    /// what they are.
1535    pub fn fill_unresolvable_body_radii(&mut self, radius_m: f64) -> Vec<UnresolvableRadius> {
1536        let unresolvable = self.unresolvable_body_radii();
1537        for radius in &unresolvable {
1538            let component = &mut self.stages[radius.stage].components[radius.component];
1539            match (&mut component.part, radius.dimension) {
1540                (Part::NoseCone(p), AutoDimension::BaseRadius) => p.base_radius_m = radius_m,
1541                (Part::BodyTube(p), AutoDimension::OuterRadius) => p.outer_radius_m = radius_m,
1542                (Part::Transition(p), AutoDimension::ForeRadius) => p.fore_radius_m = radius_m,
1543                (Part::Transition(p), AutoDimension::AftRadius) => p.aft_radius_m = radius_m,
1544                // `unresolvable_body_radii` lists only the four pairings above.
1545                _ => continue,
1546            }
1547            component.auto.retain(|auto| *auto != radius.dimension);
1548        }
1549        unresolvable
1550    }
1551
1552    fn reference_diameter_m(&self, components: &[PlacedComponent]) -> Result<f64, DesignError> {
1553        let diameter = match self.reference_diameter {
1554            ReferenceDiameter::Maximum {} => {
1555                let mut widest = 0.0f64;
1556                for c in components.iter().filter(|c| c.parent.is_none()) {
1557                    if let Some(r) = c.part.max_radius_m()? {
1558                        widest = widest.max(r);
1559                    }
1560                }
1561                2.0 * widest
1562            }
1563            // The airframe's nose cone, not a pod's.
1564            ReferenceDiameter::NoseBase {} => components
1565                .iter()
1566                .filter(|c| c.parent.is_none())
1567                .find_map(|c| match &c.part {
1568                    Part::NoseCone(nose) => Some(2.0 * nose.base_radius_m),
1569                    _ => None,
1570                })
1571                .ok_or_else(|| {
1572                    tree(
1573                        &self.name,
1574                        "the reference diameter is the nose base, but there is no nose cone",
1575                    )
1576                })?,
1577            ReferenceDiameter::Custom { diameter_m } => diameter_m,
1578        };
1579        check_dimension("reference diameter (m)", diameter, false)?;
1580        Ok(diameter)
1581    }
1582}
1583
1584/// `error` in the stage or component `id`.
1585fn within(id: &str, error: DesignError) -> DesignError {
1586    DesignError::InComponent {
1587        id: id.to_owned(),
1588        source: Box::new(error),
1589    }
1590}
1591
1592/// How many levels a body component and the parts nested in it may span, the body component being
1593/// the first: inner tubes in inner tubes far beyond any real rocket, and shallow enough that
1594/// resolving never exhausts a small (wasm) stack.
1595pub const MAX_DEPTH: usize = 32;
1596
1597fn tree(id: &str, message: impl Into<String>) -> DesignError {
1598    DesignError::Tree {
1599        id: id.to_owned(),
1600        message: message.into(),
1601    }
1602}
1603
1604fn unique(ids: &mut BTreeSet<String>, id: &str) -> Result<(), DesignError> {
1605    if id.is_empty() || !ids.insert(id.to_owned()) {
1606        return Err(DesignError::DuplicateId(id.to_owned()));
1607    }
1608    Ok(())
1609}
1610
1611/// Checks a node's id, role, position, automatic dimensions and motor mount against where it sits,
1612/// and then its children. `parent` is `None` for a body component.
1613fn check_node(
1614    ids: &mut BTreeSet<String>,
1615    node: &Component,
1616    parent: Option<&Part>,
1617    depth: usize,
1618    in_pod: bool,
1619) -> Result<(), DesignError> {
1620    unique(ids, &node.id)?;
1621    if let Some(finish) = node.finish {
1622        finish.roughness_m().map_err(|e| within(&node.id, e))?;
1623    }
1624    if depth >= MAX_DEPTH {
1625        return Err(tree(
1626            &node.id,
1627            format!("components nest more than {MAX_DEPTH} deep"),
1628        ));
1629    }
1630    let kind = node.part.kind_name();
1631    match (parent, node.part.role()) {
1632        (None | Some(Part::PodSet(_)), Role::Body) => {
1633            if node.position.is_some() {
1634                return Err(tree(
1635                    &node.id,
1636                    "a body component stacks and takes no position",
1637                ));
1638            }
1639        }
1640        (Some(Part::PodSet(_)), _) => {
1641            return Err(tree(
1642                &node.id,
1643                format!("a pod holds body components; attach a {kind} to one of them"),
1644            ));
1645        }
1646        (None, _) => {
1647            return Err(tree(
1648                &node.id,
1649                format!("a {kind} can't be a body component; attach it to one"),
1650            ));
1651        }
1652        (Some(_), Role::Body) => {
1653            return Err(tree(
1654                &node.id,
1655                format!("a {kind} is a body component; list it in a stage"),
1656            ));
1657        }
1658        // A fin set may also sit on a nose cone or a transition, its root along the surface
1659        // (ADR-166; checked where it is placed).
1660        (Some(parent), Role::External)
1661            if !(matches!(parent, Part::BodyTube(_))
1662                || matches!(node.part, Part::FinSet(_))
1663                    && matches!(parent, Part::NoseCone(_) | Part::Transition(_))) =>
1664        {
1665            return Err(tree(
1666                &node.id,
1667                format!(
1668                    "a {kind} attaches to a body tube{}, not a {}",
1669                    if matches!(node.part, Part::FinSet(_)) {
1670                        ", a nose cone or a transition"
1671                    } else {
1672                        ""
1673                    },
1674                    parent.kind_name()
1675                ),
1676            ));
1677        }
1678        (Some(parent), Role::Internal)
1679            if !(parent.is_body() || matches!(parent, Part::InnerTube(_))) =>
1680        {
1681            return Err(tree(
1682                &node.id,
1683                format!("a {kind} can't go inside a {}", parent.kind_name()),
1684            ));
1685        }
1686        (Some(_), _) => {
1687            if node.position.is_none() {
1688                return Err(tree(&node.id, "an attached part needs a position"));
1689            }
1690        }
1691    }
1692    for auto in &node.auto {
1693        if !auto.applies_to(&node.part) {
1694            return Err(tree(
1695                &node.id,
1696                format!("a {kind} has no automatic {} dimension", auto.name()),
1697            ));
1698        }
1699    }
1700    if matches!(node.part, Part::PodSet(_)) {
1701        if in_pod {
1702            return Err(tree(&node.id, "a pod set can't hang from a pod"));
1703        }
1704        if !node.overrides.is_empty() && !node.overrides_include_children {
1705            return Err(tree(
1706                &node.id,
1707                "a pod set weighs nothing of its own, so an override on it must cover its pods \
1708                 (`overrides_include_children`)",
1709            ));
1710        }
1711    }
1712    if node.motor_mount.is_some() && !matches!(node.part, Part::BodyTube(_) | Part::InnerTube(_)) {
1713        return Err(tree(&node.id, format!("a {kind} can't be a motor mount")));
1714    }
1715    if !node.children.is_empty()
1716        && !(node.part.is_body() || matches!(node.part, Part::InnerTube(_) | Part::PodSet(_)))
1717    {
1718        return Err(tree(
1719            &node.id,
1720            format!("a {kind} can't have attached parts"),
1721        ));
1722    }
1723    for child in &node.children {
1724        let in_pod = in_pod || matches!(node.part, Part::PodSet(_));
1725        check_node(ids, child, Some(&node.part), depth + 1, in_pod)?;
1726    }
1727    Ok(())
1728}
1729
1730/// Fills in the body components' automatic outer radii from their neighbors, through every stage,
1731/// by [`sweep_body_radii`]'s rule; a radius the sweep leaves unknown is an error.
1732fn resolve_body_radii(
1733    parts: &mut [Part],
1734    autos: &[&[AutoDimension]],
1735    ids: &[&str],
1736) -> Result<(), DesignError> {
1737    let (fore, aft) = sweep_body_radii(parts, autos);
1738    for (i, part) in parts.iter_mut().enumerate() {
1739        let missing = || {
1740            tree(
1741                ids[i],
1742                "an automatic radius has no fixed radius among its neighbors to take",
1743            )
1744        };
1745        match part {
1746            Part::NoseCone(p) => p.base_radius_m = aft[i].ok_or_else(missing)?,
1747            Part::BodyTube(p) => p.outer_radius_m = aft[i].ok_or_else(missing)?,
1748            Part::Transition(p) => {
1749                p.fore_radius_m = fore[i].ok_or_else(missing)?;
1750                p.aft_radius_m = aft[i].ok_or_else(missing)?;
1751            }
1752            _ => {}
1753        }
1754    }
1755    Ok(())
1756}
1757
1758/// Each body component's forward and aft radius, following automatic radii to their sources;
1759/// `None` where a radius is automatic and nothing reaches it. `parts` are the body components,
1760/// forward to aft through every stage.
1761///
1762/// Each automatic radius has a source: a nose cone's base and a transition's aft radius take the
1763/// next component's forward radius; a body tube and a transition's forward radius take the previous
1764/// component's aft radius. Sources are followed until nothing changes. Then a body tube still
1765/// unresolved takes the next component's forward radius instead (the first one that can), and the
1766/// sweep repeats.
1767fn sweep_body_radii<P: std::borrow::Borrow<Part>>(
1768    parts: &[P],
1769    autos: &[&[AutoDimension]],
1770) -> (Vec<Option<f64>>, Vec<Option<f64>>) {
1771    let n = parts.len();
1772    let is_auto = |i: usize, a: AutoDimension| autos[i].contains(&a);
1773    let mut fore: Vec<Option<f64>> = Vec::with_capacity(n);
1774    let mut aft: Vec<Option<f64>> = Vec::with_capacity(n);
1775    for (i, part) in parts.iter().enumerate() {
1776        let (f, a) = match part.borrow() {
1777            Part::NoseCone(p) => (
1778                Some(0.0),
1779                (!is_auto(i, AutoDimension::BaseRadius)).then_some(p.base_radius_m),
1780            ),
1781            Part::BodyTube(p) => {
1782                let r = (!is_auto(i, AutoDimension::OuterRadius)).then_some(p.outer_radius_m);
1783                (r, r)
1784            }
1785            Part::Transition(p) => (
1786                (!is_auto(i, AutoDimension::ForeRadius)).then_some(p.fore_radius_m),
1787                (!is_auto(i, AutoDimension::AftRadius)).then_some(p.aft_radius_m),
1788            ),
1789            _ => (None, None),
1790        };
1791        fore.push(f);
1792        aft.push(a);
1793    }
1794    loop {
1795        let mut progress = false;
1796        for i in 0..n {
1797            let previous_aft = if i > 0 { aft[i - 1] } else { None };
1798            let next_fore = fore.get(i + 1).copied().flatten();
1799            match parts[i].borrow() {
1800                Part::NoseCone(_) => {
1801                    if aft[i].is_none()
1802                        && let Some(r) = next_fore
1803                    {
1804                        aft[i] = Some(r);
1805                        progress = true;
1806                    }
1807                }
1808                Part::BodyTube(_) => {
1809                    if fore[i].is_none()
1810                        && let Some(r) = previous_aft
1811                    {
1812                        fore[i] = Some(r);
1813                        aft[i] = Some(r);
1814                        progress = true;
1815                    }
1816                }
1817                Part::Transition(_) => {
1818                    if fore[i].is_none()
1819                        && let Some(r) = previous_aft
1820                    {
1821                        fore[i] = Some(r);
1822                        progress = true;
1823                    }
1824                    if aft[i].is_none()
1825                        && let Some(r) = next_fore
1826                    {
1827                        aft[i] = Some(r);
1828                        progress = true;
1829                    }
1830                }
1831                _ => {}
1832            }
1833        }
1834        if progress {
1835            continue;
1836        }
1837        let fallback = (0..n).find(|&i| {
1838            matches!(parts[i].borrow(), Part::BodyTube(_))
1839                && fore[i].is_none()
1840                && fore.get(i + 1).copied().flatten().is_some()
1841        });
1842        match fallback {
1843            Some(i) => {
1844                fore[i] = fore[i + 1];
1845                aft[i] = fore[i + 1];
1846            }
1847            None => break,
1848        }
1849    }
1850    (fore, aft)
1851}
1852
1853/// Fills in automatic shoulder radii from the adjoining body tubes' inner radii.
1854fn resolve_shoulders(
1855    parts: &mut [Part],
1856    autos: &[&[AutoDimension]],
1857    ids: &[&str],
1858) -> Result<(), DesignError> {
1859    let inner = |parts: &[Part], i: Option<usize>| -> Option<f64> {
1860        match i.and_then(|i| parts.get(i)) {
1861            Some(Part::BodyTube(t)) => Some(t.outer_radius_m - t.thickness_m),
1862            _ => None,
1863        }
1864    };
1865    for i in 0..parts.len() {
1866        let previous = inner(parts, i.checked_sub(1));
1867        let next = inner(parts, Some(i + 1));
1868        let fit = |shoulder: &mut Option<crate::parts::Shoulder>,
1869                   radius: Option<f64>,
1870                   which: &str|
1871         -> Result<(), DesignError> {
1872            let Some(shoulder) = shoulder else {
1873                return Err(tree(
1874                    ids[i],
1875                    format!("an automatic {which} shoulder radius needs a shoulder"),
1876                ));
1877            };
1878            shoulder.outer_radius_m = radius.ok_or_else(|| {
1879                tree(
1880                    ids[i],
1881                    format!("an automatic {which} shoulder radius needs a body tube there"),
1882                )
1883            })?;
1884            Ok(())
1885        };
1886        match &mut parts[i] {
1887            Part::NoseCone(p) if autos[i].contains(&AutoDimension::ShoulderRadius) => {
1888                fit(&mut p.shoulder, next, "aft")?;
1889            }
1890            Part::Transition(p) => {
1891                if autos[i].contains(&AutoDimension::ForeShoulderRadius) {
1892                    fit(&mut p.fore_shoulder, previous, "forward")?;
1893                }
1894                if autos[i].contains(&AutoDimension::AftShoulderRadius) {
1895                    fit(&mut p.aft_shoulder, next, "aft")?;
1896                }
1897            }
1898            _ => {}
1899        }
1900    }
1901    Ok(())
1902}
1903
1904/// A part's mass properties placed with its forward end at `fore_station_m`.
1905fn place(
1906    part: &Part,
1907    body_radius_m: Option<f64>,
1908    fore_station_m: f64,
1909    id: &str,
1910) -> Result<MassProperties, DesignError> {
1911    let mass = part
1912        .mass_properties(body_radius_m)
1913        .map_err(|e| within(id, e))?;
1914    Ok(mass.translated(DVec3::new(0.0, 0.0, -fore_station_m)))
1915}
1916
1917/// The body a mass override rescales: `mass` itself, but for a packed part under a mass override,
1918/// which becomes that mass as a solid cylinder of its packing. For a part that weighs something this
1919/// is the rescaling [`Overrides::apply`] does anyway; for one that weighs nothing it replaces the
1920/// point `apply` makes of any other weightless body. OpenRocket 24.12 does the
1921/// same: on probes of a parachute, a mass component and a shock cord each weighing nothing, its
1922/// roll inertia is the override's `m r²/2` over the packing's radius `r`, and its pitch inertia and
1923/// center are the cylinder's ([ADR-063][adr-063]). `fore_station_m` is the part's forward end.
1924///
1925/// [adr-063]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-063-packed-parts-read-and-weighed-as-openrocket-packs-them-2026-09-21
1926fn packed_for_override(
1927    part: &Part,
1928    overrides: &Overrides,
1929    mass: MassProperties,
1930    fore_station_m: f64,
1931) -> Result<MassProperties, DesignError> {
1932    match (overrides.mass_kg, part.packing()) {
1933        // A packed part of any mass is its packing's cylinder, so building the cylinder of `m′`
1934        // directly is what rescaling gives, and holds for a weightless (or subnormal) mass too.
1935        (Some(mass_kg), Some(packing)) => {
1936            check_dimension("mass override (kg)", mass_kg, true)?;
1937            Ok(packing
1938                .place(mass_kg)?
1939                .translated(DVec3::new(0.0, 0.0, -fore_station_m)))
1940        }
1941        _ => Ok(mass),
1942    }
1943}
1944
1945/// The parallel stages as [`finish`] places them: each as the pod set it is laid out as, under
1946/// the body tube it hangs on, and what each weighed and spanned once placed.
1947#[derive(Default)]
1948struct Hung {
1949    /// The parallel stages hung on each body tube, by the tube's id: each stage's index and its
1950    /// pod set.
1951    stages: BTreeMap<String, Vec<(usize, Component)>>,
1952    /// Each placed parallel stage's index, mass with its children, and fore and aft stations.
1953    placed: Vec<(usize, MassProperties, (f64, f64))>,
1954}
1955
1956/// The pod set parallel stage `stage` is laid out as: under the stage's id, at its position, its
1957/// body components the pods' stack. It carries no overrides of its own; the stage's apply to the
1958/// stage's mass ([`Rocket::staged_layout`]).
1959fn parallel_pods(stage: &Stage, parallel: &ParallelStage) -> Component {
1960    Component {
1961        id: stage.id.clone(),
1962        name: stage.name.clone(),
1963        part: Part::PodSet(parallel.pods.clone()),
1964        position: Some(parallel.position),
1965        auto: Vec::new(),
1966        motor_mount: None,
1967        finish: None,
1968        overrides: Overrides::default(),
1969        overrides_include_children: false,
1970        drag_override: None,
1971        children: stage.components.clone(),
1972    }
1973}
1974
1975/// Where a parallel stage hangs: the stage and the place in its component list of the body tube.
1976#[derive(Debug, Clone, Copy)]
1977struct Carrier {
1978    stage: usize,
1979    component: usize,
1980}
1981
1982impl Rocket {
1983    /// Where each stage hangs ([`ParallelStage::on`]): `None` for an axial stage. One pass, with
1984    /// the body tubes of the axial stages before each stage looked up by id.
1985    ///
1986    /// # Errors
1987    ///
1988    /// [`DesignError::Tree`] for a parallel stage whose tube is not a body tube among the body
1989    /// components of an axial stage before it.
1990    fn carriers(&self) -> Result<Vec<Option<Carrier>>, DesignError> {
1991        let mut tubes: BTreeMap<&str, Carrier> = BTreeMap::new();
1992        let mut carriers = Vec::with_capacity(self.stages.len());
1993        for (k, stage) in self.stages.iter().enumerate() {
1994            let Some(parallel) = &stage.parallel else {
1995                for (component, c) in stage.components.iter().enumerate() {
1996                    if matches!(c.part, Part::BodyTube(_)) {
1997                        tubes.entry(&c.id).or_insert(Carrier {
1998                            stage: k,
1999                            component,
2000                        });
2001                    }
2002                }
2003                carriers.push(None);
2004                continue;
2005            };
2006            let carrier = tubes.get(parallel.on.as_str()).copied().ok_or_else(|| {
2007                tree(
2008                    &stage.id,
2009                    format!(
2010                        "a parallel stage hangs on a body tube of an axial stage before it, and \
2011                         `{}` is none",
2012                        parallel.on
2013                    ),
2014                )
2015            })?;
2016            carriers.push(Some(carrier));
2017        }
2018        Ok(carriers)
2019    }
2020}
2021
2022/// Places a component's children, applies its overrides, and returns it with its children.
2023///
2024/// Masses are worked one copy at a time: a part inside a cluster is weighed, and its overrides
2025/// applied, as one part in one tube, and only then repeated in every tube ([ADR-075][adr-075]).
2026/// So an override on an engine block in a cluster is each block's, and an override on the cluster
2027/// tube itself is the whole cluster's, since that part is all its tubes. What is stored in
2028/// `components[index]` is every copy; what is returned is one copy of the part with its children.
2029///
2030/// [adr-075]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-075-a-cluster-is-one-tube-repeated-and-a-motor-in-it-one-motor-per-tube-2026-09-25
2031fn finish(
2032    components: &mut Vec<PlacedComponent>,
2033    index: usize,
2034    node: &Component,
2035    hung: &mut Hung,
2036) -> Result<MassProperties, DesignError> {
2037    // The parallel stages that hang on this part come after its own children, each tagged with its
2038    // own stage (`Some(k)`), its mass that stage's rather than this part's.
2039    let hanging: Vec<(usize, Component)> = hung.stages.get(&node.id).cloned().unwrap_or_default();
2040    let children: Vec<(&Component, Option<usize>)> = node
2041        .children
2042        .iter()
2043        .map(|child| (child, None))
2044        .chain(hanging.iter().map(|(k, pods)| (pods, Some(*k))))
2045        .collect();
2046    let parent = &components[index];
2047    let (p_fore, p_length, stage) = (parent.fore_station_m, parent.length_m, parent.stage);
2048    let (p_kind, p_inner) = (parent.part.kind_name(), parent.part.inner_radius_m());
2049    let p_axis = parent.part.axis_offset_m();
2050    // A pod set's children are its pod's body components: they stack along the pod.
2051    let pod = matches!(parent.part, Part::PodSet(_));
2052    // What this part holds is repeated in each of its tubes when it is a cluster, and in each pod
2053    // when it is a pod set: `p_tubes` for one copy of this part, `p_contents` for all of them.
2054    let p_tubes = repeats(&parent.part).map_err(|e| within(&node.id, e))?;
2055    let p_copies = parent.copies.clone();
2056    let p_contents = parent.contents_copies().map_err(|e| within(&node.id, e))?;
2057    let p_tube_radius = match &parent.part {
2058        Part::BodyTube(tube) => Some(tube.outer_radius_m),
2059        _ => None,
2060    };
2061    // A nose cone's or transition's outer surface, which a fin set's root follows (ADR-166).
2062    let p_surface = match &parent.part {
2063        Part::NoseCone(nose) => Some(nose.profile()),
2064        Part::Transition(part) => Some(part.profile()),
2065        _ => None,
2066    }
2067    .transpose()
2068    .map_err(|e| within(&node.id, e))?;
2069    // A nose cone's or transition's bore narrows along it: its outer profile and its wall, when it
2070    // has one. A solid one has no bore.
2071    let shell = |wall: &Wall| match wall {
2072        Wall::Shell { thickness_m } => Some(*thickness_m),
2073        Wall::Filled {} => None,
2074    };
2075    let p_narrowing = match &parent.part {
2076        Part::NoseCone(nose) => shell(&nose.wall).map(|t| nose.profile().map(|p| (p, t))),
2077        Part::Transition(part) => shell(&part.wall).map(|t| part.profile().map(|p| (p, t))),
2078        _ => None,
2079    }
2080    .transpose()
2081    .map_err(|e| within(&node.id, e))?;
2082    let own = if node.overrides_include_children {
2083        parent.own
2084    } else {
2085        packed_for_override(&parent.part, &node.overrides, parent.own, p_fore)
2086            .and_then(|own| node.overrides.apply(own, p_fore))
2087            .map_err(|e| within(&node.id, e))?
2088    };
2089
2090    // Positions first: they don't depend on any automatic radius, and a ring's inner radius needs
2091    // its siblings' places.
2092    let mut stations = Vec::with_capacity(children.len());
2093    let mut previous_aft = None;
2094    for &(child, _) in &children {
2095        let length = child.length_m();
2096        check_dimension("attached part length", length, true).map_err(|e| within(&child.id, e))?;
2097        let fore = if pod {
2098            previous_aft.unwrap_or(p_fore)
2099        } else {
2100            match child.position {
2101                Some(Position::Top { aft_offset_m }) => p_fore + aft_offset_m,
2102                Some(Position::Middle { aft_offset_m }) => {
2103                    p_fore + 0.5 * (p_length - length) + aft_offset_m
2104                }
2105                Some(Position::Bottom { aft_offset_m }) => {
2106                    p_fore + p_length - length + aft_offset_m
2107                }
2108                Some(Position::After { aft_offset_m }) => {
2109                    previous_aft.unwrap_or(p_fore) + aft_offset_m
2110                }
2111                Some(Position::Absolute { station_m }) => station_m,
2112                None => return Err(tree(&child.id, "an attached part needs a position")),
2113            }
2114        };
2115        if !fore.is_finite() {
2116            return Err(within(
2117                &child.id,
2118                DesignError::Domain {
2119                    what: "attached part position (m)",
2120                    value: fore,
2121                },
2122            ));
2123        }
2124        stations.push((fore, length));
2125        previous_aft = Some(fore + length);
2126    }
2127
2128    let bore = |id: &str| {
2129        p_inner.ok_or_else(|| {
2130            tree(
2131                id,
2132                format!("an automatic radius needs a tube's inner radius, and a {p_kind} has none"),
2133            )
2134        })
2135    };
2136    // An automatic outer radius inside a nose cone or transition is its bore at whichever end of
2137    // the part is narrower: the outer radius there less the wall, measured radially, and none
2138    // where the wall meets the axis. Where the part runs past an end of its parent, the profile's
2139    // radius at that end stands. This is OpenRocket 24.12's reading, measured on probe designs
2140    // (`validation/oracles/openrocket/conventions.py`, [ADR-096][adr-096]).
2141    //
2142    // [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
2143    let bore_over = |id: &str, (fore, length): (f64, f64)| match &p_narrowing {
2144        Some((profile, wall_m)) => {
2145            let at = |station: f64| profile.radius_m(station - p_fore);
2146            Ok((at(fore).min(at(fore + length)) - wall_m).max(0.0))
2147        }
2148        None => bore(id),
2149    };
2150    // Automatic outer radii come first, in a pass of their own. They need nothing but the parent's
2151    // bore, while a ring's automatic *inner* radius reads its siblings' outer radii, so resolving
2152    // both in one pass would give a ring whose bore depended on whether the tube inside it was
2153    // written before or after it. That is [Loft lesson L60][lessons], and the reason this is two
2154    // passes rather than one.
2155    //
2156    // [lessons]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/research/loft-lessons.md
2157    let mut resolved: Vec<Part> = children.iter().map(|(c, _)| c.part.clone()).collect();
2158    if pod {
2159        // A pod's body components take their automatic radii from one another, as a stage's do.
2160        let autos: Vec<&[AutoDimension]> =
2161            node.children.iter().map(|c| c.auto.as_slice()).collect();
2162        let ids: Vec<&str> = node.children.iter().map(|c| c.id.as_str()).collect();
2163        resolve_body_radii(&mut resolved, &autos, &ids)?;
2164        resolve_shoulders(&mut resolved, &autos, &ids)?;
2165    }
2166    for ((part, &(child, _)), &station) in resolved.iter_mut().zip(&children).zip(&stations) {
2167        if child.auto.contains(&AutoDimension::OuterRadius) {
2168            match part {
2169                Part::CenteringRing(ring) => ring.outer_radius_m = bore_over(&child.id, station)?,
2170                // A wall thicker than the radius it gets is the tube solid, as it is when the
2171                // radius is stated (`hpr-io`'s `.ork` reader, and OpenRocket 24.12 on probes).
2172                Part::InnerTube(tube) => {
2173                    tube.outer_radius_m = bore_over(&child.id, station)?;
2174                    tube.thickness_m = tube.thickness_m.min(tube.outer_radius_m);
2175                }
2176                // Tubes that close the ring around the body tube they sit on, a wall thicker than
2177                // that radius cut to it, as OpenRocket 24.12 reads both (ADR-098). An external part
2178                // on anything but a body tube is refused before this, so the error is a backstop.
2179                Part::TubeFinSet(tubes) => {
2180                    let body_radius_m = p_tube_radius.ok_or_else(|| {
2181                        tree(
2182                            &child.id,
2183                            "an automatic tube fin radius needs a body tube to ring",
2184                        )
2185                    })?;
2186                    tubes.outer_radius_m =
2187                        crate::TubeFinSet::closing_radius_m(body_radius_m, tubes.count);
2188                    tubes.thickness_m = tubes.thickness_m.min(tubes.outer_radius_m);
2189                }
2190                _ => {}
2191            }
2192        }
2193    }
2194
2195    let mut parts = vec![own];
2196    for (k, &(child, hung_stage)) in children.iter().enumerate() {
2197        let (fore, length) = stations[k];
2198        let mut part = resolved[k].clone();
2199        let parent_inner = || bore(&child.id);
2200        // A packed part fills the parent's bore on its side of the parent's axis.
2201        let packed = |packing: &mut crate::parts::Packing| -> Result<(), DesignError> {
2202            let (x, y) = (
2203                packing.radial_offset_m * packing.angle_rad.cos(),
2204                packing.radial_offset_m * packing.angle_rad.sin(),
2205            );
2206            let room = parent_inner()? - (x - p_axis[0]).hypot(y - p_axis[1]);
2207            if !(room.is_finite() && room > 0.0) {
2208                return Err(tree(
2209                    &child.id,
2210                    "an automatic packed radius needs a radial offset inside the parent's bore",
2211                ));
2212            }
2213            packing.radius_m = room;
2214            Ok(())
2215        };
2216        for auto in &child.auto {
2217            match (auto, &mut part) {
2218                // Already done in the pass above.
2219                (AutoDimension::OuterRadius, _) => {}
2220                (AutoDimension::InnerRadius, Part::CenteringRing(ring)) => {
2221                    let aft = fore + length;
2222                    // A ring centers something *narrower than itself*. A sibling as wide as the
2223                    // ring is not what the ring holds (it is whatever the ring is bolted to), and
2224                    // taking its radius would leave the ring no material at all, which is how a
2225                    // full-bore coupler brushing a ring by a tenth of a millimeter made the ring
2226                    // weigh nothing. The ring's own outer radius is already resolved above.
2227                    let outer_radius_m = ring.outer_radius_m;
2228                    ring.inner_radius_m = resolved
2229                        .iter()
2230                        .zip(&stations)
2231                        .filter_map(|(sibling, &(s_fore, s_length))| match sibling {
2232                            Part::InnerTube(tube)
2233                                if tube.radial_offset_m == 0.0
2234                                    && tube.outer_radius_m < outer_radius_m
2235                                    && s_fore.max(fore) < (s_fore + s_length).min(aft) =>
2236                            {
2237                                Some(tube.outer_radius_m)
2238                            }
2239                            _ => None,
2240                        })
2241                        .fold(0.0, f64::max);
2242                }
2243                (AutoDimension::PackedRadius, Part::MassComponent(p)) => packed(&mut p.packing)?,
2244                (AutoDimension::PackedRadius, Part::Parachute(p)) => packed(&mut p.packing)?,
2245                (AutoDimension::PackedRadius, Part::Streamer(p)) => packed(&mut p.packing)?,
2246                (AutoDimension::PackedRadius, Part::ShockCord(p)) => packed(&mut p.packing)?,
2247                _ => {}
2248            }
2249        }
2250        // A fin set's root may follow a nose cone or a transition (ADR-166); on a body tube it is
2251        // level.
2252        let body_radius_m = match (&part, &p_surface) {
2253            (Part::FinSet(fins), Some(surface)) => Some(
2254                fins.root_radius_on(surface, fore - p_fore)
2255                    .map_err(|e| within(&child.id, e))?,
2256            ),
2257            _ if part.is_external() => {
2258                if let Part::FinSet(fins) = &part {
2259                    fins.check_level_root().map_err(|e| within(&child.id, e))?;
2260                }
2261                Some(
2262                    p_tube_radius
2263                        .ok_or_else(|| tree(&child.id, "external parts attach to a body tube"))?,
2264                )
2265            }
2266            _ => None,
2267        };
2268        // One copy: `finish` applies the child's overrides to it and then repeats it.
2269        let placed = place(&part, body_radius_m, fore, &child.id)?;
2270        let child_index = components.len();
2271        components.push(PlacedComponent {
2272            id: child.id.clone(),
2273            stage: hung_stage.unwrap_or(stage),
2274            parent: Some(index),
2275            part,
2276            fore_station_m: fore,
2277            length_m: length,
2278            finish: child.finish.unwrap_or_default(),
2279            body_radius_m,
2280            motor_mount: child.motor_mount,
2281            own: placed,
2282            with_children: placed,
2283            center_overridden: child.overrides.sets_axial_center(),
2284            copies: p_contents.clone(),
2285            drag_override: child.drag_override,
2286        });
2287        let mass = MassProperties::placed(finish(components, child_index, child, hung)?, &p_tubes);
2288        match hung_stage {
2289            Some(k) => hung.placed.push((k, mass, (fore, fore + length))),
2290            None => parts.push(mass),
2291        }
2292    }
2293
2294    let mut with_children = MassProperties::combine(&parts);
2295    if node.overrides_include_children {
2296        with_children = packed_for_override(
2297            &components[index].part,
2298            &node.overrides,
2299            with_children,
2300            p_fore,
2301        )
2302        .and_then(|mass| node.overrides.apply(mass, p_fore))
2303        .map_err(|e| within(&node.id, e))?;
2304    }
2305    components[index].own = MassProperties::placed(own, &p_copies);
2306    components[index].with_children = MassProperties::placed(with_children, &p_copies);
2307    Ok(with_children)
2308}
2309
2310#[cfg(test)]
2311mod tests {
2312    use proptest::prelude::*;
2313
2314    use super::*;
2315    use crate::parts::Shoulder;
2316    use crate::testing::{
2317        attached, body, bottom, fins, inner_tube, mass_component, nose, ring, rocket, stage,
2318        three_fin_rocket, top, tube,
2319    };
2320
2321    fn close(got: f64, want: f64, tol: f64, what: &str) {
2322        assert!((got - want).abs() <= tol, "{what}: {got} vs {want}");
2323    }
2324
2325    fn station(layout: &Layout, id: &str) -> f64 {
2326        layout.find(id).unwrap().1.fore_station_m
2327    }
2328
2329    /// Body components stack through both stages; each position rule puts a child where its doc
2330    /// says, worked by hand from the parent tube at stations 0.2 to 1.0.
2331    #[test]
2332    fn stacks_body_components_and_places_attached_parts() {
2333        let mut airframe = body("airframe", tube(0.8, 0.03, 0.001));
2334        let mut coupler = attached("coupler", inner_tube(0.2, 0.029, 0.001), top(0.1));
2335        coupler.children = vec![attached(
2336            "bay",
2337            mass_component(0.1, 0.05, 0.02),
2338            Position::After { aft_offset_m: 0.02 },
2339        )];
2340        airframe.children = vec![
2341            coupler,
2342            attached(
2343                "middle",
2344                mass_component(0.1, 0.1, 0.02),
2345                Position::Middle { aft_offset_m: 0.02 },
2346            ),
2347            attached("bottom", mass_component(0.1, 0.1, 0.02), bottom(-0.01)),
2348            attached(
2349                "after",
2350                mass_component(0.1, 0.004, 0.02),
2351                Position::After {
2352                    aft_offset_m: 0.001,
2353                },
2354            ),
2355            attached(
2356                "absolute",
2357                mass_component(0.1, 0.05, 0.02),
2358                Position::Absolute { station_m: 0.4 },
2359            ),
2360        ];
2361        let design = rocket(vec![
2362            stage("upper", vec![body("nose", nose(0.2, 0.03)), airframe]),
2363            stage(
2364                "booster",
2365                vec![
2366                    body(
2367                        "interstage",
2368                        Part::Transition(Transition {
2369                            shape: crate::NoseShape::Conical {},
2370                            clipped: false,
2371                            length_m: 0.1,
2372                            fore_radius_m: 0.03,
2373                            aft_radius_m: 0.04,
2374                            wall: crate::Wall::Shell { thickness_m: 0.002 },
2375                            fore_shoulder: None,
2376                            aft_shoulder: None,
2377                            material: crate::testing::cardboard(),
2378                        }),
2379                    ),
2380                    body("booster-tube", tube(0.5, 0.04, 0.001)),
2381                ],
2382            ),
2383        ]);
2384        let layout = design.layout().unwrap();
2385        let tol = 1e-15;
2386        close(station(&layout, "nose"), 0.0, tol, "nose");
2387        close(station(&layout, "airframe"), 0.2, tol, "airframe");
2388        close(station(&layout, "coupler"), 0.3, tol, "top");
2389        // The first child of the coupler goes after the coupler's forward end.
2390        close(station(&layout, "bay"), 0.32, tol, "after, first child");
2391        close(station(&layout, "middle"), 0.2 + 0.35 + 0.02, tol, "middle");
2392        close(station(&layout, "bottom"), 1.0 - 0.1 - 0.01, tol, "bottom");
2393        close(station(&layout, "after"), 0.99 + 0.001, tol, "after");
2394        close(station(&layout, "absolute"), 0.4, tol, "absolute");
2395        close(station(&layout, "interstage"), 1.0, tol, "second stage");
2396        close(station(&layout, "booster-tube"), 1.1, tol, "booster tube");
2397        close(layout.length_m, 1.6, tol, "length");
2398        let [upper, booster] = &layout.stages[..] else {
2399            panic!("two stages")
2400        };
2401        close(upper.fore_station_m, 0.0, tol, "upper fore");
2402        close(upper.aft_station_m, 1.0, tol, "upper aft");
2403        close(booster.fore_station_m, 1.0, tol, "booster fore");
2404        close(booster.aft_station_m, 1.6, tol, "booster aft");
2405        let (bay, placed) = layout.find("bay").unwrap();
2406        assert_eq!(
2407            layout.components[placed.parent.unwrap()].id,
2408            "coupler",
2409            "parent"
2410        );
2411        assert_eq!(layout.components[bay].stage, 0);
2412        assert_eq!(layout.find("booster-tube").unwrap().1.stage, 1);
2413        // A placed part's center is its own-frame center moved to its station.
2414        let own = mass_component(0.1, 0.05, 0.02)
2415            .mass_properties(None)
2416            .unwrap();
2417        close(placed.own.cg_m.z, own.cg_m.z - 0.32, 1e-15, "placed center");
2418        // The structure is every stage, and each stage every component with its children.
2419        let sum: f64 = layout.body().map(|c| c.with_children.mass_kg).sum();
2420        close(layout.structure.mass_kg, sum, 1e-15, "structure mass");
2421    }
2422
2423    /// M4.5g4 (ADR-166): a fin set sits on a nose cone with its root along the surface, its body
2424    /// radius the surface's at the root leading edge. A conical nose 0.2 m long of base radius
2425    /// 0.03 m has `r = 0.15 x`: a 0.05 m root from its aft end starts at radius 0.0225 m and
2426    /// rises 0.0075 m. On a body tube a root that rises is refused, a level root on the cone
2427    /// stands off its surface, and a launch lug still attaches only to a body tube.
2428    #[test]
2429    fn a_fin_set_on_a_nose_cone_follows_its_surface() {
2430        let fin = |end_h: f64| {
2431            let mut set = match fins(0.05, 0.04) {
2432                Part::FinSet(set) => set,
2433                _ => unreachable!("`fins` makes a fin set"),
2434            };
2435            set.planform = crate::FinPlanform::Freeform {
2436                points_m: vec![[0.0, 0.0], [0.03, 0.04], [0.05, end_h]],
2437                root_m: Vec::new(),
2438            };
2439            set
2440        };
2441        let design = |child: Component, on_the_nose: bool| {
2442            let mut nose_cone = body("nose", nose(0.2, 0.03));
2443            let mut airframe = body("airframe", tube(0.6, 0.03, 0.001));
2444            if on_the_nose {
2445                nose_cone.children = vec![child];
2446            } else {
2447                airframe.children = vec![child];
2448            }
2449            rocket(vec![stage("only", vec![nose_cone, airframe])])
2450        };
2451        let layout = design(
2452            attached("cockpit", Part::FinSet(fin(0.0075)), bottom(0.0)),
2453            true,
2454        )
2455        .layout()
2456        .unwrap();
2457        let (_, placed) = layout.find("cockpit").unwrap();
2458        close(placed.fore_station_m, 0.15, 1e-15, "root leading edge");
2459        close(placed.body_radius_m.unwrap(), 0.0225, 1e-15, "body radius");
2460        close(
2461            placed.own.mass_kg,
2462            fin(0.0075).mass_properties(0.0225).unwrap().mass_kg,
2463            1e-15,
2464            "mass",
2465        );
2466        let refused = |child: Component, on_the_nose: bool, says: &str| {
2467            let err = design(child, on_the_nose).layout().unwrap_err().to_string();
2468            assert!(err.contains(says), "{says}: {err}");
2469        };
2470        refused(
2471            attached("rising", Part::FinSet(fin(0.0075)), bottom(0.0)),
2472            false,
2473            "needs a level root",
2474        );
2475        refused(
2476            attached("level", fins(0.05, 0.04), bottom(0.0)),
2477            true,
2478            "stands",
2479        );
2480        refused(
2481            attached("short", Part::FinSet(fin(0.0075)), bottom(0.01)),
2482            true,
2483            "must stay on it",
2484        );
2485        let lug = Part::LaunchLug(crate::LaunchLug {
2486            length_m: 0.03,
2487            outer_radius_m: 0.003,
2488            thickness_m: 0.0005,
2489            angle_rad: 0.0,
2490            count: 1,
2491            spacing_m: 0.0,
2492            material: crate::testing::cardboard(),
2493        });
2494        refused(
2495            attached("lug", lug, bottom(0.0)),
2496            true,
2497            "a launch_lug attaches to a body tube, not a nose_cone",
2498        );
2499    }
2500
2501    /// Automatic radii: a nose takes the tube behind it, a transition's forward radius crosses a
2502    /// stage boundary, a tube takes the transition ahead of it, and a tube with nothing resolvable
2503    /// ahead takes the next fixed radius.
2504    #[test]
2505    fn automatic_radii_follow_neighbors_across_stages() {
2506        let auto = |mut c: Component, dims: &[AutoDimension]| {
2507            c.auto = dims.to_vec();
2508            c
2509        };
2510        let transition = Part::Transition(Transition {
2511            shape: crate::NoseShape::Conical {},
2512            clipped: false,
2513            length_m: 0.1,
2514            fore_radius_m: 0.0,
2515            aft_radius_m: 0.04,
2516            wall: crate::Wall::Filled {},
2517            fore_shoulder: Some(Shoulder {
2518                length_m: 0.05,
2519                outer_radius_m: 0.0,
2520                thickness_m: 0.002,
2521                capped: false,
2522            }),
2523            aft_shoulder: None,
2524            material: crate::testing::cardboard(),
2525        });
2526        let mut nose_cone = auto(body("nose", nose(0.2, 0.0)), &[AutoDimension::BaseRadius]);
2527        if let Part::NoseCone(n) = &mut nose_cone.part {
2528            n.shoulder = Some(Shoulder {
2529                length_m: 0.05,
2530                outer_radius_m: 0.0,
2531                thickness_m: 0.002,
2532                capped: true,
2533            });
2534        }
2535        nose_cone.auto.push(AutoDimension::ShoulderRadius);
2536        let design = rocket(vec![
2537            stage(
2538                "upper",
2539                vec![nose_cone, body("upper-tube", tube(0.5, 0.03, 0.001))],
2540            ),
2541            stage(
2542                "booster",
2543                vec![
2544                    auto(
2545                        body("interstage", transition),
2546                        &[AutoDimension::ForeRadius, AutoDimension::ForeShoulderRadius],
2547                    ),
2548                    auto(
2549                        body("booster-tube", tube(0.5, 0.0, 0.001)),
2550                        &[AutoDimension::OuterRadius],
2551                    ),
2552                ],
2553            ),
2554        ]);
2555        let layout = design.layout().unwrap();
2556        let part = |id: &str| layout.find(id).unwrap().1.part.clone();
2557        let Part::NoseCone(n) = part("nose") else {
2558            panic!()
2559        };
2560        assert_eq!(n.base_radius_m, 0.03);
2561        assert_eq!(n.shoulder.unwrap().outer_radius_m, 0.03 - 0.001);
2562        let Part::Transition(t) = part("interstage") else {
2563            panic!()
2564        };
2565        assert_eq!(t.fore_radius_m, 0.03);
2566        assert_eq!(t.fore_shoulder.unwrap().outer_radius_m, 0.03 - 0.001);
2567        let Part::BodyTube(b) = part("booster-tube") else {
2568            panic!()
2569        };
2570        assert_eq!(b.outer_radius_m, 0.04);
2571
2572        // Nothing ahead of the first tube is fixed, so it takes the tube behind it.
2573        let design = rocket(vec![stage(
2574            "only",
2575            vec![
2576                auto(body("nose", nose(0.2, 0.0)), &[AutoDimension::BaseRadius]),
2577                auto(
2578                    body("a", tube(0.3, 0.0, 0.001)),
2579                    &[AutoDimension::OuterRadius],
2580                ),
2581                body("b", tube(0.3, 0.05, 0.001)),
2582            ],
2583        )]);
2584        let layout = design.layout().unwrap();
2585        assert_eq!(layout.find("a").unwrap().1.part.aft_radius_m(), Some(0.05));
2586        assert_eq!(
2587            layout.find("nose").unwrap().1.part.aft_radius_m(),
2588            Some(0.05)
2589        );
2590        // A fixed radius ahead wins over one behind.
2591        let design = rocket(vec![stage(
2592            "only",
2593            vec![
2594                body("nose", nose(0.2, 0.02)),
2595                auto(
2596                    body("a", tube(0.3, 0.0, 0.001)),
2597                    &[AutoDimension::OuterRadius],
2598                ),
2599                body("b", tube(0.3, 0.05, 0.001)),
2600            ],
2601        )]);
2602        let layout = design.layout().unwrap();
2603        assert_eq!(layout.find("a").unwrap().1.part.aft_radius_m(), Some(0.02));
2604
2605        // Automatic all the way round has nothing to take.
2606        let design = rocket(vec![stage(
2607            "only",
2608            vec![
2609                auto(body("nose", nose(0.2, 0.0)), &[AutoDimension::BaseRadius]),
2610                auto(
2611                    body("a", tube(0.3, 0.0, 0.001)),
2612                    &[AutoDimension::OuterRadius],
2613                ),
2614            ],
2615        )]);
2616        assert!(matches!(
2617            design.layout(),
2618            Err(DesignError::Tree { ref id, .. }) if id == "nose"
2619        ));
2620    }
2621
2622    /// A conical transition with a 1 mm wall.
2623    fn cone_transition(fore_radius_m: f64, aft_radius_m: f64) -> Part {
2624        Part::Transition(Transition {
2625            shape: crate::NoseShape::Conical {},
2626            clipped: false,
2627            length_m: 0.1,
2628            fore_radius_m,
2629            aft_radius_m,
2630            wall: crate::Wall::Shell { thickness_m: 0.001 },
2631            fore_shoulder: None,
2632            aft_shoulder: None,
2633            material: crate::testing::cardboard(),
2634        })
2635    }
2636
2637    /// The chain in Loft's quirks fixture: a nose's base, a tube and a transition's forward end all
2638    /// automatic, with only the transition's aft end fixed. Each automatic radius there looks at
2639    /// another automatic one, so all three are listed, forward to aft, and filling them is all
2640    /// `layout` needs. The fixed tube behind is never listed, and a radius the neighbor rule can
2641    /// reach is never filled.
2642    #[test]
2643    fn unresolvable_body_radii_are_the_chain_with_nothing_fixed() {
2644        let auto = |mut c: Component, dims: &[AutoDimension]| {
2645            c.auto = dims.to_vec();
2646            c
2647        };
2648        let mut design = rocket(vec![stage(
2649            "only",
2650            vec![
2651                auto(body("nose", nose(0.3, 0.0)), &[AutoDimension::BaseRadius]),
2652                auto(
2653                    body("upper", tube(0.5, 0.0, 0.002)),
2654                    &[AutoDimension::OuterRadius],
2655                ),
2656                auto(
2657                    body("shoulder", cone_transition(0.0, 0.022)),
2658                    &[AutoDimension::ForeRadius],
2659                ),
2660                body("lower", tube(0.45, 0.022, 0.0018)),
2661            ],
2662        )]);
2663        let listed = |design: &Rocket| -> Vec<(usize, usize, String, AutoDimension)> {
2664            design
2665                .unresolvable_body_radii()
2666                .into_iter()
2667                .map(|r| (r.stage, r.component, r.id, r.dimension))
2668                .collect()
2669        };
2670        let chain = vec![
2671            (0, 0, "nose".to_owned(), AutoDimension::BaseRadius),
2672            (0, 1, "upper".to_owned(), AutoDimension::OuterRadius),
2673            (0, 2, "shoulder".to_owned(), AutoDimension::ForeRadius),
2674        ];
2675        assert_eq!(listed(&design), chain);
2676        assert!(design.layout().is_err());
2677
2678        let filled = design.fill_unresolvable_body_radii(0.025);
2679        let filled: Vec<_> = filled
2680            .into_iter()
2681            .map(|r| (r.stage, r.component, r.id, r.dimension))
2682            .collect();
2683        assert_eq!(filled, chain);
2684        assert!(listed(&design).is_empty());
2685        assert!(
2686            design.stages[0]
2687                .components
2688                .iter()
2689                .all(|c| c.auto.is_empty())
2690        );
2691        let layout = design.layout().unwrap();
2692        let radius = |id: &str| layout.find(id).unwrap().1.part.aft_radius_m();
2693        assert_eq!(radius("nose"), Some(0.025));
2694        assert_eq!(radius("upper"), Some(0.025));
2695        let Part::Transition(t) = &layout.find("shoulder").unwrap().1.part else {
2696            panic!("a transition")
2697        };
2698        assert_eq!((t.fore_radius_m, t.aft_radius_m), (0.025, 0.022));
2699
2700        // A design that resolves lists nothing, and filling it changes nothing.
2701        let mut design = three_fin_rocket();
2702        let before = design.clone();
2703        assert!(design.unresolvable_body_radii().is_empty());
2704        assert!(design.fill_unresolvable_body_radii(0.025).is_empty());
2705        assert_eq!(design, before);
2706        design.layout().unwrap();
2707    }
2708
2709    /// Rings take the tube's bore and the mount tube's outside; the parachute packs to the bore; a
2710    /// ring beside no inner tube is a bulkhead.
2711    #[test]
2712    fn ring_and_packed_radii_come_from_parent_and_siblings() {
2713        let layout = three_fin_rocket().layout().unwrap();
2714        let part = |id: &str| layout.find(id).unwrap().1.part.clone();
2715        for id in ["ring-fore", "ring-aft"] {
2716            let Part::CenteringRing(r) = part(id) else {
2717                panic!()
2718            };
2719            assert_eq!(r.outer_radius_m, 0.027 - 0.0015, "{id}");
2720            assert_eq!(r.inner_radius_m, 0.020, "{id}");
2721        }
2722        let Part::Parachute(p) = part("chute") else {
2723            panic!()
2724        };
2725        assert_eq!(p.packing.radius_m, 0.027 - 0.0015);
2726
2727        let mut design = three_fin_rocket();
2728        let airframe = &mut design.stages[0].components[1];
2729        // Move the fore ring forward of the mount tube, which spans stations 0.7 to 1.0.
2730        airframe.children[1].position = Some(top(0.1));
2731        let layout = design.layout().unwrap();
2732        let Part::CenteringRing(r) = layout.find("ring-fore").unwrap().1.part.clone() else {
2733            panic!()
2734        };
2735        assert_eq!(r.inner_radius_m, 0.0);
2736    }
2737
2738    /// A tube fin set written `auto` closes the ring around the 27 mm airframe it sits on: six
2739    /// tubes as wide as the body, four `1 + √2` times it, and a wall thicker than that cut to it
2740    /// (ADR-098). It weighs what the same set of a stated radius weighs.
2741    #[test]
2742    fn an_automatic_tube_fin_radius_closes_the_ring_around_its_body() {
2743        let tubes = |count: u32, thickness_m: f64| {
2744            Part::TubeFinSet(crate::TubeFinSet {
2745                count,
2746                length_m: 0.1,
2747                outer_radius_m: 0.0,
2748                thickness_m,
2749                base_angle_rad: 0.0,
2750                material: crate::Material::bulk("cardboard", 680.0),
2751            })
2752        };
2753        let with = |part: Part, auto: bool, on: usize| {
2754            let mut design = three_fin_rocket();
2755            let mut child = attached("tubes", part, bottom(0.0));
2756            if auto {
2757                child.auto = vec![AutoDimension::OuterRadius];
2758            }
2759            design.stages[0].components[on].children.push(child);
2760            design.layout()
2761        };
2762        let resolved = |layout: &Layout| match &layout.find("tubes").unwrap().1.part {
2763            Part::TubeFinSet(set) => (set.outer_radius_m, set.thickness_m),
2764            other => panic!("{other:?}"),
2765        };
2766        let layout = with(tubes(6, 0.001), true, 1).unwrap();
2767        let (r, t) = resolved(&layout);
2768        close(r, 0.027, 1e-15, "six");
2769        assert_eq!(t, 0.001);
2770        let mut stated = tubes(6, 0.001);
2771        if let Part::TubeFinSet(set) = &mut stated {
2772            set.outer_radius_m = r;
2773        }
2774        let same = with(stated, false, 1).unwrap();
2775        assert_eq!(
2776            layout.find("tubes").unwrap().1.own,
2777            same.find("tubes").unwrap().1.own
2778        );
2779        let (r, _) = resolved(&with(tubes(4, 0.001), true, 1).unwrap());
2780        close(r, 0.027 * (1.0 + 2f64.sqrt()), 1e-15, "four");
2781        let (r, _) = resolved(&with(tubes(2, 0.001), true, 1).unwrap());
2782        assert_eq!(r, 0.027);
2783        let (r, t) = resolved(&with(tubes(6, 0.05), true, 1).unwrap());
2784        assert_eq!(t, r);
2785        // On the nose cone there is no body tube to ring, and the layout says so before it looks.
2786        let error = with(tubes(6, 0.001), true, 0).unwrap_err().to_string();
2787        assert!(error.contains("attaches to a body tube"), "{error}");
2788    }
2789
2790    /// Inside a hollow nose cone or transition, an automatic outer radius is the parent's bore at
2791    /// the narrower end of the part: the profile's radius there less the wall (ADR-096). The
2792    /// sample's nose is a 0.2 m cone on a 27 mm base with a 2 mm wall, so its radius at `x` from
2793    /// the tip is `0.135 x`.
2794    #[test]
2795    fn an_automatic_radius_inside_a_nose_is_its_bore_at_the_narrow_end() {
2796        let with = |part: Part, position: Position| {
2797            let mut design = three_fin_rocket();
2798            let mut child = attached("inside", part, position);
2799            child.auto = vec![AutoDimension::OuterRadius];
2800            design.stages[0].components[0].children = vec![child];
2801            design.layout()
2802        };
2803        let radius = |layout: &Layout| match &layout.find("inside").unwrap().1.part {
2804            Part::InnerTube(tube) => (tube.outer_radius_m, tube.thickness_m),
2805            Part::CenteringRing(ring) => (ring.outer_radius_m, ring.inner_radius_m),
2806            other => panic!("{other:?}"),
2807        };
2808        let coupler = || inner_tube(0.1, 0.0, 0.001);
2809        // Stations 0.1 to 0.2 from the tip: the fore end is the narrower.
2810        let (r, t) = radius(&with(coupler(), bottom(0.0)).unwrap());
2811        close(r, 0.135 * 0.1 - 0.002, 1e-17, "at the bottom");
2812        assert_eq!(t, 0.001);
2813        // Past the base, 0.15 to 0.25: still the fore end's.
2814        let (r, _) = radius(&with(coupler(), bottom(0.05)).unwrap());
2815        close(r, 0.135 * 0.15 - 0.002, 1e-17, "past the base");
2816        // A ring's outer radius the same way; its written bore stands.
2817        let (r, bore) = radius(&with(ring(0.006, 0.0, 0.005), bottom(0.0)).unwrap());
2818        close(r, 0.135 * 0.194 - 0.002, 1e-17, "a ring");
2819        assert_eq!(bore, 0.005);
2820        // A wall thicker than the radius it gets is the tube solid.
2821        let (r, t) = radius(&with(inner_tube(0.1, 0.0, 0.02), bottom(0.0)).unwrap());
2822        assert_eq!(t, r);
2823        // At the tip the wall meets the axis, and a tube of no radius is refused.
2824        let error = with(coupler(), top(0.0)).unwrap_err();
2825        assert!(
2826            matches!(
2827                &error,
2828                DesignError::InComponent { id, source }
2829                    if id == "inside"
2830                        && matches!(**source, DesignError::Domain { what: "outer radius", value } if value == 0.0)
2831            ),
2832            "{error:?}"
2833        );
2834        // A solid nose has no bore.
2835        let mut design = three_fin_rocket();
2836        if let Part::NoseCone(nose) = &mut design.stages[0].components[0].part {
2837            nose.wall = Wall::Filled {};
2838        }
2839        let mut child = attached("inside", coupler(), bottom(0.0));
2840        child.auto = vec![AutoDimension::OuterRadius];
2841        design.stages[0].components[0].children = vec![child];
2842        let error = design.layout().unwrap_err().to_string();
2843        assert!(error.contains("a nose_cone has none"), "{error}");
2844
2845        // A transition from 30 mm to 20 mm over 0.1 m narrows aft: a coupler over its first
2846        // 0.05 m takes the radius at its aft end, 25 mm, less the wall.
2847        let transition = Part::Transition(Transition {
2848            shape: crate::shapes::NoseShape::Conical {},
2849            clipped: false,
2850            length_m: 0.1,
2851            fore_radius_m: 0.03,
2852            aft_radius_m: 0.02,
2853            wall: Wall::Shell { thickness_m: 0.002 },
2854            fore_shoulder: None,
2855            aft_shoulder: None,
2856            material: crate::testing::cardboard(),
2857        });
2858        let mut part = body("transition", transition);
2859        let mut child = attached("inside", inner_tube(0.05, 0.0, 0.001), top(0.0));
2860        child.auto = vec![AutoDimension::OuterRadius];
2861        part.children = vec![child];
2862        let design = rocket(vec![stage(
2863            "only",
2864            vec![body("tube", tube(0.3, 0.03, 0.001)), part],
2865        )]);
2866        let (r, _) = radius(&design.layout().unwrap());
2867        close(r, 0.025 - 0.002, 1e-17, "a transition");
2868    }
2869
2870    /// What a clustered tube holds is in every tube: an engine block inside a 3-ring mount has
2871    /// three copies, one on each tube's axis, and the structure gains two more tubes and two more
2872    /// blocks than the unclustered mount with its block. A ring's automatic bore is the tube's own
2873    /// radius, as OpenRocket 24.12 gives it (ADR-075), so the tubes run through the ring and the
2874    /// checks say so, as they say the cluster reaches past the airframe's bore.
2875    #[test]
2876    fn a_cluster_repeats_what_it_holds_in_every_tube() {
2877        let three: Vec<[f64; 2]> = [90.0_f64, 210.0, 330.0]
2878            .iter()
2879            .map(|a| [0.02 * a.to_radians().cos(), 0.02 * a.to_radians().sin()])
2880            .collect();
2881        let with_block = |cluster_m: Vec<[f64; 2]>| {
2882            let mut design = crate::testing::three_fin_rocket();
2883            let mount = &mut design.stages[0].components[1].children[0];
2884            if let Part::InnerTube(tube) = &mut mount.part {
2885                tube.cluster_m = cluster_m;
2886            }
2887            mount.children = vec![attached("block", inner_tube(0.01, 0.019, 0.005), top(0.0))];
2888            design
2889        };
2890        let single = with_block(Vec::new()).layout().unwrap();
2891        let clustered_design = with_block(three.clone());
2892        let clustered = clustered_design.layout().unwrap();
2893        let (_, one) = single.find("block").unwrap();
2894        let (_, block) = clustered.find("block").unwrap();
2895        assert_eq!(one.copies, [Placement::HERE]);
2896        let moved: Vec<Placement> = three.iter().copied().map(Placement::moved).collect();
2897        assert_eq!(block.copies, moved);
2898        close(
2899            block.own.mass_kg,
2900            3.0 * one.own.mass_kg,
2901            1e-15,
2902            "three blocks",
2903        );
2904        assert!(block.own.cg_m.truncate().length() < 1e-17);
2905        let (_, tube) = single.find("mmt").unwrap();
2906        let extra = 2.0 * (tube.own.mass_kg + one.own.mass_kg);
2907        close(
2908            clustered.structure.mass_kg,
2909            single.structure.mass_kg + extra,
2910            1e-14,
2911            "structure",
2912        );
2913        let (_, mount) = clustered.find("mmt").unwrap();
2914        assert_eq!(mount.contents_copies().unwrap(), moved);
2915        let (_, ring) = clustered.find("ring-fore").unwrap();
2916        let Part::CenteringRing(ring) = &ring.part else {
2917            panic!("a ring");
2918        };
2919        assert_eq!(ring.inner_radius_m, 0.02);
2920        let findings = crate::checks::check(&clustered_design).unwrap();
2921        for id in ["ring-fore", "ring-aft"] {
2922            assert!(
2923                findings.contains(&crate::Finding::RingOverlapsInnerTube {
2924                    ring: id.to_owned(),
2925                    tube: "mmt".to_owned(),
2926                }),
2927                "{findings:?}"
2928            );
2929        }
2930        // The tubes reach 0.04 m from the axis, past the airframe's 0.0255 m bore.
2931        assert!(
2932            findings.iter().any(|f| matches!(
2933                f,
2934                crate::Finding::InternalPartWiderThanParent { component, reach_m, .. }
2935                    if component == "mmt" && (reach_m - 0.04).abs() < 1e-15
2936            )),
2937            "{findings:?}"
2938        );
2939        assert!(
2940            !crate::checks::check(&with_block(Vec::new()))
2941                .unwrap()
2942                .iter()
2943                .any(|f| matches!(f, crate::Finding::RingOverlapsInnerTube { .. }))
2944        );
2945    }
2946
2947    /// The tests' rocket with a pod set of `count` pods `d = 0.05` m from the axis, the first at
2948    /// `angle_rad`, 0.1 m aft of the airframe's forward end: each pod a 0.3 m cardboard tube
2949    /// (radius 12 mm, wall 1 mm) holding a 50 g mass 0.1 m long, radius 8 mm, 0.02 m from its top.
2950    fn podded(count: u32, angle_rad: f64) -> Rocket {
2951        let mut design = three_fin_rocket();
2952        let mut pod_tube = body("pod-tube", tube(0.3, 0.012, 0.001));
2953        pod_tube.children = vec![attached(
2954            "pod-mass",
2955            mass_component(0.05, 0.1, 0.008),
2956            top(0.02),
2957        )];
2958        let mut pods = attached(
2959            "pods",
2960            Part::PodSet(PodSet {
2961                count,
2962                radial_offset_m: 0.05,
2963                angle_rad,
2964            }),
2965            top(0.1),
2966        );
2967        pods.children = vec![pod_tube];
2968        design.stages[0].components[1].children.push(pods);
2969        design
2970    }
2971
2972    /// [`podded`]'s pods as a parallel stage of their own, hung on the same tube at the same place.
2973    fn boosted(count: u32, angle_rad: f64) -> Rocket {
2974        let mut design = podded(count, angle_rad);
2975        let pods = design.stages[0].components[1]
2976            .children
2977            .pop()
2978            .expect("podded hangs its pods last");
2979        let Part::PodSet(set) = pods.part else {
2980            unreachable!("podded's last child is its pod set")
2981        };
2982        let mut boosters = stage("pods", pods.children);
2983        boosters.parallel = Some(ParallelStage {
2984            on: "airframe".to_owned(),
2985            position: pods.position.expect("an attached part has a position"),
2986            pods: set,
2987        });
2988        design.stages.push(boosters);
2989        design
2990    }
2991
2992    /// A parallel stage lays out as the same pods hung on its tube as a pod set: every part in the
2993    /// same place with the same copies and mass, bit for bit, and the structure the same. Only
2994    /// whose they are differs: the pods' parts are the parallel stage's, their mass is that stage's
2995    /// and not the tube's, and the stage spans the pods and hangs on stage 0.
2996    #[test]
2997    fn a_parallel_stage_lays_out_as_a_pod_set_of_its_own_stage() {
2998        for (count, angle_rad) in [(2, 0.0), (1, 0.3), (3, 1.0)] {
2999            let pods = podded(count, angle_rad).layout().unwrap();
3000            let boosters = boosted(count, angle_rad).layout().unwrap();
3001            assert_eq!(boosters.components.len(), pods.components.len());
3002            let own_stage = ["pods", "pod-tube", "pod-mass"];
3003            for (got, want) in boosters.components.iter().zip(&pods.components) {
3004                assert_eq!(got.id, want.id, "depth-first order kept");
3005                let theirs = own_stage.contains(&got.id.as_str());
3006                assert_eq!(got.stage, usize::from(theirs), "{}'s stage", got.id);
3007                let mut same = got.clone();
3008                same.stage = want.stage;
3009                if got.id == "airframe" {
3010                    // The tube no longer carries the pods: its mass with children is the podded
3011                    // tube's less theirs.
3012                    let (_, set) = pods.find("pods").unwrap();
3013                    close(
3014                        got.with_children.mass_kg,
3015                        want.with_children.mass_kg - set.with_children.mass_kg,
3016                        1e-15,
3017                        "the tube without its pods",
3018                    );
3019                    same.with_children = want.with_children;
3020                }
3021                assert_eq!(&same, want, "{}", got.id);
3022            }
3023            let (_, set) = pods.find("pods").unwrap();
3024            assert_eq!(boosters.stages.len(), 2);
3025            let stage = &boosters.stages[1];
3026            assert_eq!(stage.id, "pods");
3027            assert_eq!(stage.hung_on, Some(0));
3028            assert_eq!(boosters.stages[0].hung_on, None);
3029            assert_eq!(stage.mass, set.with_children);
3030            assert_eq!(
3031                (stage.fore_station_m, stage.aft_station_m),
3032                (set.fore_station_m, set.aft_station_m())
3033            );
3034            assert_eq!(boosters.length_m, pods.length_m, "the pods don't stack");
3035            close(
3036                boosters.structure.mass_kg,
3037                pods.structure.mass_kg,
3038                1e-15,
3039                "structure mass",
3040            );
3041            close(
3042                (boosters.structure.cg_m - pods.structure.cg_m).length(),
3043                0.0,
3044                1e-15,
3045                "structure center",
3046            );
3047            let inertia = boosters.structure.inertia_kg_m2 - pods.structure.inertia_kg_m2;
3048            for column in 0..3 {
3049                close(
3050                    inertia.col(column).length(),
3051                    0.0,
3052                    1e-15,
3053                    "structure inertia",
3054                );
3055            }
3056        }
3057
3058        // The design page's worked example: the two pods, each a tube and 50 g, are the stage's.
3059        let boosters = boosted(2, 0.0);
3060        let tube_kg = 790.0 * std::f64::consts::PI * (0.012_f64.powi(2) - 0.011_f64.powi(2)) * 0.3;
3061        close(
3062            boosters.layout().unwrap().stages[1].mass.mass_kg,
3063            2.0 * (tube_kg + 0.05),
3064            1e-15,
3065            "the stage's mass",
3066        );
3067        // The design page's JSON is that stage, empty but for each copy's tube.
3068        let page = include_str!("../../../docs/physics/design.md");
3069        let block = page
3070            .split("\n### Parallel stages\n")
3071            .nth(1)
3072            .and_then(|stages| stages.split("```json\n").nth(1))
3073            .and_then(|json| json.split("```").next())
3074            .expect("the Parallel stages section has a JSON block");
3075        let mut written = boosters.stages[1].clone();
3076        written.components[0].children.clear();
3077        assert_eq!(
3078            serde_json::from_str::<Stage>(block).unwrap(),
3079            written,
3080            "{block}"
3081        );
3082    }
3083
3084    /// A parallel stage hangs on a body tube of an axial stage before it, measured along that
3085    /// tube; anything else is refused by name.
3086    #[test]
3087    fn a_parallel_stage_hangs_on_a_body_tube_of_an_earlier_axial_stage() {
3088        let refused = |design: &Rocket, needle: &str| match design.layout() {
3089            Err(DesignError::Tree { id, message }) => {
3090                assert_eq!(id, "pods");
3091                assert!(message.contains(needle), "{message}");
3092            }
3093            other => panic!("expected a tree error naming `{needle}`, got {other:?}"),
3094        };
3095        let hangs = "hangs on a body tube of an axial stage before it";
3096        let on = |on: &str| {
3097            let mut design = boosted(2, 0.0);
3098            design.stages[1].parallel.as_mut().unwrap().on = on.to_owned();
3099            design
3100        };
3101        refused(&on("nose"), hangs);
3102        refused(&on("fins"), hangs);
3103        refused(&on("nowhere"), hangs);
3104        // On its own pod's tube, or listed before the stage it hangs on.
3105        refused(&on("pod-tube"), hangs);
3106        let mut first = boosted(2, 0.0);
3107        first.stages.swap(0, 1);
3108        refused(&first, hangs);
3109        // On a tube of another parallel stage.
3110        let mut nested = boosted(2, 0.0);
3111        let mut more = nested.stages[1].clone();
3112        more.id = "more".to_owned();
3113        more.components[0].id = "more-tube".to_owned();
3114        more.components[0].children[0].id = "more-mass".to_owned();
3115        more.parallel.as_mut().unwrap().on = "pod-tube".to_owned();
3116        nested.stages.push(more);
3117        match nested.layout() {
3118            Err(DesignError::Tree { id, message }) => {
3119                assert_eq!(id, "more");
3120                assert!(message.contains(hangs), "{message}");
3121            }
3122            other => panic!("expected a tree error, got {other:?}"),
3123        }
3124        // After a sibling: a parallel stage has none.
3125        let mut after = boosted(2, 0.0);
3126        after.stages[1].parallel.as_mut().unwrap().position = Position::After { aft_offset_m: 0.0 };
3127        refused(&after, "not after a sibling");
3128        // Under a mass override covering what its tube or the tube's stage holds, which doesn't
3129        // say whether it covers the parallel stage; the tube's own override does say.
3130        let covered = "under a mass override that covers what the tube or its stage holds";
3131        let heavy = Overrides {
3132            mass_kg: Some(1.0),
3133            ..Overrides::default()
3134        };
3135        let mut staged = boosted(2, 0.0);
3136        staged.stages[0].overrides = heavy;
3137        refused(&staged, covered);
3138        let mut tube = boosted(2, 0.0);
3139        tube.stages[0].components[1].overrides = heavy;
3140        tube.layout().unwrap();
3141        tube.stages[0].components[1].overrides_include_children = true;
3142        refused(&tube, covered);
3143        // An added mass with no station on the stage it hangs on: it has no fixed place once the
3144        // parallel stage drops. One at a station there, and the parallel stage's own, lay out
3145        // (`a_parallel_stages_added_mass_sits_among_its_pods`).
3146        let mut added = boosted(2, 0.0);
3147        added.stages[0].added_mass = Some(AddedMass {
3148            mass_kg: 0.1,
3149            cg_aft_m: None,
3150        });
3151        refused(&added, "carries an added mass with no station");
3152        // An added mass of zero changes nothing, so it is no matter where it would sit.
3153        let mut nothing = boosted(2, 0.0);
3154        nothing.stages[0].added_mass = Some(AddedMass {
3155            mass_kg: 0.0,
3156            cg_aft_m: None,
3157        });
3158        assert_eq!(
3159            nothing.layout().unwrap().structure,
3160            boosted(2, 0.0).layout().unwrap().structure
3161        );
3162        // One at a station there, beside one pod off the axis: OpenRocket's sits as far off the
3163        // axis as the stage's center with the pod hanging on it. On the axis, the pod is no
3164        // matter.
3165        let stationed = Some(AddedMass {
3166            mass_kg: 0.1,
3167            cg_aft_m: Some(0.1),
3168        });
3169        let mut lone = boosted(1, 0.0);
3170        lone.stages[0].added_mass = stationed;
3171        refused(&lone, "one pod off the axis");
3172        lone.stages[1]
3173            .parallel
3174            .as_mut()
3175            .unwrap()
3176            .pods
3177            .radial_offset_m = 0.0;
3178        lone.layout().unwrap();
3179        // Its pods are checked as a pod set's: a part that isn't a body component in the stack.
3180        let mut loose = boosted(2, 0.0);
3181        loose.stages[1].components[0] = attached("pod-tube", fins(0.1, 0.06), top(0.0));
3182        assert!(loose.layout().is_err());
3183        // An id the airframe already uses.
3184        let mut twice = boosted(2, 0.0);
3185        twice.stages[1].id = "airframe".to_owned();
3186        assert!(matches!(twice.layout(), Err(DesignError::DuplicateId(_))));
3187    }
3188
3189    /// A parallel stage's added mass is a point among its pods, and one at a station on the
3190    /// stage it hangs on is a point among that stage's parts, the pods not counted, each worked
3191    /// by hand ([`AddedMass`]). With no station the parallel stage keeps its pods' center and
3192    /// inertia. At a station the point sits that far aft of the parallel stage's forward end, as
3193    /// far off the axis as the pods' center is: one pod's is off it, by the pod's distance.
3194    #[test]
3195    fn a_parallel_stages_added_mass_sits_among_its_pods() {
3196        let pitch = |m: &MassProperties| m.inertia_kg_m2.x_axis.x;
3197        for (count, angle_rad) in [(2, 0.0), (1, 0.3), (3, 1.0)] {
3198            let plain = boosted(count, angle_rad).layout().unwrap();
3199            let (core, pods) = (plain.stages[0].mass, plain.stages[1].mass);
3200            let fore = plain.stages[1].fore_station_m;
3201            let off_axis = pods.cg_m.x.hypot(pods.cg_m.y);
3202            assert_eq!(count == 1, off_axis > 0.04, "{count} pods: {off_axis}");
3203
3204            // No station: at the pods' center.
3205            let mut design = boosted(count, angle_rad);
3206            design.stages[1].added_mass = Some(AddedMass {
3207                mass_kg: 0.25,
3208                cg_aft_m: None,
3209            });
3210            let layout = design.layout().unwrap();
3211            let stage = layout.stages[1].mass;
3212            close(stage.mass_kg, pods.mass_kg + 0.25, 1e-15, "mass");
3213            close((stage.cg_m - pods.cg_m).length(), 0.0, 1e-15, "center");
3214            close(pitch(&stage), pitch(&pods), 1e-15, "inertia");
3215            assert_eq!(layout.stages[0].mass, core, "the stage it hangs on");
3216
3217            // A station: 0.1 m aft of the parallel stage's forward end, level with the pods'
3218            // center.
3219            design.stages[1].added_mass = Some(AddedMass {
3220                mass_kg: 0.25,
3221                cg_aft_m: Some(0.1),
3222            });
3223            let layout = design.layout().unwrap();
3224            let stage = layout.stages[1].mass;
3225            let (m_p, x_p, x_a) = (pods.mass_kg, -pods.cg_m.z, fore + 0.1);
3226            let center = (m_p * x_p + 0.25 * x_a) / (m_p + 0.25);
3227            close(stage.mass_kg, m_p + 0.25, 1e-15, "mass at a station");
3228            close(-stage.cg_m.z, center, 1e-15, "center at a station");
3229            close(
3230                stage.cg_m.x.hypot(stage.cg_m.y),
3231                off_axis,
3232                1e-15,
3233                "off the axis",
3234            );
3235            // Across the axis, about an axis through the new center: the pods' own inertia there
3236            // and the point's, each moved along the axis only (they are level with each other).
3237            let along = m_p * (x_p - center).powi(2) + 0.25 * (x_a - center).powi(2);
3238            let trace = |m: &MassProperties| m.inertia_kg_m2.x_axis.x + m.inertia_kg_m2.y_axis.y;
3239            close(
3240                trace(&stage),
3241                trace(&pods) + 2.0 * along,
3242                1e-12,
3243                "inertia at a station",
3244            );
3245            close(
3246                stage.inertia_kg_m2.z_axis.z,
3247                pods.inertia_kg_m2.z_axis.z,
3248                1e-15,
3249                "roll at a station",
3250            );
3251
3252            // On the stage the pods hang on: a point among that stage's parts, the pods not
3253            // counted, and the parallel stage as it was. One pod off the axis is refused there
3254            // (`a_parallel_stage_hangs_on_a_body_tube_of_an_earlier_axial_stage`).
3255            if count == 1 {
3256                continue;
3257            }
3258            let mut design = boosted(count, angle_rad);
3259            design.stages[0].added_mass = Some(AddedMass {
3260                mass_kg: 0.25,
3261                cg_aft_m: Some(0.1),
3262            });
3263            let layout = design.layout().unwrap();
3264            let stage = layout.stages[0].mass;
3265            let (m_c, x_c) = (core.mass_kg, -core.cg_m.z);
3266            close(stage.mass_kg, m_c + 0.25, 1e-15, "the core's mass");
3267            close(
3268                -stage.cg_m.z,
3269                (m_c * x_c + 0.25 * 0.1) / (m_c + 0.25),
3270                1e-15,
3271                "the core's center",
3272            );
3273            assert_eq!(layout.stages[1].mass, pods, "the parallel stage");
3274            close(
3275                layout.structure.mass_kg,
3276                plain.structure.mass_kg + 0.25,
3277                1e-15,
3278                "structure",
3279            );
3280        }
3281    }
3282
3283    /// A pod's mass properties are the parallel-axis sum worked by hand: the tube and the mass as
3284    /// textbook cylinders, stacked along the pod, then moved out to each pod's axis.
3285    #[test]
3286    fn a_pod_is_its_stack_repeated_with_its_parallel_axis_term() {
3287        use std::f64::consts::{FRAC_PI_2, PI};
3288        // One pod, about its own axis. The pod set sits at station 0.2 + 0.1 = 0.3 m.
3289        let (rho, length, ro, ri) = (790.0, 0.3, 0.012, 0.011);
3290        let m_t = rho * PI * (ro * ro - ri * ri) * length;
3291        let (ax_t, tr_t) = (
3292            m_t * (ro * ro + ri * ri) / 2.0,
3293            m_t * (3.0 * (ro * ro + ri * ri) + length * length) / 12.0,
3294        );
3295        let z_t = 0.3 + 0.15;
3296        let (m_c, l_c, r_c) = (0.05, 0.1, 0.008);
3297        let (ax_c, tr_c) = (
3298            m_c * r_c * r_c / 2.0,
3299            m_c * (3.0 * r_c * r_c + l_c * l_c) / 12.0,
3300        );
3301        let z_c = 0.3 + 0.02 + 0.05;
3302        let m1 = m_t + m_c;
3303        let z1 = (m_t * z_t + m_c * z_c) / m1;
3304        let axial1 = ax_t + ax_c;
3305        let transverse1 = tr_t + m_t * (z_t - z1).powi(2) + tr_c + m_c * (z_c - z1).powi(2);
3306        let d = 0.05;
3307
3308        // Two pods on the x axis, at 0 and π.
3309        let base = three_fin_rocket().layout().unwrap();
3310        let two = podded(2, 0.0).layout().unwrap();
3311        let (_, pods) = two.find("pods").unwrap();
3312        let mass = pods.with_children;
3313        close(mass.mass_kg, 2.0 * m1, 1e-15, "two pods' mass");
3314        close(mass.cg_m.x, 0.0, 1e-16, "center x");
3315        close(mass.cg_m.y, 0.0, 1e-16, "center y");
3316        close(-mass.cg_m.z, z1, 1e-15, "center station");
3317        let i = mass.inertia_kg_m2;
3318        // Both pods lie on the x axis, so rolling about x moves them only along the pod's length.
3319        close(i.col(0).x, 2.0 * transverse1, 1e-15, "I_xx");
3320        close(i.col(1).y, 2.0 * (transverse1 + m1 * d * d), 1e-15, "I_yy");
3321        close(i.col(2).z, 2.0 * (axial1 + m1 * d * d), 1e-15, "I_zz");
3322        for (k, product) in [i.col(1).x, i.col(2).x, i.col(2).y].into_iter().enumerate() {
3323            close(product, 0.0, 1e-16, &format!("product {k}"));
3324        }
3325        close(pods.length_m, 0.3, 1e-15, "the pod's extent");
3326        assert_eq!(pods.own.mass_kg, 0.0);
3327        let (_, pod_tube) = two.find("pod-tube").unwrap();
3328        close(pod_tube.fore_station_m, 0.3, 1e-15, "pod tube station");
3329        assert_eq!(pod_tube.copies.len(), 2);
3330        close(pod_tube.copies[1].offset_m[0], -d, 1e-16, "second pod x");
3331        assert_eq!(pod_tube.copies[1].roll_rad, PI);
3332        close(
3333            two.structure.mass_kg,
3334            base.structure.mass_kg + 2.0 * m1,
3335            1e-14,
3336            "structure",
3337        );
3338
3339        // One pod at 90°: off the axis, so its product of inertia about the body origin is
3340        // `I_yz = −m y z` with `y = d`, `z = −z1`.
3341        let one = podded(1, FRAC_PI_2).layout().unwrap();
3342        let (_, pod) = one.find("pods").unwrap();
3343        let mass = pod.with_children;
3344        close(mass.mass_kg, m1, 1e-15, "one pod's mass");
3345        close(mass.cg_m.x, 0.0, 1e-16, "center x");
3346        close(mass.cg_m.y, d, 1e-16, "center y");
3347        let i = mass.inertia_kg_m2;
3348        close(i.col(0).x, transverse1, 1e-15, "I_xx about its center");
3349        close(i.col(2).z, axial1, 1e-15, "I_zz about its center");
3350        let about_origin = mass.inertia_about(DVec3::ZERO);
3351        close(about_origin.col(2).y, m1 * d * z1, 1e-15, "I_yz");
3352        close(
3353            about_origin.col(2).z,
3354            axial1 + m1 * d * d,
3355            1e-15,
3356            "I_zz about the axis",
3357        );
3358        close(
3359            one.structure.cg_m.y,
3360            (base.structure.mass_kg * base.structure.cg_m.y + m1 * d)
3361                / (base.structure.mass_kg + m1),
3362            1e-15,
3363            "the rocket's center across the axis",
3364        );
3365    }
3366
3367    /// What a pod holds turns with its pod, as a rotational pattern: a mass 3 mm off the pod's
3368    /// axis, outward on the pod at 0°, is outward on the pod at 180° too, so the pair's center
3369    /// stays on the axis; alone at 90° it sits at `y = d + e`. A center override inside a pod is measured
3370    /// in the pod as written, and turns with it. An override on the pod set, covering its pods, is
3371    /// all the pods' mass; one on a part inside a pod is each copy's.
3372    #[test]
3373    fn what_a_pod_holds_turns_with_it_and_overrides_keep_their_scope() {
3374        use std::f64::consts::{FRAC_PI_2, PI};
3375        let (d, e) = (0.05, 0.003);
3376        let off_axis = |count: u32, angle_rad: f64| {
3377            let mut design = podded(count, angle_rad);
3378            let pod_tube = &mut design.stages[0].components[1].children[6].children[0];
3379            if let Part::MassComponent(mass) = &mut pod_tube.children[0].part {
3380                mass.packing.radial_offset_m = e;
3381            }
3382            design
3383        };
3384        let (rho, length, ro, ri) = (790.0, 0.3, 0.012, 0.011);
3385        let m_t = rho * PI * (ro * ro - ri * ri) * length;
3386        let m_c = 0.05;
3387
3388        let two = off_axis(2, 0.0).layout().unwrap();
3389        let pods = two.find("pods").unwrap().1.with_children;
3390        close(pods.cg_m.x, 0.0, 1e-16, "the pair's center x");
3391        close(pods.cg_m.y, 0.0, 1e-16, "the pair's center y");
3392        let roll = pods
3393            .inertia_about(DVec3::new(0.0, 0.0, pods.cg_m.z))
3394            .col(2)
3395            .z;
3396        let hand = 2.0
3397            * (m_t * (ro * ro + ri * ri) / 2.0
3398                + m_t * d * d
3399                + m_c * 0.008 * 0.008 / 2.0
3400                + m_c * (d + e) * (d + e));
3401        close(roll, hand, 1e-15, "the pair's roll inertia");
3402
3403        let one = off_axis(1, FRAC_PI_2).layout().unwrap();
3404        let (_, mass) = one.find("pod-mass").unwrap();
3405        close(mass.own.cg_m.x, 0.0, 1e-16, "the turned mass's x");
3406        close(mass.own.cg_m.y, d + e, 1e-16, "the turned mass's y");
3407
3408        // The pod tube's center set 10 mm out from the pod's axis, as written.
3409        let mut design = podded(1, FRAC_PI_2);
3410        let pod_tube = &mut design.stages[0].components[1].children[6].children[0];
3411        pod_tube.overrides.cg_xy_m = Some([0.01, 0.0]);
3412        let layout = design.layout().unwrap();
3413        let (_, tube) = layout.find("pod-tube").unwrap();
3414        close(tube.own.cg_m.x, 0.0, 1e-16, "the overridden center's x");
3415        close(
3416            tube.own.cg_m.y,
3417            d + 0.01,
3418            1e-16,
3419            "the overridden center's y",
3420        );
3421
3422        let set_to = |mass_kg: f64, on_set: bool| {
3423            let mut design = podded(2, 0.0);
3424            let pods = &mut design.stages[0].components[1].children[6];
3425            if on_set {
3426                pods.overrides.mass_kg = Some(mass_kg);
3427                pods.overrides_include_children = true;
3428            } else {
3429                pods.children[0].children[0].overrides.mass_kg = Some(mass_kg);
3430            }
3431            let layout = design.layout().unwrap();
3432            layout.find("pods").unwrap().1.with_children.mass_kg
3433        };
3434        close(set_to(0.3, true), 0.3, 1e-15, "an override on the pod set");
3435        close(
3436            set_to(0.1, false),
3437            2.0 * (m_t + 0.1),
3438            1e-15,
3439            "an override in each pod",
3440        );
3441    }
3442
3443    /// A pod's nose cone is not the airframe's: the nose-base reference diameter doesn't take it.
3444    #[test]
3445    fn a_pod_s_nose_is_not_the_reference_nose() {
3446        let mut design = podded(2, 0.0);
3447        let pods = &mut design.stages[0].components[1].children[6];
3448        pods.children.insert(0, body("pod-nose", nose(0.06, 0.012)));
3449        design.stages[0].components.remove(0);
3450        design.reference_diameter = ReferenceDiameter::NoseBase {};
3451        let error = design.layout().unwrap_err().to_string();
3452        assert!(error.contains("there is no nose cone"), "{error}");
3453    }
3454
3455    /// A pod's body components stack from the pod set and take their automatic radii from one
3456    /// another; a motor in a pod is one motor per pod; a pod's tubes are not internal parts to
3457    /// the checks; and the wrong trees are refused.
3458    #[test]
3459    fn pods_stack_hold_motors_and_refuse_the_wrong_trees() {
3460        let mut design = podded(3, 0.0);
3461        let pods = &mut design.stages[0].components[1].children[6];
3462        // The pods' aft ends 0.2 m past the airframe's, at 1.2 m: 1.0 − 0.36 + 0.2 = 0.84 m.
3463        pods.position = Some(bottom(0.2));
3464        let mut pod_nose = body("pod-nose", nose(0.06, 0.0));
3465        pod_nose.auto = vec![AutoDimension::BaseRadius];
3466        pods.children.insert(0, pod_nose);
3467        pods.children[1].motor_mount = Some(MotorMount { overhang_m: 0.005 });
3468        design.configurations.push(Configuration {
3469            id: "pods".to_owned(),
3470            name: String::new(),
3471            motors: vec![crate::testing::motor("pod-tube", 0.018, 0.1)],
3472        });
3473        let layout = design.layout().unwrap();
3474        let (_, set) = layout.find("pods").unwrap();
3475        close(set.length_m, 0.36, 1e-15, "the pods' extent");
3476        let (_, cone) = layout.find("pod-nose").unwrap();
3477        let Part::NoseCone(cone_part) = &cone.part else {
3478            panic!("a nose cone");
3479        };
3480        assert_eq!(cone_part.base_radius_m, 0.012);
3481        close(cone.fore_station_m, 0.84, 1e-15, "pod nose station");
3482        close(station(&layout, "pod-tube"), 0.9, 1e-15, "pod tube station");
3483        let three = PodSet {
3484            count: 3,
3485            radial_offset_m: 0.05,
3486            angle_rad: 0.0,
3487        }
3488        .pods()
3489        .unwrap();
3490        assert_eq!(cone.copies, three);
3491        assert_eq!(layout.find("pod-mass").unwrap().1.copies, three);
3492
3493        let assembly = design.assemble("pods").unwrap();
3494        assert_eq!(assembly.motors.len(), 3);
3495        for (motor, pod) in assembly.motors.iter().zip(&three) {
3496            assert_eq!([motor.nozzle_m.x, motor.nozzle_m.y], pod.offset_m);
3497            close(motor.nozzle_station_m(), 1.2 + 0.005, 1e-15, "nozzle");
3498        }
3499
3500        // The pods run past the airframe's end, which the checks allow a pod.
3501        let findings = crate::checks::check(&design).unwrap();
3502        assert!(
3503            !findings.iter().any(|f| format!("{f:?}").contains("pod")),
3504            "{findings:?}"
3505        );
3506
3507        // The design page's JSON is the tests' pod set, empty but for its tube.
3508        let page = include_str!("../../../docs/physics/design.md");
3509        let block = page
3510            .split("\n### Pods\n")
3511            .nth(1)
3512            .and_then(|pods| pods.split("```json\n").nth(1))
3513            .and_then(|json| json.split("```").next())
3514            .expect("the Pods section has a JSON block");
3515        let mut written = podded(2, 0.0).stages[0].components[1].children[6].clone();
3516        written.children[0].children.clear();
3517        assert_eq!(
3518            serde_json::from_str::<Component>(block).unwrap(),
3519            written,
3520            "{block}"
3521        );
3522
3523        let json = serde_json::to_string(&design).unwrap();
3524        assert!(json.contains("\"pod_set\""));
3525        assert_eq!(serde_json::from_str::<Rocket>(&json).unwrap(), design);
3526
3527        let refused = |edit: &dyn Fn(&mut Component), want: &str| {
3528            let mut design = podded(2, 0.0);
3529            edit(&mut design.stages[0].components[1].children[6]);
3530            let error = design.layout().unwrap_err().to_string();
3531            assert!(error.contains(want), "{error}");
3532        };
3533        refused(
3534            &|pods| {
3535                pods.children
3536                    .push(attached("fin", fins(0.1, 0.05), top(0.0)))
3537            },
3538            "a pod holds body components",
3539        );
3540        refused(
3541            &|pods| pods.children[0].position = Some(top(0.0)),
3542            "stacks and takes no position",
3543        );
3544        refused(
3545            &|pods| {
3546                if let Part::PodSet(set) = &mut pods.part {
3547                    set.count = 0;
3548                }
3549            },
3550            "pod count",
3551        );
3552        refused(
3553            &|pods| {
3554                if let Part::PodSet(set) = &mut pods.part {
3555                    set.radial_offset_m = f64::NAN;
3556                }
3557            },
3558            "pod radial offset",
3559        );
3560        refused(
3561            &|pods| {
3562                if let Part::PodSet(set) = &mut pods.part {
3563                    set.count = PodSet::MAX_COUNT + 1;
3564                }
3565            },
3566            "pod count (1 to 64)",
3567        );
3568        refused(
3569            &|pods| pods.overrides.mass_kg = Some(0.2),
3570            "an override on it must cover its pods",
3571        );
3572        refused(
3573            &|pods| {
3574                let mut inner = pods.clone();
3575                inner.id = "inner-pods".to_owned();
3576                inner.children[0].id = "inner-tube".to_owned();
3577                inner.children[0].children[0].id = "inner-mass".to_owned();
3578                pods.children[0].children.push(inner);
3579            },
3580            "a pod set can't hang from a pod",
3581        );
3582        let mut on_nose = podded(2, 0.0);
3583        let pods = on_nose.stages[0].components[1].children.pop().unwrap();
3584        on_nose.stages[0].components[0].children.push(pods);
3585        let error = on_nose.layout().unwrap_err().to_string();
3586        assert!(error.contains("attaches to a body tube"), "{error}");
3587    }
3588
3589    /// A pod of no length (OpenRocket's "phantom body": a tube of no length, radius or wall) weighs
3590    /// nothing and holds what hangs from it at the pod's axis. A launch lug on it, turned to π, is
3591    /// the textbook hollow cylinder with its axis its own radius inward of the pod's, `d − R`, on
3592    /// both pods, since it turns with its pod; the pair's inertia is worked by hand. An empty pod
3593    /// set lays out and weighs nothing (M1.13b2).
3594    #[test]
3595    fn a_pod_of_no_length_holds_its_parts_at_the_pod_s_axis() {
3596        use std::f64::consts::PI;
3597        let (rho, length, ro, ri, d) = (790.0, 0.05, 0.004, 0.0035, 0.05);
3598        let lug = LaunchLug {
3599            length_m: length,
3600            outer_radius_m: ro,
3601            thickness_m: ro - ri,
3602            angle_rad: PI,
3603            count: 1,
3604            spacing_m: 0.0,
3605            material: crate::testing::cardboard(),
3606        };
3607        let mut phantom = body("phantom", tube(0.0, 0.0, 0.0));
3608        phantom.children = vec![attached(
3609            "pod-lug",
3610            Part::LaunchLug(lug),
3611            Position::Middle { aft_offset_m: 0.0 },
3612        )];
3613        let mut pods = attached(
3614            "pods",
3615            Part::PodSet(PodSet {
3616                count: 2,
3617                radial_offset_m: d,
3618                angle_rad: 0.0,
3619            }),
3620            top(0.1),
3621        );
3622        pods.children = vec![phantom];
3623        let mut design = three_fin_rocket();
3624        design.stages[0].components[1].children.push(pods);
3625        let base = three_fin_rocket().layout().unwrap();
3626        let layout = design.layout().unwrap();
3627
3628        let (_, set) = layout.find("pods").unwrap();
3629        assert_eq!(set.length_m, 0.0);
3630        let (_, phantom) = layout.find("phantom").unwrap();
3631        assert_eq!(phantom.own.mass_kg, 0.0);
3632        close(phantom.fore_station_m, 0.3, 1e-15, "the phantom's station");
3633        // Centered on a tube of no length at 0.3 m: from 0.275 m to 0.325 m.
3634        close(
3635            station(&layout, "pod-lug"),
3636            0.3 - 0.5 * length,
3637            1e-15,
3638            "lug station",
3639        );
3640        let m = rho * PI * (ro * ro - ri * ri) * length;
3641        let axial = m * (ro * ro + ri * ri) / 2.0;
3642        let transverse = m * (3.0 * (ro * ro + ri * ri) + length * length) / 12.0;
3643        let r = d - ro;
3644        let mass = set.with_children;
3645        close(mass.mass_kg, 2.0 * m, 1e-18, "two lugs' mass");
3646        close(mass.cg_m.x, 0.0, 1e-16, "center x");
3647        close(mass.cg_m.y, 0.0, 1e-16, "center y");
3648        close(-mass.cg_m.z, 0.3, 1e-15, "center station");
3649        let i = mass.inertia_kg_m2;
3650        close(i.col(0).x, 2.0 * transverse, 1e-18, "I_xx");
3651        close(i.col(1).y, 2.0 * (transverse + m * r * r), 1e-18, "I_yy");
3652        close(i.col(2).z, 2.0 * (axial + m * r * r), 1e-18, "I_zz");
3653        // Alone, the first pod's lug sits at `x = d − R`.
3654        let (_, lug) = layout.find("pod-lug").unwrap();
3655        close(lug.own.cg_m.x, 0.0, 1e-16, "the pair's center");
3656        let Part::LaunchLug(one) = &lug.part else {
3657            unreachable!("the lug")
3658        };
3659        let one = MassProperties::placed(one.mass_properties(0.0).unwrap(), &lug.copies[..1]);
3660        close(one.cg_m.x, r, 1e-16, "the first lug across the axis");
3661
3662        let mut empty = design.clone();
3663        let pods = empty.stages[0].components[1].children.last_mut();
3664        pods.expect("the pod set").children.clear();
3665        let layout = empty.layout().unwrap();
3666        let (_, set) = layout.find("pods").unwrap();
3667        assert!(set.length_m.is_sign_positive());
3668        assert_eq!(set.with_children.mass_kg, 0.0);
3669        assert_eq!(set.with_children.inertia_kg_m2, DMat3::ZERO);
3670        assert_eq!(layout.structure, base.structure);
3671
3672        // Only a pod may hold a body component of no length: a stage refuses one.
3673        let mut flat = three_fin_rocket();
3674        flat.stages[0]
3675            .components
3676            .push(body("flat", tube(0.0, 0.0, 0.0)));
3677        let error = flat.layout().unwrap_err();
3678        assert!(
3679            matches!(
3680                error,
3681                DesignError::InComponent { ref id, ref source }
3682                    if id == "flat" && matches!(**source, DesignError::Domain {
3683                        what: "body component length",
3684                        ..
3685                    })
3686            ),
3687            "{error:?}"
3688        );
3689    }
3690
3691    /// An override on a part inside a cluster is each copy's: set to the part's own mass it changes
3692    /// nothing, and doubled it doubles every copy. Both a solid part (an engine block) and a packed
3693    /// one (a mass component, rebuilt as its packing's cylinder) are worked one tube at a time.
3694    #[test]
3695    fn an_override_inside_a_cluster_is_each_copy_s() {
3696        let three: Vec<[f64; 2]> = [90.0_f64, 210.0, 330.0]
3697            .iter()
3698            .map(|a| [0.02 * a.to_radians().cos(), 0.02 * a.to_radians().sin()])
3699            .collect();
3700        let with = |part: Part, mass_kg: Option<f64>| {
3701            let mut design = crate::testing::three_fin_rocket();
3702            let mount = &mut design.stages[0].components[1].children[0];
3703            if let Part::InnerTube(tube) = &mut mount.part {
3704                tube.cluster_m = three.clone();
3705            }
3706            let mut inside = attached("inside", part, top(0.0));
3707            inside.overrides.mass_kg = mass_kg;
3708            mount.children = vec![inside];
3709            design.layout().unwrap()
3710        };
3711        for part in [
3712            inner_tube(0.01, 0.019, 0.005),
3713            mass_component(0.05, 0.04, 0.015),
3714        ] {
3715            let free = with(part.clone(), None);
3716            let (_, one) = free.find("inside").unwrap();
3717            let each_kg = one.own.mass_kg / 3.0;
3718            let same = with(part.clone(), Some(each_kg));
3719            let (a, b) = (&free.structure, &same.structure);
3720            close(b.mass_kg, a.mass_kg, 1e-15, "structure mass");
3721            assert!(
3722                (b.cg_m - a.cg_m).length() < 1e-15,
3723                "{:?} vs {:?}",
3724                b.cg_m,
3725                a.cg_m
3726            );
3727            for (x, y) in [
3728                (a.inertia_kg_m2.x_axis, b.inertia_kg_m2.x_axis),
3729                (a.inertia_kg_m2.y_axis, b.inertia_kg_m2.y_axis),
3730                (a.inertia_kg_m2.z_axis, b.inertia_kg_m2.z_axis),
3731            ] {
3732                assert!((x - y).length() < 1e-15, "{x:?} vs {y:?}");
3733            }
3734            let doubled = with(part, Some(2.0 * each_kg));
3735            let (_, inside) = doubled.find("inside").unwrap();
3736            close(inside.own.mass_kg, 6.0 * each_kg, 1e-15, "doubled");
3737            assert!(inside.own.cg_m.truncate().length() < 1e-17);
3738        }
3739    }
3740
3741    /// The tree's structure equals the parts placed by hand at their stations and combined.
3742    #[test]
3743    fn tree_structure_matches_parts_placed_by_hand() {
3744        let design = three_fin_rocket();
3745        let layout = design.layout().unwrap();
3746        let bore = 0.027 - 0.0015;
3747        let placed = |part: Part, body_radius: Option<f64>, s: f64| {
3748            part.mass_properties(body_radius)
3749                .unwrap()
3750                .translated(DVec3::new(0.0, 0.0, -s))
3751        };
3752        let mut chute = design.stages[0].components[1].children[4].part.clone();
3753        if let Part::Parachute(p) = &mut chute {
3754            p.packing.radius_m = bore;
3755        }
3756        let parts = [
3757            placed(nose(0.2, 0.027), None, 0.0),
3758            placed(tube(0.8, 0.027, 0.0015), None, 0.2),
3759            placed(inner_tube(0.3, 0.020, 0.001), None, 0.7),
3760            placed(ring(0.006, bore, 0.020), None, 1.0 - 0.006 - 0.25),
3761            placed(ring(0.006, bore, 0.020), None, 1.0 - 0.006 - 0.02),
3762            placed(fins(0.1, 0.06), Some(0.027), 0.9),
3763            placed(chute, None, 0.25),
3764            placed(
3765                design.stages[0].components[1].children[5].part.clone(),
3766                Some(0.027),
3767                0.2 + 0.5 * (0.8 - 0.05),
3768            ),
3769        ];
3770        let want = MassProperties::combine(&parts);
3771        let got = layout.structure;
3772        close(got.mass_kg, want.mass_kg, 1e-15 * want.mass_kg, "mass");
3773        assert!(
3774            (got.cg_m - want.cg_m).length() < 1e-14,
3775            "{:?} vs {:?}",
3776            got.cg_m,
3777            want.cg_m
3778        );
3779        let scale = want
3780            .inertia_kg_m2
3781            .to_cols_array()
3782            .iter()
3783            .fold(0.0f64, |m, v| m.max(v.abs()));
3784        let diff = (got.inertia_kg_m2 - want.inertia_kg_m2)
3785            .to_cols_array()
3786            .iter()
3787            .fold(0.0f64, |m, v| m.max(v.abs()));
3788        assert!(diff < 1e-13 * scale, "{diff:e}");
3789        assert_eq!(layout.stages[0].mass, got);
3790    }
3791
3792    fn tensor_close(a: DMat3, b: DMat3, rel: f64) {
3793        let scale = b.to_cols_array().iter().fold(0.0f64, |m, v| m.max(v.abs()));
3794        let diff = (a - b)
3795            .to_cols_array()
3796            .iter()
3797            .fold(0.0f64, |m, v| m.max(v.abs()));
3798        assert!(diff <= rel * scale, "{a:?}\nvs\n{b:?}");
3799    }
3800
3801    /// Each override does what `Overrides` says, alone or over the children, nested overrides
3802    /// apply first, and a stage's overrides cover the stage.
3803    #[test]
3804    fn overrides_rescale_move_and_replace() {
3805        let bay = || attached("bay", mass_component(0.4, 0.1, 0.02), top(0.3));
3806        let mut airframe = body("airframe", tube(0.8, 0.03, 0.001));
3807        airframe.children = vec![bay()];
3808        let plain = rocket(vec![stage(
3809            "s",
3810            vec![body("nose", nose(0.2, 0.03)), airframe.clone()],
3811        )]);
3812        let base = plain.layout().unwrap();
3813        let (_, tube_plain) = base.find("airframe").unwrap();
3814        let (_, bay_plain) = base.find("bay").unwrap();
3815
3816        // Mass alone: the tube doubles, keeping its center, and its tensor doubles.
3817        let mut overridden = airframe.clone();
3818        overridden.overrides.mass_kg = Some(2.0 * tube_plain.own.mass_kg);
3819        let design = rocket(vec![stage(
3820            "s",
3821            vec![body("nose", nose(0.2, 0.03)), overridden.clone()],
3822        )]);
3823        let layout = design.layout().unwrap();
3824        let (_, t) = layout.find("airframe").unwrap();
3825        close(
3826            t.own.mass_kg,
3827            2.0 * tube_plain.own.mass_kg,
3828            1e-15,
3829            "scaled mass",
3830        );
3831        assert!((t.own.cg_m - tube_plain.own.cg_m).length() < 1e-15);
3832        tensor_close(
3833            t.own.inertia_kg_m2,
3834            tube_plain.own.inertia_kg_m2 * 2.0,
3835            1e-14,
3836        );
3837        let with = MassProperties::combine([&t.own, &bay_plain.with_children]);
3838        assert_eq!(t.with_children, with, "the child is still added");
3839
3840        // Center and inertia over the tube and its child together.
3841        overridden.overrides = Overrides {
3842            mass_kg: Some(1.5),
3843            cg_aft_m: Some(0.35),
3844            cg_xy_m: Some([0.001, -0.002]),
3845            inertia: Some(InertiaOverride::axisymmetric(0.001, 0.08)),
3846        };
3847        overridden.overrides_include_children = true;
3848        let design = rocket(vec![stage(
3849            "s",
3850            vec![body("nose", nose(0.2, 0.03)), overridden.clone()],
3851        )]);
3852        let layout = design.layout().unwrap();
3853        let (_, t) = layout.find("airframe").unwrap();
3854        assert_eq!(t.own, tube_plain.own, "own mass untouched");
3855        close(t.with_children.mass_kg, 1.5, 0.0, "mass");
3856        close(
3857            t.with_children.cg_m.z,
3858            -(0.2 + 0.35),
3859            1e-15,
3860            "center from the tube's forward end",
3861        );
3862        assert_eq!(
3863            (t.with_children.cg_m.x, t.with_children.cg_m.y),
3864            (0.001, -0.002)
3865        );
3866        assert_eq!(
3867            t.with_children.inertia_kg_m2,
3868            DMat3::from_diagonal(DVec3::new(0.08, 0.08, 0.001))
3869        );
3870
3871        // A stage override applies last, over everything, from the stage's forward end.
3872        let mut design = design;
3873        design.stages[0].overrides = Overrides {
3874            mass_kg: Some(3.0),
3875            cg_aft_m: Some(0.5),
3876            cg_xy_m: None,
3877            inertia: None,
3878        };
3879        let layout = design.layout().unwrap();
3880        let stage_mass = layout.stages[0].mass;
3881        close(stage_mass.mass_kg, 3.0, 0.0, "stage mass");
3882        close(stage_mass.cg_m.z, -0.5, 1e-15, "stage center");
3883        let bodies: Vec<MassProperties> = layout.body().map(|c| c.with_children).collect();
3884        let unscaled = MassProperties::combine(&bodies);
3885        // Without `cg_xy_m` the stage keeps its offset, which the airframe's override gave it.
3886        assert!(unscaled.cg_m.x.abs() > 1e-5);
3887        assert_eq!(
3888            (stage_mass.cg_m.x, stage_mass.cg_m.y),
3889            (unscaled.cg_m.x, unscaled.cg_m.y)
3890        );
3891        tensor_close(
3892            stage_mass.inertia_kg_m2,
3893            unscaled.inertia_kg_m2 * (3.0 / unscaled.mass_kg),
3894            1e-14,
3895        );
3896        assert_eq!(layout.structure, stage_mass);
3897
3898        // An added mass comes before the stage's override, which covers it too.
3899        design.stages[0].added_mass = Some(AddedMass {
3900            mass_kg: 1.0,
3901            cg_aft_m: Some(0.1),
3902        });
3903        let under = design.layout().unwrap().stages[0].mass;
3904        close(under.mass_kg, 3.0, 0.0, "stage mass over an added mass");
3905        close(under.cg_m.z, -0.5, 1e-15, "stage center over an added mass");
3906
3907        // A massless body given a mass becomes a point mass at its center.
3908        let center = DVec3::new(0.0, 0.0, -0.4);
3909        let point = Overrides {
3910            mass_kg: Some(0.25),
3911            ..Overrides::default()
3912        }
3913        .apply(MassProperties::point(0.0, center), 0.0)
3914        .unwrap();
3915        assert_eq!(point, MassProperties::point(0.25, center));
3916
3917        // But a massless packed part takes it as a solid cylinder of its packing (ADR-063),
3918        // whether or not the override covers the parts inside.
3919        for covering in [false, true] {
3920            let mut airframe = airframe.clone();
3921            airframe.children = vec![attached(
3922                "ballast",
3923                mass_component(0.0, 0.1, 0.02),
3924                top(0.3),
3925            )];
3926            airframe.children[0].overrides.mass_kg = Some(0.25);
3927            airframe.children[0].overrides_include_children = covering;
3928            let design = rocket(vec![stage(
3929                "s",
3930                vec![body("nose", nose(0.2, 0.03)), airframe],
3931            )]);
3932            let layout = design.layout().unwrap();
3933            let (_, b) = layout.find("ballast").unwrap();
3934            let b = if covering { b.with_children } else { b.own };
3935            assert_eq!(b.mass_kg, 0.25);
3936            close(b.cg_m.z, -(0.2 + 0.3 + 0.05), 1e-15, "packing's center");
3937            let (r, l) = (0.02_f64, 0.1_f64);
3938            close(
3939                b.inertia_kg_m2.z_axis.z,
3940                0.5 * 0.25 * r * r,
3941                1e-15,
3942                "roll, m r²/2",
3943            );
3944            close(
3945                b.inertia_kg_m2.x_axis.x,
3946                0.25 * (3.0 * r * r + l * l) / 12.0,
3947                1e-15,
3948                "pitch, m (3r² + l²)/12",
3949            );
3950        }
3951
3952        // Overrides that make no real body are refused.
3953        let in_stage = |design: &Rocket| match design.layout() {
3954            Err(DesignError::InComponent { id, source }) if id == "s" => *source,
3955            other => panic!("{other:?}"),
3956        };
3957        let mut bad = plain.clone();
3958        bad.stages[0].overrides.mass_kg = Some(-1.0);
3959        assert!(matches!(in_stage(&bad), DesignError::Domain { .. }));
3960        let mut bad = plain.clone();
3961        bad.stages[0].overrides.inertia = Some(InertiaOverride::axisymmetric(1.0, 0.1));
3962        assert!(matches!(in_stage(&bad), DesignError::UnphysicalInertia(_)));
3963        for broken in [
3964            Overrides {
3965                cg_aft_m: Some(f64::NAN),
3966                ..Overrides::default()
3967            },
3968            Overrides {
3969                cg_xy_m: Some([0.0, f64::INFINITY]),
3970                ..Overrides::default()
3971            },
3972        ] {
3973            let mut bad = plain.clone();
3974            bad.stages[0].overrides = broken;
3975            assert!(matches!(in_stage(&bad), DesignError::Domain { .. }));
3976        }
3977        let mut bad = plain.clone();
3978        bad.stages[0].overrides.inertia = Some(InertiaOverride {
3979            xy_kg_m2: f64::NAN,
3980            ..InertiaOverride::axisymmetric(0.1, 1.0)
3981        });
3982        assert!(matches!(in_stage(&bad), DesignError::UnphysicalInertia(_)));
3983        // Zero mass scales the tensor to zero, but a massless body can't be given an inertia.
3984        let mut zero = plain.clone();
3985        zero.stages[0].overrides.mass_kg = Some(0.0);
3986        assert_eq!(zero.layout().unwrap().structure.inertia_kg_m2, DMat3::ZERO);
3987        let mut bad = plain;
3988        bad.stages[0].overrides.mass_kg = Some(0.0);
3989        bad.stages[0].overrides.inertia = Some(InertiaOverride::axisymmetric(1.0, 5.0));
3990        assert!(matches!(in_stage(&bad), DesignError::UnphysicalInertia(_)));
3991    }
3992
3993    /// A tree that doesn't hold together is refused with the offending id.
3994    #[test]
3995    fn malformed_trees_are_refused() {
3996        let base = || {
3997            rocket(vec![stage(
3998                "s",
3999                vec![
4000                    body("nose", nose(0.2, 0.03)),
4001                    body("tube", tube(0.5, 0.03, 0.001)),
4002                ],
4003            )])
4004        };
4005        let tree_error = |design: Rocket, want: &str| match design.layout() {
4006            Err(DesignError::Tree { id, .. }) => assert_eq!(id, want),
4007            other => panic!("{want}: {other:?}"),
4008        };
4009
4010        let mut d = base();
4011        d.stages[0].components[1].children =
4012            vec![attached("mmt", inner_tube(0.2, 0.01, 0.001), top(0.0))];
4013        d.stages[0].components[1].children[0].children =
4014            vec![attached("fins", fins(0.1, 0.05), top(0.0))];
4015        tree_error(d, "fins");
4016
4017        // A lug has no footing on a nose cone; a fin set may sit there with its root along the
4018        // surface (ADR-166), which a level trapezoid's is not.
4019        let mut d = base();
4020        let lug = Part::LaunchLug(crate::LaunchLug {
4021            length_m: 0.03,
4022            outer_radius_m: 0.003,
4023            thickness_m: 0.0005,
4024            angle_rad: 0.0,
4025            count: 1,
4026            spacing_m: 0.0,
4027            material: crate::testing::cardboard(),
4028        });
4029        d.stages[0].components[0].children = vec![attached("lug", lug, top(0.0))];
4030        tree_error(d, "lug");
4031        let mut d = base();
4032        d.stages[0].components[0].children = vec![attached("fins", fins(0.1, 0.05), top(0.0))];
4033        match d.layout() {
4034            Err(DesignError::InComponent { id, source }) => {
4035                assert_eq!(id, "fins");
4036                assert!(
4037                    matches!(&*source, DesignError::Geometry(m) if m.contains("stands")),
4038                    "{source}"
4039                );
4040            }
4041            other => panic!("fins on the nose: {other:?}"),
4042        }
4043
4044        let mut d = base();
4045        d.stages[0].components[1].children =
4046            vec![attached("inner-body", tube(0.1, 0.02, 0.001), top(0.0))];
4047        tree_error(d, "inner-body");
4048
4049        let mut d = base();
4050        d.stages[0]
4051            .components
4052            .push(body("ballast", mass_component(0.1, 0.1, 0.01)));
4053        tree_error(d, "ballast");
4054
4055        let mut d = base();
4056        d.stages[0].components[1].children = vec![body("unplaced", mass_component(0.1, 0.1, 0.01))];
4057        tree_error(d, "unplaced");
4058
4059        let mut d = base();
4060        d.stages[0].components[1].position = Some(top(0.0));
4061        tree_error(d, "tube");
4062
4063        let mut d = base();
4064        d.stages[0].components[1].auto = vec![AutoDimension::BaseRadius];
4065        tree_error(d, "tube");
4066
4067        let mut d = base();
4068        d.stages[0].components[1].children =
4069            vec![attached("ring", ring(0.005, 0.02, 0.0), top(0.0))];
4070        d.stages[0].components[1].children[0].motor_mount = Some(MotorMount::default());
4071        tree_error(d, "ring");
4072
4073        let mut d = base();
4074        d.stages[0].components[1].children =
4075            vec![attached("bay", mass_component(0.1, 0.1, 0.01), top(0.0))];
4076        d.stages[0].components[1].children[0].children =
4077            vec![attached("x", mass_component(0.1, 0.1, 0.01), top(0.0))];
4078        tree_error(d, "bay");
4079
4080        let mut d = base();
4081        d.stages[0].components[0].children =
4082            vec![attached("weight", mass_component(0.1, 0.05, 0.0), top(0.0))];
4083        d.stages[0].components[0].children[0].auto = vec![AutoDimension::PackedRadius];
4084        tree_error(d, "weight");
4085
4086        let mut d = base();
4087        d.stages.push(stage("empty", Vec::new()));
4088        tree_error(d, "empty");
4089
4090        let mut d = base();
4091        d.stages[0].components[1].id = "nose".to_owned();
4092        assert_eq!(d.layout(), Err(DesignError::DuplicateId("nose".to_owned())));
4093        let mut d = base();
4094        d.stages[0].components[1].id = String::new();
4095        assert!(matches!(d.layout(), Err(DesignError::DuplicateId(_))));
4096
4097        let mut d = base();
4098        d.stages.clear();
4099        assert!(matches!(d.layout(), Err(DesignError::Tree { .. })));
4100    }
4101
4102    /// A child's own override applies before its parent's override over the subtree: the parent's
4103    /// mass override rescales a total that already holds the child's overridden mass.
4104    #[test]
4105    fn nested_overrides_apply_deepest_first() {
4106        let mut airframe = body("airframe", tube(0.8, 0.03, 0.001));
4107        let mut bay = attached("bay", mass_component(0.4, 0.1, 0.02), top(0.3));
4108        bay.overrides.mass_kg = Some(1.0);
4109        airframe.children = vec![bay];
4110        let plain = rocket(vec![stage("s", vec![airframe.clone()])]);
4111        let layout = plain.layout().unwrap();
4112        let (_, t) = layout.find("airframe").unwrap();
4113        let (_, b) = layout.find("bay").unwrap();
4114        assert_eq!(b.own.mass_kg, 1.0);
4115        close(
4116            t.with_children.mass_kg,
4117            t.own.mass_kg + 1.0,
4118            1e-15,
4119            "child override inside",
4120        );
4121
4122        airframe.overrides.mass_kg = Some(3.0);
4123        airframe.overrides_include_children = true;
4124        let layout = rocket(vec![stage("s", vec![airframe])]).layout().unwrap();
4125        let (_, t2) = layout.find("airframe").unwrap();
4126        close(
4127            t2.with_children.mass_kg,
4128            3.0,
4129            0.0,
4130            "parent override over the total",
4131        );
4132        // The rescaled subtree keeps the center of the tube plus the 1 kg bay, not the 0.4 kg bay.
4133        close(
4134            t2.with_children.cg_m.z,
4135            t.with_children.cg_m.z,
4136            1e-15,
4137            "center kept",
4138        );
4139    }
4140
4141    /// The aft radius and aft shoulder take the tube behind a transition; missing shoulders, a
4142    /// shoulder with no tube, a nose-base reference with no nose, too deep a tree, and a bad part
4143    /// are all refused with the offending id.
4144    #[test]
4145    fn aft_radii_and_resolution_errors() {
4146        let boattail = |aft_shoulder: bool| {
4147            let mut c = body(
4148                "flare",
4149                Part::Transition(Transition {
4150                    shape: crate::NoseShape::Conical {},
4151                    clipped: false,
4152                    length_m: 0.1,
4153                    fore_radius_m: 0.03,
4154                    aft_radius_m: 0.0,
4155                    wall: crate::Wall::Shell { thickness_m: 0.002 },
4156                    fore_shoulder: None,
4157                    aft_shoulder: aft_shoulder.then_some(Shoulder {
4158                        length_m: 0.04,
4159                        outer_radius_m: 0.0,
4160                        thickness_m: 0.002,
4161                        capped: false,
4162                    }),
4163                    material: crate::testing::cardboard(),
4164                }),
4165            );
4166            c.auto = vec![AutoDimension::AftRadius, AutoDimension::AftShoulderRadius];
4167            c
4168        };
4169        let with = |flare: Component, last: Component| {
4170            rocket(vec![stage(
4171                "s",
4172                vec![
4173                    body("nose", nose(0.2, 0.03)),
4174                    body("upper", tube(0.5, 0.03, 0.001)),
4175                    flare,
4176                    last,
4177                ],
4178            )])
4179        };
4180        let layout = with(boattail(true), body("lower", tube(0.4, 0.04, 0.0015)))
4181            .layout()
4182            .unwrap();
4183        let Part::Transition(t) = layout.find("flare").unwrap().1.part.clone() else {
4184            panic!()
4185        };
4186        assert_eq!(t.aft_radius_m, 0.04);
4187        assert_eq!(t.aft_shoulder.unwrap().outer_radius_m, 0.04 - 0.0015);
4188
4189        let tree_id = |result: Result<Layout, DesignError>| match result {
4190            Err(DesignError::Tree { id, .. }) => id,
4191            other => panic!("{other:?}"),
4192        };
4193        // No shoulder to size.
4194        let lower = || body("lower", tube(0.4, 0.04, 0.0015));
4195        assert_eq!(tree_id(with(boattail(false), lower()).layout()), "flare");
4196        // A shoulder into a transition, not a tube.
4197        let mut cone = boattail(true);
4198        cone.id = "cone".to_owned();
4199        cone.auto = vec![AutoDimension::AftShoulderRadius];
4200        if let Part::Transition(t) = &mut cone.part {
4201            t.aft_radius_m = 0.02;
4202        }
4203        assert_eq!(tree_id(with(boattail(true), cone).layout()), "flare");
4204
4205        let mut no_nose = with(boattail(true), lower());
4206        no_nose.stages[0].components.remove(0);
4207        no_nose.reference_diameter = ReferenceDiameter::NoseBase {};
4208        assert!(matches!(no_nose.layout(), Err(DesignError::Tree { .. })));
4209
4210        // A body tube holding `n` nested inner tubes: `n + 1` levels.
4211        let nest = |n: usize| {
4212            let mut deepest = attached("t0", inner_tube(0.1, 0.02, 0.001), top(0.0));
4213            for k in 1..n {
4214                let mut outer = attached(&format!("t{k}"), inner_tube(0.1, 0.02, 0.001), top(0.0));
4215                outer.children = vec![deepest];
4216                deepest = outer;
4217            }
4218            let mut airframe = body("airframe", tube(0.5, 0.03, 0.001));
4219            airframe.children = vec![deepest];
4220            rocket(vec![stage("s", vec![airframe])])
4221        };
4222        nest(MAX_DEPTH - 1).layout().unwrap();
4223        assert_eq!(tree_id(nest(MAX_DEPTH).layout()), "t0");
4224
4225        // A part's own error names the part.
4226        let bad = with(boattail(true), body("lower", tube(0.4, 0.04, -0.001)));
4227        assert!(matches!(
4228            bad.layout(),
4229            Err(DesignError::InComponent { ref id, ref source })
4230                if id == "lower" && matches!(**source, DesignError::Domain { .. })
4231        ));
4232        let mut bad = with(boattail(true), lower());
4233        bad.stages[0].components[1].children = vec![attached(
4234            "lost",
4235            mass_component(0.1, 0.1, 0.01),
4236            top(f64::NAN),
4237        )];
4238        assert!(matches!(
4239            bad.layout(),
4240            Err(DesignError::InComponent { ref id, .. }) if id == "lost"
4241        ));
4242    }
4243
4244    /// An automatic packed radius fills the bore on the part's side of the axis, and an offset
4245    /// outside the bore is refused.
4246    #[test]
4247    fn packed_radius_leaves_room_for_the_offset() {
4248        let mut design = three_fin_rocket();
4249        if let Part::Parachute(chute) = &mut design.stages[0].components[1].children[4].part {
4250            chute.packing.radial_offset_m = 0.005;
4251        }
4252        let layout = design.layout().unwrap();
4253        let Part::Parachute(chute) = layout.find("chute").unwrap().1.part.clone() else {
4254            panic!()
4255        };
4256        close(
4257            chute.packing.radius_m,
4258            0.0255 - 0.005,
4259            1e-15,
4260            "packed radius",
4261        );
4262        assert!(crate::checks::check(&design).unwrap().is_empty());
4263        if let Part::Parachute(chute) = &mut design.stages[0].components[1].children[4].part {
4264            chute.packing.radial_offset_m = 0.03;
4265        }
4266        assert!(matches!(
4267            design.layout(),
4268            Err(DesignError::Tree { ref id, .. }) if id == "chute"
4269        ));
4270    }
4271
4272    #[test]
4273    fn design_round_trips_through_json() {
4274        let design = three_fin_rocket();
4275        let text = serde_json::to_string_pretty(&design).unwrap();
4276        let back: Rocket = serde_json::from_str(&text).unwrap();
4277        assert_eq!(back, design);
4278        assert_eq!(back.layout().unwrap(), design.layout().unwrap());
4279        // Unknown fields are refused, not dropped.
4280        let bad = text.replacen("\"auto\"", "\"autos\"", 1);
4281        assert!(serde_json::from_str::<Rocket>(&bad).is_err());
4282    }
4283
4284    /// A random spine for the property below: a kind (0 a nose cone, first only; 1 a tube; 2 a
4285    /// transition), whether each end is automatic, and each end's fixed radius in centimeters.
4286    type SpineSpec = Vec<(usize, bool, bool, u8, u8)>;
4287
4288    fn random_spine(spec: &SpineSpec, split: usize) -> Rocket {
4289        let mut components = Vec::new();
4290        for (k, &(kind, fore_auto, aft_auto, fore_cm, aft_cm)) in spec.iter().enumerate() {
4291            let (fore, aft) = (f64::from(fore_cm) * 0.01, f64::from(aft_cm) * 0.01);
4292            let id = format!("c{k}");
4293            let mut c = match kind {
4294                0 if k == 0 => body(&id, nose(0.2, aft)),
4295                2 => body(&id, cone_transition(fore, aft)),
4296                _ => body(&id, tube(0.3, aft, 0.001)),
4297            };
4298            c.auto = match &c.part {
4299                Part::NoseCone(_) if aft_auto => vec![AutoDimension::BaseRadius],
4300                Part::BodyTube(_) if aft_auto => vec![AutoDimension::OuterRadius],
4301                Part::Transition(_) => [
4302                    (fore_auto, AutoDimension::ForeRadius),
4303                    (aft_auto, AutoDimension::AftRadius),
4304                ]
4305                .into_iter()
4306                .filter_map(|(on, dimension)| on.then_some(dimension))
4307                .collect(),
4308                _ => Vec::new(),
4309            };
4310            components.push(c);
4311        }
4312        // Split into two stages somewhere, so the property crosses a stage boundary too.
4313        let split = split.clamp(1, components.len());
4314        let aft = components.split_off(split);
4315        let mut stages = vec![stage("upper", components)];
4316        if !aft.is_empty() {
4317            stages.push(stage("lower", aft));
4318        }
4319        rocket(stages)
4320    }
4321
4322    proptest! {
4323        /// Over random spines, `unresolvable_body_radii` is empty exactly when `layout` succeeds;
4324        /// filling what it lists is all `layout` then needs; and every radius the neighbor rule
4325        /// could already reach comes out as it did before the fill.
4326        #[test]
4327        fn unresolvable_radii_are_exactly_what_layout_refuses(
4328            spec in proptest::collection::vec((0usize..3, any::<bool>(), any::<bool>(), 1u8..5, 1u8..5), 1..7),
4329            split in 1usize..7,
4330        ) {
4331            let mut design = random_spine(&spec, split);
4332            let unresolvable = design.unresolvable_body_radii();
4333            prop_assert_eq!(unresolvable.is_empty(), design.layout().is_ok(), "{:?}", unresolvable);
4334
4335            let body = |design: &Rocket| -> (Vec<Part>, Vec<Vec<AutoDimension>>) {
4336                design
4337                    .stages
4338                    .iter()
4339                    .flat_map(|s| s.components.iter())
4340                    .map(|c| (c.part.clone(), c.auto.clone()))
4341                    .unzip()
4342            };
4343            let (parts, autos) = body(&design);
4344            let autos: Vec<&[AutoDimension]> = autos.iter().map(Vec::as_slice).collect();
4345            let (fore, aft) = sweep_body_radii(&parts, &autos);
4346
4347            let filled = design.fill_unresolvable_body_radii(0.025);
4348            prop_assert_eq!(&filled, &unresolvable);
4349            prop_assert!(design.unresolvable_body_radii().is_empty());
4350            let layout = design.layout();
4351            prop_assert!(layout.is_ok(), "{:?}", layout.as_ref().err());
4352            let layout = layout.unwrap();
4353            for (n, placed) in layout.body().enumerate() {
4354                let (f, a) = match &placed.part {
4355                    Part::NoseCone(p) => (None, Some(p.base_radius_m)),
4356                    Part::BodyTube(p) => (Some(p.outer_radius_m), Some(p.outer_radius_m)),
4357                    Part::Transition(p) => (Some(p.fore_radius_m), Some(p.aft_radius_m)),
4358                    _ => (None, None),
4359                };
4360                // A radius the sweep reached before the fill is the one layout gives after it.
4361                if let (Some(before), Some(after)) = (fore[n], f) {
4362                    prop_assert_eq!(before, after, "forward radius of {}", placed.id);
4363                }
4364                if let (Some(before), Some(after)) = (aft[n], a) {
4365                    prop_assert_eq!(before, after, "aft radius of {}", placed.id);
4366                }
4367            }
4368        }
4369
4370        /// Placed at random along a tube and rolled, point-like masses sum to the structure's mass
4371        /// and center, and sliding every part aft by `d` slides the center by `d` without changing
4372        /// the tensor.
4373        #[test]
4374        fn structure_is_the_mass_weighted_sum_and_slides_rigidly(
4375            parts in proptest::collection::vec((0.01f64..2.0, 0.0f64..0.7, 0.0f64..0.02, -3.0f64..3.0), 1..6),
4376            d in -0.1f64..0.1,
4377        ) {
4378            let build = |shift: f64| {
4379                let mut airframe = body("airframe", tube(1.0, 0.03, 0.001));
4380                airframe.children = parts
4381                    .iter()
4382                    .enumerate()
4383                    .map(|(k, &(m, s, r, angle))| {
4384                        let mut c = attached(&format!("m{k}"), mass_component(m, 0.05, 0.005), top(s + shift));
4385                        if let Part::MassComponent(p) = &mut c.part {
4386                            p.packing.radial_offset_m = r;
4387                            p.packing.angle_rad = angle;
4388                        }
4389                        c
4390                    })
4391                    .collect();
4392                // A massless tube leaves only the masses.
4393                if let Part::BodyTube(t) = &mut airframe.part {
4394                    t.material = crate::Material::bulk("none", 0.0);
4395                }
4396                rocket(vec![stage("s", vec![airframe])]).layout().unwrap()
4397            };
4398            let layout = build(0.0);
4399            let total: f64 = parts.iter().map(|p| p.0).sum();
4400            prop_assert!((layout.structure.mass_kg - total).abs() <= 1e-12 * total);
4401            let moment: f64 = parts.iter().map(|&(m, s, _, _)| m * -(s + 0.025)).sum();
4402            prop_assert!((layout.structure.cg_m.z - moment / total).abs() <= 1e-12);
4403            let slid = build(d);
4404            prop_assert!((slid.structure.cg_m.z - (layout.structure.cg_m.z - d)).abs() <= 1e-12);
4405            let scale = layout.structure.inertia_kg_m2.to_cols_array().iter().fold(1e-12f64, |m, v| m.max(v.abs()));
4406            let diff = (slid.structure.inertia_kg_m2 - layout.structure.inertia_kg_m2)
4407                .to_cols_array()
4408                .iter()
4409                .fold(0.0f64, |m, v| m.max(v.abs()));
4410            prop_assert!(diff <= 1e-9 * scale, "{diff:e} of {scale:e}");
4411        }
4412    }
4413
4414    /// [`StageOverrideRule::PartsInPlace`] leaves a stage's parts where the design puts them:
4415    /// its inertia is theirs about the stage's center, the mass an override adds and an added
4416    /// mass with no station sit at that center, and the mass and the center are what the default
4417    /// rule gives. Held to the parallel-axis theorem by hand, on the lower of two stages.
4418    #[test]
4419    fn a_stages_overrides_leave_its_parts_in_place_by_its_rule() {
4420        let mut design = three_fin_rocket();
4421        let mut booster = design.stages[0].clone();
4422        booster.id = "booster".to_owned();
4423        booster
4424            .components
4425            .retain(|c| matches!(c.part, Part::BodyTube(_)));
4426        for (index, component) in booster.components.iter_mut().enumerate() {
4427            component.id = format!("booster-{index}");
4428            component.children.clear();
4429        }
4430        design.stages.push(booster);
4431        let plain = design.layout().unwrap();
4432        let parts = plain.stages[1].mass;
4433        let fore = plain.stages[1].fore_station_m;
4434        let with = |rule: StageOverrideRule, added: Option<AddedMass>, overrides: Overrides| {
4435            let mut design = design.clone();
4436            design.stages[1].override_rule = rule;
4437            design.stages[1].added_mass = added;
4438            design.stages[1].overrides = overrides;
4439            design.layout().map(|layout| layout.stages[1].mass)
4440        };
4441        let in_place =
4442            |added, overrides| with(StageOverrideRule::PartsInPlace, added, overrides).unwrap();
4443        let rescaled =
4444            |added, overrides| with(StageOverrideRule::Rescaled, added, overrides).unwrap();
4445        let pitch = |mass: &MassProperties| mass.inertia_kg_m2.x_axis.x;
4446        let roll = |mass: &MassProperties| mass.inertia_kg_m2.z_axis.z;
4447        let (m_p, x_p) = (parts.mass_kg, -parts.cg_m.z);
4448        let c = fore + 0.3;
4449        assert!((x_p - c).abs() > 0.05, "{x_p} {c}");
4450        let heavy = Overrides {
4451            mass_kg: Some(4.0),
4452            ..Overrides::default()
4453        };
4454        let center = Overrides {
4455            cg_aft_m: Some(0.3),
4456            ..Overrides::default()
4457        };
4458        let both = Overrides {
4459            mass_kg: Some(4.0),
4460            cg_aft_m: Some(0.3),
4461            ..Overrides::default()
4462        };
4463
4464        // No override: the two rules are the same stage, bit for bit.
4465        assert_eq!(in_place(None, Overrides::default()), parts);
4466
4467        // A mass alone: the parts' inertia, not scaled.
4468        let stage = in_place(None, heavy);
4469        close(stage.mass_kg, 4.0, 0.0, "mass under a mass");
4470        close(stage.cg_m.z, parts.cg_m.z, 1e-15, "center under a mass");
4471        close(pitch(&stage), pitch(&parts), 1e-15, "pitch under a mass");
4472        close(roll(&stage), roll(&parts), 1e-15, "roll under a mass");
4473        close(
4474            pitch(&rescaled(None, heavy)),
4475            pitch(&parts) * 4.0 / m_p,
4476            1e-12,
4477            "the default rule scales it",
4478        );
4479
4480        // A center alone, and both: the parts' inertia about the new center.
4481        let about_c = pitch(&parts) + m_p * (x_p - c).powi(2);
4482        for (overrides, mass_kg) in [(center, m_p), (both, 4.0)] {
4483            let stage = in_place(None, overrides);
4484            close(stage.mass_kg, mass_kg, 1e-15, "mass");
4485            close(-stage.cg_m.z, c, 1e-15, "center");
4486            close(pitch(&stage), about_c, 1e-12, "pitch about the center");
4487            close(roll(&stage), roll(&parts), 1e-15, "roll");
4488            let default = rescaled(None, overrides);
4489            assert_eq!(
4490                (default.mass_kg, default.cg_m),
4491                (stage.mass_kg, stage.cg_m),
4492                "{overrides:?}"
4493            );
4494        }
4495
4496        // An added mass with no station sits at the stage's center: beside a center override,
4497        // at the override's.
4498        let added = AddedMass {
4499            mass_kg: 0.5,
4500            cg_aft_m: None,
4501        };
4502        let stage = in_place(Some(added), center);
4503        close(stage.mass_kg, m_p + 0.5, 1e-15, "mass with an added mass");
4504        close(-stage.cg_m.z, c, 1e-15, "center with an added mass");
4505        close(pitch(&stage), about_c, 1e-12, "the added mass adds nothing");
4506        // With no center override it sits at the parts' center, as under the default rule.
4507        assert_eq!(
4508            in_place(Some(added), heavy),
4509            MassProperties {
4510                mass_kg: 4.0,
4511                ..parts
4512            }
4513        );
4514
4515        // An added mass at a station has a place of its own, among the parts.
4516        let stationed = AddedMass {
4517            mass_kg: 0.5,
4518            cg_aft_m: Some(0.1),
4519        };
4520        let whole = stationed.add_to(parts, fore).unwrap();
4521        let stage = in_place(Some(stationed), heavy);
4522        close(pitch(&stage), pitch(&whole), 1e-15, "a stationed mass");
4523        let stage = in_place(Some(stationed), center);
4524        close(
4525            pitch(&stage),
4526            pitch(&whole) + whole.mass_kg * (-whole.cg_m.z - c).powi(2),
4527            1e-12,
4528            "a stationed mass under a center",
4529        );
4530
4531        // A stated inertia replaces the tensor; a mass of nothing leaves none.
4532        let stated = Overrides {
4533            inertia: Some(InertiaOverride::axisymmetric(0.01, 0.2)),
4534            ..both
4535        };
4536        let stage = in_place(None, stated);
4537        assert_eq!(
4538            stage.inertia_kg_m2,
4539            InertiaOverride::axisymmetric(0.01, 0.2).tensor()
4540        );
4541        let nothing = Overrides {
4542            mass_kg: Some(0.0),
4543            ..center
4544        };
4545        let stage = in_place(None, nothing);
4546        assert_eq!((stage.mass_kg, stage.inertia_kg_m2), (0.0, DMat3::ZERO));
4547        assert!(
4548            with(
4549                StageOverrideRule::PartsInPlace,
4550                None,
4551                Overrides {
4552                    mass_kg: Some(-1.0),
4553                    ..Overrides::default()
4554                }
4555            )
4556            .is_err()
4557        );
4558    }
4559
4560    /// The rule is written only when it isn't the default, by its snake-case name, and reads
4561    /// back; a name it doesn't have is refused.
4562    #[test]
4563    fn a_stages_override_rule_reads_and_writes_by_name() {
4564        let mut stage = crate::testing::stage("s", Vec::new());
4565        let json = serde_json::to_string(&stage).unwrap();
4566        assert!(!json.contains("override_rule"), "{json}");
4567        stage.override_rule = StageOverrideRule::PartsInPlace;
4568        let json = serde_json::to_string(&stage).unwrap();
4569        assert!(
4570            json.contains(r#""override_rule":"parts_in_place""#),
4571            "{json}"
4572        );
4573        assert_eq!(serde_json::from_str::<Stage>(&json).unwrap(), stage);
4574        let rescaled = json.replace("parts_in_place", "rescaled");
4575        assert_eq!(
4576            serde_json::from_str::<Stage>(&rescaled)
4577                .unwrap()
4578                .override_rule,
4579            StageOverrideRule::Rescaled
4580        );
4581        assert!(
4582            serde_json::from_str::<Stage>(&json.replace("parts_in_place", "in_place")).is_err()
4583        );
4584    }
4585
4586    /// A stage's added mass is a point mass among its parts ([`AddedMass`]), worked by hand: with
4587    /// no station it sits at the parts' center and moves nothing; with one it sits that far aft
4588    /// of its own stage's forward end, as far off the axis as the parts' center is, and the
4589    /// stage's center and inertia follow the parallel-axis theorem. A whole-stage center override then moves the two together.
4590    #[test]
4591    fn a_stages_added_mass_is_a_point_among_its_parts() {
4592        // Two stages, so that the lower one's forward end isn't the tip.
4593        let mut design = three_fin_rocket();
4594        let mut booster = design.stages[0].clone();
4595        booster.id = "booster".to_owned();
4596        booster
4597            .components
4598            .retain(|c| matches!(c.part, Part::BodyTube(_)));
4599        for (index, component) in booster.components.iter_mut().enumerate() {
4600            component.id = format!("booster-{index}");
4601            component.children.clear();
4602        }
4603        design.stages.push(booster);
4604        let plain = design.layout().unwrap();
4605        let parts = plain.stages[1].mass;
4606        let fore = plain.stages[1].fore_station_m;
4607        assert!(fore > 0.5 && parts.mass_kg > 0.0, "{fore} {parts:?}");
4608        let with = |added: Option<AddedMass>, overrides: Overrides| {
4609            let mut design = design.clone();
4610            design.stages[1].added_mass = added;
4611            design.stages[1].overrides = overrides;
4612            design.layout()
4613        };
4614        let none = Overrides::default();
4615        let pitch = |mass: &MassProperties| mass.inertia_kg_m2.x_axis.x;
4616        let roll = |mass: &MassProperties| mass.inertia_kg_m2.z_axis.z;
4617
4618        // No station: at the parts' center. Only the mass changes.
4619        let added = AddedMass {
4620            mass_kg: 0.5,
4621            cg_aft_m: None,
4622        };
4623        let layout = with(Some(added), none).unwrap();
4624        let stage = layout.stages[1].mass;
4625        close(stage.mass_kg, parts.mass_kg + 0.5, 1e-15, "mass");
4626        close(stage.cg_m.z, parts.cg_m.z, 1e-15, "center");
4627        close(pitch(&stage), pitch(&parts), 1e-12, "pitch inertia");
4628        close(roll(&stage), roll(&parts), 1e-15, "roll inertia");
4629        assert!(!layout.stages[1].center_overridden);
4630        // The other stage is untouched, and the rocket is the two stages.
4631        assert_eq!(layout.stages[0], plain.stages[0]);
4632        close(
4633            layout.structure.mass_kg,
4634            plain.structure.mass_kg + 0.5,
4635            1e-15,
4636            "rocket mass",
4637        );
4638
4639        // A station, 0.1 m aft of the lower stage's forward end.
4640        let stationed = AddedMass {
4641            mass_kg: 0.5,
4642            cg_aft_m: Some(0.1),
4643        };
4644        let layout = with(Some(stationed), none).unwrap();
4645        let stage = layout.stages[1].mass;
4646        let (m_p, x_p, x_a) = (parts.mass_kg, -parts.cg_m.z, fore + 0.1);
4647        let x = (m_p * x_p + 0.5 * x_a) / (m_p + 0.5);
4648        close(stage.mass_kg, m_p + 0.5, 1e-15, "mass");
4649        close(-stage.cg_m.z, x, 1e-15, "center");
4650        assert!(
4651            (x - x_p).abs() > 0.01,
4652            "the point moves the center: {x} {x_p}"
4653        );
4654        close(
4655            pitch(&stage),
4656            pitch(&parts) + m_p * (x_p - x).powi(2) + 0.5 * (x_a - x).powi(2),
4657            1e-12,
4658            "pitch inertia",
4659        );
4660        close(roll(&stage), roll(&parts), 1e-15, "roll inertia");
4661        assert_eq!((stage.cg_m.x, stage.cg_m.y), (0.0, 0.0));
4662        assert!(layout.stages[1].center_overridden);
4663
4664        // A whole-stage center moves the parts and the added mass together; a whole-stage mass
4665        // is the two together's.
4666        let center = Overrides {
4667            cg_aft_m: Some(0.3),
4668            ..Overrides::default()
4669        };
4670        let stage = with(Some(added), center).unwrap().stages[1].mass;
4671        close(stage.mass_kg, m_p + 0.5, 1e-15, "mass under a center");
4672        close(-stage.cg_m.z, fore + 0.3, 1e-15, "center under a center");
4673        close(
4674            pitch(&stage),
4675            pitch(&parts),
4676            1e-12,
4677            "inertia under a center",
4678        );
4679        let heavy = Overrides {
4680            mass_kg: Some(4.0),
4681            ..Overrides::default()
4682        };
4683        let stage = with(Some(stationed), heavy).unwrap().stages[1].mass;
4684        close(stage.mass_kg, 4.0, 0.0, "mass under a mass");
4685        close(-stage.cg_m.z, x, 1e-15, "center under a mass");
4686
4687        // Nothing added changes nothing, at a station or not.
4688        for cg_aft_m in [None, Some(0.1)] {
4689            let nothing = AddedMass {
4690                mass_kg: 0.0,
4691                cg_aft_m,
4692            };
4693            let layout = with(Some(nothing), none).unwrap();
4694            assert_eq!(layout.stages[1].mass, plain.stages[1].mass);
4695            assert_eq!(layout.structure, plain.structure);
4696        }
4697
4698        // Refused: a negative or non-finite mass, a non-finite station, and a mass with no
4699        // station on parts that weigh nothing.
4700        let what = |added: AddedMass, parts: MassProperties| match added.add_to(parts, 0.0) {
4701            Err(DesignError::Domain { what, .. }) => what,
4702            other => panic!("{other:?}"),
4703        };
4704        for mass_kg in [-0.1, f64::NAN, f64::INFINITY] {
4705            let bad = AddedMass {
4706                mass_kg,
4707                cg_aft_m: None,
4708            };
4709            assert_eq!(what(bad, parts), "added mass (kg)");
4710            assert!(with(Some(bad), none).is_err());
4711        }
4712        for station in [f64::NAN, f64::NEG_INFINITY] {
4713            let bad = AddedMass {
4714                mass_kg: 0.5,
4715                cg_aft_m: Some(station),
4716            };
4717            assert_eq!(what(bad, parts), "added mass's station (m)");
4718        }
4719        let weightless = MassProperties::point(0.0, DVec3::new(0.0, 0.0, -0.4));
4720        assert_eq!(
4721            what(added, weightless),
4722            "added mass with no station, on parts that weigh nothing (kg)"
4723        );
4724        // With a station the point is the whole stage, on the axis even if the weightless
4725        // parts' place is off it.
4726        assert_eq!(
4727            stationed.add_to(weightless, 1.0).unwrap(),
4728            MassProperties::point(0.5, DVec3::new(0.0, 0.0, -1.1))
4729        );
4730        let nowhere = MassProperties::point(0.0, DVec3::new(0.02, 0.0, -0.4));
4731        assert_eq!(
4732            stationed.add_to(nowhere, 1.0).unwrap(),
4733            MassProperties::point(0.5, DVec3::new(0.0, 0.0, -1.1))
4734        );
4735
4736        // A station moves the point along the axis only: beside parts whose center is off the
4737        // axis it sits as far off it as that center, so the stage's center stays there too.
4738        let off_axis = MassProperties::point(0.25, DVec3::new(0.003, -0.004, -0.4));
4739        let level = stationed.add_to(off_axis, 1.0).unwrap();
4740        close(level.cg_m.x, 0.003, 1e-15, "off the axis, one way");
4741        close(level.cg_m.y, -0.004, 1e-15, "off the axis, the other");
4742        close(
4743            -level.cg_m.z,
4744            (0.25 * 0.4 + 0.5 * 1.1) / 0.75,
4745            1e-15,
4746            "center along the axis",
4747        );
4748        close(
4749            pitch(&level),
4750            0.25 * 0.5 / 0.75 * 0.7_f64.powi(2),
4751            1e-15,
4752            "inertia of two points in line with the axis",
4753        );
4754        close(
4755            roll(&level),
4756            0.0,
4757            1e-18,
4758            "roll inertia of two points in line",
4759        );
4760
4761        // It is written only when there is one, and read back the same.
4762        let json = serde_json::to_string(&design).unwrap();
4763        assert!(!json.contains("added_mass"), "{json}");
4764        let mut carrying = design.clone();
4765        carrying.stages[1].added_mass = Some(stationed);
4766        let json = serde_json::to_string(&carrying).unwrap();
4767        assert!(
4768            json.contains(r#""added_mass":{"mass_kg":0.5,"cg_aft_m":0.1}"#),
4769            "{json}"
4770        );
4771        assert_eq!(serde_json::from_str::<Rocket>(&json).unwrap(), carrying);
4772    }
4773
4774    /// A layout written before the move to US spelling, its parts and stages holding
4775    /// `centre_overridden`, reads as the same layout: a part and a stage that set an axial center
4776    /// hold `true` under the old key, which a missing alias would read as `false`.
4777    #[test]
4778    fn a_layout_with_the_old_uk_key_reads_the_same() {
4779        let mut design = three_fin_rocket();
4780        design.stages[0].overrides.cg_aft_m = Some(0.4);
4781        design.stages[0].components[0].overrides.cg_aft_m = Some(0.1);
4782        let layout = design.layout().unwrap();
4783        assert!(layout.stages[0].center_overridden);
4784        let text = serde_json::to_string(&layout).unwrap();
4785        let old = text.replace("\"center_overridden\"", "\"centre_overridden\"");
4786        assert!(!old.contains("\"center_overridden\""));
4787        assert!(
4788            old.matches("\"centre_overridden\":true").count() >= 2,
4789            "a part and a stage: {old}"
4790        );
4791        assert_eq!(serde_json::from_str::<Layout>(&old).unwrap(), layout);
4792    }
4793}