Skip to main content

hpr_sim/
pieces.rs

1//! Ejected pieces: an airframe that comes apart at any joint, or lets a payload out, and the pieces
2//! that fly on to their own landings.
3//!
4//! A [`Separation`] parts the stack at a stage boundary. An [`Ejection`] parts it anywhere else:
5//! at the joint aft of any body component (a nose cone pushed off its airframe, say), or around a
6//! payload carried inside (an internal component and everything inside it). Each has a trigger, as
7//! a recovery device does. The pieces are fixed before the flight by where the airframe can part.
8//! At any moment a body is the pieces still joined, and its mass is the sum of theirs (the
9//! decision record on ejected pieces, [ADR-085][adr-085], which extends the one on separation,
10//! [ADR-014][adr-014]).
11//!
12//! Method: `docs/physics/recovery.md`, *Ejected pieces*.
13//!
14//! [adr-014]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-014-separation-bodies-their-masses-and-their-descents-2026-09-17
15//! [adr-085]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-085-ejected-pieces-an-airframe-that-parts-at-any-joint-2026-09-26
16
17use hpr_design::{Assembly, Component, MassProperties, Rocket};
18use serde::{Deserialize, Serialize};
19
20use crate::error::SimError;
21use crate::recovery::{DeviceDrag, Separation, Trigger};
22
23/// Where an airframe parts at an [`Ejection`].
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case", deny_unknown_fields)]
26#[non_exhaustive]
27pub enum Parting {
28    /// At the joint just aft of the body component with this id. Everything aft of the joint, up
29    /// to the next joint that can part, is a new piece. The part forward of it keeps its number,
30    /// so an ejected nose cone is the forward side of the joint after the nose.
31    AftOf {
32        /// The id of the body component forward of the joint.
33        component: String,
34    },
35    /// Around the internal component with this id: it and everything inside it leave the piece
36    /// that carries it, as a payload pushed out of a body tube does. It must be inside the
37    /// airframe, one part (not one copy of a cluster's), and not inside another payload.
38    Payload {
39        /// The id of the internal component that leaves.
40        component: String,
41    },
42}
43
44/// A piece of the airframe leaving the rest on a trigger: the airframe parts at a joint, or lets a
45/// payload out.
46///
47/// The piece it makes flies on as a body of its own, numbered after the separation's aft body:
48/// with a [`Separation`] the first ejection makes body 2, without one body 1, and each ejection
49/// after it the next number, in the order given. A body is the pieces still joined, and it is
50/// numbered by the piece nearest the nose among them, so the body that keeps the nose is always
51/// body 0. Pieces joined by a shock cord fly as one, so a joint whose pieces stay tied together
52/// is not an ejection at all.
53///
54/// When the airframe first comes apart each body starts at its own center of mass with the
55/// velocity that point had. A body already flying as a point mass has no attitude to place its
56/// pieces by, so they start where it was, at its velocity. Every motor must have burned out by the
57/// time an ejection fires. The decision record on ejected pieces, [ADR-085][adr-085], has the
58/// reasoning.
59///
60/// An ejection can push its two sides apart with an impulse `J` ([`Self::with_impulse`]), the
61/// charge's or spring's: the side forward of the joint, or a payload, which leaves forward, takes
62/// `+J` along the airframe's axis toward the nose, and the other side `−J`, so each changes
63/// velocity by `J/m` for its own mass `m` and the momentum is unchanged. The axis is the
64/// airframe's while it flies with nothing open. A body with no attitude of its own (a point mass,
65/// or a stack whose attitude froze when a device opened earlier) is taken to point its forward end
66/// against its velocity through the air if it hangs from a device, any but a tumble, open just
67/// before that instant, and along it, as a stable airframe does, if nothing is open or it only
68/// tumbles; below 1 mm/s through the air, up ([ADR-086][adr-086]). Partings at one instant part a
69/// body together. A separation adds no impulse, and a pushed payload in the nose's piece is
70/// refused.
71///
72/// [adr-085]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-085-ejected-pieces-an-airframe-that-parts-at-any-joint-2026-09-26
73/// [adr-086]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-086-ejection-impulse-and-tumbling-pieces-2026-09-26
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75#[serde(deny_unknown_fields)]
76#[non_exhaustive]
77pub struct Ejection {
78    /// When the piece leaves: the same triggers as a recovery device's.
79    pub trigger: Trigger,
80    /// Where the airframe parts.
81    pub parting: Parting,
82    /// The impulse `J` that pushes the two sides apart, N·s: zero (the default) for none.
83    #[serde(default, skip_serializing_if = "is_zero")]
84    pub impulse_n_s: f64,
85}
86
87/// Whether an impulse is zero, so a file without one writes none.
88fn is_zero(impulse_n_s: &f64) -> bool {
89    *impulse_n_s == 0.0
90}
91
92impl Ejection {
93    /// The airframe parting at the joint aft of body component `component`, on `trigger`.
94    #[must_use]
95    pub fn aft_of(trigger: Trigger, component: impl Into<String>) -> Self {
96        Self {
97            trigger,
98            parting: Parting::AftOf {
99                component: component.into(),
100            },
101            impulse_n_s: 0.0,
102        }
103    }
104
105    /// Internal component `component` and what it holds leaving the airframe, on `trigger`.
106    #[must_use]
107    pub fn payload(trigger: Trigger, component: impl Into<String>) -> Self {
108        Self {
109            trigger,
110            parting: Parting::Payload {
111                component: component.into(),
112            },
113            impulse_n_s: 0.0,
114        }
115    }
116
117    /// The same ejection, pushing its two sides apart with the impulse `impulse_n_s`, N·s: the
118    /// side forward of the joint, or the payload, gets it toward the nose, and the other side its
119    /// opposite. [`crate::Simulation::with_ejections`] refuses one that is negative or not
120    /// finite. A pushed payload needs a way out forward: one in the nose's piece is refused when
121    /// the flight starts, and one whose section's forward joint hasn't parted when it leaves is
122    /// an error in flight.
123    #[must_use]
124    pub fn with_impulse(mut self, impulse_n_s: f64) -> Self {
125        self.impulse_n_s = impulse_n_s;
126        self
127    }
128}
129
130/// The pieces a design can come apart into, fixed before the flight by its separations and its
131/// ejections.
132///
133/// Piece 0 is the one with the nose. Separation `k` makes piece `k + 1`, and ejection `k` makes
134/// the piece after the separations'. A split's index in that order is its piece's minus one.
135#[derive(Debug, Clone)]
136pub(crate) struct Pieces {
137    /// The piece that carries each piece, when it is a payload or a parallel stage; `None` for a
138    /// section.
139    host: Vec<Option<usize>>,
140    /// Whether each piece is a parallel stage: hung beside the piece that carries it, with tubes
141    /// and fins of its own, it leaves at a separation as a payload leaves its host.
142    beside: Vec<bool>,
143    /// The section pieces, nose to tail.
144    sections: Vec<usize>,
145    /// The structure of each piece: mass properties that add up to it, motors not included.
146    structure: Vec<Vec<MassProperties>>,
147    /// The piece of each placed motor.
148    motor_piece: Vec<usize>,
149    /// The first and last stage each piece has a component in.
150    stages: Vec<(usize, usize)>,
151    /// The piece of each placed component.
152    piece_of: Vec<usize>,
153}
154
155impl Pieces {
156    /// The pieces of `assembly` (assembled from `rocket`) under `separations` and `ejections`.
157    ///
158    /// # Errors
159    ///
160    /// [`SimError::Parting`] for an ejection that names a component the design doesn't have, a
161    /// joint aft of an internal component or of the last body component, a pod's body component as
162    /// a joint or a payload, a payload that is a body component, an external part, one of several
163    /// copies in a cluster or inside another payload, two partings at one joint or of one payload,
164    /// or a split through a stage or component whose overridden mass doesn't say how it divides;
165    /// [`SimError::Domain`] for a separation with no stage aft of it.
166    pub(crate) fn new(
167        rocket: &Rocket,
168        assembly: &Assembly,
169        separations: &[Separation],
170        ejections: &[Ejection],
171    ) -> Result<Self, SimError> {
172        let components = &assembly.layout.components;
173        let refuse = |what: &'static str, component: &str| SimError::Parting {
174            what,
175            component: component.to_owned(),
176        };
177        let find = |id: &str| {
178            components
179                .iter()
180                .position(|component| component.id == id)
181                .ok_or_else(|| refuse("an ejection names a component the design doesn't have", id))
182        };
183        let top: Vec<usize> = (0..components.len())
184            .filter(|&index| components[index].parent.is_none())
185            .collect();
186        let count = 1 + separations.len() + ejections.len();
187
188        // Where each section starts, as a position in `top`, and each payload.
189        let mut starts: Vec<(usize, usize)> = Vec::new();
190        let mut payloads: Vec<(usize, usize)> = Vec::new();
191        let mut beside = vec![false; count];
192        let mut piece = 1;
193        for separation in separations {
194            let first = separation.after_stage + 1;
195            if assembly
196                .layout
197                .stages
198                .get(first)
199                .is_some_and(|stage| stage.hung_on.is_some())
200            {
201                // A parallel stage drops alone (`Simulation::with_separations` checks that what a
202                // separation drops hangs together): the pod set it is laid out as, and everything
203                // in it, leaves the piece it hangs on (ADR-171).
204                let pods = (0..components.len()).find(|&index| {
205                    components[index].stage == first
206                        && components[index]
207                            .parent
208                            .is_some_and(|parent| components[parent].stage != first)
209                });
210                let Some(pods) = pods else {
211                    return Err(SimError::Domain {
212                        what: "stage boundary of a separation (the parallel stage aft of it has no \
213                               parts)",
214                        value: separation.after_stage as f64,
215                    });
216                };
217                payloads.push((pods, piece));
218                beside[piece] = true;
219                piece += 1;
220                continue;
221            }
222            let Some(at) = top
223                .iter()
224                .position(|&index| components[index].stage > separation.after_stage)
225            else {
226                return Err(SimError::Domain {
227                    what: "stage boundary of a separation (there is no stage aft of it)",
228                    value: separation.after_stage as f64,
229                });
230            };
231            starts.push((at, piece));
232            piece += 1;
233        }
234        for ejection in ejections {
235            match &ejection.parting {
236                Parting::AftOf { component } => {
237                    let index = find(component)?;
238                    if components[index].parent.is_some() && components[index].part.is_body() {
239                        return Err(refuse(
240                            "a pod's body component leaves with the tube its pod set hangs \
241                             from, at no joint of its own and not as a payload",
242                            component,
243                        ));
244                    }
245                    if components[index].parent.is_some() {
246                        return Err(refuse(
247                            "a joint is aft of a body component, and this one is inside another \
248                             (a part carried inside is a `Parting::Payload`)",
249                            component,
250                        ));
251                    }
252                    // `index` is a body component, so it is in `top`.
253                    let Some(at) = top.iter().position(|&body| body == index).map(|at| at + 1)
254                    else {
255                        return Err(refuse(
256                            "a body component missing from the layout",
257                            component,
258                        ));
259                    };
260                    if at >= top.len() {
261                        return Err(refuse(
262                            "a joint aft of the last body component (nothing is aft of it)",
263                            component,
264                        ));
265                    }
266                    if starts.iter().any(|(start, _)| *start == at) {
267                        return Err(refuse(
268                            "two partings at the joint aft of this component (a separation's \
269                             stage boundary is a joint too)",
270                            component,
271                        ));
272                    }
273                    starts.push((at, piece));
274                }
275                Parting::Payload { component } => {
276                    let index = find(component)?;
277                    if components[index].part.is_body() && components[index].parent.is_some() {
278                        return Err(refuse(
279                            "a pod's body component leaves with the tube its pod set hangs \
280                             from, at no joint of its own and not as a payload",
281                            component,
282                        ));
283                    }
284                    if components[index].parent.is_none() {
285                        return Err(refuse(
286                            "a payload is carried inside the airframe, and this is a body \
287                             component (a body component leaves at a joint, `Parting::AftOf`)",
288                            component,
289                        ));
290                    }
291                    if components[index].body_radius_m.is_some() {
292                        return Err(refuse(
293                            "a payload is carried inside the airframe, and this part is outside it",
294                            component,
295                        ));
296                    }
297                    if components[index].copies.len() != 1 {
298                        return Err(refuse(
299                            "a payload that isn't exactly one part (one of several copies in a \
300                             cluster of tubes, or none)",
301                            component,
302                        ));
303                    }
304                    if payloads.iter().any(|(payload, _)| *payload == index) {
305                        return Err(refuse("two ejections of one payload", component));
306                    }
307                    payloads.push((index, piece));
308                }
309            }
310            piece += 1;
311        }
312
313        // A payload inside another would need a piece carried by a piece; not flown yet.
314        for &(payload, _) in &payloads {
315            let mut ancestor = components[payload].parent;
316            while let Some(index) = ancestor {
317                if payloads.iter().any(|(other, _)| *other == index) {
318                    return Err(refuse(
319                        "a payload inside another payload",
320                        &components[payload].id,
321                    ));
322                }
323                ancestor = components[index].parent;
324            }
325        }
326
327        // Every component's piece. A parent is placed before its children, so its piece is known.
328        let mut piece_of = vec![0; components.len()];
329        let mut host = vec![None; count];
330        let mut sections = vec![0];
331        let mut section = 0;
332        let mut position = 0;
333        for index in 0..components.len() {
334            let carried = match components[index].parent {
335                None => {
336                    if let Some(&(_, start)) = starts.iter().find(|(at, _)| *at == position) {
337                        section = start;
338                        sections.push(start);
339                    }
340                    position += 1;
341                    section
342                }
343                Some(parent) => piece_of[parent],
344            };
345            piece_of[index] = match payloads.iter().find(|(payload, _)| *payload == index) {
346                Some(&(_, payload)) => {
347                    host[payload] = Some(carried);
348                    payload
349                }
350                None => carried,
351            };
352        }
353
354        // Whether a component's subtree in its own stage spans more than one piece. A parallel
355        // stage hung on a component is no part of its mass (`with_children`), so it doesn't count.
356        let same_stage =
357            |index: usize, parent: usize| components[index].stage == components[parent].stage;
358        let mut mixed = vec![false; components.len()];
359        for index in (0..components.len()).rev() {
360            if let Some(parent) = components[index].parent
361                && same_stage(index, parent)
362                && (mixed[index] || piece_of[index] != piece_of[parent])
363            {
364                mixed[parent] = true;
365            }
366        }
367        let mut children: Vec<Vec<usize>> = vec![Vec::new(); components.len()];
368        for (index, component) in components.iter().enumerate() {
369            if let Some(parent) = component.parent
370                && same_stage(index, parent)
371            {
372                children[parent].push(index);
373            }
374        }
375
376        // The structure: a stage wholly in one piece by its own mass, which carries the stage's
377        // overrides and added mass; otherwise its components, each by its subtree's mass where that subtree is in
378        // one piece and by its own mass plus its children's where it isn't.
379        let mut structure: Vec<Vec<MassProperties>> = vec![Vec::new(); count];
380        for (stage, placed) in assembly.layout.stages.iter().enumerate() {
381            let pieces: Vec<usize> = (0..components.len())
382                .filter(|&index| components[index].stage == stage)
383                .map(|index| piece_of[index])
384                .collect();
385            if let Some(&first) = pieces.first()
386                && pieces.iter().all(|&piece| piece == first)
387            {
388                structure[first].push(placed.mass);
389                continue;
390            }
391            if rocket
392                .stages
393                .iter()
394                .find(|stage| stage.id == placed.id)
395                .is_some_and(|stage| !stage.overrides.is_empty())
396            {
397                return Err(refuse(
398                    "a parting through a stage whose mass is overridden (the override doesn't \
399                     say which piece its mass is in)",
400                    &placed.id,
401                ));
402            }
403            if rocket
404                .stages
405                .iter()
406                .find(|stage| stage.id == placed.id)
407                .is_some_and(|stage| stage.added_mass.is_some())
408            {
409                return Err(refuse(
410                    "a parting through a stage that carries an added mass (it doesn't say \
411                     which piece the mass is in)",
412                    &placed.id,
413                ));
414            }
415            // The stage's roots: its body components, or a parallel stage's pod set.
416            let mut pending: Vec<usize> = (0..components.len())
417                .filter(|&index| {
418                    components[index].stage == stage
419                        && components[index]
420                            .parent
421                            .is_none_or(|parent| !same_stage(index, parent))
422                })
423                .rev()
424                .collect();
425            while let Some(index) = pending.pop() {
426                let component = &components[index];
427                if !mixed[index] {
428                    structure[piece_of[index]].push(component.with_children);
429                    continue;
430                }
431                if node(rocket, &component.id).is_some_and(|node| {
432                    node.overrides_include_children && !node.overrides.is_empty()
433                }) {
434                    return Err(refuse(
435                        "a parting inside a component whose overridden mass covers what it holds \
436                         (the override doesn't say which piece that mass is in)",
437                        &component.id,
438                    ));
439                }
440                structure[piece_of[index]].push(component.own);
441                pending.extend(children[index].iter().rev());
442            }
443        }
444
445        let motor_piece = assembly
446            .motors
447            .iter()
448            .map(|motor| {
449                components
450                    .iter()
451                    .position(|component| component.id == motor.mount)
452                    .map(|index| piece_of[index])
453                    .ok_or_else(|| refuse("a motor's mount is not in the design", &motor.mount))
454            })
455            .collect::<Result<Vec<_>, _>>()?;
456
457        let mut stages = vec![(usize::MAX, 0); count];
458        for (index, component) in components.iter().enumerate() {
459            let (first, last) = &mut stages[piece_of[index]];
460            *first = (*first).min(component.stage);
461            *last = (*last).max(component.stage);
462        }
463        for (first, last) in &mut stages {
464            if *first == usize::MAX {
465                // A piece with no component can't happen: every parting leaves one on each side.
466                (*first, *last) = (0, 0);
467            }
468        }
469
470        Ok(Self {
471            host,
472            beside,
473            sections,
474            structure,
475            motor_piece,
476            stages,
477            piece_of,
478        })
479    }
480
481    /// How many pieces there are.
482    pub(crate) fn count(&self) -> usize {
483        self.host.len()
484    }
485
486    /// The body each piece is in when the splits with `open[split]` have happened: the body's
487    /// number is its lead piece's, the section nearest the nose among its pieces, or the payload
488    /// itself for a payload flying alone.
489    pub(crate) fn leaders(&self, open: &[bool]) -> Vec<usize> {
490        let mut leader: Vec<usize> = (0..self.count()).collect();
491        let mut current = 0;
492        for &section in &self.sections {
493            if section == 0 || open[section - 1] {
494                current = section;
495            }
496            leader[section] = current;
497        }
498        for piece in 0..self.count() {
499            leader[piece] = self.lead(piece, open, &leader);
500        }
501        leader
502    }
503
504    /// The lead piece of `piece`'s body, with the sections' in `sections_led`.
505    fn lead(&self, piece: usize, open: &[bool], sections_led: &[usize]) -> usize {
506        match self.host[piece] {
507            None => sections_led[piece],
508            Some(_) if open[piece - 1] => piece,
509            Some(host) => self.lead(host, open, sections_led),
510        }
511    }
512
513    /// The mass properties of the pieces for which `member` is true, with their motors at flight
514    /// time `t_s`, each lit at its `ignition_s`.
515    pub(crate) fn mass_properties(
516        &self,
517        member: impl Fn(usize) -> bool,
518        assembly: &Assembly,
519        t_s: f64,
520        ignition_s: &[Option<f64>],
521    ) -> MassProperties {
522        let mut parts: Vec<MassProperties> = Vec::new();
523        for (piece, structure) in self.structure.iter().enumerate() {
524            if member(piece) {
525                parts.extend(structure);
526            }
527        }
528        for ((motor, ignition), piece) in assembly
529            .motors
530            .iter()
531            .zip(ignition_s)
532            .zip(&self.motor_piece)
533        {
534            if member(*piece) {
535                parts.push(motor.mass_properties_lit(t_s, *ignition));
536            }
537        }
538        MassProperties::combine(parts.iter())
539    }
540
541    /// The impulse the motors of the pieces for which `member` is true still have to give at
542    /// flight time `t_s`, each lit at its `ignition_s`, N·s: each lit motor's curve total less
543    /// what it gave by then (ADR-172). A body's descent is a point mass with no thrust, so a body
544    /// dropped with a motor still burning leaves this out. A motor not yet lit counts nothing:
545    /// the flight refuses to drop one.
546    pub(crate) fn impulse_left_n_s(
547        &self,
548        member: impl Fn(usize) -> bool,
549        assembly: &Assembly,
550        t_s: f64,
551        ignition_s: &[Option<f64>],
552    ) -> f64 {
553        let mut left_n_s = 0.0;
554        for ((motor, ignition), piece) in assembly
555            .motors
556            .iter()
557            .zip(ignition_s)
558            .zip(&self.motor_piece)
559        {
560            if let (true, Some(ignition_s)) = (member(*piece), ignition)
561                && *ignition_s <= t_s
562            {
563                let curve = motor.mounted.motor.curve();
564                left_n_s += curve.total_impulse_ns() - curve.impulse_ns(t_s - ignition_s);
565            }
566        }
567        left_n_s
568    }
569
570    /// Refuses a pushed payload in the nose's piece: it leaves forward, and that piece is closed at
571    /// the nose. It needs the flight's separation as well as its `ejections`, the ones these
572    /// pieces were made with, so it runs when the flight starts, whatever order the builders came
573    /// in.
574    ///
575    /// # Errors
576    ///
577    /// [`SimError::Parting`], naming the payload.
578    pub(crate) fn check_pushed_payloads(&self, ejections: &[Ejection]) -> Result<(), SimError> {
579        // The ejections make the last pieces, in order.
580        let first_ejection = self.count() - ejections.len();
581        for (index, ejection) in ejections.iter().enumerate() {
582            if let Parting::Payload { component } = &ejection.parting
583                && ejection.impulse_n_s > 0.0
584                && self.host[first_ejection + index] == Some(0)
585            {
586                return Err(SimError::Parting {
587                    what: "a pushed payload leaves forward, but the piece holding it is closed at \
588                           the nose (part a joint ahead, or give it no impulse)",
589                    component: component.clone(),
590                });
591            }
592        }
593        Ok(())
594    }
595
596    /// The piece that carries `piece`, when it is a payload.
597    pub(crate) fn host(&self, piece: usize) -> Option<usize> {
598        self.host[piece]
599    }
600
601    /// The piece on the other side of the split that makes `piece` (not piece 0), and whether
602    /// `piece` is forward of that split: a section is aft of its joint, with the section forward
603    /// of the joint on the other side, and a payload leaves its host forward.
604    pub(crate) fn across(&self, piece: usize) -> (usize, bool) {
605        match self.host[piece] {
606            Some(host) => (host, true),
607            None => {
608                let at = self.sections.iter().position(|&section| section == piece);
609                // Every section is in the list, piece 0 first; piece 0 makes no split, so the
610                // section a split makes has one ahead of it.
611                debug_assert!(
612                    at.is_some_and(|at| at > 0),
613                    "piece {piece} is no split's section"
614                );
615                (self.sections[at.unwrap_or(0).saturating_sub(1)], false)
616            }
617        }
618    }
619
620    /// The drag area of piece `piece` tumbling on its own: its own components' body profile and
621    /// fins ([`DeviceDrag::tumbling_where`]).
622    ///
623    /// # Errors
624    ///
625    /// [`SimError::Domain`] for a piece that isn't one, or a payload (it is inside the airframe,
626    /// with no body tube or fin of its own for the model to take), and as
627    /// [`DeviceDrag::tumbling`].
628    pub(crate) fn tumbling(
629        &self,
630        piece: usize,
631        assembly: &Assembly,
632    ) -> Result<DeviceDrag, SimError> {
633        if piece >= self.count() {
634            return Err(SimError::Domain {
635                what: "piece to tumble (there is one per split, and the nose's)",
636                value: piece as f64,
637            });
638        }
639        if self.host[piece].is_some() && !self.beside[piece] {
640            return Err(SimError::Domain {
641                what: "piece to tumble (a payload has no body tube or fin of its own, which the \
642                       tumble model covers)",
643                value: piece as f64,
644            });
645        }
646        DeviceDrag::tumbling_where(assembly, |index, _| self.piece_of[index] == piece)
647    }
648
649    /// The first and last stage the pieces for which `member` is true have a component in.
650    pub(crate) fn stages(&self, member: impl Fn(usize) -> bool) -> (usize, usize) {
651        let mut span: Option<(usize, usize)> = None;
652        for (piece, &(first, last)) in self.stages.iter().enumerate() {
653            if member(piece) {
654                span = Some(span.map_or((first, last), |(a, b)| (a.min(first), b.max(last))));
655            }
656        }
657        span.unwrap_or((0, 0))
658    }
659}
660
661/// The design's component with id `id`, searched through every stage.
662pub(crate) fn node<'a>(rocket: &'a Rocket, id: &str) -> Option<&'a Component> {
663    fn within<'a>(components: &'a [Component], id: &str) -> Option<&'a Component> {
664        components.iter().find_map(|component| {
665            if component.id == id {
666                Some(component)
667            } else {
668                within(&component.children, id)
669            }
670        })
671    }
672    rocket
673        .stages
674        .iter()
675        .find_map(|stage| within(&stage.components, id))
676}
677
678#[cfg(test)]
679mod tests {
680    use hpr_atmos::{ConstantWind, Wind};
681    use hpr_core::DVec3;
682    use hpr_design::{Part, Position};
683
684    use super::*;
685    use crate::flight::{EventKind, FlightResult, FlightSettings, Simulation, Termination};
686    use crate::rail::Rail;
687    use crate::recovery::{
688        BodyEvent, CanopyType, Device, DeviceDrag, Inflation, terminal_speed_m_s,
689    };
690    use crate::state::State;
691    use crate::testing::{UniformAir, analytic_environment, analytic_wind_environment, design};
692
693    const G: f64 = 9.806_65;
694    /// The I175 burns out at 2.5 s; a drop starts well after that.
695    const START_S: f64 = 10.0;
696    const PAYLOAD_KG: f64 = 0.25;
697
698    /// The 54 mm single-stage test design with a 0.25 kg payload carried in its airframe, 0.15 m
699    /// aft of the airframe's forward end.
700    fn with_payload() -> Rocket {
701        let mut rocket = design("synthetic-54mm-three-fin");
702        let airframe = &mut rocket.stages[0].components[1];
703        assert_eq!(airframe.id, "sustainer-airframe");
704        let mut payload = airframe
705            .children
706            .iter()
707            .find(|child| child.id == "altimeter")
708            .cloned()
709            .unwrap();
710        payload.id = "payload".to_owned();
711        let Part::MassComponent(mass) = &mut payload.part else {
712            panic!("the altimeter is a mass component");
713        };
714        mass.mass_kg = PAYLOAD_KG;
715        payload.position = Some(Position::Top { aft_offset_m: 0.15 });
716        airframe.children.push(payload);
717        rocket
718    }
719
720    /// The two-stage test design with its booster strapped beside the sustainer's airframe as a
721    /// parallel stage of `count` pods.
722    fn strapped(count: u32) -> Rocket {
723        let mut rocket = design("synthetic-two-stage-75mm-54mm");
724        let booster = &mut rocket.stages[1];
725        booster.components.retain(|c| c.id != "interstage");
726        booster.parallel = Some(hpr_design::ParallelStage {
727            on: "sustainer-airframe".to_owned(),
728            position: Position::Bottom { aft_offset_m: 0.0 },
729            pods: hpr_design::PodSet {
730                count,
731                radial_offset_m: 0.06815,
732                angle_rad: 0.0,
733            },
734        });
735        rocket
736    }
737
738    /// However the partings cut a rocket with a parallel stage, its pieces' structures add up to
739    /// the rocket's: the parallel stage is weighed once, in the piece it is in, whether the stage
740    /// it hangs on is cut (a payload out of the sustainer) or it is (a payload out of a pod).
741    #[test]
742    fn the_pieces_of_a_parallel_stage_weigh_the_rocket() {
743        let apogee = Trigger::Apogee;
744        let drop = Separation::new(apogee, 0);
745        for (count, separations, ejections) in [
746            (
747                2,
748                vec![],
749                vec![Ejection::payload(apogee, "sustainer-parachute")],
750            ),
751            (
752                2,
753                vec![drop],
754                vec![Ejection::payload(apogee, "sustainer-parachute")],
755            ),
756            (2, vec![drop], vec![Ejection::aft_of(apogee, "nose")]),
757            (
758                1,
759                vec![],
760                vec![Ejection::payload(apogee, "booster-electronics")],
761            ),
762            (1, vec![drop], vec![]),
763        ] {
764            let rocket = strapped(count);
765            let assembly = rocket.assemble("j760-i175").unwrap();
766            let pieces = Pieces::new(&rocket, &assembly, &separations, &ejections).unwrap();
767            let total = MassProperties::combine(pieces.structure.iter().flatten());
768            let want = assembly.layout.structure;
769            let label = format!(
770                "{count} pods, {} separations, {ejections:?}",
771                separations.len()
772            );
773            assert!(
774                (total.mass_kg - want.mass_kg).abs() < 1e-12 * want.mass_kg,
775                "{label}: {} against {}",
776                total.mass_kg,
777                want.mass_kg
778            );
779            assert!((total.cg_m - want.cg_m).length() < 1e-12, "{label}");
780            let inertia = total.inertia_kg_m2 - want.inertia_kg_m2;
781            for column in 0..3 {
782                assert!(inertia.col(column).length() < 1e-12, "{label}");
783            }
784        }
785    }
786
787    /// A canopy of `diameter_m` on `body`, fired by `trigger`.
788    fn canopy(body: usize, diameter_m: f64, trigger: Trigger) -> Device {
789        Device::new(
790            "canopy",
791            DeviceDrag::canopy(CanopyType::FlatCircular, diameter_m),
792            trigger,
793        )
794        .on_body(body)
795    }
796
797    /// The nose cone under its own 0.45 m canopy from apogee, the airframe under a 0.9 m one from
798    /// apogee, and the payload under a 0.6 m one as it leaves at 300 m.
799    fn devices() -> Vec<Device> {
800        let payload_height = Trigger::Altitude {
801            height_above_ground_m: 300.0,
802        };
803        vec![
804            canopy(0, 0.45, Trigger::Apogee),
805            canopy(1, 0.9, Trigger::Apogee),
806            canopy(2, 0.6, payload_height),
807        ]
808    }
809
810    /// The nose cone pushed off at apogee, and the payload out of the airframe at 300 m.
811    fn ejections() -> Vec<Ejection> {
812        vec![
813            Ejection::aft_of(Trigger::Apogee, "nose"),
814            Ejection::payload(
815                Trigger::Altitude {
816                    height_above_ground_m: 300.0,
817                },
818                "payload",
819            ),
820        ]
821    }
822
823    fn simulation(environment: crate::Environment) -> Simulation {
824        Simulation::new(
825            &with_payload(),
826            "i175",
827            environment,
828            Rail::vertical(3.0),
829            FlightSettings {
830                max_time_s: 3600.0,
831                ..FlightSettings::default()
832            },
833        )
834        .unwrap()
835        .with_recovery(devices())
836        .unwrap()
837        .with_ejections(ejections())
838        .unwrap()
839    }
840
841    /// The state with the center of mass `height_m` above the site, nose up, moving at
842    /// `velocity_enu_m_s` and turning at `body_rate_rad_s`.
843    fn dropped(
844        sim: &Simulation,
845        height_m: f64,
846        velocity_enu_m_s: DVec3,
847        body_rate_rad_s: DVec3,
848    ) -> State {
849        let attitude = Rail::vertical(3.0).attitude();
850        let cg_m = sim.assembly().mass_properties(START_S).cg_m;
851        State {
852            position_enu_m: DVec3::new(0.0, 0.0, height_m) - attitude.mul_vec3(cg_m),
853            velocity_enu_m_s,
854            attitude,
855            body_rate_rad_s,
856        }
857    }
858
859    /// The mass of the layout's component `id` with everything inside it, kg.
860    fn component_kg(sim: &Simulation, id: &str) -> f64 {
861        sim.assembly()
862            .layout
863            .components
864            .iter()
865            .find(|component| component.id == id)
866            .unwrap()
867            .with_children
868            .mass_kg
869    }
870
871    fn close(a: f64, b: f64, relative: f64, what: &str) {
872        assert!((a - b).abs() <= relative * b.abs(), "{what}: {a} vs {b}");
873    }
874
875    #[test]
876    fn an_ejected_nose_cone_and_payload_each_land_under_their_own_canopy() {
877        // The milestone's design, flown from the pad in a 4 m/s wind from the west: the nose cone
878        // leaves at apogee, the payload at 300 m, and each piece reaches the ground on its own,
879        // somewhere of its own.
880        let wind = ConstantWind::new(4.0, 1.5 * std::f64::consts::PI).unwrap();
881        let sim = simulation(analytic_wind_environment(UniformAir::sea_level(), G, wind));
882        let result = sim.run(&mut ()).unwrap();
883        assert_eq!(result.termination, Termination::Separated);
884        let apogee = result.event(EventKind::Apogee).unwrap().sample;
885        let ejected = result.event(EventKind::Ejection(0)).unwrap().sample;
886        assert!((ejected.time_s - apogee.time_s).abs() < 1e-9, "{ejected:?}");
887        assert!(result.event(EventKind::Ejection(1)).is_none());
888        assert_eq!(result.bodies.len(), 3);
889        for (index, body) in result.bodies.iter().enumerate() {
890            assert_eq!(body.body, index);
891            assert_eq!(body.termination, Termination::GroundHit, "body {index}");
892            assert_eq!(body.pieces, vec![index]);
893            // The nose cone's canopy opens on the stack in the pass that parts it, so its
894            // deployment is the flight's; the others open on their own bodies.
895            let deployment = EventKind::Deployment(index);
896            assert!(
897                body.event(deployment).is_some() || result.event(deployment).is_some(),
898                "body {index}"
899            );
900        }
901        // The payload leaves the airframe's body at its height, and starts its own flight there.
902        let airframe = &result.bodies[1];
903        let payload = &result.bodies[2];
904        let parting = airframe.event(EventKind::Ejection(1)).unwrap().sample;
905        assert!(
906            (parting.height_above_ground_m - 300.0).abs() < 1e-6,
907            "{parting:?}"
908        );
909        assert_eq!(payload.start_sample.time_s, parting.time_s);
910        assert!(result.bodies_landed());
911        // Every piece is in the nose's stage and opens its canopy as it parts: no separated
912        // part's warning (M10.1d5, ADR-200), neither #179 nor #354.
913        assert!(result.bodies.iter().all(|body| body.stages == (0, 0)));
914        let peak = crate::metrics::Peak {
915            value: 0.5,
916            time_s: 0.0,
917            height_above_ground_m: 0.0,
918        };
919        assert_eq!(
920            crate::issues::separated_part_issue_warnings(&result, Some(peak)),
921            []
922        );
923        let landings = result.landings();
924        assert_eq!(landings.len(), 3);
925        for landing in &landings {
926            assert!(landing.height_above_ground_m.abs() < 1e-6, "{landing:?}");
927        }
928        // Measured: apogee at 14.985 s; the nose cone (0.063 kg) lands at 559.21 s, 2 048 m
929        // downwind, the airframe (0.556 kg) at 331.76 s and the payload (0.250 kg), let out at
930        // 261.17 s, at 331.33 s, both near 1 135 m.
931        let pinned = [
932            (559.212, 2_047.87),
933            (331.760, 1_136.24),
934            (331.332, 1_134.53),
935        ];
936        for (landing, (time_s, east_m)) in landings.iter().zip(pinned) {
937            assert!((landing.time_s - time_s).abs() < 0.05, "{landing:?}");
938            assert!((landing.cg_enu_m.x - east_m).abs() < 0.5, "{landing:?}");
939        }
940        // Under a canopy a piece drifts with the wind, so the nose cone's extra time aloft puts it
941        // that many seconds of wind further on: 911.6 m against 4 m/s × 227.5 s = 909.8 m.
942        let apart_m = landings[0].cg_enu_m.x - landings[1].cg_enu_m.x;
943        let drift_m = 4.0 * (landings[0].time_s - landings[1].time_s);
944        close(apart_m, drift_m, 0.01, "the nose cone's extra drift");
945    }
946
947    /// #231's other half: an ejection known to come while the rocket is still on the rail is
948    /// refused when it comes, not fired late at the rail exit. A rail long enough to hold the
949    /// rocket past its burnout makes one.
950    #[test]
951    fn an_ejection_on_the_rail_is_refused() {
952        let environment =
953            || analytic_wind_environment(UniformAir::sea_level(), G, ConstantWind::calm());
954        let burnout_s = simulation(environment())
955            .run(&mut ())
956            .unwrap()
957            .event(EventKind::Burnout)
958            .unwrap()
959            .sample
960            .time_s;
961        let charge = Trigger::Time {
962            time_s: burnout_s + 0.2,
963        };
964        let error = Simulation::new(
965            &with_payload(),
966            "i175",
967            environment(),
968            Rail::vertical(2000.0),
969            FlightSettings::default(),
970        )
971        .unwrap()
972        .with_recovery(vec![
973            canopy(0, 0.45, charge),
974            canopy(1, 0.9, Trigger::Apogee),
975        ])
976        .unwrap()
977        .with_ejections(vec![Ejection::aft_of(charge, "nose")])
978        .unwrap()
979        .run(&mut ())
980        .expect_err("an ejection on the rail");
981        assert!(
982            matches!(error, SimError::Domain { what, value }
983                if what == "time of an ejection, s (it must come once the rocket has left the rail)"
984                    && value == burnout_s + 0.2),
985            "{error:?}"
986        );
987    }
988
989    #[test]
990    fn a_nose_cone_ejected_before_apogee_leaves_the_summary_with_no_apogee_or_shock() {
991        // Body 0 of an ejection is its lead piece, here the nose cone alone: its apogee under its
992        // own canopy is not the rocket's, so the summary has none, as it had before body 0's
993        // apogee stood in for a separation's (ADR-165).
994        let environment =
995            || analytic_wind_environment(UniformAir::sea_level(), G, ConstantWind::calm());
996        let apogee_s = simulation(environment())
997            .run(&mut ())
998            .unwrap()
999            .event(EventKind::Apogee)
1000            .unwrap()
1001            .sample
1002            .time_s;
1003        let early = Trigger::Time {
1004            time_s: apogee_s - 3.0,
1005        };
1006        let sim = Simulation::new(
1007            &with_payload(),
1008            "i175",
1009            environment(),
1010            Rail::vertical(3.0),
1011            FlightSettings {
1012                max_time_s: 3600.0,
1013                ..FlightSettings::default()
1014            },
1015        )
1016        .unwrap()
1017        .with_recovery(vec![
1018            canopy(0, 0.45, early),
1019            canopy(1, 0.9, Trigger::Apogee),
1020        ])
1021        .unwrap()
1022        .with_ejections(vec![Ejection::aft_of(early, "nose")])
1023        .unwrap();
1024        let mut metrics = crate::metrics::FlightMetrics::new();
1025        let result = sim.run(&mut metrics).unwrap();
1026        assert_eq!(result.termination, Termination::Separated);
1027        assert!(result.event(EventKind::Ejection(0)).is_some());
1028        assert!(result.event(EventKind::Apogee).is_none());
1029        let nose = result.bodies.iter().find(|body| body.body == 0).unwrap();
1030        assert!(nose.event(EventKind::Apogee).is_some());
1031        let summary = metrics.summary(&result, sim.environment()).unwrap();
1032        assert_eq!(summary.apogee, None);
1033        // Nor is the opening shock of the nose cone's own canopy, which opens at the charge and
1034        // pulls on the nose cone alone, the rocket's (#1519): the stack flew no step under it, so
1035        // the summary has none.
1036        let charge_s = result.event(EventKind::Ejection(0)).unwrap().sample.time_s;
1037        let opened_s = result
1038            .event(EventKind::Deployment(0))
1039            .unwrap()
1040            .sample
1041            .time_s;
1042        assert_eq!(opened_s, charge_s);
1043        assert_eq!(summary.max_descent_acceleration_m_s2, None);
1044        // Each piece has its own figure all the same (#1532). The cone's is its canopy's drag
1045        // over the cone's own mass as the charge fires, `q C_D S / m`. The airframe's canopy
1046        // opens at the airframe's own apogee, at rest in the calm air, so its figure is its
1047        // steady fall's, one g.
1048        let own = &summary.body_max_descent_acceleration_m_s2;
1049        assert_eq!(own.iter().map(|peak| peak.body).collect::<Vec<_>>(), [0, 1]);
1050        let fired = result.event(EventKind::Ejection(0)).unwrap().sample;
1051        let cone = nose.final_sample;
1052        assert!(cone.mass_kg < 0.5 * fired.mass_kg, "{cone:?}");
1053        let rho = UniformAir::sea_level().0.density_kg_m3;
1054        let cone_per_kg =
1055            0.5 * rho * fired.airspeed_m_s.powi(2) * cone.recovery_drag_area_m2 / cone.mass_kg;
1056        assert!(cone_per_kg > 5.0 * G, "{cone_per_kg}");
1057        assert!(
1058            (own[0].value / cone_per_kg - 1.0).abs() < 1e-9,
1059            "{} vs {cone_per_kg}",
1060            own[0].value
1061        );
1062        assert_eq!(own[0].time_s, charge_s);
1063        assert!((own[1].value / G - 1.0).abs() < 0.01, "{}", own[1].value);
1064
1065        // The nose's canopy, fired by the charge but opening 0.5 s after it, would leave the
1066        // nose climbing through the lag with no drag: refused at the charge (M4.6a's review).
1067        let error = Simulation::new(
1068            &with_payload(),
1069            "i175",
1070            environment(),
1071            Rail::vertical(3.0),
1072            FlightSettings {
1073                max_time_s: 3600.0,
1074                ..FlightSettings::default()
1075            },
1076        )
1077        .unwrap()
1078        .with_recovery(vec![
1079            canopy(0, 0.45, early).with_lag_s(0.5),
1080            canopy(1, 0.9, Trigger::Apogee),
1081        ])
1082        .unwrap()
1083        .with_ejections(vec![Ejection::aft_of(early, "nose")])
1084        .unwrap()
1085        .run(&mut ())
1086        .expect_err("a nose climbing with nothing open");
1087        assert!(
1088            matches!(
1089                error,
1090                SimError::Domain { what, value }
1091                    if what.starts_with("time of a split with nothing left to burn, before \
1092                                         apogee")
1093                        && (value - (apogee_s - 3.0)).abs() < 1e-9
1094            ),
1095            "{error:?}"
1096        );
1097    }
1098
1099    #[test]
1100    fn the_pieces_masses_add_up_and_each_split_conserves_momentum() {
1101        // Split with wind, a sideways velocity and a body rate, so that `ω × r` is in each
1102        // body's start and the check is not the trivial one.
1103        let air = UniformAir::sea_level();
1104        let sim = simulation(analytic_wind_environment(
1105            air,
1106            G,
1107            ConstantWind::new(5.0, 0.9).unwrap(),
1108        ));
1109        let start = dropped(
1110            &sim,
1111            1_500.0,
1112            DVec3::new(3.0, 0.0, -2.0),
1113            DVec3::new(0.0, 0.6, 0.0),
1114        );
1115        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1116        let [nose, airframe, payload] = &result.bodies[..] else {
1117            panic!("{} bodies", result.bodies.len());
1118        };
1119
1120        // At the first split the two bodies are the whole rocket, and the nose cone and the
1121        // payload are their own components' masses.
1122        let first = result.event(EventKind::Ejection(0)).unwrap().sample;
1123        let whole = sim.assembly().mass_properties(first.time_s);
1124        close(
1125            nose.start_sample.mass_kg + airframe.start_sample.mass_kg,
1126            whole.mass_kg,
1127            1e-12,
1128            "the two bodies' mass",
1129        );
1130        close(
1131            nose.mass_kg,
1132            component_kg(&sim, "nose"),
1133            1e-12,
1134            "the nose cone",
1135        );
1136        close(payload.mass_kg, PAYLOAD_KG, 1e-12, "the payload");
1137        close(
1138            nose.mass_kg + airframe.mass_kg + payload.mass_kg,
1139            whole.mass_kg,
1140            1e-12,
1141            "the three pieces' mass",
1142        );
1143
1144        // Momentum at the first split: each body leaves with its own center of mass's velocity,
1145        // and together they carry the stack's.
1146        let momentum = nose.start_sample.cg_velocity_enu_m_s * nose.start_sample.mass_kg
1147            + airframe.start_sample.cg_velocity_enu_m_s * airframe.start_sample.mass_kg;
1148        let expected = first.cg_velocity_enu_m_s * whole.mass_kg;
1149        assert!(
1150            (momentum - expected).length() < 1e-9 * expected.length(),
1151            "{momentum} vs {expected}"
1152        );
1153        // Each starts where its own center of mass was: the nose cone's is its component's.
1154        let state = result.final_sample.state;
1155        let nose_cg_m = sim
1156            .assembly()
1157            .layout
1158            .components
1159            .iter()
1160            .find(|component| component.id == "nose")
1161            .unwrap()
1162            .with_children
1163            .cg_m;
1164        let expected = state.point_enu_m(nose_cg_m);
1165        assert!(
1166            (nose.start_sample.cg_enu_m - expected).length() < 1e-12,
1167            "{} vs {expected}",
1168            nose.start_sample.cg_enu_m
1169        );
1170        let gap = (nose.start_sample.cg_enu_m - airframe.start_sample.cg_enu_m).length();
1171        assert!(gap > 0.3, "{gap}");
1172
1173        // Momentum at the second, on the way down: the payload leaves the airframe's body at
1174        // its point and velocity, and the masses before and after agree.
1175        let parting = airframe.event(EventKind::Ejection(1)).unwrap().sample;
1176        close(
1177            parting.mass_kg,
1178            airframe.mass_kg + payload.mass_kg,
1179            1e-12,
1180            "the airframe's body before the payload left",
1181        );
1182        assert_eq!(payload.start_sample.cg_enu_m, parting.cg_enu_m);
1183        let before = parting.cg_velocity_enu_m_s * parting.mass_kg;
1184        let after = parting.cg_velocity_enu_m_s * airframe.mass_kg
1185            + payload.start_sample.cg_velocity_enu_m_s * payload.mass_kg;
1186        assert!(
1187            (after - before).length() < 1e-9 * before.length(),
1188            "{after} vs {before}"
1189        );
1190    }
1191
1192    #[test]
1193    fn each_piece_comes_down_at_its_own_terminal_speed() {
1194        // In uniform air each body ends its descent at `√(2 m g/(ρ C_D S))` for its own mass and
1195        // canopy: the airframe at its mass after the payload left.
1196        let air = UniformAir::sea_level();
1197        let sim = simulation(analytic_environment(air, G));
1198        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
1199        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1200        assert!(result.bodies_landed());
1201        let rho = air.0.density_kg_m3;
1202        for body in &result.bodies {
1203            let landing = body.event(EventKind::GroundHit).unwrap().sample;
1204            let drag_area_m2 = sim.recovery()[body.body].drag.drag_area_m2();
1205            let terminal_m_s = terminal_speed_m_s(body.mass_kg, drag_area_m2, rho, G);
1206            close(
1207                -landing.vertical_speed_m_s,
1208                terminal_m_s,
1209                1e-3,
1210                &format!("body {}", body.body),
1211            );
1212            assert_eq!(landing.mass_kg, body.mass_kg);
1213            assert!((landing.recovery_drag_area_m2 - drag_area_m2).abs() < 1e-12);
1214        }
1215    }
1216
1217    /// The milestone's design and devices, with `ejections` in place of its own.
1218    fn simulation_with(environment: crate::Environment, ejections: Vec<Ejection>) -> Simulation {
1219        Simulation::new(
1220            &with_payload(),
1221            "i175",
1222            environment,
1223            Rail::vertical(3.0),
1224            FlightSettings {
1225                max_time_s: 3600.0,
1226                ..FlightSettings::default()
1227            },
1228        )
1229        .unwrap()
1230        .with_recovery(devices())
1231        .unwrap()
1232        .with_ejections(ejections)
1233        .unwrap()
1234    }
1235
1236    /// The same ejections as [`ejections`], each pushing with `impulse_n_s`.
1237    fn pushed(impulse_n_s: f64) -> Vec<Ejection> {
1238        ejections()
1239            .into_iter()
1240            .map(|ejection| ejection.with_impulse(impulse_n_s))
1241            .collect()
1242    }
1243
1244    fn close_vec(a: DVec3, b: DVec3, relative: f64, what: &str) {
1245        assert!(
1246            (a - b).length() <= relative * b.length(),
1247            "{what}: {a} vs {b}"
1248        );
1249    }
1250
1251    /// As [`dropped`], from the attitude of a rail at `elevation_deg` and `azimuth_deg`.
1252    fn dropped_at(
1253        sim: &Simulation,
1254        (elevation_deg, azimuth_deg): (f64, f64),
1255        height_m: f64,
1256        velocity_enu_m_s: DVec3,
1257        body_rate_rad_s: DVec3,
1258    ) -> State {
1259        let attitude = Rail {
1260            elevation_rad: elevation_deg.to_radians(),
1261            azimuth_rad: azimuth_deg.to_radians(),
1262            ..Rail::vertical(3.0)
1263        }
1264        .attitude();
1265        let cg_m = sim.assembly().mass_properties(START_S).cg_m;
1266        State {
1267            position_enu_m: DVec3::new(0.0, 0.0, height_m) - attitude.mul_vec3(cg_m),
1268            velocity_enu_m_s,
1269            attitude,
1270            body_rate_rad_s,
1271        }
1272    }
1273
1274    /// The change in the velocity each body starts with, between two flights that are the same
1275    /// until they part.
1276    fn start_change(pushed: &FlightResult, unpushed: &FlightResult, body: usize) -> DVec3 {
1277        pushed.bodies[body].start_sample.cg_velocity_enu_m_s
1278            - unpushed.bodies[body].start_sample.cg_velocity_enu_m_s
1279    }
1280
1281    #[test]
1282    fn an_impulse_changes_each_pieces_velocity_by_j_over_m_and_conserves_momentum() {
1283        // 1 N·s on each ejection, in wind, from a stack tilted 60° up toward 30° east of north,
1284        // moving sideways and turning at 0.6 rad/s. The first parting, from the stack in free
1285        // flight, pushes along its axis. At the second the airframe hangs under its canopy, so
1286        // the payload leaves against its velocity through the air, toward the canopy.
1287        const J: f64 = 1.0;
1288        let wind = ConstantWind::new(5.0, 0.9).unwrap();
1289        let wind_enu = wind.wind(0.0).unwrap().velocity_enu_m_s;
1290        let fly = |impulse_n_s: f64| {
1291            let environment = analytic_wind_environment(UniformAir::sea_level(), G, wind);
1292            let sim = simulation_with(environment, pushed(impulse_n_s));
1293            let start = dropped_at(
1294                &sim,
1295                (60.0, 30.0),
1296                1_500.0,
1297                DVec3::new(3.0, 0.0, -2.0),
1298                DVec3::new(0.0, 0.6, 0.0),
1299            );
1300            let result = sim.run_free(START_S, start, &mut ()).unwrap();
1301            (sim, result)
1302        };
1303        let (sim, pushed) = fly(J);
1304        let (_, unpushed) = fly(0.0);
1305        let [nose, airframe, payload] = &pushed.bodies[..] else {
1306            panic!("{} bodies", pushed.bodies.len());
1307        };
1308
1309        // The first parting: by hand, the axis of a rail 60° up toward 30° east of north is
1310        // (cos 60° sin 30°, cos 60° cos 30°, sin 60°) in east, north, up. The nose cone, forward
1311        // of the joint, gains `J/m` along it, and the airframe with the payload inside loses
1312        // `J/m` for its own mass.
1313        let first = pushed.event(EventKind::Ejection(0)).unwrap().sample;
1314        assert_eq!(
1315            first,
1316            unpushed.event(EventKind::Ejection(0)).unwrap().sample
1317        );
1318        let (elevation, azimuth) = (60_f64.to_radians(), 30_f64.to_radians());
1319        let axis = DVec3::new(
1320            elevation.cos() * azimuth.sin(),
1321            elevation.cos() * azimuth.cos(),
1322            elevation.sin(),
1323        );
1324        let whole = sim.assembly().mass_properties(first.time_s);
1325        let nose_kg = component_kg(&sim, "nose");
1326        let rest_kg = whole.mass_kg - nose_kg;
1327        close(nose.start_sample.mass_kg, nose_kg, 1e-12, "the nose cone");
1328        close(airframe.start_sample.mass_kg, rest_kg, 1e-12, "the rest");
1329        close_vec(
1330            start_change(&pushed, &unpushed, 0),
1331            axis * (J / nose_kg),
1332            1e-9,
1333            "the nose cone's push",
1334        );
1335        close_vec(
1336            start_change(&pushed, &unpushed, 1),
1337            -axis * (J / rest_kg),
1338            1e-9,
1339            "the airframe's push",
1340        );
1341        // 1 N·s on the 0.063 kg nose cone is 15.9 m/s.
1342        close(J / nose_kg, 15.85, 1e-3, "the nose cone's change of speed");
1343        let momentum = nose.start_sample.cg_velocity_enu_m_s * nose.start_sample.mass_kg
1344            + airframe.start_sample.cg_velocity_enu_m_s * airframe.start_sample.mass_kg;
1345        close_vec(
1346            momentum,
1347            first.cg_velocity_enu_m_s * whole.mass_kg,
1348            1e-9,
1349            "the momentum at the first parting",
1350        );
1351
1352        // The second, on the way down: by hand, 1 N·s on the 0.25 kg payload is 4 m/s, against
1353        // the airframe's velocity through the air.
1354        let parting = airframe.event(EventKind::Ejection(1)).unwrap();
1355        let (before, after) = (parting.sample, parting.after.unwrap());
1356        assert!(before.recovery_drag_area_m2 > 0.0, "{before:?}");
1357        let through_air = (before.cg_velocity_enu_m_s - wind_enu).normalize();
1358        close(
1359            payload.start_sample.mass_kg,
1360            PAYLOAD_KG,
1361            1e-12,
1362            "the payload",
1363        );
1364        close(
1365            after.mass_kg,
1366            before.mass_kg - PAYLOAD_KG,
1367            1e-12,
1368            "the airframe after",
1369        );
1370        close_vec(
1371            payload.start_sample.cg_velocity_enu_m_s - before.cg_velocity_enu_m_s,
1372            -through_air * 4.0,
1373            1e-9,
1374            "the payload's push",
1375        );
1376        close_vec(
1377            after.cg_velocity_enu_m_s - before.cg_velocity_enu_m_s,
1378            through_air * (J / after.mass_kg),
1379            1e-9,
1380            "the airframe's push",
1381        );
1382        assert_eq!(after.cg_enu_m, before.cg_enu_m);
1383        assert_eq!(payload.start_sample.cg_enu_m, before.cg_enu_m);
1384        close_vec(
1385            after.cg_velocity_enu_m_s * after.mass_kg
1386                + payload.start_sample.cg_velocity_enu_m_s * payload.start_sample.mass_kg,
1387            before.cg_velocity_enu_m_s * before.mass_kg,
1388            1e-9,
1389            "the momentum at the second parting",
1390        );
1391
1392        // Every piece still lands, each at its own terminal speed once the push has died away.
1393        assert!(pushed.bodies_landed());
1394        let rho = UniformAir::sea_level().0.density_kg_m3;
1395        for body in &pushed.bodies {
1396            let landing = body.event(EventKind::GroundHit).unwrap().sample;
1397            let drag_area_m2 = sim.recovery()[body.body].drag.drag_area_m2();
1398            let terminal_m_s = terminal_speed_m_s(body.mass_kg, drag_area_m2, rho, G);
1399            close(
1400                landing.airspeed_m_s,
1401                terminal_m_s,
1402                1e-3,
1403                &format!("body {}", body.body),
1404            );
1405        }
1406    }
1407
1408    #[test]
1409    fn a_body_with_nothing_open_is_pushed_along_its_flight() {
1410        // The airframe's canopy waits for 200 m, so at 300 m it falls with nothing open, nose
1411        // first as a stable airframe does, and the payload leaves down its velocity through the
1412        // air.
1413        let at_200_m = Trigger::Altitude {
1414            height_above_ground_m: 200.0,
1415        };
1416        let sim = Simulation::new(
1417            &with_payload(),
1418            "i175",
1419            analytic_environment(UniformAir::sea_level(), G),
1420            Rail::vertical(3.0),
1421            FlightSettings {
1422                max_time_s: 3600.0,
1423                ..FlightSettings::default()
1424            },
1425        )
1426        .unwrap()
1427        .with_recovery(vec![
1428            canopy(0, 0.45, Trigger::Apogee),
1429            canopy(1, 0.9, at_200_m),
1430            canopy(2, 0.6, at_200_m),
1431        ])
1432        .unwrap()
1433        .with_ejections(pushed(1.0))
1434        .unwrap();
1435        let start = dropped(&sim, 1_500.0, DVec3::new(2.0, 1.0, -0.5), DVec3::ZERO);
1436        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1437        let airframe = &result.bodies[1];
1438        let payload = &result.bodies[2];
1439        let parting = airframe.event(EventKind::Ejection(1)).unwrap();
1440        let (before, after) = (parting.sample, parting.after.unwrap());
1441        assert_eq!(before.recovery_drag_area_m2, 0.0);
1442        let through_air = before.cg_velocity_enu_m_s.normalize();
1443        close_vec(
1444            payload.start_sample.cg_velocity_enu_m_s - before.cg_velocity_enu_m_s,
1445            through_air * 4.0,
1446            1e-9,
1447            "the payload's push",
1448        );
1449        close_vec(
1450            after.cg_velocity_enu_m_s - before.cg_velocity_enu_m_s,
1451            -through_air * (1.0 / after.mass_kg),
1452            1e-9,
1453            "the airframe's push",
1454        );
1455        assert!(result.bodies_landed());
1456    }
1457
1458    #[test]
1459    fn a_stack_already_hanging_from_a_device_is_pushed_up_its_flight() {
1460        // A drogue on the stack at apogee, from a stack tilted 60°, and the nose cone off at
1461        // 300 m. By then the stack has hung from the drogue for minutes: its attitude is the one
1462        // frozen at apogee, which says nothing of how it hangs, so the push goes up its velocity
1463        // through the air, as on a body under a canopy (found in review: it went along the
1464        // frozen axis, nearly sideways).
1465        let at_300_m = Trigger::Altitude {
1466            height_above_ground_m: 300.0,
1467        };
1468        let wind = ConstantWind::new(4.0, 2.0).unwrap();
1469        let wind_enu = wind.wind(0.0).unwrap().velocity_enu_m_s;
1470        let fly = |impulse_n_s: f64| {
1471            let sim = Simulation::new(
1472                &with_payload(),
1473                "i175",
1474                analytic_wind_environment(UniformAir::sea_level(), G, wind),
1475                Rail::vertical(3.0),
1476                FlightSettings {
1477                    max_time_s: 3600.0,
1478                    ..FlightSettings::default()
1479                },
1480            )
1481            .unwrap()
1482            .with_recovery(vec![
1483                canopy(0, 0.3, Trigger::Apogee),
1484                canopy(1, 0.9, at_300_m),
1485            ])
1486            .unwrap()
1487            .with_ejections(vec![
1488                Ejection::aft_of(at_300_m, "nose").with_impulse(impulse_n_s),
1489            ])
1490            .unwrap();
1491            let start = dropped_at(
1492                &sim,
1493                (60.0, 30.0),
1494                1_500.0,
1495                DVec3::new(3.0, 0.0, -2.0),
1496                DVec3::ZERO,
1497            );
1498            let result = sim.run_free(START_S, start, &mut ()).unwrap();
1499            (sim, result)
1500        };
1501        let (sim, pushed) = fly(1.0);
1502        let (_, unpushed) = fly(0.0);
1503        let first = pushed.event(EventKind::Ejection(0)).unwrap().sample;
1504        assert!(
1505            (first.height_above_ground_m - 300.0).abs() < 1e-6,
1506            "{first:?}"
1507        );
1508        let through_air = (first.cg_velocity_enu_m_s - wind_enu).normalize();
1509        let nose_kg = component_kg(&sim, "nose");
1510        let rest_kg = sim.assembly().mass_properties(first.time_s).mass_kg - nose_kg;
1511        let nose_push = start_change(&pushed, &unpushed, 0);
1512        close_vec(
1513            nose_push,
1514            -through_air * (1.0 / nose_kg),
1515            1e-9,
1516            "the nose cone's push",
1517        );
1518        close_vec(
1519            start_change(&pushed, &unpushed, 1),
1520            through_air * (1.0 / rest_kg),
1521            1e-9,
1522            "the airframe's push",
1523        );
1524        // Not the frozen axis: that points 60° up, the push nearly straight up.
1525        let frozen_axis = pushed.final_sample.state.attitude.mul_vec3(DVec3::Z);
1526        assert!(nose_push.normalize().dot(frozen_axis) < 0.95, "{nose_push}");
1527        assert!(pushed.bodies_landed());
1528    }
1529
1530    #[test]
1531    fn a_push_in_still_air_is_taken_as_up() {
1532        // Climbing straight up in calm air, the nose cone leaves on a timer; the payload leaves
1533        // the airframe's body at its own apogee, where it doesn't move through the air, so the
1534        // push is up: 4 m/s on the payload. The airframe's canopy waits for 200 m, so nothing is
1535        // open, and along its velocity (a hair downward, past the apogee) would point down.
1536        let sim = Simulation::new(
1537            &with_payload(),
1538            "i175",
1539            analytic_environment(UniformAir::sea_level(), G),
1540            Rail::vertical(3.0),
1541            FlightSettings {
1542                max_time_s: 3600.0,
1543                ..FlightSettings::default()
1544            },
1545        )
1546        .unwrap()
1547        .with_recovery(vec![
1548            canopy(0, 0.45, Trigger::Apogee),
1549            canopy(
1550                1,
1551                0.9,
1552                Trigger::Altitude {
1553                    height_above_ground_m: 200.0,
1554                },
1555            ),
1556            canopy(2, 0.6, Trigger::Apogee),
1557        ])
1558        .unwrap()
1559        .with_ejections(vec![
1560            Ejection::aft_of(Trigger::Time { time_s: START_S }, "nose"),
1561            Ejection::payload(Trigger::Apogee, "payload").with_impulse(1.0),
1562        ])
1563        .unwrap();
1564        let start = dropped(&sim, 1_000.0, DVec3::new(0.0, 0.0, 20.0), DVec3::ZERO);
1565        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1566        let airframe = &result.bodies[1];
1567        let payload = &result.bodies[2];
1568        let parting = airframe.event(EventKind::Ejection(1)).unwrap().sample;
1569        assert!(parting.airspeed_m_s < 1e-3, "{parting:?}");
1570        assert_eq!(parting.recovery_drag_area_m2, 0.0);
1571        close_vec(
1572            payload.start_sample.cg_velocity_enu_m_s - parting.cg_velocity_enu_m_s,
1573            DVec3::new(0.0, 0.0, 4.0),
1574            1e-9,
1575            "the payload's push",
1576        );
1577        assert!(result.bodies_landed());
1578    }
1579
1580    #[test]
1581    fn a_separation_with_pushed_ejections_pushes_only_the_ejections_sides() {
1582        // The two-stage design parts at its stage boundary and pushes its nose cone off with
1583        // 1 N·s, both at apogee from the stack in free flight: the booster (body 1, the
1584        // separation's) gets no push, and the nose cone and the sustainer's airframe (body 2)
1585        // share the one push along the axis.
1586        let fly = |impulse_n_s: f64| {
1587            let rocket = design("synthetic-two-stage-75mm-54mm");
1588            let assembly = rocket.assemble("j760-i175").unwrap();
1589            let tumble = DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap();
1590            let sim = Simulation::new(
1591                &rocket,
1592                "j760-i175",
1593                analytic_environment(UniformAir::sea_level(), G),
1594                Rail::vertical(6.0),
1595                FlightSettings {
1596                    max_time_s: 3600.0,
1597                    ..FlightSettings::default()
1598                },
1599            )
1600            .unwrap()
1601            .with_separation(Separation::new(Trigger::Apogee, 0))
1602            .unwrap()
1603            .with_ejections(vec![
1604                Ejection::aft_of(Trigger::Apogee, "nose").with_impulse(impulse_n_s),
1605            ])
1606            .unwrap()
1607            .with_recovery(vec![
1608                canopy(0, 0.6, Trigger::Apogee),
1609                Device::new("booster", tumble, Trigger::Apogee).on_body(1),
1610                canopy(2, 1.2, Trigger::Apogee),
1611            ])
1612            .unwrap();
1613            let start = dropped_at(
1614                &sim,
1615                (70.0, 200.0),
1616                1_500.0,
1617                DVec3::new(0.0, 0.0, -0.5),
1618                DVec3::ZERO,
1619            );
1620            let result = sim.run_free(START_S, start, &mut ()).unwrap();
1621            (sim, result)
1622        };
1623        let (sim, pushed) = fly(1.0);
1624        let (_, unpushed) = fly(0.0);
1625        let axis = pushed.final_sample.state.attitude.mul_vec3(DVec3::Z);
1626        assert_eq!(start_change(&pushed, &unpushed, 1), DVec3::ZERO);
1627        let nose_kg = pushed.bodies[0].start_sample.mass_kg;
1628        let airframe_kg = pushed.bodies[2].start_sample.mass_kg;
1629        close(nose_kg, component_kg(&sim, "nose"), 1e-12, "the nose cone");
1630        close_vec(
1631            start_change(&pushed, &unpushed, 0),
1632            axis * (1.0 / nose_kg),
1633            1e-9,
1634            "the nose cone's push",
1635        );
1636        close_vec(
1637            start_change(&pushed, &unpushed, 2),
1638            -axis * (1.0 / airframe_kg),
1639            1e-9,
1640            "the airframe's push",
1641        );
1642        let first = pushed.event(EventKind::Separation).unwrap().sample;
1643        let whole_kg = sim.assembly().mass_properties(first.time_s).mass_kg;
1644        let momentum: DVec3 = pushed
1645            .bodies
1646            .iter()
1647            .map(|body| body.start_sample.cg_velocity_enu_m_s * body.start_sample.mass_kg)
1648            .sum();
1649        close_vec(
1650            momentum,
1651            first.cg_velocity_enu_m_s * whole_kg,
1652            1e-9,
1653            "the momentum",
1654        );
1655    }
1656
1657    #[test]
1658    fn pushed_sections_parting_together_on_the_way_down_push_as_the_stack_does() {
1659        // The booster section leaves at apogee; at 300 m the nose and the interstage both leave
1660        // the body left, each with 1 N·s, in one pass, as the stack's partings do at the first:
1661        // each final body takes the pushes of the joints on its sides. By hand, on the way the
1662        // nose points (against the velocity through the air, under the canopy it hangs from since
1663        // apogee): the nose cone `+J/m`, the sustainer's airframe between the two joints `−J/m +
1664        // J/m = 0`, and the interstage `−J/m`. Given in either order, the same (found in review:
1665        // taken one at a time, the order moved the nose cone's push from 15.85 to 17.66 m/s).
1666        let at_300_m = Trigger::Altitude {
1667            height_above_ground_m: 300.0,
1668        };
1669        let orders = [
1670            vec![
1671                Ejection::aft_of(Trigger::Apogee, "interstage"),
1672                Ejection::aft_of(at_300_m, "nose").with_impulse(1.0),
1673                Ejection::aft_of(at_300_m, "sustainer-airframe").with_impulse(1.0),
1674            ],
1675            vec![
1676                Ejection::aft_of(Trigger::Apogee, "interstage"),
1677                Ejection::aft_of(at_300_m, "sustainer-airframe").with_impulse(1.0),
1678                Ejection::aft_of(at_300_m, "nose").with_impulse(1.0),
1679            ],
1680        ];
1681        let mut landings = Vec::new();
1682        for (order, ejections) in orders.into_iter().enumerate() {
1683            let (sim, result) = two_stage_pieces(ejections, 4);
1684            assert!(result.bodies_landed(), "order {order}");
1685            // Both partings are the nose's body's, at the one instant.
1686            let nose = &result.bodies[0];
1687            let partings: Vec<&BodyEvent> = nose
1688                .events
1689                .iter()
1690                .filter(|event| matches!(event.kind, EventKind::Ejection(_)))
1691                .collect();
1692            assert_eq!(partings.len(), 2, "order {order}");
1693            let (before, after) = (partings[0].sample, partings[0].after.unwrap());
1694            assert_eq!(partings[1].sample, before);
1695            let nose_ward = -before.cg_velocity_enu_m_s.normalize();
1696            let (airframe, interstage) = if order == 0 {
1697                (&result.bodies[2], &result.bodies[3])
1698            } else {
1699                (&result.bodies[3], &result.bodies[2])
1700            };
1701            close(
1702                after.mass_kg,
1703                component_kg(&sim, "nose"),
1704                1e-12,
1705                "the nose cone",
1706            );
1707            let change = |velocity: DVec3| velocity - before.cg_velocity_enu_m_s;
1708            close_vec(
1709                change(after.cg_velocity_enu_m_s),
1710                nose_ward * (1.0 / after.mass_kg),
1711                1e-9,
1712                "the nose cone's push",
1713            );
1714            assert!(
1715                change(airframe.start_sample.cg_velocity_enu_m_s).length() < 1e-12,
1716                "order {order}: {}",
1717                change(airframe.start_sample.cg_velocity_enu_m_s)
1718            );
1719            close_vec(
1720                change(interstage.start_sample.cg_velocity_enu_m_s),
1721                -nose_ward * (1.0 / interstage.start_sample.mass_kg),
1722                1e-9,
1723                "the interstage's push",
1724            );
1725            let momentum = after.cg_velocity_enu_m_s * after.mass_kg
1726                + airframe.start_sample.cg_velocity_enu_m_s * airframe.start_sample.mass_kg
1727                + interstage.start_sample.cg_velocity_enu_m_s * interstage.start_sample.mass_kg;
1728            close_vec(
1729                momentum,
1730                before.cg_velocity_enu_m_s * before.mass_kg,
1731                1e-9,
1732                "the momentum",
1733            );
1734            landings.push([
1735                nose.final_sample.cg_enu_m,
1736                airframe.final_sample.cg_enu_m,
1737                interstage.final_sample.cg_enu_m,
1738            ]);
1739        }
1740        for (first, second) in landings[0].iter().zip(&landings[1]) {
1741            assert!((*first - *second).length() < 1e-6, "{first} vs {second}");
1742        }
1743    }
1744
1745    #[test]
1746    fn a_device_opening_as_its_body_parts_is_not_yet_hung_from() {
1747        // The airframe falls with nothing open, and its canopy and the payload's parting both
1748        // come at 300 m. At that instant it doesn't yet hang from the canopy, so the payload
1749        // leaves down its flight, whether the canopy opens at once or fills over a second (found
1750        // in review: the push flipped with the inflation law).
1751        let at_300_m = Trigger::Altitude {
1752            height_above_ground_m: 300.0,
1753        };
1754        let changes: Vec<DVec3> = [
1755            Inflation::Instant,
1756            Inflation::FillingTime {
1757                time_s: 1.0,
1758                exponent: 2.0,
1759            },
1760        ]
1761        .into_iter()
1762        .map(|inflation| {
1763            let sim = Simulation::new(
1764                &with_payload(),
1765                "i175",
1766                analytic_environment(UniformAir::sea_level(), G),
1767                Rail::vertical(3.0),
1768                FlightSettings {
1769                    max_time_s: 3600.0,
1770                    ..FlightSettings::default()
1771                },
1772            )
1773            .unwrap()
1774            .with_recovery(vec![
1775                canopy(0, 0.45, Trigger::Apogee),
1776                canopy(1, 0.9, at_300_m).with_inflation(inflation),
1777                canopy(2, 0.6, at_300_m),
1778            ])
1779            .unwrap()
1780            .with_ejections(pushed(1.0))
1781            .unwrap();
1782            let start = dropped(&sim, 1_500.0, DVec3::new(2.0, 1.0, -0.5), DVec3::ZERO);
1783            let result = sim.run_free(START_S, start, &mut ()).unwrap();
1784            let parting = result.bodies[1]
1785                .event(EventKind::Ejection(1))
1786                .unwrap()
1787                .sample;
1788            let change =
1789                result.bodies[2].start_sample.cg_velocity_enu_m_s - parting.cg_velocity_enu_m_s;
1790            close_vec(
1791                change,
1792                parting.cg_velocity_enu_m_s.normalize() * 4.0,
1793                1e-9,
1794                "the payload's push",
1795            );
1796            change
1797        })
1798        .collect();
1799        assert!(changes[0].z < -3.9, "{}", changes[0]);
1800    }
1801
1802    #[test]
1803    fn a_pushed_payload_whose_way_forward_is_still_closed_is_refused_in_flight() {
1804        // The payload is pushed out at apogee, but the joint forward of its airframe only parts
1805        // at 300 m: it has no way out forward then.
1806        let sim = simulation_with(
1807            analytic_environment(UniformAir::sea_level(), G),
1808            vec![
1809                Ejection::aft_of(
1810                    Trigger::Altitude {
1811                        height_above_ground_m: 300.0,
1812                    },
1813                    "nose",
1814                ),
1815                Ejection::payload(Trigger::Apogee, "payload").with_impulse(1.0),
1816            ],
1817        );
1818        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
1819        let error = sim.run_free(START_S, start, &mut ()).unwrap_err();
1820        assert!(
1821            matches!(error, SimError::Domain { what, value }
1822                if what.starts_with("time of a pushed payload's ejection") && value == START_S),
1823            "{error:?}"
1824        );
1825    }
1826
1827    /// The milestone's design with `devices` and the nose cone pushed off at 300 m with
1828    /// `impulse_n_s`, dropped from a stack tilted 60° in a 4 m/s wind.
1829    fn nose_off_at_300_m(devices: Vec<Device>, impulse_n_s: f64) -> (Simulation, FlightResult) {
1830        let at_300_m = Trigger::Altitude {
1831            height_above_ground_m: 300.0,
1832        };
1833        let sim = Simulation::new(
1834            &with_payload(),
1835            "i175",
1836            analytic_wind_environment(
1837                UniformAir::sea_level(),
1838                G,
1839                ConstantWind::new(4.0, 2.0).unwrap(),
1840            ),
1841            Rail::vertical(3.0),
1842            FlightSettings {
1843                max_time_s: 3600.0,
1844                ..FlightSettings::default()
1845            },
1846        )
1847        .unwrap()
1848        .with_recovery(devices)
1849        .unwrap()
1850        .with_ejections(vec![
1851            Ejection::aft_of(at_300_m, "nose").with_impulse(impulse_n_s),
1852        ])
1853        .unwrap();
1854        let start = dropped_at(
1855            &sim,
1856            (60.0, 30.0),
1857            1_500.0,
1858            DVec3::new(3.0, 0.0, -2.0),
1859            DVec3::ZERO,
1860        );
1861        let result = sim.run_free(START_S, start, &mut ()).unwrap();
1862        (sim, result)
1863    }
1864
1865    /// The nose cone's change of velocity at its parting from [`nose_off_at_300_m`] with 1 N·s,
1866    /// against the same flight unpushed, over the unit velocity through the air there and the
1867    /// push's size `J/m`.
1868    fn nose_push_through_air(devices: impl Fn() -> Vec<Device>) -> f64 {
1869        let (sim, pushed) = nose_off_at_300_m(devices(), 1.0);
1870        let (_, unpushed) = nose_off_at_300_m(devices(), 0.0);
1871        let first = pushed.event(EventKind::Ejection(0)).unwrap().sample;
1872        let wind_enu = ConstantWind::new(4.0, 2.0)
1873            .unwrap()
1874            .wind(0.0)
1875            .unwrap()
1876            .velocity_enu_m_s;
1877        let through_air = (first.cg_velocity_enu_m_s - wind_enu).normalize();
1878        let push = start_change(&pushed, &unpushed, 0);
1879        let size_m_s = 1.0 / component_kg(&sim, "nose");
1880        // Along the velocity through the air, one way or the other, and nowhere else.
1881        let along = push.dot(through_air) / size_m_s;
1882        close_vec(
1883            push,
1884            through_air * along * size_m_s,
1885            1e-9,
1886            "the push's line",
1887        );
1888        along
1889    }
1890
1891    #[test]
1892    fn a_stack_tumbling_since_apogee_is_pushed_along_its_flight() {
1893        // Only a tumble on the stack since apogee: its attitude froze then, so the push goes by
1894        // its velocity through the air, but it hangs from nothing, so the nose cone is pushed
1895        // along it, as a stable airframe's nose would point.
1896        let along = nose_push_through_air(|| {
1897            let tumble = DeviceDrag::tumbling(&with_payload().assemble("i175").unwrap()).unwrap();
1898            vec![
1899                Device::new("tumble", tumble, Trigger::Apogee),
1900                canopy(
1901                    1,
1902                    0.9,
1903                    Trigger::Altitude {
1904                        height_above_ground_m: 300.0,
1905                    },
1906                ),
1907            ]
1908        });
1909        close(along, 1.0, 1e-9, "along the flight");
1910    }
1911
1912    #[test]
1913    fn a_drogue_released_as_the_body_parts_is_still_hung_from() {
1914        // A drogue on the stack since apogee, cut away by a main that opens at 300 m, as the nose
1915        // cone leaves. Up to that instant the stack hung from the drogue, so the nose cone goes
1916        // against its velocity through the air whether the main opens at once, releasing the drogue at
1917        // that instant, or fills over a second (found in review: the push flipped with the law).
1918        for inflation in [
1919            Inflation::Instant,
1920            Inflation::FillingTime {
1921                time_s: 1.0,
1922                exponent: 2.0,
1923            },
1924        ] {
1925            let along = nose_push_through_air(|| {
1926                vec![
1927                    canopy(0, 0.3, Trigger::Apogee).with_release_by(1),
1928                    canopy(
1929                        0,
1930                        0.9,
1931                        Trigger::Altitude {
1932                            height_above_ground_m: 300.0,
1933                        },
1934                    )
1935                    .with_inflation(inflation),
1936                    canopy(
1937                        1,
1938                        0.9,
1939                        Trigger::Altitude {
1940                            height_above_ground_m: 300.0,
1941                        },
1942                    ),
1943                ]
1944            });
1945            close(along, -1.0, 1e-9, &format!("{inflation:?}"));
1946        }
1947    }
1948
1949    #[test]
1950    fn one_charge_can_push_off_the_nose_cone_and_let_the_payload_out() {
1951        // Both at apogee from the stack in free flight, 1 N·s each: by hand, along the axis, the
1952        // nose cone `+1 N·s`, the payload, leaving forward through the joint that opens with it,
1953        // `+1 N·s`, and the airframe between them `−2 N·s`, each over its own mass.
1954        let fly = |impulse_n_s: f64| {
1955            let sim = Simulation::new(
1956                &with_payload(),
1957                "i175",
1958                analytic_environment(UniformAir::sea_level(), G),
1959                Rail::vertical(3.0),
1960                FlightSettings {
1961                    max_time_s: 3600.0,
1962                    ..FlightSettings::default()
1963                },
1964            )
1965            .unwrap()
1966            .with_recovery(vec![
1967                canopy(0, 0.45, Trigger::Apogee),
1968                canopy(1, 0.9, Trigger::Apogee),
1969                canopy(2, 0.6, Trigger::Apogee),
1970            ])
1971            .unwrap()
1972            .with_ejections(vec![
1973                Ejection::aft_of(Trigger::Apogee, "nose").with_impulse(impulse_n_s),
1974                Ejection::payload(Trigger::Apogee, "payload").with_impulse(impulse_n_s),
1975            ])
1976            .unwrap();
1977            let start = dropped_at(
1978                &sim,
1979                (70.0, 120.0),
1980                1_500.0,
1981                DVec3::new(0.0, 0.0, -0.5),
1982                DVec3::ZERO,
1983            );
1984            sim.run_free(START_S, start, &mut ()).unwrap()
1985        };
1986        let (pushed, unpushed) = (fly(1.0), fly(0.0));
1987        assert!(pushed.bodies_landed());
1988        let axis = pushed.final_sample.state.attitude.mul_vec3(DVec3::Z);
1989        for (body, impulse_n_s) in [(0, 1.0), (1, -2.0), (2, 1.0)] {
1990            let kg = pushed.bodies[body].start_sample.mass_kg;
1991            close_vec(
1992                start_change(&pushed, &unpushed, body),
1993                axis * (impulse_n_s / kg),
1994                1e-9,
1995                &format!("body {body}"),
1996            );
1997        }
1998        close(
1999            pushed.bodies[2].start_sample.mass_kg,
2000            PAYLOAD_KG,
2001            1e-12,
2002            "the payload",
2003        );
2004    }
2005
2006    #[test]
2007    fn a_pushed_payload_behind_a_separation_is_accepted_in_either_builder_order() {
2008        // The two-stage design's booster electronics, pushed out at apogee, are in the booster's
2009        // piece, forward of which the separation parts: a way out, whichever builder comes first.
2010        // Without the separation they would be in the nose's piece, and refused at the start.
2011        let rocket = design("synthetic-two-stage-75mm-54mm");
2012        let tumble =
2013            DeviceDrag::tumbling_stages(&rocket.assemble("j760-i175").unwrap(), (1, 1)).unwrap();
2014        let devices = || {
2015            vec![
2016                canopy(0, 1.2, Trigger::Apogee),
2017                Device::new("booster", tumble, Trigger::Apogee).on_body(1),
2018                canopy(2, 0.3, Trigger::Apogee),
2019            ]
2020        };
2021        let ejections =
2022            || vec![Ejection::payload(Trigger::Apogee, "booster-electronics").with_impulse(1.0)];
2023        let base = || {
2024            Simulation::new(
2025                &rocket,
2026                "j760-i175",
2027                analytic_environment(UniformAir::sea_level(), G),
2028                Rail::vertical(6.0),
2029                FlightSettings {
2030                    max_time_s: 3600.0,
2031                    ..FlightSettings::default()
2032                },
2033            )
2034            .unwrap()
2035        };
2036        let separation = Separation::new(Trigger::Apogee, 0);
2037        let orders = [
2038            base()
2039                .with_separation(separation)
2040                .unwrap()
2041                .with_ejections(ejections())
2042                .unwrap()
2043                .with_recovery(devices())
2044                .unwrap(),
2045            base()
2046                .with_ejections(ejections())
2047                .unwrap()
2048                .with_separation(separation)
2049                .unwrap()
2050                .with_recovery(devices())
2051                .unwrap(),
2052        ];
2053        for sim in orders {
2054            let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2055            let result = sim.run_free(START_S, start, &mut ()).unwrap();
2056            assert!(result.bodies_landed());
2057        }
2058        let error = base()
2059            .with_ejections(ejections())
2060            .unwrap()
2061            .with_recovery(vec![
2062                canopy(0, 1.2, Trigger::Apogee),
2063                canopy(1, 0.3, Trigger::Apogee),
2064            ])
2065            .unwrap()
2066            .run(&mut ())
2067            .unwrap_err();
2068        assert!(
2069            matches!(&error, SimError::Parting { what, component }
2070                if what.starts_with("a pushed payload leaves forward")
2071                    && component == "booster-electronics"),
2072            "{error:?}"
2073        );
2074        // With the separation, one in the sustainer's airframe is still in the nose's piece.
2075        let error = base()
2076            .with_separation(separation)
2077            .unwrap()
2078            .with_ejections(vec![
2079                Ejection::payload(Trigger::Apogee, "sustainer-parachute").with_impulse(1.0),
2080            ])
2081            .unwrap()
2082            .with_recovery(devices())
2083            .unwrap()
2084            .run(&mut ())
2085            .unwrap_err();
2086        assert!(
2087            matches!(&error, SimError::Parting { what, component }
2088                if what.starts_with("a pushed payload leaves forward")
2089                    && component == "sustainer-parachute"),
2090            "{error:?}"
2091        );
2092    }
2093
2094    #[test]
2095    fn a_drogue_cut_away_before_the_parting_is_not_hung_from() {
2096        // A drogue on the stack since apogee, released at 600 m by a tumble: by 300 m, where the
2097        // nose cone is pushed off, the stack hangs from nothing, so the push goes along its
2098        // velocity through the air.
2099        let along = nose_push_through_air(|| {
2100            let tumble = DeviceDrag::tumbling(&with_payload().assemble("i175").unwrap()).unwrap();
2101            vec![
2102                canopy(0, 0.3, Trigger::Apogee).with_release_by(1),
2103                Device::new(
2104                    "tumble",
2105                    tumble,
2106                    Trigger::Altitude {
2107                        height_above_ground_m: 600.0,
2108                    },
2109                ),
2110                canopy(
2111                    1,
2112                    0.9,
2113                    Trigger::Altitude {
2114                        height_above_ground_m: 300.0,
2115                    },
2116                ),
2117            ]
2118        });
2119        close(along, 1.0, 1e-9, "along the flight");
2120    }
2121
2122    #[test]
2123    fn a_parting_without_an_impulse_records_the_body_after_it_unpushed() {
2124        // With no impulse the body after a parting on the way down has the same point and
2125        // velocity, and only its mass steps.
2126        let sim = simulation(analytic_environment(UniformAir::sea_level(), G));
2127        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2128        let result = sim.run_free(START_S, start, &mut ()).unwrap();
2129        let airframe = &result.bodies[1];
2130        let parting = airframe.event(EventKind::Ejection(1)).unwrap();
2131        let after = parting.after.unwrap();
2132        assert_eq!(
2133            after.cg_velocity_enu_m_s,
2134            parting.sample.cg_velocity_enu_m_s
2135        );
2136        assert_eq!(after.cg_enu_m, parting.sample.cg_enu_m);
2137        close(after.mass_kg, airframe.mass_kg, 1e-12, "the airframe after");
2138        // Only partings carry one.
2139        for body in &result.bodies {
2140            for event in &body.events {
2141                let parts = matches!(event.kind, EventKind::Ejection(_) | EventKind::Separation);
2142                assert_eq!(event.after.is_some(), parts, "{event:?}");
2143            }
2144        }
2145    }
2146
2147    #[test]
2148    fn a_tumbling_nose_cone_lands_at_its_tumble_models_terminal_speed() {
2149        // The nose cone pushed off at apogee with nothing but its own tumble; the airframe, with
2150        // the payload still inside, under its canopy.
2151        let air = UniformAir::sea_level();
2152        let base = Simulation::new(
2153            &with_payload(),
2154            "i175",
2155            analytic_environment(air, G),
2156            Rail::vertical(3.0),
2157            FlightSettings {
2158                max_time_s: 3600.0,
2159                ..FlightSettings::default()
2160            },
2161        )
2162        .unwrap()
2163        .with_ejections(vec![
2164            Ejection::aft_of(Trigger::Apogee, "nose").with_impulse(0.5),
2165        ])
2166        .unwrap();
2167        let tumble = base.tumbling_piece(0).unwrap();
2168        let DeviceDrag::Tumble {
2169            drag_area_m2,
2170            body_profile_m2,
2171            fin_area_m2,
2172        } = tumble
2173        else {
2174            panic!("{tumble:?}");
2175        };
2176        // By hand: the nose is a 0.25 m tangent ogive on the 54 mm airframe, whose arc has radius
2177        // `ρ = (R² + L²)/(2R)`, and whose side area is `L√(ρ² − L²) + ρ² asin(L/ρ) + 2(R − ρ)L`.
2178        // It has no fins, so its drag area is 0.56 times that.
2179        let nose = sim_component(&base, "nose");
2180        let (length_m, radius_m) = (0.25_f64, nose.part.aft_radius_m().unwrap());
2181        let arc_m = (radius_m * radius_m + length_m * length_m) / (2.0 * radius_m);
2182        let side_m2 = length_m * (arc_m * arc_m - length_m * length_m).sqrt()
2183            + arc_m * arc_m * (length_m / arc_m).asin()
2184            + 2.0 * (radius_m - arc_m) * length_m;
2185        close(body_profile_m2, side_m2, 1e-12, "the nose cone's side area");
2186        assert_eq!(fin_area_m2, 0.0);
2187        close(
2188            drag_area_m2,
2189            0.56 * side_m2,
2190            1e-12,
2191            "the nose cone's drag area",
2192        );
2193
2194        let sim = base
2195            .with_recovery(vec![
2196                Device::new("nose tumble", tumble, Trigger::Apogee).on_body(0),
2197                canopy(1, 0.9, Trigger::Apogee),
2198            ])
2199            .unwrap();
2200        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2201        let result = sim.run_free(START_S, start, &mut ()).unwrap();
2202        assert!(result.bodies_landed());
2203        let nose_body = &result.bodies[0];
2204        close(
2205            nose_body.mass_kg,
2206            component_kg(&sim, "nose"),
2207            1e-12,
2208            "the nose cone",
2209        );
2210        let landing = nose_body.event(EventKind::GroundHit).unwrap().sample;
2211        let terminal_m_s =
2212            terminal_speed_m_s(nose_body.mass_kg, drag_area_m2, air.0.density_kg_m3, G);
2213        close(
2214            -landing.vertical_speed_m_s,
2215            terminal_m_s,
2216            1e-6,
2217            "the nose cone's landing",
2218        );
2219        // Measured: 13.849 m/s for the 0.0631 kg nose cone on its 5.27e-3 m² drag area.
2220        assert!((terminal_m_s - 13.849).abs() < 1e-3, "{terminal_m_s}");
2221    }
2222
2223    /// The layout's component `id`.
2224    fn sim_component<'a>(sim: &'a Simulation, id: &str) -> &'a hpr_design::PlacedComponent {
2225        sim.assembly()
2226            .layout
2227            .components
2228            .iter()
2229            .find(|component| component.id == id)
2230            .unwrap()
2231    }
2232
2233    #[test]
2234    fn the_pieces_tumbling_areas_add_up_to_the_whole_airframes() {
2235        // Cut into sections, the airframe's tumble is theirs summed: here the nose cone, and the
2236        // airframe with its fins.
2237        let sim = Simulation::new(
2238            &with_payload(),
2239            "i175",
2240            analytic_environment(UniformAir::sea_level(), G),
2241            Rail::vertical(3.0),
2242            FlightSettings::default(),
2243        )
2244        .unwrap()
2245        .with_ejections(vec![
2246            Ejection::aft_of(Trigger::Apogee, "nose"),
2247            Ejection::payload(Trigger::Apogee, "payload"),
2248        ])
2249        .unwrap();
2250        let area = |drag: DeviceDrag| match drag {
2251            DeviceDrag::Tumble {
2252                drag_area_m2,
2253                body_profile_m2,
2254                fin_area_m2,
2255            } => [drag_area_m2, body_profile_m2, fin_area_m2],
2256            other => panic!("{other:?}"),
2257        };
2258        let whole = area(DeviceDrag::tumbling(sim.assembly()).unwrap());
2259        let nose = area(sim.tumbling_piece(0).unwrap());
2260        let rest = area(sim.tumbling_piece(1).unwrap());
2261        for k in 0..3 {
2262            close(nose[k] + rest[k], whole[k], 1e-12, "the sum");
2263        }
2264        assert!(nose[2] == 0.0 && rest[2] > 0.0, "{nose:?} {rest:?}");
2265
2266        // A payload has no tube or fin of its own, and piece 3 is not made.
2267        for (piece, starts) in [
2268            (2, "piece to tumble (a payload has no body tube or fin"),
2269            (3, "piece to tumble (there is one per split"),
2270        ] {
2271            let error = sim.tumbling_piece(piece).unwrap_err();
2272            assert!(
2273                matches!(error, SimError::Domain { what, value }
2274                    if what.starts_with(starts) && value == piece as f64),
2275                "{error:?}"
2276            );
2277        }
2278    }
2279
2280    #[test]
2281    fn an_ejection_with_a_separation_numbers_the_bodies_after_it() {
2282        // The two-stage design parts at its stage boundary and pushes its nose cone off, both at
2283        // apogee: the booster is body 1, the nose cone keeps body 0, and the sustainer's airframe
2284        // is the ejection's body 2.
2285        let air = UniformAir::sea_level();
2286        let rocket = design("synthetic-two-stage-75mm-54mm");
2287        let assembly = rocket.assemble("j760-i175").unwrap();
2288        let tumble = DeviceDrag::tumbling_stages(&assembly, (1, 1)).unwrap();
2289        let sim = Simulation::new(
2290            &rocket,
2291            "j760-i175",
2292            analytic_environment(air, G),
2293            Rail::vertical(6.0),
2294            FlightSettings {
2295                max_time_s: 3600.0,
2296                ..FlightSettings::default()
2297            },
2298        )
2299        .unwrap()
2300        .with_ejections(vec![Ejection::aft_of(Trigger::Apogee, "nose")])
2301        .unwrap()
2302        .with_recovery(vec![
2303            canopy(0, 0.6, Trigger::Apogee),
2304            Device::new("booster", tumble, Trigger::Apogee).on_body(1),
2305            canopy(2, 1.2, Trigger::Apogee),
2306        ])
2307        .unwrap()
2308        .with_separation(Separation::new(Trigger::Apogee, 0))
2309        .unwrap();
2310        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2311        let result = sim.run_free(START_S, start, &mut ()).unwrap();
2312        assert!(result.event(EventKind::Separation).is_some());
2313        assert!(result.event(EventKind::Ejection(0)).is_some());
2314        assert!(result.bodies_landed());
2315        let stages: Vec<(usize, usize)> = result.bodies.iter().map(|body| body.stages).collect();
2316        assert_eq!(stages, vec![(0, 0), (1, 1), (0, 0)]);
2317        let whole_kg = sim.assembly().mass_properties(START_S).mass_kg;
2318        let sum_kg: f64 = result.bodies.iter().map(|body| body.mass_kg).sum();
2319        close(sum_kg, whole_kg, 1e-12, "the bodies' mass");
2320        close(
2321            result.bodies[0].mass_kg,
2322            component_kg(&sim, "nose"),
2323            1e-12,
2324            "the nose cone",
2325        );
2326        // The booster is its stage and motor, as a separation alone makes it.
2327        let lit = vec![Some(0.0); sim.assembly().motors.len()];
2328        let booster = crate::recovery::body_mass_properties(sim.assembly(), (1, 1), START_S, &lit);
2329        close(
2330            result.bodies[1].mass_kg,
2331            booster.mass_kg,
2332            1e-12,
2333            "the booster",
2334        );
2335    }
2336
2337    #[test]
2338    fn a_split_on_the_way_down_waits_for_its_own_trigger() {
2339        // The payload's height is below where the airframe's body starts, so it leaves only on
2340        // the way down; a payload whose height is never reached lands inside its airframe.
2341        let sim = simulation(analytic_environment(UniformAir::sea_level(), G));
2342        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2343        let result = sim.run_free(START_S, start, &mut ()).unwrap();
2344        let parting = result.bodies[1]
2345            .event(EventKind::Ejection(1))
2346            .unwrap()
2347            .sample;
2348        assert!(parting.time_s > START_S + 10.0, "{parting:?}");
2349        assert!(parting.vertical_speed_m_s < 0.0);
2350
2351        // With the payload let out on a timer after the landing, it never leaves.
2352        let late = Simulation::new(
2353            &with_payload(),
2354            "i175",
2355            analytic_environment(UniformAir::sea_level(), G),
2356            Rail::vertical(3.0),
2357            FlightSettings {
2358                max_time_s: 3600.0,
2359                ..FlightSettings::default()
2360            },
2361        )
2362        .unwrap()
2363        .with_recovery(devices())
2364        .unwrap()
2365        .with_ejections(vec![
2366            Ejection::aft_of(Trigger::Apogee, "nose"),
2367            Ejection::payload(Trigger::Time { time_s: 3_000.0 }, "payload"),
2368        ])
2369        .unwrap();
2370        let result = late.run_free(START_S, start, &mut ()).unwrap();
2371        assert_eq!(result.bodies.len(), 2);
2372        assert_eq!(result.bodies[1].pieces, vec![1, 2]);
2373        assert!(result.bodies[1].event(EventKind::Ejection(1)).is_none());
2374        let whole_kg = late.assembly().mass_properties(START_S).mass_kg;
2375        close(
2376            result.bodies[0].mass_kg + result.bodies[1].mass_kg,
2377            whole_kg,
2378            1e-12,
2379            "the two bodies",
2380        );
2381    }
2382
2383    /// The two-stage test design with no separation, flown from a drop at 1,500 m with a canopy
2384    /// on each of its `bodies` and `ejections`.
2385    fn two_stage_pieces(ejections: Vec<Ejection>, bodies: usize) -> (Simulation, FlightResult) {
2386        let air = UniformAir::sea_level();
2387        let sim = Simulation::new(
2388            &design("synthetic-two-stage-75mm-54mm"),
2389            "j760-i175",
2390            analytic_environment(air, G),
2391            Rail::vertical(6.0),
2392            FlightSettings {
2393                max_time_s: 3600.0,
2394                ..FlightSettings::default()
2395            },
2396        )
2397        .unwrap()
2398        .with_recovery(
2399            (0..bodies)
2400                .map(|body| canopy(body, 0.8, Trigger::Apogee))
2401                .collect(),
2402        )
2403        .unwrap()
2404        .with_ejections(ejections)
2405        .unwrap();
2406        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2407        let result = sim.run_free(START_S, start, &mut ()).unwrap();
2408        (sim, result)
2409    }
2410
2411    #[test]
2412    fn partings_that_fire_together_on_the_way_down_count_each_piece_once() {
2413        // The booster section leaves at apogee. At 300 m two more partings fire in the same pass
2414        // on the body left: aft of the nose and aft of the sustainer's airframe. They part it
2415        // together, whichever is listed first, and each piece is counted once (found in review:
2416        // taken one at a time, the interstage was counted twice, 1.7651 kg landed from a
2417        // 1.6752 kg rocket). Both are the parting body's events.
2418        let at_300_m = Trigger::Altitude {
2419            height_above_ground_m: 300.0,
2420        };
2421        let orders = [
2422            vec![
2423                Ejection::aft_of(Trigger::Apogee, "interstage"),
2424                Ejection::aft_of(at_300_m, "nose"),
2425                Ejection::aft_of(at_300_m, "sustainer-airframe"),
2426            ],
2427            vec![
2428                Ejection::aft_of(Trigger::Apogee, "interstage"),
2429                Ejection::aft_of(at_300_m, "sustainer-airframe"),
2430                Ejection::aft_of(at_300_m, "nose"),
2431            ],
2432        ];
2433        for (order, ejections) in orders.into_iter().enumerate() {
2434            let (sim, result) = two_stage_pieces(ejections, 4);
2435            assert!(result.bodies_landed(), "order {order}");
2436            let pieces: Vec<Vec<usize>> = result
2437                .bodies
2438                .iter()
2439                .map(|body| body.pieces.clone())
2440                .collect();
2441            assert_eq!(
2442                pieces,
2443                vec![vec![0], vec![1], vec![2], vec![3]],
2444                "order {order}"
2445            );
2446            let whole_kg = sim.assembly().mass_properties(START_S).mass_kg;
2447            let sum_kg: f64 = result.bodies.iter().map(|body| body.mass_kg).sum();
2448            close(
2449                sum_kg,
2450                whole_kg,
2451                1e-12,
2452                &format!("order {order}: the bodies' mass"),
2453            );
2454            // Each body is its own components: the nose, and the interstage alone.
2455            close(
2456                result.bodies[0].mass_kg,
2457                component_kg(&sim, "nose"),
2458                1e-12,
2459                "the nose cone",
2460            );
2461            let interstage = if order == 0 { 3 } else { 2 };
2462            close(
2463                result.bodies[interstage].mass_kg,
2464                component_kg(&sim, "interstage"),
2465                1e-12,
2466                &format!("order {order}: the interstage"),
2467            );
2468            for kind in [EventKind::Ejection(1), EventKind::Ejection(2)] {
2469                assert!(
2470                    result.bodies[0].event(kind).is_some(),
2471                    "order {order}: {kind:?}"
2472                );
2473                assert!(
2474                    result.bodies[2].event(kind).is_none(),
2475                    "order {order}: {kind:?}"
2476                );
2477            }
2478        }
2479    }
2480
2481    /// The parting error of `ejections` on the payload design, with a device on every body.
2482    fn refused(ejections: Vec<Ejection>) -> SimError {
2483        let devices = (0..=ejections.len())
2484            .map(|body| canopy(body, 0.5, Trigger::Apogee))
2485            .collect();
2486        Simulation::new(
2487            &with_payload(),
2488            "i175",
2489            analytic_environment(UniformAir::sea_level(), G),
2490            Rail::vertical(3.0),
2491            FlightSettings::default(),
2492        )
2493        .unwrap()
2494        .with_recovery(devices)
2495        .unwrap()
2496        .with_ejections(ejections)
2497        .unwrap_err()
2498    }
2499
2500    fn what(error: SimError) -> (&'static str, String) {
2501        match error {
2502            SimError::Parting { what, component } => (what, component),
2503            SimError::Domain { what, .. } => (what, String::new()),
2504            other => panic!("{other:?}"),
2505        }
2506    }
2507
2508    #[test]
2509    fn partings_the_design_cant_make_are_refused() {
2510        let apogee = Trigger::Apogee;
2511        let cases: Vec<(Vec<Ejection>, &str, &str)> = vec![
2512            (
2513                vec![Ejection::aft_of(apogee, "fairing")],
2514                "an ejection names a component the design doesn't have",
2515                "fairing",
2516            ),
2517            (
2518                vec![Ejection::aft_of(apogee, "payload")],
2519                "a joint is aft of a body component, and this one is inside another (a part \
2520                 carried inside is a `Parting::Payload`)",
2521                "payload",
2522            ),
2523            (
2524                vec![Ejection::aft_of(apogee, "sustainer-airframe")],
2525                "a joint aft of the last body component (nothing is aft of it)",
2526                "sustainer-airframe",
2527            ),
2528            (
2529                vec![Ejection::payload(apogee, "sustainer-fins")],
2530                "a payload is carried inside the airframe, and this part is outside it",
2531                "sustainer-fins",
2532            ),
2533            (
2534                vec![Ejection::payload(apogee, "nose")],
2535                "a payload is carried inside the airframe, and this is a body component (a body \
2536                 component leaves at a joint, `Parting::AftOf`)",
2537                "nose",
2538            ),
2539            (
2540                vec![
2541                    Ejection::aft_of(apogee, "nose"),
2542                    Ejection::aft_of(Trigger::Time { time_s: 20.0 }, "nose"),
2543                ],
2544                "two partings at the joint aft of this component (a separation's stage boundary \
2545                 is a joint too)",
2546                "nose",
2547            ),
2548            (
2549                vec![
2550                    Ejection::payload(apogee, "payload"),
2551                    Ejection::payload(apogee, "payload"),
2552                ],
2553                "two ejections of one payload",
2554                "payload",
2555            ),
2556        ];
2557        for (ejections, expected, component) in cases {
2558            assert_eq!(
2559                what(refused(ejections)),
2560                (expected, component.to_owned()),
2561                "{expected}"
2562            );
2563        }
2564
2565        // A payload inside another payload.
2566        let mut rocket = with_payload();
2567        let airframe = &mut rocket.stages[0].components[1];
2568        let mut inner = airframe
2569            .children
2570            .iter()
2571            .find(|child| child.id == "altimeter")
2572            .cloned()
2573            .unwrap();
2574        inner.id = "inner".to_owned();
2575        inner.position = Some(Position::Top { aft_offset_m: 0.0 });
2576        let outer = airframe
2577            .children
2578            .iter_mut()
2579            .find(|child| child.id == "sustainer-motor-mount")
2580            .unwrap();
2581        outer.children.push(inner);
2582        let error = Simulation::new(
2583            &rocket,
2584            "i175",
2585            analytic_environment(UniformAir::sea_level(), G),
2586            Rail::vertical(3.0),
2587            FlightSettings::default(),
2588        )
2589        .unwrap()
2590        .with_ejections(vec![
2591            Ejection::payload(apogee, "sustainer-motor-mount"),
2592            Ejection::payload(apogee, "inner"),
2593        ])
2594        .unwrap_err();
2595        assert_eq!(
2596            what(error),
2597            ("a payload inside another payload", "inner".to_owned())
2598        );
2599
2600        // A pod's body tube is neither a joint nor a payload, though one pod's is a single copy.
2601        let mut rocket = with_payload();
2602        let airframe = &mut rocket.stages[0].components[1];
2603        let mut pod_tube = airframe.clone();
2604        pod_tube.id = "pod-tube".to_owned();
2605        pod_tube.auto.clear();
2606        pod_tube.motor_mount = None;
2607        pod_tube.children.clear();
2608        let mut pods = pod_tube.clone();
2609        pods.id = "pods".to_owned();
2610        pods.part = hpr_design::Part::PodSet(hpr_design::PodSet {
2611            count: 1,
2612            radial_offset_m: 0.2,
2613            angle_rad: 0.0,
2614        });
2615        pods.position = Some(Position::Top { aft_offset_m: 0.0 });
2616        pods.children = vec![pod_tube];
2617        airframe.children.push(pods);
2618        let assembly = rocket.assemble("i175").unwrap();
2619        for ejection in [
2620            Ejection::payload(apogee, "pod-tube"),
2621            Ejection::aft_of(apogee, "pod-tube"),
2622        ] {
2623            let error = Pieces::new(&rocket, &assembly, &[], &[ejection])
2624                .err()
2625                .unwrap();
2626            assert_eq!(
2627                what(error),
2628                (
2629                    "a pod's body component leaves with the tube its pod set hangs from, at no \
2630                     joint of its own and not as a payload",
2631                    "pod-tube".to_owned()
2632                )
2633            );
2634        }
2635
2636        // A stage whose mass is overridden can't be divided between pieces.
2637        let mut rocket = with_payload();
2638        rocket.stages[0].overrides.mass_kg = Some(1.0);
2639        let error = Simulation::new(
2640            &rocket,
2641            "i175",
2642            analytic_environment(UniformAir::sea_level(), G),
2643            Rail::vertical(3.0),
2644            FlightSettings::default(),
2645        )
2646        .unwrap()
2647        .with_ejections(vec![Ejection::payload(apogee, "payload")])
2648        .unwrap_err();
2649        assert_eq!(
2650            what(error),
2651            (
2652                "a parting through a stage whose mass is overridden (the override doesn't say \
2653                 which piece its mass is in)",
2654                "sustainer".to_owned()
2655            )
2656        );
2657
2658        // Nor can a stage that carries an added mass, with a station or without.
2659        for cg_aft_m in [None, Some(0.3)] {
2660            let mut rocket = with_payload();
2661            rocket.stages[0].added_mass = Some(hpr_design::AddedMass {
2662                mass_kg: 1.0,
2663                cg_aft_m,
2664            });
2665            let error = Simulation::new(
2666                &rocket,
2667                "i175",
2668                analytic_environment(UniformAir::sea_level(), G),
2669                Rail::vertical(3.0),
2670                FlightSettings::default(),
2671            )
2672            .unwrap()
2673            .with_ejections(vec![Ejection::payload(apogee, "payload")])
2674            .unwrap_err();
2675            assert_eq!(
2676                what(error),
2677                (
2678                    "a parting through a stage that carries an added mass (it doesn't say which \
2679                     piece the mass is in)",
2680                    "sustainer".to_owned()
2681                )
2682            );
2683        }
2684
2685        // Nor can an airframe whose override covers what it holds lose a payload from inside.
2686        let mut rocket = with_payload();
2687        rocket.stages[0].components[1].overrides.mass_kg = Some(1.0);
2688        rocket.stages[0].components[1].overrides_include_children = true;
2689        let error = Simulation::new(
2690            &rocket,
2691            "i175",
2692            analytic_environment(UniformAir::sea_level(), G),
2693            Rail::vertical(3.0),
2694            FlightSettings::default(),
2695        )
2696        .unwrap()
2697        .with_ejections(vec![Ejection::payload(apogee, "payload")])
2698        .unwrap_err();
2699        assert_eq!(
2700            what(error),
2701            (
2702                "a parting inside a component whose overridden mass covers what it holds (the \
2703                 override doesn't say which piece that mass is in)",
2704                "sustainer-airframe".to_owned()
2705            )
2706        );
2707    }
2708
2709    #[test]
2710    fn ejections_outside_their_domain_are_refused() {
2711        // During the burn: every body is a point mass of constant mass.
2712        let error = refused(vec![Ejection::aft_of(
2713            Trigger::Time { time_s: 0.5 },
2714            "nose",
2715        )]);
2716        assert_eq!(
2717            what(error).0,
2718            "time of an ejection (every motor must have burned out by then; this is when one of \
2719             them does)"
2720        );
2721        let error = refused(vec![Ejection::aft_of(
2722            Trigger::Altitude {
2723                height_above_ground_m: -1.0,
2724            },
2725            "nose",
2726        )]);
2727        assert_eq!(
2728            what(error).0,
2729            "height above the launch site at which a piece is ejected, m"
2730        );
2731        // A pushed payload leaves forward, and with no joint forward of it that is the nose tip:
2732        // refused when the flight starts, since a separation given later could open one. Without
2733        // a push it may still leave.
2734        let payload_only = |impulse_n_s: f64| {
2735            Simulation::new(
2736                &with_payload(),
2737                "i175",
2738                analytic_environment(UniformAir::sea_level(), G),
2739                Rail::vertical(3.0),
2740                FlightSettings::default(),
2741            )
2742            .unwrap()
2743            .with_recovery(vec![
2744                canopy(0, 0.5, Trigger::Apogee),
2745                canopy(1, 0.5, Trigger::Apogee),
2746            ])
2747            .unwrap()
2748            .with_ejections(vec![
2749                Ejection::payload(Trigger::Apogee, "payload").with_impulse(impulse_n_s),
2750            ])
2751            .unwrap()
2752            .run(&mut ())
2753        };
2754        let (what_, component) = what(payload_only(1.0).unwrap_err());
2755        assert!(
2756            what_.starts_with(
2757                "a pushed payload leaves forward, but the piece holding it is closed at the nose"
2758            ) && component == "payload",
2759            "{what_}"
2760        );
2761        assert!(payload_only(0.0).is_ok());
2762        for impulse_n_s in [-1.0, f64::NAN, f64::INFINITY] {
2763            let error = refused(vec![
2764                Ejection::aft_of(Trigger::Apogee, "nose").with_impulse(impulse_n_s),
2765            ]);
2766            assert!(
2767                matches!(error, SimError::Domain { what, value }
2768                    if what == "impulse of an ejection, N·s (zero or more: it pushes the two \
2769                                sides apart)"
2770                        && (value == impulse_n_s || value.is_nan() && impulse_n_s.is_nan())),
2771                "{error:?}"
2772            );
2773        }
2774
2775        // Every body needs a device, and no device may name a body that isn't made.
2776        let base = || {
2777            Simulation::new(
2778                &with_payload(),
2779                "i175",
2780                analytic_environment(UniformAir::sea_level(), G),
2781                Rail::vertical(3.0),
2782                FlightSettings::default(),
2783            )
2784            .unwrap()
2785        };
2786        let error = base()
2787            .with_recovery(vec![canopy(0, 0.5, Trigger::Apogee)])
2788            .unwrap()
2789            .with_ejections(vec![Ejection::aft_of(Trigger::Apogee, "nose")])
2790            .unwrap_err();
2791        assert!(
2792            matches!(error, SimError::Domain { what, value }
2793                if what.starts_with("recovery devices on a separated body") && value == 1.0),
2794            "{error:?}"
2795        );
2796        // That one only when the flight starts: a separation given later would make body 2.
2797        let error = base()
2798            .with_ejections(vec![Ejection::aft_of(Trigger::Apogee, "nose")])
2799            .unwrap()
2800            .with_recovery(vec![
2801                canopy(0, 0.5, Trigger::Apogee),
2802                canopy(1, 0.5, Trigger::Apogee),
2803                canopy(2, 0.5, Trigger::Apogee),
2804            ])
2805            .unwrap()
2806            .run(&mut ())
2807            .unwrap_err();
2808        assert!(
2809            matches!(error, SimError::Domain { what, value }
2810                if what.starts_with("body a device is attached to") && value == 2.0),
2811            "{error:?}"
2812        );
2813    }
2814
2815    #[test]
2816    fn a_flight_without_partings_is_unchanged() {
2817        // No ejection, no separation: one piece, no bodies, and the same flight to the bit as one
2818        // never given the empty list.
2819        let sim = Simulation::new(
2820            &with_payload(),
2821            "i175",
2822            analytic_environment(UniformAir::sea_level(), G),
2823            Rail::vertical(3.0),
2824            FlightSettings {
2825                max_time_s: 3600.0,
2826                ..FlightSettings::default()
2827            },
2828        )
2829        .unwrap()
2830        .with_recovery(vec![canopy(0, 0.9, Trigger::Apogee)])
2831        .unwrap();
2832        let plain: FlightResult = sim.run(&mut ()).unwrap();
2833        let result = sim
2834            .with_ejections(Vec::new())
2835            .unwrap()
2836            .run(&mut ())
2837            .unwrap();
2838        assert_eq!(result.termination, Termination::GroundHit);
2839        assert!(result.bodies.is_empty());
2840        assert_eq!(result, plain);
2841    }
2842
2843    #[test]
2844    fn an_override_that_covers_only_its_own_part_still_divides() {
2845        // The airframe's own mass overridden, not what it holds: the payload's mass is still its
2846        // own, and the pieces still add up to the rocket.
2847        let mut rocket = with_payload();
2848        rocket.stages[0].components[1].overrides.mass_kg = Some(0.5);
2849        let sim = Simulation::new(
2850            &rocket,
2851            "i175",
2852            analytic_environment(UniformAir::sea_level(), G),
2853            Rail::vertical(3.0),
2854            FlightSettings {
2855                max_time_s: 3600.0,
2856                ..FlightSettings::default()
2857            },
2858        )
2859        .unwrap()
2860        .with_recovery(devices())
2861        .unwrap()
2862        .with_ejections(ejections())
2863        .unwrap();
2864        let start = dropped(&sim, 1_500.0, DVec3::new(0.0, 0.0, -0.5), DVec3::ZERO);
2865        let result = sim.run_free(START_S, start, &mut ()).unwrap();
2866        assert!(result.bodies_landed());
2867        let whole_kg = sim.assembly().mass_properties(START_S).mass_kg;
2868        let sum_kg: f64 = result.bodies.iter().map(|body| body.mass_kg).sum();
2869        close(sum_kg, whole_kg, 1e-12, "the pieces' mass");
2870        close(result.bodies[2].mass_kg, PAYLOAD_KG, 1e-12, "the payload");
2871    }
2872
2873    #[test]
2874    fn refusals_in_flight_name_what_fired() {
2875        // The two-stage design with its sustainer lit by the separation half a second after the
2876        // booster burns out.
2877        let mut rocket = design("synthetic-two-stage-75mm-54mm");
2878        rocket.configurations[0]
2879            .motors
2880            .iter_mut()
2881            .find(|motor| motor.mount == "sustainer-motor-mount")
2882            .unwrap()
2883            .ignition = hpr_design::Ignition::Separation { delay_s: 0.0 };
2884        let build = || {
2885            Simulation::new(
2886                &rocket,
2887                "j760-i175",
2888                analytic_environment(UniformAir::sea_level(), G),
2889                Rail::vertical(6.0),
2890                FlightSettings {
2891                    max_time_s: 3600.0,
2892                    ..FlightSettings::default()
2893                },
2894            )
2895            .unwrap()
2896        };
2897        let booster = build()
2898            .assembly()
2899            .motors
2900            .iter()
2901            .position(|motor| motor.mount == "booster-motor-mount")
2902            .unwrap();
2903        let sustainer = 1 - booster;
2904        let devices = (0..3)
2905            .map(|body| canopy(body, 0.8, Trigger::Time { time_s: 0.0 }))
2906            .collect::<Vec<_>>();
2907        let domain = |error: SimError| match error {
2908            SimError::Domain { what, .. } => what,
2909            other => panic!("{other:?}"),
2910        };
2911
2912        // A powered separation in a flight with ejections: the sustainer's pieces aren't tracked.
2913        let error = build()
2914            .with_recovery(devices.clone())
2915            .unwrap()
2916            .with_separation(Separation::new(
2917                Trigger::Burnout {
2918                    motor: booster,
2919                    delay_s: 0.5,
2920                },
2921                0,
2922            ))
2923            .unwrap()
2924            .with_ejections(vec![Ejection::aft_of(Trigger::Apogee, "nose")])
2925            .unwrap()
2926            .run(&mut ())
2927            .unwrap_err();
2928        assert_eq!(
2929            domain(error),
2930            "time of a powered separation in a flight with ejections (the pieces of a sustainer \
2931             aren't tracked)"
2932        );
2933
2934        // An ejection ahead of a separation that would light the sustainer.
2935        let error = build()
2936            .with_recovery(devices.clone())
2937            .unwrap()
2938            .with_separation(Separation::new(Trigger::Time { time_s: 3_000.0 }, 0))
2939            .unwrap()
2940            .with_ejections(vec![Ejection::aft_of(Trigger::Apogee, "nose")])
2941            .unwrap()
2942            .run(&mut ())
2943            .unwrap_err();
2944        assert_eq!(
2945            domain(error),
2946            "time of an ejection before the separation that lights a motor (the pieces would \
2947             never light it)"
2948        );
2949
2950        // An ejection timed from the sustainer, which has no ignition before the flight.
2951        let error = build()
2952            .with_recovery(devices)
2953            .unwrap()
2954            .with_separation(Separation::new(Trigger::Time { time_s: 3_000.0 }, 0))
2955            .unwrap()
2956            .with_ejections(vec![Ejection::aft_of(
2957                Trigger::MotorDelay { motor: sustainer },
2958                "nose",
2959            )])
2960            .unwrap_err();
2961        assert_eq!(
2962            domain(error),
2963            "index of the motor an ejection is timed from (it has no ignition time before the \
2964             flight, so the ejection could never fire)"
2965        );
2966    }
2967
2968    #[test]
2969    fn an_ejection_reads_and_writes_as_json() {
2970        let ejection = Ejection::payload(
2971            Trigger::Altitude {
2972                height_above_ground_m: 300.0,
2973            },
2974            "payload",
2975        );
2976        let text = serde_json::to_string(&ejection).unwrap();
2977        assert_eq!(
2978            text,
2979            r#"{"trigger":{"altitude":{"height_above_ground_m":300.0}},"parting":{"payload":{"component":"payload"}}}"#
2980        );
2981        assert_eq!(serde_json::from_str::<Ejection>(&text).unwrap(), ejection);
2982        // An impulse is written when there is one, and read back.
2983        let pushed = ejection.clone().with_impulse(0.75);
2984        let text = serde_json::to_string(&pushed).unwrap();
2985        assert!(text.ends_with(r#""impulse_n_s":0.75}"#), "{text}");
2986        assert_eq!(serde_json::from_str::<Ejection>(&text).unwrap(), pushed);
2987        // A misspelt field is refused, inside the parting as well as outside it.
2988        for text in [
2989            r#"{"trigger":"apogee","parting":{"aft_of":{"component":"nose","x":1}}}"#,
2990            r#"{"trigger":"apogee","parting":{"aft_of":{"component":"nose"}},"x":1}"#,
2991        ] {
2992            assert!(serde_json::from_str::<Ejection>(text).is_err(), "{text}");
2993        }
2994        let read: Ejection = serde_json::from_str(
2995            r#"{"trigger":"apogee","parting":{"aft_of":{"component":"nose"}}}"#,
2996        )
2997        .unwrap();
2998        assert_eq!(read, Ejection::aft_of(Trigger::Apogee, "nose"));
2999    }
3000}