Skip to main content

hpr_sim/
staging.rs

1//! Staging: what a sustainer flies on after a powered separation.
2//!
3//! A [`Separation`] cuts the stack after a stage boundary. When the nose's body (body 0) still
4//! has a motor to burn at that moment, it is a sustainer and flies on in six degrees of freedom on
5//! the models built here: the design cut after the boundary, with the nose body's motors, and its
6//! own aerodynamics ([`hpr_aero::AeroModel`] on the cut layout, whose aft end is the sustainer's).
7//! The flight's state is the nose tip's, which the sustainer keeps, so it carries across the split
8//! unchanged; the mass steps down by the booster's, which descends as a point mass as every body
9//! did before (the decision record on separation, [ADR-014][adr-014]). Each motor burns on its own
10//! clock from its [`hpr_design::Ignition`], and a motor lit by the separation counts from it (the
11//! decision record on staging, [ADR-074][adr-074]).
12//!
13//! Method: `docs/physics/staging.md`.
14//!
15//! [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
16//! [adr-074]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-074-ignition-times-and-powered-staging-the-sustainer-flies-on-as-a-rigid-body-2026-09-25
17
18use std::borrow::Cow;
19
20use hpr_aero::AeroModel;
21use hpr_design::{Assembly, Configuration, Ignition, MassProperties, MountedMotor, Rocket};
22
23use crate::error::SimError;
24use crate::recovery::Separation;
25
26/// A vehicle a flight flew in six degrees of freedom, as one rigid body: the launch stack, or a
27/// sustainer a powered separation handed the flight to ([`crate::Simulation::flown_vehicles`]).
28#[derive(Debug, Clone)]
29#[non_exhaustive]
30pub struct FlownVehicle<'a> {
31    /// Its assembled design: the stack's ([`crate::Simulation::assembly`]), or a sustainer's, the
32    /// design cut after its separation's boundary with the nose body's motors.
33    pub assembly: Cow<'a, Assembly>,
34    /// Its aerodynamic model: the stack's ([`crate::Simulation::aero`]), or a sustainer's, built
35    /// again on the cut design as the flight built it. A rebuilt one keeps the cut design's
36    /// geometry and its stations, not the flight's drag scale or base-drag setting, which bear on
37    /// neither.
38    pub aero: Cow<'a, AeroModel>,
39    /// Each of its motors' ignition time on the flight's clock, s, in [`Assembly::motors`]'s
40    /// order; `None` for one that never lights, which stays loaded.
41    pub ignition_s: Vec<Option<f64>>,
42    /// When it began to fly on its own, s after launch: `None` for the stack, which flies from
43    /// the start; the separation's time for a sustainer.
44    pub from_s: Option<f64>,
45    /// When it stopped, s after launch: the next powered separation's time; `None` for the last
46    /// vehicle, which flies to the flight's end.
47    pub until_s: Option<f64>,
48}
49
50impl FlownVehicle<'_> {
51    /// Its mass properties at each instant its center of gravity's distance from the axis can be
52    /// largest while it flies: at its start (the stack's with every motor loaded, as at launch),
53    /// at each of its motors' ignitions and burnouts between its start and its end, and at its
54    /// end; for the stack also with every motor spent ([`Assembly::dry_mass_properties`]), as if
55    /// it flew past every burnout. A motor's propellant sits on the motor's own axis, so while
56    /// one motor burns the center of gravity moves along a straight line in the cross-section,
57    /// and its distance from the axis is largest at an end of the burn: these instants hold the
58    /// largest exactly while at most one motor burns at a time. Two off-axis motors burning
59    /// together at different rates can put a larger distance between them.
60    #[must_use]
61    pub fn mass_samples(&self) -> Vec<MassProperties> {
62        let start_s = self.from_s.unwrap_or(0.0);
63        let inside = |t: f64| t > start_s && self.until_s.is_none_or(|until_s| t < until_s);
64        let mut times_s = vec![start_s];
65        for (motor, ignition_s) in self.assembly.motors.iter().zip(&self.ignition_s) {
66            let Some(ignition_s) = *ignition_s else {
67                continue;
68            };
69            let burnout_s = ignition_s + motor.mounted.motor.burnout_time_s();
70            times_s.extend([ignition_s, burnout_s].into_iter().filter(|&t| inside(t)));
71        }
72        times_s.extend(self.until_s);
73        let mut samples: Vec<MassProperties> = times_s
74            .into_iter()
75            .map(|t| self.assembly.mass_properties_lit(t, &self.ignition_s))
76            .collect();
77        if self.from_s.is_none() {
78            samples.push(self.assembly.mass_properties(0.0));
79            samples.push(self.assembly.dry_mass_properties());
80        }
81        samples
82    }
83}
84
85/// What a sustainer flies on after a powered separation.
86#[derive(Debug, Clone)]
87pub(crate) struct Sustainer {
88    /// The design cut after the separation's boundary, with the nose body's motors.
89    pub(crate) assembly: Assembly,
90    /// Its aerodynamics.
91    pub(crate) aero: AeroModel,
92    /// Each of its motors' index among the whole stack's.
93    pub(crate) motors: Vec<usize>,
94}
95
96impl Sustainer {
97    /// The models of `rocket`'s stages `0..=separation.after_stage` with the motors `stack` puts
98    /// in them.
99    ///
100    /// # Errors
101    ///
102    /// [`SimError::Domain`] if those stages carry no motor (a separation of them isn't powered),
103    /// and errors assembling the cut design or building its aerodynamics.
104    pub(crate) fn of(
105        rocket: &Rocket,
106        configuration_id: &str,
107        stack: &Assembly,
108        separation: Separation,
109    ) -> Result<Self, SimError> {
110        let motors: Vec<usize> = stack
111            .motors
112            .iter()
113            .enumerate()
114            .filter(|(_, motor)| motor.stage <= separation.after_stage)
115            .map(|(index, _)| index)
116            .collect();
117        if motors.is_empty() {
118            return Err(SimError::Domain {
119                what: "count of motors in a sustainer (a powered separation's nose body has none)",
120                value: 0.0,
121            });
122        }
123        let mut cut = rocket.clone();
124        cut.stages.truncate(separation.after_stage + 1);
125        // One configuration with the nose body's motors, in the stack's order: each mount once,
126        // since a cluster's mount places its motor in every tube again, in the same order. Their
127        // ignition times come from the stack's (a burnout can name a booster's mount, which the
128        // cut has not), so each is written as lit at launch and given its time when the sustainer
129        // flies; one set never to light stays so.
130        let mut mounts: Vec<MountedMotor> = Vec::new();
131        for &index in &motors {
132            let mounted = &stack.motors[index].mounted;
133            if mounts.iter().all(|m| m.mount != mounted.mount) {
134                let mut mounted = mounted.clone();
135                if mounted.ignition != Ignition::Never {
136                    mounted.ignition = Ignition::Launch;
137                }
138                mounts.push(mounted);
139            }
140        }
141        cut.configurations = vec![Configuration {
142            id: configuration_id.to_owned(),
143            name: String::new(),
144            motors: mounts,
145        }];
146        let assembly = cut.assemble(configuration_id)?;
147        // The cut places the same motors in the same order; a failure is kept with its tube.
148        debug_assert!(
149            assembly.motors.len() == motors.len()
150                && assembly.motors.iter().zip(&motors).all(|(cut, &index)| {
151                    let stacked = &stack.motors[index];
152                    cut.nozzle_m == stacked.nozzle_m
153                        && cut.tube == stacked.tube
154                        && cut.fails == stacked.fails
155                })
156        );
157        let aero = AeroModel::new(&assembly.layout)?;
158        Ok(Self {
159            assembly,
160            aero,
161            motors,
162        })
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use hpr_design::{Ignition, Rocket};
169
170    use crate::environment::Environment;
171    use crate::error::SimError;
172    use crate::flight::{EventKind, FlightResult, FlightSettings, Simulation, Termination};
173    use crate::rail::Rail;
174    use crate::recorder::{FlightStep, Observer, Sample};
175    use crate::recovery::{CanopyType, Device, DeviceDrag, Separation, Trigger};
176    use hpr_core::{DQuat, DVec3};
177
178    use crate::testing::{
179        ConstantDrag, UniformAir, analytic_environment, constant_drag, design, site,
180    };
181
182    /// The synthetic two-stage design's configuration: a J760 in the booster, an I175 in the
183    /// sustainer.
184    const CONFIGURATION: &str = "j760-i175";
185    const BOOSTER_MOUNT: &str = "booster-motor-mount";
186    const SUSTAINER_MOUNT: &str = "sustainer-motor-mount";
187
188    /// The two-stage design with the sustainer lit by `ignition`.
189    fn two_stage(ignition: Ignition) -> Rocket {
190        let mut rocket = design("synthetic-two-stage-75mm-54mm");
191        let configuration = rocket
192            .configurations
193            .iter_mut()
194            .find(|c| c.id == CONFIGURATION)
195            .unwrap();
196        let sustainer = configuration
197            .motors
198            .iter_mut()
199            .find(|m| m.mount == SUSTAINER_MOUNT)
200            .unwrap();
201        sustainer.ignition = ignition;
202        rocket
203    }
204
205    /// The index of the motor in `mount` among the assembly's motors.
206    fn motor_index(sim: &Simulation, mount: &str) -> usize {
207        sim.assembly()
208            .motors
209            .iter()
210            .position(|m| m.mount == mount)
211            .unwrap()
212    }
213
214    /// The design flown from a 6 m vertical rail in the standard atmosphere: a canopy on the
215    /// sustainer at apogee, and the booster tumbling from the separation.
216    fn staged(rocket: &Rocket, separation: impl Fn(&Simulation) -> Separation) -> Simulation {
217        staged_with(
218            rocket,
219            Rail::vertical(6.0),
220            BOOSTER_AT_SEPARATION,
221            separation,
222        )
223        .unwrap()
224    }
225
226    /// A booster's devices act only once it flies, so a time of zero opens it at the separation.
227    const BOOSTER_AT_SEPARATION: Trigger = Trigger::Time { time_s: 0.0 };
228
229    /// As [`staged`], from `rail`, with the booster's tumble fired by `booster`.
230    fn staged_with(
231        rocket: &Rocket,
232        rail: Rail,
233        booster: Trigger,
234        separation: impl Fn(&Simulation) -> Separation,
235    ) -> Result<Simulation, SimError> {
236        let sim = Simulation::new(
237            rocket,
238            CONFIGURATION,
239            Environment::standard(site()).unwrap(),
240            rail,
241            FlightSettings::default(),
242        )
243        .unwrap();
244        let tumble = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
245        let separation = separation(&sim);
246        sim.with_recovery(vec![
247            Device::new(
248                "sustainer main",
249                DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
250                Trigger::Apogee,
251            ),
252            Device::new("booster tumble", tumble, booster).on_body(1),
253        ])
254        .unwrap()
255        .with_separation(separation)
256    }
257
258    /// The booster's burnout in the flight's time: it lights at launch.
259    fn booster_burnout_s(sim: &Simulation) -> f64 {
260        sim.assembly().motors[motor_index(sim, BOOSTER_MOUNT)]
261            .mounted
262            .motor
263            .burnout_time_s()
264    }
265
266    /// The serial plan: the separation 0.5 s after the booster's burnout, the sustainer lit 1 s
267    /// after it, so it coasts half a second on its own before it lights.
268    fn serial_plan() -> Simulation {
269        let rocket = two_stage(Ignition::Burnout {
270            mount: BOOSTER_MOUNT.to_owned(),
271            delay_s: 1.0,
272        });
273        staged(&rocket, |sim| {
274            Separation::new(
275                Trigger::Burnout {
276                    motor: motor_index(sim, BOOSTER_MOUNT),
277                    delay_s: 0.5,
278                },
279                0,
280            )
281        })
282    }
283
284    /// The flight's sample at the start of every accepted step.
285    #[derive(Default)]
286    struct StepStarts(Vec<Sample>);
287
288    impl Observer for StepStarts {
289        fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
290            self.0.push(step.sample(step.start_s())?);
291            Ok(())
292        }
293    }
294
295    fn time_of(result: &FlightResult, kind: EventKind) -> f64 {
296        result
297            .event(kind)
298            .unwrap_or_else(|| panic!("no {kind:?} in {:?}", kinds(result)))
299            .sample
300            .time_s
301    }
302
303    fn kinds(result: &FlightResult) -> Vec<EventKind> {
304        result.events.iter().map(|event| event.kind).collect()
305    }
306
307    /// #231: a separation known to come while the rocket is still on the rail is refused when
308    /// it comes, not fired late at the rail exit. A rail long enough to hold the rocket past the
309    /// booster's burnout stands in for a booster that never lights.
310    #[test]
311    fn a_separation_on_the_rail_is_refused() {
312        let rocket = two_stage(Ignition::Burnout {
313            mount: BOOSTER_MOUNT.to_owned(),
314            delay_s: 1.0,
315        });
316        let separation = |sim: &Simulation| {
317            Separation::new(
318                Trigger::Burnout {
319                    motor: motor_index(sim, BOOSTER_MOUNT),
320                    delay_s: 0.5,
321                },
322                0,
323            )
324        };
325        let sim = staged_with(
326            &rocket,
327            Rail::vertical(2000.0),
328            BOOSTER_AT_SEPARATION,
329            separation,
330        )
331        .unwrap();
332        let separation_s = booster_burnout_s(&sim) + 0.5;
333        let error = sim.run(&mut ()).expect_err("a separation on the rail");
334        assert!(
335            matches!(error, SimError::Domain { what, value }
336                if what.starts_with("time of a separation, s (it must come once the rocket has \
337                                     left the rail)")
338                    && value == separation_s),
339            "{error:?}"
340        );
341        // The same plan from the 6 m rail separates in free flight.
342        let flown = serial_plan().run(&mut ()).unwrap();
343        assert_eq!(time_of(&flown, EventKind::Separation), separation_s);
344    }
345
346    #[test]
347    fn serial_plan_timing_and_mass_step() {
348        // Loft lesson L93: the sustainer lights at the booster's burnout plus its delay, the mass
349        // steps down by the booster's at the separation, and a trigger the flight never reaches
350        // never lights anything.
351        let sim = serial_plan();
352        let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
353        let mut starts = StepStarts::default();
354        let result = sim.run(&mut starts).unwrap();
355        let burnout_s = booster_burnout_s(&sim);
356        let separation_s = time_of(&result, EventKind::Separation);
357        let ignition_s = time_of(&result, EventKind::Ignition(sustainer));
358        assert!(
359            (separation_s - (burnout_s + 0.5)).abs() < 1e-12,
360            "{separation_s}"
361        );
362        assert!(
363            (ignition_s - (burnout_s + 1.0)).abs() < 1e-12,
364            "{ignition_s}"
365        );
366
367        // The mass steps down by exactly the booster's, and holds until the sustainer lights.
368        let stack_kg = result.event(EventKind::Separation).unwrap().sample.mass_kg;
369        assert_eq!(result.bodies.len(), 1, "the booster alone descends");
370        let booster = &result.bodies[0];
371        assert_eq!((booster.body, booster.stages), (1, (1, 1)));
372        let sustainer_kg = stack_kg - booster.mass_kg;
373        let coasting: Vec<&Sample> = starts
374            .0
375            .iter()
376            .filter(|s| s.time_s >= separation_s && s.time_s < ignition_s)
377            .collect();
378        assert!(coasting.len() >= 2, "{}", coasting.len());
379        for sample in coasting {
380            assert!(
381                (sample.mass_kg - sustainer_kg).abs() < 1e-12 * stack_kg,
382                "{} kg at {} s against {sustainer_kg}",
383                sample.mass_kg,
384                sample.time_s
385            );
386        }
387        // The booster is a real share: its structure and a spent J760.
388        assert!(booster.mass_kg > 0.2 * stack_kg && booster.mass_kg < 0.8 * stack_kg);
389        // The sustainer lands with only its own structure and its spent motor.
390        let spent = super::super::recovery::body_mass_properties(
391            sim.assembly(),
392            (0, 0),
393            f64::MAX,
394            &[Some(0.0), Some(0.0)],
395        );
396        assert_eq!(result.termination, Termination::GroundHit);
397        assert!(
398            (result.final_sample.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
399            "{} against {}",
400            result.final_sample.mass_kg,
401            spent.mass_kg
402        );
403
404        // Unreachable: a sustainer lit by a separation that the flight never reaches (timed after
405        // it lands) never lights, and is carried to the ground loaded.
406        let rocket = two_stage(Ignition::Separation { delay_s: 0.0 });
407        let sim = staged(&rocket, |_| {
408            Separation::new(Trigger::Time { time_s: 3_000.0 }, 0)
409        });
410        let result = sim.run(&mut ()).unwrap();
411        assert_eq!(result.termination, Termination::GroundHit);
412        assert!(result.event(EventKind::Separation).is_none());
413        assert!(result.event(EventKind::Ignition(sustainer)).is_none());
414        assert!(result.bodies.is_empty());
415        let loaded = sim
416            .assembly()
417            .mass_properties_lit(f64::MAX, &[Some(0.0), None]);
418        assert!(
419            (result.final_sample.mass_kg - loaded.mass_kg).abs() < 1e-12 * loaded.mass_kg,
420            "{} against {}",
421            result.final_sample.mass_kg,
422            loaded.mass_kg
423        );
424    }
425
426    /// A sustainer whose mount is a cluster of two flies on after a powered separation with both
427    /// its motors: each lights at the booster's burnout plus its delay and burns out on its own
428    /// clock, and the sustainer lands with both spent. (Two I175s aft leave this sustainer
429    /// unstable: it is 0.165 rad off the flow when they light and tumbles, so its apogee is no
430    /// test of the thrust; `a_cluster_sums_its_motors_thrust_and_mass` is.)
431    #[test]
432    fn a_clustered_sustainer_flies_on_with_every_motor() {
433        clustered_sustainer(&[]);
434    }
435
436    /// A sustainer tube that fails to light stays out through the separation: its motor never
437    /// lights and lands loaded, while the other tube's flies as before.
438    #[test]
439    fn a_failed_sustainer_tube_stays_out_after_the_separation() {
440        clustered_sustainer(&[1]);
441    }
442
443    /// The two-stage rocket with its sustainer mount a pair of tubes (8 mm apart, so they cross:
444    /// a timing test, not a buildable rocket), each tube in `failed` never lighting.
445    fn clustered_sustainer(failed: &[usize]) {
446        let mut rocket = two_stage(Ignition::Burnout {
447            mount: BOOSTER_MOUNT.to_owned(),
448            delay_s: 1.0,
449        });
450        rocket.configurations[0]
451            .motors
452            .iter_mut()
453            .find(|m| m.mount == SUSTAINER_MOUNT)
454            .unwrap()
455            .failed_tubes = failed.to_vec();
456        let mount = rocket.stages[0].components[1]
457            .children
458            .iter_mut()
459            .find(|c| c.id == SUSTAINER_MOUNT)
460            .unwrap();
461        let hpr_design::Part::InnerTube(tube) = &mut mount.part else {
462            panic!("an inner tube");
463        };
464        tube.cluster_m = vec![[-0.004, 0.0], [0.004, 0.0]];
465        let separation = |sim: &Simulation| {
466            Separation::new(
467                Trigger::Burnout {
468                    motor: motor_index(sim, BOOSTER_MOUNT),
469                    delay_s: 0.5,
470                },
471                0,
472            )
473        };
474        let sim = staged(&rocket, separation);
475        assert_eq!(sim.assembly().motors.len(), 3);
476        let result = sim.run(&mut ()).unwrap();
477        let burnout_s = booster_burnout_s(&sim);
478        let mut ignitions = [Some(0.0); 3];
479        for tube in 0..2 {
480            let motor = 1 + tube;
481            assert_eq!(sim.assembly().motors[motor].tube, tube);
482            if failed.contains(&tube) {
483                assert!(result.event(EventKind::Ignition(motor)).is_none());
484                ignitions[motor] = None;
485                continue;
486            }
487            let lit = time_of(&result, EventKind::Ignition(motor));
488            assert!((lit - (burnout_s + 1.0)).abs() < 1e-12, "{motor}: {lit}");
489        }
490        let i175 = &sim.assembly().motors[1].mounted.motor;
491        assert!(
492            (time_of(&result, EventKind::Burnout) - (burnout_s + 1.0 + i175.burnout_time_s()))
493                .abs()
494                < 1e-12
495        );
496        let spent = super::super::recovery::body_mass_properties(
497            sim.assembly(),
498            (0, 0),
499            f64::MAX,
500            &ignitions,
501        );
502        assert_eq!(result.termination, Termination::GroundHit);
503        assert!(
504            (result.final_sample.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
505            "{} against {}",
506            result.final_sample.mass_kg,
507            spent.mass_kg
508        );
509    }
510
511    /// A sustainer cut at a powered separation keeps a motor set never to light unlit: beside the
512    /// lit motor, a second mount's motor set `Never` gives no ignition and lands loaded.
513    #[test]
514    fn a_sustainer_keeps_a_motor_set_never_to_light_through_the_separation() {
515        const SECOND: &str = "sustainer-second-mount";
516        let mut rocket = two_stage(Ignition::Burnout {
517            mount: BOOSTER_MOUNT.to_owned(),
518            delay_s: 1.0,
519        });
520        let airframe = &mut rocket.stages[0].components[1].children;
521        let mut mount = airframe
522            .iter()
523            .find(|c| c.id == SUSTAINER_MOUNT)
524            .unwrap()
525            .clone();
526        mount.id = SECOND.to_owned();
527        airframe.push(mount);
528        let motors = &mut rocket.configurations[0].motors;
529        let mut unlit = motors
530            .iter()
531            .find(|m| m.mount == SUSTAINER_MOUNT)
532            .unwrap()
533            .clone();
534        unlit.mount = SECOND.to_owned();
535        unlit.ignition = Ignition::Never;
536        motors.push(unlit);
537        let sim = staged(&rocket, |sim| {
538            Separation::new(
539                Trigger::Burnout {
540                    motor: motor_index(sim, BOOSTER_MOUNT),
541                    delay_s: 0.5,
542                },
543                0,
544            )
545        });
546        let second = motor_index(&sim, SECOND);
547        let result = sim.run(&mut ()).unwrap();
548        assert!(result.event(EventKind::Separation).is_some());
549        assert!(result.event(EventKind::Ignition(second)).is_none());
550        let lit = time_of(
551            &result,
552            EventKind::Ignition(motor_index(&sim, SUSTAINER_MOUNT)),
553        );
554        assert!(
555            (lit - (booster_burnout_s(&sim) + 1.0)).abs() < 1e-12,
556            "{lit}"
557        );
558        let mut ignitions = sim.assembly().ignition_times_s(|_| Some(0.0));
559        assert_eq!(ignitions[second], None);
560        ignitions[motor_index(&sim, BOOSTER_MOUNT)] = Some(0.0);
561        let spent = super::super::recovery::body_mass_properties(
562            sim.assembly(),
563            (0, 0),
564            f64::MAX,
565            &ignitions,
566        );
567        assert_eq!(result.termination, Termination::GroundHit);
568        assert!(
569            (result.final_sample.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
570            "{} against {}",
571            result.final_sample.mass_kg,
572            spent.mass_kg
573        );
574    }
575
576    /// A sustainer set never to light flies as one whose only tube fails: carried loaded, with
577    /// no thrust, to the apogee separation, and both bodies land.
578    #[test]
579    fn a_sustainer_set_never_to_light_flies_as_a_motor_out() {
580        let never = staged(&two_stage(Ignition::Never), |_| {
581            Separation::new(Trigger::Apogee, 0)
582        })
583        .run(&mut ())
584        .unwrap();
585        let mut out = two_stage(Ignition::Launch);
586        out.configurations[0]
587            .motors
588            .iter_mut()
589            .find(|m| m.mount == SUSTAINER_MOUNT)
590            .unwrap()
591            .failed_tubes = vec![0];
592        let out = staged(&out, |_| Separation::new(Trigger::Apogee, 0))
593            .run(&mut ())
594            .unwrap();
595        assert_eq!(kinds(&never), kinds(&out));
596        assert_eq!(
597            never.event(EventKind::Apogee).unwrap().sample,
598            out.event(EventKind::Apogee).unwrap().sample
599        );
600        assert!(never.bodies_landed(), "{:?}", never.bodies);
601        // No motor lit after launch: the sustainer's ignition never comes.
602        let ignitions = never
603            .events
604            .iter()
605            .filter_map(|e| match e.kind {
606                EventKind::Ignition(motor) => Some(motor),
607                _ => None,
608            })
609            .collect::<Vec<usize>>();
610        assert!(ignitions.is_empty(), "{ignitions:?}");
611    }
612
613    #[test]
614    fn apogee_separation_fires_in_flight_and_booster_flies_to_landing() {
615        // Loft lesson L30: Loft fixed the separation before the flight, so an apogee or height
616        // trigger fell back to the burnout, and it never flew the booster. Here an apogee
617        // separation fires at the flight's own apogee, a height one where the flight passes the
618        // height, and every booster flies to the ground.
619        let rocket = two_stage(Ignition::Launch);
620        let sim = staged(&rocket, |_| Separation::new(Trigger::Apogee, 0));
621        let result = sim.run(&mut ()).unwrap();
622        let apogee_s = time_of(&result, EventKind::Apogee);
623        let separation_s = time_of(&result, EventKind::Separation);
624        assert_eq!(separation_s, apogee_s);
625        assert!(separation_s > time_of(&result, EventKind::Burnout) + 5.0);
626        assert_eq!(result.termination, Termination::Separated);
627        assert!(result.bodies_landed(), "{:?}", result.bodies);
628        assert_eq!(result.landings().len(), 2);
629
630        // A height, on the way down: 300 m, located where the flight crosses it.
631        let sim = staged(&rocket, |_| {
632            Separation::new(
633                Trigger::Altitude {
634                    height_above_ground_m: 300.0,
635                },
636                0,
637            )
638        });
639        let result = sim.run(&mut ()).unwrap();
640        let at = result.event(EventKind::Separation).unwrap().sample;
641        assert!(
642            (at.height_above_ground_m - 300.0).abs() < 1e-6,
643            "{}",
644            at.height_above_ground_m
645        );
646        assert!(at.vertical_speed_m_s < 0.0);
647        assert!(result.bodies_landed(), "{:?}", result.bodies);
648
649        // Powered: the booster flies to the ground while the sustainer flies on to its own.
650        let result = serial_plan().run(&mut ()).unwrap();
651        assert_eq!(result.termination, Termination::GroundHit);
652        assert!(result.bodies_landed(), "{:?}", result.bodies);
653        let landings = result.landings();
654        assert_eq!(landings.len(), 2);
655        assert!(
656            landings
657                .iter()
658                .all(|l| l.height_above_ground_m.abs() < 1e-6)
659        );
660        // Two separate landings, not one body counted twice.
661        assert!(landings[0].time_s != landings[1].time_s);
662    }
663
664    #[test]
665    fn staged_events_come_in_order() {
666        let sim = serial_plan();
667        let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
668        let result = sim.run(&mut ()).unwrap();
669        let order = [
670            EventKind::Liftoff,
671            EventKind::RailExit,
672            EventKind::Separation,
673            EventKind::Ignition(sustainer),
674            EventKind::Burnout,
675            EventKind::Apogee,
676            EventKind::GroundHit,
677        ];
678        let times: Vec<f64> = order.iter().map(|&kind| time_of(&result, kind)).collect();
679        for pair in times.windows(2) {
680            assert!(pair[0] < pair[1], "{order:?}: {times:?}");
681        }
682        // The canopy's charge fires at the apogee and, with no lag, it deploys there too.
683        for kind in [EventKind::Trigger(0), EventKind::Deployment(0)] {
684            assert_eq!(time_of(&result, kind), time_of(&result, EventKind::Apogee));
685        }
686        // Every event is in time order, and the burnout is recorded once, at the sustainer's.
687        for pair in result.events.windows(2) {
688            assert!(pair[0].sample.time_s <= pair[1].sample.time_s);
689        }
690        let burnouts = result
691            .events
692            .iter()
693            .filter(|e| e.kind == EventKind::Burnout)
694            .count();
695        assert_eq!(burnouts, 1);
696        let i175 = &sim.assembly().motors[sustainer].mounted.motor;
697        let expected = time_of(&result, EventKind::Ignition(sustainer)) + i175.burnout_time_s();
698        assert!((time_of(&result, EventKind::Burnout) - expected).abs() < 1e-12);
699        // No motor lit at launch has an ignition event.
700        let booster = motor_index(&sim, BOOSTER_MOUNT);
701        assert!(result.event(EventKind::Ignition(booster)).is_none());
702        // The booster's own flight starts at the separation and runs in order to the ground.
703        let body = &result.bodies[0];
704        assert_eq!(
705            body.start_sample.time_s,
706            time_of(&result, EventKind::Separation)
707        );
708        for pair in body.events.windows(2) {
709            assert!(pair[0].sample.time_s <= pair[1].sample.time_s);
710        }
711        assert_eq!(body.termination, Termination::GroundHit);
712
713        // A sustainer lit by its separation: the burnout is recorded at the booster's, when
714        // nothing else is due, and again at the sustainer's.
715        let rocket = two_stage(Ignition::Separation { delay_s: 0.25 });
716        let sim = staged(&rocket, |sim| {
717            Separation::new(
718                Trigger::Burnout {
719                    motor: motor_index(sim, BOOSTER_MOUNT),
720                    delay_s: 0.5,
721                },
722                0,
723            )
724        });
725        let result = sim.run(&mut ()).unwrap();
726        let burnouts: Vec<f64> = result
727            .events
728            .iter()
729            .filter(|e| e.kind == EventKind::Burnout)
730            .map(|e| e.sample.time_s)
731            .collect();
732        let separation_s = time_of(&result, EventKind::Separation);
733        let ignition_s = time_of(&result, EventKind::Ignition(sustainer));
734        assert!((ignition_s - (separation_s + 0.25)).abs() < 1e-12);
735        assert_eq!(burnouts.len(), 2, "{burnouts:?}");
736        assert!((burnouts[0] - booster_burnout_s(&sim)).abs() < 1e-12);
737        assert!((burnouts[1] - (ignition_s + i175.burnout_time_s())).abs() < 1e-12);
738    }
739
740    #[test]
741    fn a_powered_separation_conserves_linear_momentum() {
742        // The separation adds no impulse (the decision record on separation, ADR-014): the
743        // sustainer keeps the nose tip's motion and the booster leaves with its own center of
744        // mass's velocity, so their momenta add to the stack's. The sustainer is unlit and the
745        // booster spent, so no center of mass moves inside its body. A rail 10° off vertical
746        // makes the rocket turn, so the rotation's share, `ω × r`, is not zero.
747        let rocket = two_stage(Ignition::Burnout {
748            mount: BOOSTER_MOUNT.to_owned(),
749            delay_s: 1.0,
750        });
751        let rail = Rail {
752            elevation_rad: 80.0_f64.to_radians(),
753            ..Rail::vertical(6.0)
754        };
755        let sim = staged_with(&rocket, rail, BOOSTER_AT_SEPARATION, |sim| {
756            Separation::new(
757                Trigger::Burnout {
758                    motor: motor_index(sim, BOOSTER_MOUNT),
759                    delay_s: 0.5,
760                },
761                0,
762            )
763        })
764        .unwrap();
765        let mut starts = StepStarts::default();
766        let result = sim.run(&mut starts).unwrap();
767        let stack = result.event(EventKind::Separation).unwrap().sample;
768        let booster = &result.bodies[0];
769        let sustainer = starts
770            .0
771            .iter()
772            .find(|s| s.time_s == stack.time_s && s.mass_kg < stack.mass_kg)
773            .expect("the sustainer's first step");
774        let rate = stack.state.body_rate_rad_s.length();
775        assert!(rate > 1e-3, "{rate}");
776        let before = stack.cg_velocity_enu_m_s * stack.mass_kg;
777        let after = sustainer.cg_velocity_enu_m_s * sustainer.mass_kg
778            + booster.start_sample.cg_velocity_enu_m_s * booster.mass_kg;
779        assert!(
780            (after - before).length() < 1e-9 * before.length(),
781            "{after:?} against {before:?}"
782        );
783        // And the masses add up.
784        assert!(
785            (sustainer.mass_kg + booster.mass_kg - stack.mass_kg).abs() < 1e-12 * stack.mass_kg
786        );
787    }
788
789    const MIDDLE_MOUNT: &str = "middle-motor-mount";
790
791    /// The two-stage design with a copy of its sustainer's airframe, motor mount and I175 as a
792    /// middle stage between it and the booster: stages 0 (the nose's), 1 (the middle) and 2 (the
793    /// booster). The middle lights by `middle` and the sustainer by `sustainer`.
794    fn three_stage(middle: Ignition, sustainer: Ignition) -> Rocket {
795        fn rename(component: &mut hpr_design::Component) {
796            component.id = component.id.replace("sustainer", "middle");
797            for child in &mut component.children {
798                rename(child);
799            }
800        }
801        let mut rocket = two_stage(sustainer);
802        let mut stage = rocket.stages[0].clone();
803        stage.id = "middle".to_owned();
804        stage.components.retain(|c| c.id != "nose");
805        stage.components.iter_mut().for_each(rename);
806        rocket.stages.insert(1, stage);
807        let configuration = rocket
808            .configurations
809            .iter_mut()
810            .find(|c| c.id == CONFIGURATION)
811            .unwrap();
812        let mut motor = configuration
813            .motors
814            .iter()
815            .find(|m| m.mount == SUSTAINER_MOUNT)
816            .unwrap()
817            .clone();
818        motor.mount = MIDDLE_MOUNT.to_owned();
819        motor.ignition = middle;
820        configuration.motors.push(motor);
821        rocket
822    }
823
824    /// The three-stage design flown from a 6 m vertical rail, a canopy on the sustainer at
825    /// apogee and the booster and middle each tumbling from the separation that drops it.
826    fn three_staged(
827        rocket: &Rocket,
828        separations: impl Fn(&Simulation) -> Vec<Separation>,
829    ) -> Result<Simulation, SimError> {
830        let sim = Simulation::new(
831            rocket,
832            CONFIGURATION,
833            Environment::standard(site()).unwrap(),
834            Rail::vertical(6.0),
835            FlightSettings::default(),
836        )
837        .unwrap();
838        let booster = DeviceDrag::tumbling_stages(sim.assembly(), (2, 2)).unwrap();
839        let middle = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
840        let separations = separations(&sim);
841        sim.with_recovery(vec![
842            Device::new(
843                "sustainer main",
844                DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
845                Trigger::Apogee,
846            ),
847            Device::new("booster tumble", booster, BOOSTER_AT_SEPARATION).on_body(1),
848            Device::new("middle tumble", middle, BOOSTER_AT_SEPARATION).on_body(2),
849        ])
850        .unwrap()
851        .with_separations(separations)
852    }
853
854    /// The booster drops at its burnout as the middle lights, and the middle at its own as the
855    /// sustainer lights, as OpenRocket's three-stage example flies.
856    fn burnout_chain() -> (Rocket, impl Fn(&Simulation) -> Vec<Separation>) {
857        let rocket = three_stage(
858            Ignition::Burnout {
859                mount: BOOSTER_MOUNT.to_owned(),
860                delay_s: 0.0,
861            },
862            Ignition::Burnout {
863                mount: MIDDLE_MOUNT.to_owned(),
864                delay_s: 0.0,
865            },
866        );
867        let separations = |sim: &Simulation| {
868            vec![
869                Separation::new(
870                    Trigger::Burnout {
871                        motor: motor_index(sim, BOOSTER_MOUNT),
872                        delay_s: 0.0,
873                    },
874                    1,
875                ),
876                Separation::new(
877                    Trigger::Burnout {
878                        motor: motor_index(sim, MIDDLE_MOUNT),
879                        delay_s: 0.0,
880                    },
881                    0,
882                ),
883            ]
884        };
885        (rocket, separations)
886    }
887
888    /// Each separated body's steps, as an observer sees them: their ends, each with the body's
889    /// sample and acceleration at the middle of the step.
890    #[derive(Default)]
891    struct BodySteps(Vec<(usize, f64, f64, crate::recovery::BodySample, DVec3)>);
892
893    impl Observer for BodySteps {
894        fn body_step(
895            &mut self,
896            body: usize,
897            step: &dyn crate::recorder::BodyStep,
898        ) -> Result<(), SimError> {
899            let middle = 0.5 * (step.start_s() + step.end_s());
900            self.0.push((
901                body,
902                step.start_s(),
903                step.end_s(),
904                step.sample(middle)?,
905                step.acceleration_enu_m_s2(middle)?,
906            ));
907            Ok(())
908        }
909    }
910
911    #[test]
912    fn an_observer_sees_each_accepted_step_of_a_separated_body_and_changes_no_flight() {
913        let sim = serial_plan();
914        let mut steps = BodySteps::default();
915        let watched = sim.run(&mut steps).unwrap();
916        assert_eq!(watched, sim.run(&mut ()).unwrap());
917        let [booster] = watched.bodies.as_slice() else {
918            panic!("one dropped body: {:?}", watched.bodies);
919        };
920        let seen = &steps.0;
921        assert!(seen.iter().all(|step| step.0 == booster.body));
922        // The integrator's own work on the body: every step accepted, none skipped between its
923        // stops, from where its flight starts to where it ends.
924        assert_eq!(
925            seen.len() as u64,
926            booster.stats.accepted_steps,
927            "{:?}",
928            booster.stats
929        );
930        assert_eq!(seen[0].1, booster.start_sample.time_s);
931        assert!(seen.windows(2).all(|pair| pair[0].2 == pair[1].1));
932        assert_eq!(seen.last().unwrap().2, booster.final_sample.time_s);
933        // The acceleration is the sample's velocity's own rate: across a step, the velocities at
934        // the middles of two neighbors differ by the mean of their accelerations over the time
935        // between them, to the second order of a step well inside the fall.
936        let tall = seen.len() / 2;
937        let (a, b) = (&seen[tall], &seen[tall + 1]);
938        let dt = b.3.time_s - a.3.time_s;
939        let by_difference = (b.3.cg_velocity_enu_m_s - a.3.cg_velocity_enu_m_s) / dt;
940        let by_equation = (a.4 + b.4) * 0.5;
941        assert!(
942            (by_difference - by_equation).length() < 0.01 * by_equation.length().max(1.0),
943            "{by_difference} against {by_equation} over {dt} s"
944        );
945    }
946
947    #[test]
948    fn two_powered_separations_drop_the_booster_then_the_middle() {
949        // Each separation drops the stages behind it as a body of its own, numbered in the order
950        // they drop, and hands the flight on to a sustainer cut at its boundary: the mass steps
951        // down by the dropped body's at each, and the momentum is unchanged (ADR-014).
952        let (rocket, separations) = burnout_chain();
953        let sim = three_staged(&rocket, separations).unwrap();
954        let booster_out_s = booster_burnout_s(&sim);
955        let middle_out_s = booster_out_s
956            + sim.assembly().motors[motor_index(&sim, MIDDLE_MOUNT)]
957                .mounted
958                .motor
959                .burnout_time_s();
960        let mut starts = StepStarts::default();
961        let result = sim.run(&mut starts).unwrap();
962        assert_eq!(result.termination, Termination::GroundHit);
963        let splits: Vec<_> = result
964            .events
965            .iter()
966            .filter(|event| event.kind == EventKind::Separation)
967            .map(|event| event.sample)
968            .collect();
969        assert_eq!(splits.len(), 2, "{:?}", kinds(&result));
970        assert!((splits[0].time_s - booster_out_s).abs() < 1e-9);
971        assert!((splits[1].time_s - middle_out_s).abs() < 1e-9);
972        // The middle and the sustainer each light after launch, the booster at it.
973        let ignitions = result
974            .events
975            .iter()
976            .filter(|event| matches!(event.kind, EventKind::Ignition(_)))
977            .count();
978        assert_eq!(ignitions, 2, "{:?}", kinds(&result));
979        let bodies: Vec<_> = result
980            .bodies
981            .iter()
982            .map(|body| (body.body, body.stages))
983            .collect();
984        assert_eq!(bodies, [(1, (2, 2)), (2, (1, 1))]);
985        for (split, body) in splits.iter().zip(&result.bodies) {
986            assert_eq!(body.termination, Termination::GroundHit);
987            let flown = starts
988                .0
989                .iter()
990                .find(|s| s.time_s == split.time_s && s.mass_kg < split.mass_kg)
991                .expect("the sustainer's first step after the split");
992            assert!(
993                (flown.mass_kg + body.mass_kg - split.mass_kg).abs() < 1e-12 * split.mass_kg,
994                "{} + {} against {}",
995                flown.mass_kg,
996                body.mass_kg,
997                split.mass_kg
998            );
999            let before = split.cg_velocity_enu_m_s * split.mass_kg;
1000            let after = flown.cg_velocity_enu_m_s * flown.mass_kg
1001                + body.start_sample.cg_velocity_enu_m_s * body.mass_kg;
1002            assert!(
1003                (after - before).length() < 1e-9 * before.length(),
1004                "{after:?} against {before:?}"
1005            );
1006        }
1007        // The sustainer climbs on after the second split, past where it parted.
1008        let apogee = result.event(EventKind::Apogee).unwrap().sample;
1009        assert!(apogee.time_s > middle_out_s);
1010        assert!(apogee.height_above_ground_m > splits[1].height_above_ground_m + 100.0);
1011        // The same flight to the bit, run again.
1012        let again = three_staged(&rocket, burnout_chain().1)
1013            .unwrap()
1014            .run(&mut ())
1015            .unwrap();
1016        assert_eq!(again.final_sample, result.final_sample);
1017        assert_eq!(again.bodies, result.bodies);
1018    }
1019
1020    #[test]
1021    fn a_motor_lit_by_the_first_separation_counts_from_it_at_the_second() {
1022        // The middle lights at the first separation, so its burnout has no time before the
1023        // flight; the second separation is timed after it. At the second split the middle must be
1024        // counted lit from the first (as `Ignition::Separation` says), so its body leaves with
1025        // the motor's dry mass, not its loaded one, and the spent check sees it burn.
1026        let rocket = three_stage(
1027            Ignition::Separation { delay_s: 0.0 },
1028            Ignition::Separation { delay_s: 0.0 },
1029        );
1030        let flight = |second_s: f64| {
1031            three_staged(&rocket, |sim| {
1032                vec![
1033                    Separation::new(
1034                        Trigger::Burnout {
1035                            motor: motor_index(sim, BOOSTER_MOUNT),
1036                            delay_s: 0.0,
1037                        },
1038                        1,
1039                    ),
1040                    Separation::new(Trigger::Time { time_s: second_s }, 0),
1041                ]
1042            })
1043            .unwrap()
1044        };
1045        let probe = flight(30.0);
1046        let booster_out_s = booster_burnout_s(&probe);
1047        let middle = &probe.assembly().motors[motor_index(&probe, MIDDLE_MOUNT)];
1048        let middle_out_s = booster_out_s + middle.mounted.motor.burnout_time_s();
1049        let dry_kg = middle.dry_mass_properties().mass_kg;
1050        let loaded_kg = middle.mass_properties_lit(0.0, None).mass_kg;
1051        assert!(loaded_kg > dry_kg + 0.05);
1052        let result = flight(middle_out_s + 0.5).run(&mut ()).unwrap();
1053        let middle_body = result.bodies.iter().find(|body| body.body == 2).unwrap();
1054        let structure_kg = probe.assembly().layout.stages[1].mass.mass_kg;
1055        assert!(
1056            (middle_body.mass_kg - (structure_kg + dry_kg)).abs() < 1e-9,
1057            "{} against {} + {}",
1058            middle_body.mass_kg,
1059            structure_kg,
1060            dry_kg
1061        );
1062        // Timed while the middle still burns, the second separation is refused by its burnout.
1063        let error = flight(middle_out_s - 0.2).run(&mut ()).unwrap_err();
1064        assert!(
1065            matches!(error, SimError::Domain { what, value }
1066                if what.contains("aft body's motors must have burned out")
1067                    && (value - middle_out_s).abs() < 1e-9),
1068            "{error}"
1069        );
1070    }
1071
1072    #[test]
1073    fn several_separations_refuse_what_they_cannot_fly() {
1074        let (rocket, separations) = burnout_chain();
1075        let sim = || {
1076            Simulation::new(
1077                &rocket,
1078                CONFIGURATION,
1079                Environment::standard(site()).unwrap(),
1080                Rail::vertical(6.0),
1081                FlightSettings::default(),
1082            )
1083            .unwrap()
1084        };
1085        let (booster, middle) = (
1086            motor_index(&sim(), BOOSTER_MOUNT),
1087            motor_index(&sim(), MIDDLE_MOUNT),
1088        );
1089        let at = |motor, after_stage| {
1090            Separation::new(
1091                Trigger::Burnout {
1092                    motor,
1093                    delay_s: 0.0,
1094                },
1095                after_stage,
1096            )
1097        };
1098        // Boundaries that don't move forward.
1099        let error = sim()
1100            .with_separations(vec![at(middle, 0), at(booster, 1)])
1101            .unwrap_err();
1102        assert!(
1103            matches!(error, SimError::Domain { what, value }
1104                if what.contains("forward of the one before") && value == 1.0),
1105            "{error}"
1106        );
1107        // Times known before the flight in the other order.
1108        let error = sim()
1109            .with_separations(vec![
1110                Separation::new(Trigger::Time { time_s: 9.0 }, 1),
1111                Separation::new(Trigger::Time { time_s: 8.0 }, 0),
1112            ])
1113            .unwrap_err();
1114        assert!(
1115            matches!(error, SimError::Domain { what, value }
1116                if what.contains("before the separation ahead of it") && value == 8.0),
1117            "{error}"
1118        );
1119        // Ejections with more than one separation, in either builder order.
1120        let ejection = crate::Ejection::aft_of(Trigger::Apogee, "nose");
1121        let error = sim()
1122            .with_separations(separations(&sim()))
1123            .unwrap()
1124            .with_ejections(vec![ejection.clone()])
1125            .unwrap_err();
1126        assert!(
1127            matches!(error, SimError::Unsupported { what } if what.contains("more than one separation")),
1128            "{error}"
1129        );
1130        let error = sim()
1131            .with_ejections(vec![ejection])
1132            .unwrap()
1133            .with_separations(separations(&sim()))
1134            .unwrap_err();
1135        assert!(
1136            matches!(error, SimError::Unsupported { what } if what.contains("more than one separation")),
1137            "{error}"
1138        );
1139        // A body with no device of its own.
1140        let error = sim()
1141            .with_recovery(vec![
1142                Device::new(
1143                    "sustainer main",
1144                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1145                    Trigger::Apogee,
1146                ),
1147                Device::new(
1148                    "booster tumble",
1149                    DeviceDrag::tumbling_stages(sim().assembly(), (2, 2)).unwrap(),
1150                    BOOSTER_AT_SEPARATION,
1151                )
1152                .on_body(1),
1153            ])
1154            .unwrap()
1155            .with_separations(separations(&sim()))
1156            .unwrap_err();
1157        assert!(
1158            matches!(error, SimError::Domain { what, value }
1159                if what.contains("every body needs one") && value == 2.0),
1160            "{error}"
1161        );
1162        // A first separation that leaves nothing ahead of it to burn, with a second to come: the
1163        // middle and the sustainer never light.
1164        let unlit = three_stage(Ignition::Never, Ignition::Never);
1165        let error = three_staged(&unlit, |sim| {
1166            vec![
1167                at(motor_index(sim, BOOSTER_MOUNT), 1),
1168                Separation::new(Trigger::Time { time_s: 40.0 }, 0),
1169            ]
1170        })
1171        .unwrap()
1172        .run(&mut ())
1173        .unwrap_err();
1174        assert!(
1175            matches!(error, SimError::Domain { what, .. }
1176                if what.contains("leaving nothing ahead to burn")),
1177            "{error}"
1178        );
1179        // The second separation's trigger comes before the first's: the middle can't drop while
1180        // the booster still holds it.
1181        let error = three_staged(&rocket, |sim| {
1182            vec![
1183                Separation::new(Trigger::Apogee, 1),
1184                at(motor_index(sim, MIDDLE_MOUNT), 0),
1185            ]
1186        })
1187        .unwrap()
1188        .run(&mut ())
1189        .unwrap_err();
1190        assert!(
1191            matches!(error, SimError::Domain { what, .. }
1192                if what.contains("fires before the separation ahead of it")),
1193            "{error}"
1194        );
1195    }
1196
1197    #[test]
1198    fn a_whole_base_under_power_holds_through_a_powered_separation() {
1199        // OpenRocket's rule (ADR-097): the base keeps its whole drag while a motor burns, so the
1200        // axial coefficient doesn't step at a burnout, the booster's or the sustainer's lit after
1201        // the separation. hpr's own rule takes the burning motor's area off the base, so the
1202        // coefficient steps up at each burnout.
1203        let rocket = two_stage(Ignition::Burnout {
1204            mount: BOOSTER_MOUNT.to_owned(),
1205            delay_s: 1.0,
1206        });
1207        let steps = |whole: bool| {
1208            let sim = staged(&rocket, |sim| {
1209                Separation::new(
1210                    Trigger::Burnout {
1211                        motor: motor_index(sim, BOOSTER_MOUNT),
1212                        delay_s: 0.5,
1213                    },
1214                    0,
1215                )
1216            });
1217            let sim = if whole {
1218                sim.with_full_base_drag_under_power()
1219            } else {
1220                sim
1221            };
1222            let mut starts = StepStarts::default();
1223            let result = sim.run(&mut starts).unwrap();
1224            let burnouts = [
1225                booster_burnout_s(&sim),
1226                time_of(&result, EventKind::Burnout),
1227            ];
1228            // The coefficient's relative step across each burnout, from the last step start
1229            // before it to the first at or after it.
1230            burnouts
1231                .iter()
1232                .map(|&t| {
1233                    let before = starts.0.iter().rfind(|s| s.time_s < t).unwrap();
1234                    let after = starts.0.iter().find(|s| s.time_s >= t).unwrap();
1235                    assert!(before.thrust_n > 0.0 && after.thrust_n == 0.0);
1236                    after.axial_coefficient / before.axial_coefficient - 1.0
1237                })
1238                .collect::<Vec<f64>>()
1239        };
1240        // The airspeed changes over the few milliseconds between the samples, so even the whole
1241        // base's coefficient moves a little: 0.25% and 0.29% here, against 13% and 15%.
1242        let (relieved, whole) = (steps(false), steps(true));
1243        for (relieved, whole) in relieved.into_iter().zip(whole) {
1244            assert!(relieved > 0.1, "{relieved}");
1245            assert!(whole.abs() < 0.005, "{whole}");
1246        }
1247    }
1248
1249    #[test]
1250    fn a_drag_scale_holds_through_a_powered_separation() {
1251        // A drag scale isn't the whole stack's, as a table is: the sustainer lit after the
1252        // separation keeps it. Across the separation the axial coefficient steps from the stack's
1253        // to the sustainer's, a few milliseconds apart at one Mach number. Scaled on both sides,
1254        // the step is the unscaled flight's; dropped at the separation, it would be smaller by
1255        // the scale: −4.5% here, with the scale left off the sustainer. The two flights reach
1256        // the separation at Mach 1.037 and 1.009, which moves the step by 0.25%.
1257        let rocket = two_stage(Ignition::Burnout {
1258            mount: BOOSTER_MOUNT.to_owned(),
1259            delay_s: 1.0,
1260        });
1261        let step = |scale: f64| {
1262            let sim = staged(&rocket, |sim| {
1263                Separation::new(
1264                    Trigger::Burnout {
1265                        motor: motor_index(sim, BOOSTER_MOUNT),
1266                        delay_s: 0.5,
1267                    },
1268                    0,
1269                )
1270            })
1271            .with_drag_scale(scale)
1272            .unwrap();
1273            let mut starts = StepStarts::default();
1274            let result = sim.run(&mut starts).unwrap();
1275            let separated_s = time_of(&result, EventKind::Separation);
1276            let before = starts.0.iter().rfind(|s| s.time_s < separated_s).unwrap();
1277            let after = starts.0.iter().find(|s| s.time_s > separated_s).unwrap();
1278            (
1279                after.axial_coefficient / before.axial_coefficient,
1280                before.mach,
1281            )
1282        };
1283        let (plain, plain_mach) = step(1.0);
1284        let (scaled, scaled_mach) = step(1.05);
1285        let change = scaled / plain - 1.0;
1286        assert!(
1287            change.abs() < 0.005,
1288            "{change}: {plain} {scaled} at Mach {plain_mach} and {scaled_mach}"
1289        );
1290    }
1291
1292    #[test]
1293    fn staging_refuses_what_it_cannot_fly() {
1294        // A drag table or drag model is the whole stack's; the sustainer would fly it on the
1295        // wrong shape.
1296        let rocket = two_stage(Ignition::Burnout {
1297            mount: BOOSTER_MOUNT.to_owned(),
1298            delay_s: 1.0,
1299        });
1300        let booster = motor_index(
1301            &Simulation::new(
1302                &rocket,
1303                CONFIGURATION,
1304                Environment::standard(site()).unwrap(),
1305                Rail::vertical(6.0),
1306                FlightSettings::default(),
1307            )
1308            .unwrap(),
1309            BOOSTER_MOUNT,
1310        );
1311        type Override = fn(Simulation) -> Simulation;
1312        let overrides: [(Override, &str); 2] = [
1313            (|sim| sim.with_drag_table(constant_drag(0.5)), "a table"),
1314            (|sim| sim.with_drag_model(ConstantDrag(0.5)), "a drag model"),
1315        ];
1316        for (with_override, flown) in overrides {
1317            let sim = with_override(
1318                Simulation::new(
1319                    &rocket,
1320                    CONFIGURATION,
1321                    Environment::standard(site()).unwrap(),
1322                    Rail::vertical(6.0),
1323                    FlightSettings::default(),
1324                )
1325                .unwrap(),
1326            );
1327            let tumble = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
1328            let sim = sim
1329                .with_recovery(vec![
1330                    Device::new(
1331                        "sustainer main",
1332                        DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1333                        Trigger::Apogee,
1334                    ),
1335                    Device::new("booster tumble", tumble, BOOSTER_AT_SEPARATION).on_body(1),
1336                ])
1337                .unwrap();
1338            let error = sim
1339                .with_separation(Separation::new(
1340                    Trigger::Burnout {
1341                        motor: booster,
1342                        delay_s: 0.5,
1343                    },
1344                    0,
1345                ))
1346                .unwrap()
1347                .run(&mut ())
1348                .unwrap_err();
1349            assert!(
1350                matches!(error, SimError::Domain { what, .. }
1351                if what.starts_with("time of a powered separation (a drag table or drag model")),
1352                "{flown} flown past a powered separation: {error:?}"
1353            );
1354        }
1355
1356        // A separation timed before the booster burns out, and a delay out of its domain.
1357        for (motor_delay_s, what) in [(-0.5, "negative delay"), (f64::NAN, "delay NaN")] {
1358            let error = Simulation::new(
1359                &rocket,
1360                CONFIGURATION,
1361                Environment::standard(site()).unwrap(),
1362                Rail::vertical(6.0),
1363                FlightSettings::default(),
1364            )
1365            .unwrap()
1366            .with_separation(Separation::new(
1367                Trigger::Burnout {
1368                    motor: booster,
1369                    delay_s: motor_delay_s,
1370                },
1371                0,
1372            ))
1373            .expect_err(what);
1374            assert!(
1375                matches!(error, SimError::Domain { what, .. } if what.contains("after a motor's burnout")),
1376                "{what}: {error:?}"
1377            );
1378        }
1379        let error = Simulation::new(
1380            &rocket,
1381            CONFIGURATION,
1382            Environment::standard(site()).unwrap(),
1383            Rail::vertical(6.0),
1384            FlightSettings::default(),
1385        )
1386        .unwrap()
1387        .with_separation(Separation::new(Trigger::Time { time_s: 0.5 }, 0))
1388        .expect_err("the booster still burning");
1389        let burnout_s = rocket.assemble(CONFIGURATION).unwrap().motors[booster]
1390            .mounted
1391            .motor
1392            .burnout_time_s();
1393        assert!(
1394            matches!(error, SimError::Domain { value, .. } if value == burnout_s),
1395            "{error:?}"
1396        );
1397
1398        // A booster whose device waits for its own apogee would coast there with no drag.
1399        let sim = staged_with(&rocket, Rail::vertical(6.0), Trigger::Apogee, |_| {
1400            Separation::new(
1401                Trigger::Burnout {
1402                    motor: booster,
1403                    delay_s: 0.5,
1404                },
1405                0,
1406            )
1407        })
1408        .unwrap();
1409        let error = sim.run(&mut ()).expect_err("a booster with nothing open");
1410        let nothing_open = |error: &SimError| {
1411            matches!(error, SimError::Domain { what, value }
1412                if what.contains("booster has no airframe drag") && (value - (burnout_s + 0.5)).abs() < 1e-12)
1413        };
1414        assert!(nothing_open(&error), "{error:?}");
1415        // Nor one that opens after the split: any lag leaves a coast with nothing open.
1416        let rocket_sim = Simulation::new(
1417            &rocket,
1418            CONFIGURATION,
1419            Environment::standard(site()).unwrap(),
1420            Rail::vertical(6.0),
1421            FlightSettings::default(),
1422        )
1423        .unwrap();
1424        let tumble = DeviceDrag::tumbling_stages(rocket_sim.assembly(), (1, 1)).unwrap();
1425        let error = rocket_sim
1426            .with_recovery(vec![
1427                Device::new(
1428                    "sustainer main",
1429                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1430                    Trigger::Apogee,
1431                ),
1432                Device::new("booster tumble", tumble, BOOSTER_AT_SEPARATION)
1433                    .with_lag_s(0.1)
1434                    .on_body(1),
1435            ])
1436            .unwrap()
1437            .with_separation(Separation::new(
1438                Trigger::Burnout {
1439                    motor: booster,
1440                    delay_s: 0.5,
1441                },
1442                0,
1443            ))
1444            .unwrap()
1445            .run(&mut ())
1446            .expect_err("a booster whose device opens after the split");
1447        assert!(nothing_open(&error), "{error:?}");
1448
1449        // A separation timed from the sustainer it lights could never fire.
1450        let lit_by_it = two_stage(Ignition::Separation { delay_s: 0.0 });
1451        let error = staged_with(
1452            &lit_by_it,
1453            Rail::vertical(6.0),
1454            BOOSTER_AT_SEPARATION,
1455            |sim| {
1456                Separation::new(
1457                    Trigger::Burnout {
1458                        motor: motor_index(sim, SUSTAINER_MOUNT),
1459                        delay_s: 0.5,
1460                    },
1461                    0,
1462                )
1463            },
1464        )
1465        .expect_err("a separation that could never fire");
1466        let sustainer = rocket
1467            .assemble(CONFIGURATION)
1468            .unwrap()
1469            .motors
1470            .iter()
1471            .position(|m| m.mount == SUSTAINER_MOUNT)
1472            .unwrap();
1473        assert!(
1474            matches!(error, SimError::Domain { what, value }
1475                if what.contains("could never fire") && value == sustainer as f64),
1476            "{error:?}"
1477        );
1478
1479        // A sustainer with a canopy already open is in the point-mass descent, which can't fly
1480        // it under thrust.
1481        let sim = Simulation::new(
1482            &rocket,
1483            CONFIGURATION,
1484            Environment::standard(site()).unwrap(),
1485            Rail::vertical(6.0),
1486            FlightSettings::default(),
1487        )
1488        .unwrap();
1489        let tumble = DeviceDrag::tumbling_stages(sim.assembly(), (1, 1)).unwrap();
1490        let error = sim
1491            .with_recovery(vec![
1492                Device::new(
1493                    "sustainer main",
1494                    DeviceDrag::canopy(CanopyType::FlatCircular, 1.2),
1495                    Trigger::Time { time_s: 1.0 },
1496                ),
1497                Device::new("booster tumble", tumble, BOOSTER_AT_SEPARATION).on_body(1),
1498            ])
1499            .unwrap()
1500            .with_separation(Separation::new(
1501                Trigger::Burnout {
1502                    motor: booster,
1503                    delay_s: 0.5,
1504                },
1505                0,
1506            ))
1507            .unwrap()
1508            .run(&mut ())
1509            .expect_err("a powered separation in the descent");
1510        assert!(
1511            matches!(error, SimError::Domain { what, .. } if what.contains("still has a motor to burn")),
1512            "{error:?}"
1513        );
1514    }
1515
1516    #[test]
1517    fn an_air_start_lights_at_its_time_and_burns_on_its_own_clock() {
1518        // No separation: the sustainer lights 3 s after launch with the spent booster still on.
1519        let rocket = two_stage(Ignition::Time { time_s: 3.0 });
1520        let sim = Simulation::new(
1521            &rocket,
1522            CONFIGURATION,
1523            Environment::standard(site()).unwrap(),
1524            Rail::vertical(6.0),
1525            FlightSettings::default(),
1526        )
1527        .unwrap()
1528        .with_recovery(vec![Device::new(
1529            "main",
1530            DeviceDrag::canopy(CanopyType::FlatCircular, 1.5),
1531            Trigger::Apogee,
1532        )])
1533        .unwrap();
1534        let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1535        let result = sim.run(&mut ()).unwrap();
1536        let lit = result.event(EventKind::Ignition(sustainer)).unwrap().sample;
1537        assert_eq!(lit.time_s, 3.0);
1538        // Lit, it is still loaded: the booster spent, the sustainer full.
1539        let mut ignition_s = vec![Some(0.0); sim.assembly().motors.len()];
1540        ignition_s[sustainer] = Some(3.0);
1541        let expected = sim.assembly().mass_properties_lit(3.0, &ignition_s);
1542        assert!((lit.mass_kg - expected.mass_kg).abs() < 1e-12 * expected.mass_kg);
1543        let full = sim.assembly().motors[sustainer]
1544            .mass_properties(0.0)
1545            .mass_kg;
1546        let dry = sim.assembly().motors[sustainer]
1547            .dry_mass_properties()
1548            .mass_kg;
1549        let booster_dry = sim.assembly().dry_mass_properties().mass_kg - dry;
1550        assert!(
1551            (lit.mass_kg - (booster_dry + full)).abs() < 1e-9,
1552            "{}",
1553            lit.mass_kg
1554        );
1555        // It burns out on its own clock, and the rocket lands with both motors spent.
1556        let i175 = &sim.assembly().motors[sustainer].mounted.motor;
1557        assert!(
1558            (time_of(&result, EventKind::Burnout) - (3.0 + i175.burnout_time_s())).abs() < 1e-12
1559        );
1560        let spent = sim.assembly().dry_mass_properties().mass_kg;
1561        assert!((result.final_sample.mass_kg - spent).abs() < 1e-12 * spent);
1562        assert_eq!(result.termination, Termination::GroundHit);
1563    }
1564
1565    /// The single-stage design with its motor mount a cluster of three tubes on a ring of radius
1566    /// `A` (at 0°, 120° and 240°) holding its I175 in each, and `failed` the tubes whose motor
1567    /// fails. The tubes would not fit its airframe; the equations don't ask.
1568    fn cluster_of_three(failed: Vec<usize>) -> hpr_design::Assembly {
1569        let mut rocket = design("synthetic-54mm-three-fin");
1570        let mount = rocket.stages[0].components[1]
1571            .children
1572            .iter_mut()
1573            .find(|c| c.id == SUSTAINER_MOUNT)
1574            .unwrap();
1575        let hpr_design::Part::InnerTube(tube) = &mut mount.part else {
1576            panic!("an inner tube");
1577        };
1578        tube.cluster_m = [0.0_f64, 120.0, 240.0]
1579            .iter()
1580            .map(|a| [A * a.to_radians().cos(), A * a.to_radians().sin()])
1581            .collect();
1582        rocket.configurations[0].motors[0].failed_tubes = failed;
1583        let id = rocket.configurations[0].id.clone();
1584        rocket.assemble(&id).unwrap()
1585    }
1586
1587    /// The cluster's ring radius, m.
1588    const A: f64 = 0.02;
1589
1590    /// The angular acceleration of `assembly` at rest in a vacuum, `t` seconds into the burn, its
1591    /// motors lit as it says, and the evaluation.
1592    fn at_rest(assembly: &hpr_design::Assembly, t: f64) -> (DVec3, crate::dynamics::Evaluation) {
1593        use crate::dynamics::{Conditions, Phase, Vehicle};
1594        let ignition_s = assembly.ignition_times_s(|_| None);
1595        let aero = hpr_aero::AeroModel::new(&assembly.layout).unwrap();
1596        let vehicle = Vehicle::lit(assembly.clone(), aero, ignition_s).unwrap();
1597        let environment = analytic_environment(UniformAir::vacuum(), 9.806_65);
1598        let state = crate::state::State {
1599            position_enu_m: DVec3::new(0.0, 0.0, 1000.0),
1600            velocity_enu_m_s: DVec3::ZERO,
1601            attitude: DQuat::IDENTITY,
1602            body_rate_rad_s: DVec3::ZERO,
1603        };
1604        let evaluation = vehicle
1605            .evaluate(
1606                &environment,
1607                0.0,
1608                Conditions {
1609                    phase: Phase::Free,
1610                    window: (t - 0.1, t + 0.1),
1611                    drag_area_m2: 0.0,
1612                    pivot: None,
1613                },
1614                t,
1615                &state.to_array(),
1616            )
1617            .unwrap();
1618        (
1619            DVec3::from_slice(&evaluation.derivative[10..13]),
1620            evaluation,
1621        )
1622    }
1623
1624    /// The angular acceleration the lit motors' thrust gives `assembly` at rest, by hand: each
1625    /// lit motor pushes `T ẑ` at its nozzle `pᵢ`, so about the center of mass `c` the moment is
1626    /// `M = Σ (pᵢ − c) × T ẑ = T (Σ (yᵢ − c_y), −Σ (xᵢ − c_x), 0)`, and `ω̇ = I_c⁻¹ M`.
1627    fn by_hand(assembly: &hpr_design::Assembly, t: f64) -> DVec3 {
1628        let lit = assembly.ignition_times_s(|_| None);
1629        let mass = assembly.mass_properties_lit(t, &lit);
1630        let c = mass.cg_m;
1631        let mut moment = DVec3::ZERO;
1632        for (placed, ignition) in assembly.motors.iter().zip(&lit) {
1633            if ignition.is_some() {
1634                let thrust = placed.mounted.motor.thrust_at_pressure_n(t, 0.0);
1635                let (x, y) = (placed.nozzle_m.x - c.x, placed.nozzle_m.y - c.y);
1636                moment += DVec3::new(thrust * y, -thrust * x, 0.0);
1637            }
1638        }
1639        mass.inertia_kg_m2.inverse() * moment
1640    }
1641
1642    /// Three motors in one mount sum their thrust and their mass: at rest, 1 s into the burn, the
1643    /// cluster pushes three times the one motor's thrust and weighs the structure and three
1644    /// motors. On the ring the thrusts balance, so it turns only as far as its center of mass sits
1645    /// off the axis (its rail buttons put it 0.033 mm aside at 1 s): as the hand calculation
1646    /// says, to the mass-flow terms (below), 3.2e-6 of it here; the check allows 1e-5.
1647    #[test]
1648    fn a_cluster_sums_its_motors_thrust_and_mass() {
1649        let assembly = cluster_of_three(Vec::new());
1650        assert_eq!(assembly.motors.len(), 3);
1651        let motor = &assembly.motors[0].mounted.motor;
1652        let t = 1.0;
1653        let (omega_dot, evaluation) = at_rest(&assembly, t);
1654        // In a vacuum the thrust is the curve's plus the exit's full pressure term.
1655        let one = motor.thrust_at_pressure_n(t, 0.0);
1656        assert!((evaluation.thrust_n - 3.0 * one).abs() <= 1e-12 * one);
1657        let want = assembly.layout.structure.mass_kg + 3.0 * motor.state(t).total.mass_kg;
1658        assert!((evaluation.mass.mass_kg - want).abs() <= 1e-12 * want);
1659        let want = by_hand(&assembly, t);
1660        let error = (omega_dot - want).length() / want.length();
1661        assert!(error <= 1e-5, "{omega_dot:?} vs {want:?}: {error:e}");
1662    }
1663
1664    /// A motor out gives the pitch moment the hand calculation predicts (Loft lesson L31, whose
1665    /// clusters were on the axis only). With the motor at 0° out, the two lit at 120° and 240°
1666    /// push on the side away from it: `Σ xᵢ = −A`, `Σ yᵢ = 0`, so about the center of mass `c`
1667    /// (pulled toward the loaded motor) the moment is `T (−2 c_y, A + 2 c_x, 0)`, a pitch about
1668    /// `+y` that leans the nose toward the motor out, 225 times the full cluster's; the rocket's
1669    /// products of inertia (its fins and rail buttons) turn a little of it into roll and yaw
1670    /// through `I_c⁻¹`. The rest of the equations add the mass-flow terms (the center's own motion
1671    /// as two motors burn and one doesn't, and the jets'), which here are 3.7e-7 of it; the check
1672    /// allows 1e-6.
1673    #[test]
1674    fn cluster_motor_out_produces_pitch_moment() {
1675        let assembly = cluster_of_three(vec![0]);
1676        let fails: Vec<bool> = assembly.motors.iter().map(|m| m.fails).collect();
1677        assert_eq!(fails, [true, false, false]);
1678        let t = 1.0;
1679        let (omega_dot, evaluation) = at_rest(&assembly, t);
1680        let motor = &assembly.motors[1].mounted.motor;
1681        let thrust = motor.thrust_at_pressure_n(t, 0.0);
1682        assert!((evaluation.thrust_n - 2.0 * thrust).abs() <= 1e-12 * thrust);
1683        let lit = assembly.ignition_times_s(|_| None);
1684        let mass = assembly.mass_properties_lit(t, &lit);
1685        let c = mass.cg_m;
1686        assert!(c.x > 1e-3, "{c:?}");
1687        let moment = DVec3::new(-2.0 * thrust * c.y, thrust * (A + 2.0 * c.x), 0.0);
1688        let want = mass.inertia_kg_m2.inverse() * moment;
1689        // The numbers the design page works through: 193.98 N, 1.33 mm, 4.396 N m, 41.80 rad/s².
1690        assert!((thrust - 193.98).abs() < 5e-3 && (c.x - 1.33e-3).abs() < 5e-6);
1691        assert!((moment.y - 4.396).abs() < 5e-4 && (want.y - 41.80).abs() < 5e-3);
1692        assert!(((by_hand(&assembly, t) - want).length()) <= 1e-12 * want.length());
1693        assert!(want.y > 0.0);
1694        let error = (omega_dot - want).length() / want.length();
1695        assert!(error <= 1e-6, "{omega_dot:?} vs {want:?}: {error:e}");
1696        // Mostly a pitch; the full cluster's turn is under a fortieth of it (1/225 measured).
1697        assert!(omega_dot.y > 50.0 * omega_dot.x.abs().max(omega_dot.z.abs()));
1698        let (full, _) = at_rest(&cluster_of_three(Vec::new()), t);
1699        assert!(full.length() < omega_dot.length() / 40.0, "{full:?}");
1700    }
1701
1702    /// A flight-metrics watcher that also reads both margins at 201 points across each step it
1703    /// keeps stability for.
1704    struct Scanned {
1705        metrics: crate::metrics::FlightMetrics,
1706        least_static: f64,
1707        least_flight: f64,
1708    }
1709
1710    impl Observer for Scanned {
1711        fn step(&mut self, step: &dyn FlightStep) -> Result<(), SimError> {
1712            let kept = self.metrics.stability().len();
1713            self.metrics.step(step)?;
1714            if self.metrics.stability().len() > kept {
1715                let (a, b) = (step.start_s(), step.end_s());
1716                for i in 0..=200 {
1717                    let s = step.stability(a + (b - a) * f64::from(i) / 200.0)?;
1718                    let least = |m: Option<f64>, least: f64| m.map_or(least, |m| m.min(least));
1719                    self.least_static = least(s.static_margin.margin_cal, self.least_static);
1720                    self.least_flight = least(s.flight_margin.margin_cal, self.least_flight);
1721                }
1722            }
1723            Ok(())
1724        }
1725
1726        fn event(&mut self, event: &crate::flight::FlightEvent) {
1727            self.metrics.event(event);
1728        }
1729
1730        // The watcher needs the dropped booster's steps too: its summary counts them.
1731        fn body_step(
1732            &mut self,
1733            body: usize,
1734            step: &dyn crate::recorder::BodyStep,
1735        ) -> Result<(), SimError> {
1736            self.metrics.body_step(body, step)
1737        }
1738    }
1739
1740    #[test]
1741    fn metrics_follow_a_powered_separation() {
1742        // The serial plan: the booster drops under power and lands on its own. The summary gives
1743        // the sustainer's landing and the booster's, and the margins switch to the sustainer's
1744        // diameter at the split. Only the sustainer's motor has an optimum delay: the booster's
1745        // charge would fire in the booster, which never reaches the sustainer's apogee.
1746        let sim = serial_plan();
1747        let mut metrics = crate::metrics::FlightMetrics::new();
1748        let result = sim.run(&mut metrics).unwrap();
1749        let summary = metrics.summary(&result, sim.environment()).unwrap();
1750        assert!(summary.landing.is_some());
1751        assert_eq!(summary.body_landings.len(), 1);
1752        assert_eq!(summary.body_landings[0].body, Some(1));
1753        let split_s = time_of(&result, EventKind::Separation);
1754        let series = metrics.stability();
1755        let before = series.iter().find(|s| s.time_s < split_s).unwrap();
1756        let after = series.iter().rev().find(|s| s.time_s > split_s).unwrap();
1757        assert!(after.reference_diameter_m < before.reference_diameter_m);
1758        // The split has two entries, the stack's and then the sustainer's own.
1759        let at_split: Vec<_> = series.iter().filter(|s| s.time_s == split_s).collect();
1760        assert_eq!(at_split.len(), 2);
1761        assert_eq!(at_split[1].reference_diameter_m, after.reference_diameter_m);
1762
1763        // The least margins, against a scan of every step at 201 points: at or below the scan,
1764        // and above it by less than the scan's own spacing can hide. The sustainer's static
1765        // margin holds from the split until it lights, and is least at the split; its flight
1766        // margin is least inside a step, between two entries.
1767        let mut scanned = Scanned {
1768            metrics: crate::metrics::FlightMetrics::new(),
1769            least_static: f64::INFINITY,
1770            least_flight: f64::INFINITY,
1771        };
1772        let result = sim.run(&mut scanned).unwrap();
1773        let summary = scanned.metrics.summary(&result, sim.environment()).unwrap();
1774        let (least_static, least_flight) = (
1775            summary.min_static_margin_cal.unwrap(),
1776            summary.min_flight_margin_cal.unwrap(),
1777        );
1778        for (least, scan) in [
1779            (least_static.value, scanned.least_static),
1780            (least_flight.value, scanned.least_flight),
1781        ] {
1782            // A least only gives way to one lower by more than rounding (1e-12).
1783            assert!(
1784                least <= scan + 1e-12 && scan - least < 1e-7,
1785                "{least} against {scan}"
1786            );
1787        }
1788        assert_eq!(least_static.time_s, split_s);
1789        assert_eq!(
1790            at_split[1].static_margin.margin_cal,
1791            Some(least_static.value)
1792        );
1793        let series = scanned.metrics.stability();
1794        assert!(series.iter().all(|s| s.time_s != least_flight.time_s));
1795
1796        let best = crate::metrics::optimum_delays(&sim).unwrap().unwrap();
1797        let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1798        assert_eq!(best.len(), 1);
1799        assert_eq!(best[0].motor, sustainer);
1800        let lit_s = booster_burnout_s(&sim) + 1.0;
1801        let burnout_s = lit_s
1802            + sim.assembly().motors[sustainer]
1803                .mounted
1804                .motor
1805                .burnout_time_s();
1806        assert!((best[0].burnout_s - burnout_s).abs() < 1e-9);
1807        assert!((best[0].delay_s - (best[0].apogee_s - burnout_s)).abs() < 1e-9);
1808    }
1809
1810    /// `Separation::powered_at` is the flight's own test, to its edge: the serial plan's split
1811    /// comes before the sustainer lights, so it is powered and a sustainer flies on, and so it is
1812    /// until the instant the sustainer burns out, but not at it. With the sustainer set never to
1813    /// light the same split is not powered: the flight ends there, every body a point mass, and
1814    /// the summary's apogee, the stack having none before the split, is the nose body's own
1815    /// (ADR-165). `Trigger::known_time_s` gives the split's time the flight fires it at.
1816    #[test]
1817    fn powered_at_is_the_flights_test_and_the_nose_body_has_the_apogee() {
1818        let sim = serial_plan();
1819        let assembly = sim.assembly();
1820        let separation = sim.separation().unwrap();
1821        let split_s = separation.trigger.known_time_s(assembly).unwrap().unwrap();
1822        assert_eq!(split_s, booster_burnout_s(&sim) + 0.5);
1823        assert!(separation.powered_at(assembly, split_s));
1824        let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1825        let burnout_s = booster_burnout_s(&sim)
1826            + 1.0
1827            + assembly.motors[sustainer].mounted.motor.burnout_time_s();
1828        assert!(separation.powered_at(assembly, burnout_s - 1e-9));
1829        assert!(!separation.powered_at(assembly, burnout_s));
1830        let result = sim.run(&mut ()).unwrap();
1831        assert_eq!(time_of(&result, EventKind::Separation), split_s);
1832        assert_eq!(result.termination, Termination::GroundHit);
1833        assert_eq!(result.bodies.len(), 1);
1834        // Apogee and altitude triggers are watched for, not known.
1835        assert_eq!(Trigger::Apogee.known_time_s(assembly).unwrap(), None);
1836
1837        let unlit = staged(&two_stage(Ignition::Never), |sim| {
1838            Separation::new(
1839                Trigger::Burnout {
1840                    motor: motor_index(sim, BOOSTER_MOUNT),
1841                    delay_s: 0.5,
1842                },
1843                0,
1844            )
1845        });
1846        let separation = unlit.separation().unwrap();
1847        assert!(!separation.powered_at(unlit.assembly(), split_s));
1848        let mut metrics = crate::metrics::FlightMetrics::new();
1849        let result = unlit.run(&mut metrics).unwrap();
1850        assert_eq!(result.termination, Termination::Separated);
1851        assert!(result.event(EventKind::Apogee).is_none());
1852        let nose = result.bodies.iter().find(|body| body.body == 0).unwrap();
1853        let apogee = nose.event(EventKind::Apogee).unwrap().sample;
1854        assert!(apogee.time_s > split_s);
1855        let summary = metrics.summary(&result, unlit.environment()).unwrap();
1856        let flown = summary.apogee.unwrap();
1857        assert_eq!(flown.time_s, apogee.time_s);
1858        assert_eq!(flown.height_above_ground_m, apogee.height_above_ground_m);
1859        assert_eq!(
1860            flown.gain_m,
1861            summary
1862                .launch_height_m
1863                .map(|start| apogee.height_above_ground_m - start)
1864        );
1865    }
1866
1867    #[test]
1868    fn a_held_flight_holds_a_separation_after_the_last_burnout() {
1869        // The sustainer lights 1 s after the booster burns out, still attached, and the stack
1870        // separates a delay after the sustainer burns out: part of the recovery. However long
1871        // the delay, the held flight coasts through to the same apogee.
1872        let rocket = two_stage(Ignition::Burnout {
1873            mount: BOOSTER_MOUNT.to_owned(),
1874            delay_s: 1.0,
1875        });
1876        let with_delay = |delay_s: f64| {
1877            staged(&rocket, |sim| {
1878                Separation::new(
1879                    Trigger::Burnout {
1880                        motor: motor_index(sim, SUSTAINER_MOUNT),
1881                        delay_s,
1882                    },
1883                    0,
1884                )
1885            })
1886        };
1887        let (short, long) = (with_delay(3.0), with_delay(30.0));
1888        let flown = short.run(&mut ()).unwrap();
1889        assert_eq!(flown.termination, Termination::Separated);
1890        let a = crate::metrics::optimum_delays(&short).unwrap().unwrap();
1891        let b = crate::metrics::optimum_delays(&long).unwrap().unwrap();
1892        assert_eq!(a.len(), 2);
1893        assert_eq!(b.len(), 2);
1894        // Each flight still stops its steps at its own separation time, so the two agree to the
1895        // integration's tolerance rather than bit for bit: the apogee is where the vertical speed
1896        // crosses zero at g, so 3e-5 m/s of it is 3e-6 s.
1897        for (a, b) in a.iter().zip(&b) {
1898            assert_eq!((a.motor, a.burnout_s), (b.motor, b.burnout_s));
1899            assert!((a.delay_s - b.delay_s).abs() < 1e-5, "{a:?} vs {b:?}");
1900        }
1901        // The short delay's separation came before that apogee.
1902        assert!(time_of(&flown, EventKind::Separation) < a[0].apogee_s);
1903    }
1904
1905    /// The two-stage design with its booster strapped beside the sustainer instead of stacked
1906    /// behind it: the booster's tube, without its interstage, as a parallel stage of `count` pods
1907    /// whose aft ends meet the sustainer's, each with a J760; the sustainer's I175 lit at launch.
1908    fn strapped(count: u32) -> Rocket {
1909        let mut rocket = two_stage(Ignition::Launch);
1910        let booster = &mut rocket.stages[1];
1911        booster.components.retain(|c| c.id != "interstage");
1912        booster.parallel = Some(hpr_design::ParallelStage {
1913            on: "sustainer-airframe".to_owned(),
1914            position: hpr_design::Position::Bottom { aft_offset_m: 0.0 },
1915            pods: hpr_design::PodSet {
1916                count,
1917                radial_offset_m: 0.02815 + 0.04,
1918                angle_rad: 0.0,
1919            },
1920        });
1921        rocket
1922    }
1923
1924    /// Strap-on boosters take their added mass with them (ADR-341): with 0.3 kg added to the
1925    /// parallel stage, at a station or with none, the stack's structure is that much heavier,
1926    /// the pods descend that much heavier, and the sustainer lands with what it lands with when
1927    /// the pods carry none. The same holds for the mass at a station on the sustainer, turned
1928    /// about: it stays with the sustainer.
1929    #[test]
1930    fn strap_on_boosters_take_their_added_mass_with_them() {
1931        let flown = |rocket: &Rocket| {
1932            let sim = staged(rocket, |sim| {
1933                Separation::new(
1934                    Trigger::Burnout {
1935                        motor: motor_index(sim, BOOSTER_MOUNT),
1936                        delay_s: 0.0,
1937                    },
1938                    0,
1939                )
1940            });
1941            let result = sim.run(&mut ()).unwrap();
1942            assert_eq!(result.bodies.len(), 1);
1943            [
1944                sim.assembly().layout.structure.mass_kg,
1945                result.bodies[0].mass_kg,
1946                result.final_sample.mass_kg,
1947            ]
1948        };
1949        let plain = flown(&strapped(2));
1950        for cg_aft_m in [None, Some(0.2)] {
1951            let mut rocket = strapped(2);
1952            rocket.stages[1].added_mass = Some(hpr_design::AddedMass {
1953                mass_kg: 0.3,
1954                cg_aft_m,
1955            });
1956            let added = flown(&rocket);
1957            assert!((added[0] - plain[0] - 0.3).abs() < 1e-12, "{added:?}");
1958            assert!((added[1] - plain[1] - 0.3).abs() < 1e-12, "{added:?}");
1959            assert!((added[2] - plain[2]).abs() < 1e-12, "{added:?}");
1960        }
1961        let mut rocket = strapped(2);
1962        rocket.stages[0].added_mass = Some(hpr_design::AddedMass {
1963            mass_kg: 0.3,
1964            cg_aft_m: Some(0.2),
1965        });
1966        let added = flown(&rocket);
1967        assert!((added[0] - plain[0] - 0.3).abs() < 1e-12, "{added:?}");
1968        assert!((added[1] - plain[1]).abs() < 1e-12, "{added:?}");
1969        assert!((added[2] - plain[2] - 0.3).abs() < 1e-12, "{added:?}");
1970    }
1971
1972    /// Strap-on boosters burn beside the sustainer and drop at their separation, a boundary after
1973    /// the stage they hang on: the mass steps down by exactly the pods' structure and their spent
1974    /// motors, the sustainer burns on, and it climbs higher than with the pods carried to apogee.
1975    #[test]
1976    fn strap_on_boosters_burn_beside_the_sustainer_and_drop() {
1977        let rocket = strapped(2);
1978        let sim = staged(&rocket, |sim| {
1979            Separation::new(
1980                Trigger::Burnout {
1981                    motor: motor_index(sim, BOOSTER_MOUNT),
1982                    delay_s: 0.0,
1983                },
1984                0,
1985            )
1986        });
1987        assert_eq!(
1988            sim.assembly().motors.len(),
1989            3,
1990            "a J760 in each pod and the I175"
1991        );
1992        let result = sim.run(&mut ()).unwrap();
1993        let burnout_s = booster_burnout_s(&sim);
1994        let separation_s = time_of(&result, EventKind::Separation);
1995        assert!((separation_s - burnout_s).abs() < 1e-12, "{separation_s}");
1996        let sustainer = motor_index(&sim, SUSTAINER_MOUNT);
1997        let sustainer_burnout_s = sim.assembly().motors[sustainer]
1998            .mounted
1999            .motor
2000            .burnout_time_s();
2001        assert!(sustainer_burnout_s > separation_s, "a powered separation");
2002
2003        // The pods descend alone, with their structure and both spent J760s.
2004        assert_eq!(result.bodies.len(), 1);
2005        let pods = &result.bodies[0];
2006        assert_eq!((pods.body, pods.stages), (1, (1, 1)));
2007        let spent = super::super::recovery::body_mass_properties(
2008            sim.assembly(),
2009            (1, 1),
2010            f64::MAX,
2011            &[Some(0.0); 3],
2012        );
2013        assert!(
2014            (pods.mass_kg - spent.mass_kg).abs() < 1e-12 * spent.mass_kg,
2015            "{} against {}",
2016            pods.mass_kg,
2017            spent.mass_kg
2018        );
2019        let structure = sim.assembly().layout.stages[1].mass.mass_kg;
2020        assert!(pods.mass_kg > structure, "the spent cases go with the pods");
2021
2022        // The sustainer lands with its own structure and its spent motor only.
2023        let core = super::super::recovery::body_mass_properties(
2024            sim.assembly(),
2025            (0, 0),
2026            f64::MAX,
2027            &[Some(0.0); 3],
2028        );
2029        assert_eq!(result.termination, Termination::GroundHit);
2030        assert!(
2031            (result.final_sample.mass_kg - core.mass_kg).abs() < 1e-12 * core.mass_kg,
2032            "{} against {}",
2033            result.final_sample.mass_kg,
2034            core.mass_kg
2035        );
2036
2037        // Carried to the ground, the pods' dead mass and drag cost height.
2038        let carried = staged(&rocket, |_| {
2039            Separation::new(Trigger::Time { time_s: 3_000.0 }, 0)
2040        })
2041        .run(&mut ())
2042        .unwrap();
2043        assert!(carried.bodies.is_empty());
2044        let apogee = |result: &FlightResult| {
2045            result
2046                .event(EventKind::Apogee)
2047                .unwrap()
2048                .sample
2049                .height_above_ground_m
2050        };
2051        assert!(
2052            apogee(&result) > apogee(&carried),
2053            "{} against {}",
2054            apogee(&result),
2055            apogee(&carried)
2056        );
2057    }
2058
2059    /// A drag override on a parallel stage, or one covering the stage it hangs on, is refused: how
2060    /// OpenRocket flies either hasn't been measured. One on the stage that doesn't cover what it
2061    /// holds flies.
2062    #[test]
2063    fn a_drag_override_near_a_parallel_stage_is_refused() {
2064        let aero = |rocket: &Rocket| {
2065            let assembly = rocket.assemble(CONFIGURATION).unwrap();
2066            hpr_aero::AeroModel::new(&assembly.layout).map(|_| ())
2067        };
2068        let stated = |include_children| hpr_design::DragOverride {
2069            coefficient: 0.5,
2070            include_children,
2071        };
2072        for (stage, include_children, refused) in [
2073            (1, false, Some("a drag override on a parallel stage")),
2074            (1, true, Some("a drag override on a parallel stage")),
2075            (0, true, Some("covering a stage a parallel stage hangs on")),
2076            (0, false, None),
2077        ] {
2078            let mut rocket = strapped(2);
2079            rocket.stages[stage].drag_override = Some(stated(include_children));
2080            match (aero(&rocket), refused) {
2081                (Ok(()), None) => {}
2082                (Err(error), Some(want)) => {
2083                    assert!(error.to_string().contains(want), "{error}");
2084                }
2085                (got, want) => panic!("stage {stage}, {include_children}: {got:?}, {want:?}"),
2086            }
2087        }
2088    }
2089
2090    /// A separation drops every stage after its boundary, so a parallel stage hung on the stage
2091    /// the nose keeps can't go with an axial booster behind it; dropping the booster first, then
2092    /// the pods, flies.
2093    #[test]
2094    fn a_separation_drops_only_what_hangs_together() {
2095        fn rename(component: &mut hpr_design::Component) {
2096            component.id = component.id.replace("booster", "strap");
2097            for child in &mut component.children {
2098                rename(child);
2099            }
2100        }
2101        // The sustainer, a pair of motorless pods on it, and the stacked booster behind.
2102        let mut rocket = two_stage(Ignition::Launch);
2103        let mut pods = strapped(2).stages[1].clone();
2104        pods.id = "straps".to_owned();
2105        pods.components.iter_mut().for_each(rename);
2106        rocket.stages.insert(1, pods);
2107        let simulation = || {
2108            Simulation::new(
2109                &rocket,
2110                CONFIGURATION,
2111                Environment::standard(site()).unwrap(),
2112                Rail::vertical(6.0),
2113                FlightSettings::default(),
2114            )
2115            .unwrap()
2116        };
2117        let booster = motor_index(&simulation(), BOOSTER_MOUNT);
2118        let at_burnout = |after_stage| {
2119            Separation::new(
2120                Trigger::Burnout {
2121                    motor: booster,
2122                    delay_s: 0.0,
2123                },
2124                after_stage,
2125            )
2126        };
2127        match simulation().with_separation(at_burnout(0)) {
2128            Err(SimError::Domain { what, value }) => {
2129                assert!(what.contains("must hang together"), "{what}");
2130                assert_eq!(value, 0.0);
2131            }
2132            other => panic!("expected the hang-together refusal, got {other:?}"),
2133        }
2134        // The booster alone, then the pods.
2135        simulation().with_separation(at_burnout(1)).unwrap();
2136        simulation()
2137            .with_separations(vec![
2138                at_burnout(1),
2139                Separation::new(Trigger::Time { time_s: 5.0 }, 0),
2140            ])
2141            .unwrap();
2142    }
2143
2144    /// ADR-172: a powered separation told to ([`Separation::dropping_burning`]) drops a booster
2145    /// still burning, as OpenRocket's first burnout of a stage drops its other motors, and the
2146    /// booster's descent says how much of its curve's impulse it leaves out. Not told to, or
2147    /// unpowered, or with a motor behind still to light, it is refused.
2148    #[test]
2149    fn a_powered_separation_drops_a_burning_booster_only_when_told() {
2150        let rocket = two_stage(Ignition::Separation { delay_s: 0.0 });
2151        let flown = Simulation::new(
2152            &rocket,
2153            CONFIGURATION,
2154            Environment::standard(site()).unwrap(),
2155            Rail::vertical(6.0),
2156            FlightSettings::default(),
2157        )
2158        .unwrap();
2159        let split_s = 0.5 * booster_burnout_s(&flown);
2160        let at_split = |_: &Simulation| Separation::new(Trigger::Time { time_s: split_s }, 0);
2161        let burning = |error: &SimError| {
2162            matches!(error, SimError::Domain { what, .. }
2163                if what.contains("the aft body's motors must have burned out"))
2164        };
2165        let refused = |rocket: &Rocket, separation: &dyn Fn(&Simulation) -> Separation| {
2166            staged_with(
2167                rocket,
2168                Rail::vertical(6.0),
2169                BOOSTER_AT_SEPARATION,
2170                separation,
2171            )
2172            .expect_err("refused")
2173        };
2174        let error = refused(&rocket, &at_split);
2175        assert!(burning(&error), "{error:?}");
2176
2177        let result = staged(&rocket, |sim| at_split(sim).dropping_burning())
2178            .run(&mut ())
2179            .unwrap();
2180        assert!((time_of(&result, EventKind::Separation) - split_s).abs() < 1e-12);
2181        let curve = flown.assembly().motors[motor_index(&flown, BOOSTER_MOUNT)]
2182            .mounted
2183            .motor
2184            .curve();
2185        let left_n_s = curve.total_impulse_ns() - curve.impulse_ns(split_s);
2186        assert!(left_n_s > 0.1 * curve.total_impulse_ns(), "{left_n_s}");
2187        let booster = result
2188            .bodies
2189            .iter()
2190            .find(|body| body.body == 1)
2191            .expect("the booster's descent");
2192        assert!(
2193            (booster.impulse_left_n_s - left_n_s).abs() <= 1e-12 * left_n_s,
2194            "{} against {left_n_s}",
2195            booster.impulse_left_n_s
2196        );
2197        for body in result.bodies.iter().filter(|body| body.body != 1) {
2198            assert_eq!(body.impulse_left_n_s, 0.0, "body {}", body.body);
2199        }
2200
2201        // Unpowered: the sustainer never lights, so nothing ahead burns at the split.
2202        let error = refused(&two_stage(Ignition::Never), &|sim| {
2203            at_split(sim).dropping_burning()
2204        });
2205        assert!(burning(&error), "{error:?}");
2206
2207        // A booster lit after the split is still to light there, powered or not.
2208        let mut late = two_stage(Ignition::Launch);
2209        late.configurations
2210            .iter_mut()
2211            .find(|c| c.id == CONFIGURATION)
2212            .unwrap()
2213            .motors
2214            .iter_mut()
2215            .find(|m| m.mount == BOOSTER_MOUNT)
2216            .unwrap()
2217            .ignition = Ignition::Time {
2218            time_s: split_s + 1.0,
2219        };
2220        let error = refused(&late, &|sim| at_split(sim).dropping_burning());
2221        assert!(burning(&error), "{error:?}");
2222    }
2223}