Skip to main content

hpr_sim/
flight.rs

1//! A flight from ignition to the ground: the pad, the rail and free flight, their events, and how
2//! the flight ends.
3//!
4//! [`Simulation::run`] integrates the rigid-body equations (`crate::dynamics`) phase by phase:
5//!
6//! - **Pad:** the state holds still until the force along the rail exceeds friction (liftoff).
7//! - **Rail:** one degree of freedom along the rail until the last guide leaves its top (rail
8//!   exit, `crate::rail`). If the rocket stops on the rail it falls back to the pad phase.
9//! - **Free:** six degrees of freedom until the ground.
10//! - **Descent:** once a recovery device deploys, a point mass under the open devices' drag area
11//!   (`crate::recovery`), with the attitude frozen where it deployed.
12//!
13//! Every ignition, thrust-curve knot and burnout is a stop time, so no step straddles a change in
14//! the thrust's slope or the start or end of a burn, and each interval knows which motors burn.
15//! Each motor burns on its own clock from its ignition ([`hpr_design::Ignition`]).
16//!
17//! **Staging.** A [`Separation`] whose nose body still has a motor to burn is powered: that body,
18//! the sustainer, flies on in six degrees of freedom on its own stages' aerodynamics and mass, and
19//! the aft body, the booster, descends to its landing as a point mass ([`FlightResult::bodies`]).
20//! The state is the nose tip's, which the sustainer keeps, so it carries straight across the split
21//! (the decision record on staging, [ADR-074][adr-074]). Liftoff, rail
22//! exit, apogee (the center of mass's height rate crossing zero), ground contact (its ellipsoidal
23//! height reaching the site's) and user events are located by the integrator's event finder.
24//!
25//! A flight ends on the ground ([`Termination::GroundHit`]), with no liftoff by the last burnout
26//! ([`Termination::NoLiftoff`]), stalled back onto the pad ([`Termination::StalledOnRail`]), at
27//! the time cap ([`Termination::TimeCap`]) or at the step limit ([`Termination::StepLimit`]).
28//! Anything else that stops it is an error. With no recovery device the flight is ballistic to
29//! the ground.
30//!
31//! Method: `docs/physics/flight.md` and `docs/physics/recovery.md`.
32//!
33//! [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
34
35use std::borrow::Cow;
36use std::fmt;
37use std::ops::ControlFlow;
38use std::sync::Arc;
39
40use hpr_aero::{AeroModel, DragModel, DragTable, NormalForceTable};
41use hpr_core::DVec3;
42use hpr_design::checks::has_errors;
43use hpr_design::{LaidOut, Rocket};
44use serde::{Deserialize, Serialize};
45
46use crate::dynamics::{Conditions, Evaluation, Phase, Vehicle};
47use crate::environment::Environment;
48use crate::error::SimError;
49use crate::events::Direction;
50use crate::histories::{MassHistory, ThrustHistory};
51use crate::integrator::{
52    Adaptive, Advance, IntegrationError, Integrator, Method, OdeSystem, Stats, Step,
53};
54use crate::metrics::Stability;
55use crate::pieces::{Ejection, Pieces};
56use crate::rail::{Guides, Pivot, Rail};
57use crate::recorder::{BodyStep, FlightStep, Observer, Sample};
58use crate::recovery::{self, BodyEvent, BodyFlight, BodySample, Device, Run, Separation, Trigger};
59use crate::releases::{MassRelease, ReleasedFlight, Releases};
60use crate::shifts::{MassShift, Shifts};
61use crate::staging::{FlownVehicle, Sustainer};
62use crate::state::{STATE_LEN, State};
63
64/// The airspeed below which a body with no attitude of its own is taken to be still in the air, m/s:
65/// the way an ejection's push points is then up rather than along its drift (ADR-086).
66const STILL_AIR_M_S: f64 = 1e-3;
67
68/// How the refusals of a trigger read for a mass shift or a mass release, where a device's would
69/// name a device.
70struct TriggerWords {
71    /// A height that is not positive and finite.
72    height: &'static str,
73    /// A time before launch.
74    time: &'static str,
75    /// A motor that isn't there, for a delay.
76    delay_motor: &'static str,
77    /// A motor with no ejection delay in seconds.
78    no_delay: &'static str,
79    /// A motor with no ignition known before the flight.
80    never: &'static str,
81}
82
83/// A mass shift's words.
84const SHIFT_WORDS: TriggerWords = TriggerWords {
85    height: "height above the launch site at which a part starts to move, m",
86    time: "start time of a mass shift after launch, s",
87    delay_motor: "index of the motor whose delay starts a mass shift",
88    no_delay: "the motor whose delay starts a mass shift has no ejection delay in seconds (it is \
89               plugged, or its delay is unset)",
90    never: "index of the motor a mass shift is timed from (it has no ignition time before the \
91            flight, so the shift could never start)",
92};
93
94/// A mass release's words.
95const RELEASE_WORDS: TriggerWords = TriggerWords {
96    height: "height above the launch site at which a part is released, m",
97    time: "time of a mass release after launch, s",
98    delay_motor: "index of the motor whose delay releases a part",
99    no_delay: "the motor whose delay releases a part has no ejection delay in seconds (it is \
100               plugged, or its delay is unset)",
101    never: "index of the motor a mass release is timed from (it has no ignition time before the \
102            flight, so the part could never be released)",
103};
104
105/// How a flight is integrated and when it gives up.
106#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
107#[serde(default, deny_unknown_fields)]
108pub struct FlightSettings {
109    /// The integration method and tolerances.
110    pub method: Method,
111    /// The flight stops with [`Termination::TimeCap`] at this time after launch, s.
112    pub max_time_s: f64,
113    /// The flight stops with [`Termination::StepLimit`] after this many attempted steps.
114    pub step_limit: u64,
115    /// Fly a design whose checks report errors.
116    pub accept_design_errors: bool,
117}
118
119impl Default for FlightSettings {
120    /// Dormand–Prince 5(4) with `rtol = atol = 1e-8` and unit weights (1.1 ms and an apogee
121    /// converged to 3e-5 m for a Level 2 flight, `docs/physics/flight.md`), a one-hour time cap, a
122    /// limit of 10⁶ steps, and design errors refused.
123    fn default() -> Self {
124        Self {
125            method: Method::DormandPrince54(Adaptive::default()),
126            max_time_s: 3600.0,
127            step_limit: crate::integrator::DEFAULT_STEP_LIMIT,
128            accept_design_errors: false,
129        }
130    }
131}
132
133/// What happened.
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136#[non_exhaustive]
137pub enum EventKind {
138    /// The force along the rail first exceeded friction.
139    Liftoff,
140    /// The last rail guide left the top of the rail.
141    RailExit,
142    /// Every motor lit, or due to light at a known time, has burned out: the last motor's thrust
143    /// curve ended. It is recorded again if a motor lights afterwards, as a sustainer lit by its
144    /// separation does.
145    Burnout,
146    /// The center of mass's height rate crossed zero from above.
147    Apogee,
148    /// The center of mass reached the launch site's ellipsoidal height, descending.
149    GroundHit,
150    /// A recovery device's charge fired, by its index in the flight's devices.
151    Trigger(usize),
152    /// A recovery device deployed (line stretch), its lag after the trigger, by its index. The
153    /// first deployment starts the descent phase. A device that was released before its charge
154    /// fired never deploys.
155    Deployment(usize),
156    /// A recovery device was released, by its index: the device that releases it is fully open
157    /// from this instant, so the drag area never dips between them.
158    Release(usize),
159    /// The stack came apart at its separation's stage boundary; the descents of the bodies that
160    /// don't fly on are in [`FlightResult::bodies`].
161    Separation,
162    /// A piece left the airframe at an ejection, by its index in the flight's ejections
163    /// ([`crate::Ejection`]); the bodies it leaves are in [`FlightResult::bodies`].
164    Ejection(usize),
165    /// A part started to move along the airframe, by its index in the flight's mass shifts
166    /// ([`crate::MassShift`]).
167    Shift(usize),
168    /// A part left the airframe, by its index in the flight's mass releases
169    /// ([`crate::MassRelease`]); its own flight is in [`FlightResult::released`], and the event's
170    /// sample is the rocket just before it left.
171    MassRelease(usize),
172    /// A user event, by its index in the order added.
173    User(usize),
174    /// A motor lit after launch, by its index in [`hpr_design::Assembly::motors`].
175    Ignition(usize),
176}
177
178/// An event and the flight's sample at it.
179#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
180pub struct FlightEvent {
181    /// What happened.
182    pub kind: EventKind,
183    /// The flight at that instant.
184    pub sample: Sample,
185}
186
187/// Why a flight ended ([Loft lesson L25][l25]: every way of stopping is named).
188///
189/// [l25]: https://hpr.fusionspace.co/decisions-and-roadmap.html#l25
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192#[non_exhaustive]
193pub enum Termination {
194    /// The center of mass reached the ground.
195    GroundHit,
196    /// Every motor burned out before the rocket lifted off.
197    NoLiftoff,
198    /// The rocket lifted off but stopped on the rail and every motor has burned out.
199    StalledOnRail,
200    /// The time cap was reached.
201    TimeCap,
202    /// The integrator's step limit was reached.
203    StepLimit,
204    /// The stack separated, and each body flew on as its own descent
205    /// ([`FlightResult::bodies`]).
206    Separated,
207}
208
209/// A finished flight.
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct FlightResult {
212    /// Why it ended.
213    pub termination: Termination,
214    /// Its events, in order.
215    pub events: Vec<FlightEvent>,
216    /// The flight where it ended. After a [`Termination::Separated`] this is the **stack** at the
217    /// separation, not a landing: the landings are in `bodies` (see [`Self::landings`]). After a
218    /// powered separation it is the sustainer's.
219    pub final_sample: Sample,
220    /// The integrator's work.
221    pub stats: Stats,
222    /// The descents of the separated bodies, in body order: every body that flew on its own when
223    /// the flight ended with [`Termination::Separated`] (pieces whose parting never fired land as
224    /// one body), the booster alone after a powered separation (the sustainer's
225    /// flight is the rest of this result), and none otherwise.
226    #[serde(default, skip_serializing_if = "Vec::is_empty")]
227    pub bodies: Vec<BodyFlight>,
228    /// The flights of the parts released in flight ([`crate::MassRelease`]), in the order they
229    /// left; none without releases. They are not among [`Self::bodies`] or [`Self::landings`].
230    #[serde(default, skip_serializing_if = "Vec::is_empty")]
231    pub released: Vec<ReleasedFlight>,
232}
233
234impl FlightResult {
235    /// Whether every separated body in [`Self::bodies`] landed. A flight that ends with
236    /// [`Termination::Separated`] says only that the stack came apart: each body's own
237    /// [`BodyFlight::termination`] says whether it reached the ground, and a body can run out of
238    /// time or steps on its own. After a powered separation the sustainer's own landing is
239    /// [`Self::termination`].
240    #[must_use]
241    pub fn bodies_landed(&self) -> bool {
242        !self.bodies.is_empty()
243            && self
244                .bodies
245                .iter()
246                .all(|body| body.termination == Termination::GroundHit)
247    }
248
249    /// Where the flight put things on the ground: the final sample's position when it (or after a
250    /// powered separation, the sustainer) landed, then each separated body's landing.
251    #[must_use]
252    pub fn landings(&self) -> Vec<BodySample> {
253        let bodies = self
254            .bodies
255            .iter()
256            .filter(|body| body.termination == Termination::GroundHit)
257            .map(|body| body.final_sample);
258        if self.termination == Termination::GroundHit {
259            std::iter::once(BodySample {
260                time_s: self.final_sample.time_s,
261                cg_enu_m: self.final_sample.cg_enu_m,
262                cg_velocity_enu_m_s: self.final_sample.cg_velocity_enu_m_s,
263                height_above_ground_m: self.final_sample.height_above_ground_m,
264                vertical_speed_m_s: self.final_sample.vertical_speed_m_s,
265                airspeed_m_s: self.final_sample.airspeed_m_s,
266                recovery_drag_area_m2: self.final_sample.recovery_drag_area_m2,
267                mass_kg: self.final_sample.mass_kg,
268            })
269            .chain(bodies)
270            .collect()
271        } else {
272            bodies.collect()
273        }
274    }
275
276    /// The first event of `kind`.
277    #[must_use]
278    pub fn event(&self, kind: EventKind) -> Option<&FlightEvent> {
279        self.events.iter().find(|event| event.kind == kind)
280    }
281}
282
283/// A user event: `function(sample)` crossing zero in `direction` during free flight. It is
284/// recorded and the flight continues.
285pub struct UserEvent {
286    /// A name for reports.
287    pub name: String,
288    /// The crossing direction.
289    pub direction: Direction,
290    /// The event function.
291    pub function: Box<dyn Fn(&Sample) -> f64 + Send + Sync>,
292}
293
294impl fmt::Debug for UserEvent {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_struct("UserEvent")
297            .field("name", &self.name)
298            .field("direction", &self.direction)
299            .finish_non_exhaustive()
300    }
301}
302
303/// A rocket, its surroundings, its rail and its settings, ready to fly.
304#[derive(Debug)]
305pub struct Simulation {
306    vehicle: Vehicle,
307    environment: Environment,
308    rail: Rail,
309    guides: Guides,
310    settings: FlightSettings,
311    user_events: Vec<UserEvent>,
312    devices: Vec<Device>,
313    /// The trigger times known before the flight, one per device: a time after launch or a
314    /// motor's delay after its burnout, and `None` for the triggers the flight watches for.
315    trigger_times_s: Vec<Option<f64>>,
316    /// The separations, in the order they fire, each further forward than the one before.
317    separations: Vec<Separation>,
318    /// Each separation's trigger time, when it is one that is known before the flight.
319    separation_times_s: Vec<Option<f64>>,
320    /// The pieces that leave the airframe, and when.
321    ejections: Vec<Ejection>,
322    /// Each ejection's trigger time, when it is one that is known before the flight.
323    ejection_times_s: Vec<Option<f64>>,
324    /// The parts that move along the airframe, in the order given.
325    shifts: Vec<MassShift>,
326    /// The parts released in flight, in the order given.
327    releases: Vec<MassRelease>,
328    /// Each released part as the design places it.
329    release_parts: Releases,
330    /// Each release's trigger time, when it is one that is known before the flight.
331    release_times_s: Vec<Option<f64>>,
332    /// The design, kept to build a sustainer's models from at a powered separation.
333    rocket: Rocket,
334    /// The configuration flown.
335    configuration_id: String,
336    /// Whether the aerodynamics were replaced by a table or a drag model, which is the whole
337    /// stack's only.
338    aero_overridden: bool,
339    /// Whether the recovery charges are held: no device on the stack fires, whatever its trigger
340    /// ([`crate::metrics::optimum_delays`] flies the ascent so).
341    recovery_held: bool,
342    /// Whether the flight has a tip-off phase ([`Simulation::with_tip_off`]).
343    tip_off: bool,
344}
345
346impl Simulation {
347    /// Assembles `rocket` in configuration `configuration_id`, runs its checks and builds its
348    /// aerodynamic model.
349    ///
350    /// # Errors
351    ///
352    /// [`SimError::DesignChecks`] if the checks report errors and the settings don't accept them;
353    /// errors assembling the design or building its aerodynamics; a bad rail, rail geometry or
354    /// time cap.
355    pub fn new(
356        rocket: &Rocket,
357        configuration_id: &str,
358        environment: Environment,
359        rail: Rail,
360        settings: FlightSettings,
361    ) -> Result<Self, SimError> {
362        Self::from_laid_out(
363            rocket.lay_out()?,
364            configuration_id,
365            environment,
366            rail,
367            settings,
368        )
369    }
370
371    /// As [`Simulation::new`], on a design laid out already ([`hpr_design::LaidOut`]). The checks
372    /// and the assembly share its layout, which is most of the cost of building a simulation; a
373    /// Monte Carlo run lays out each flight from the nominal one's
374    /// ([`hpr_design::LaidOut::relay`]).
375    ///
376    /// # Errors
377    ///
378    /// As [`Simulation::new`].
379    pub fn from_laid_out(
380        laid_out: LaidOut,
381        configuration_id: &str,
382        environment: Environment,
383        rail: Rail,
384        settings: FlightSettings,
385    ) -> Result<Self, SimError> {
386        let findings = laid_out.check()?;
387        if has_errors(&findings) && !settings.accept_design_errors {
388            return Err(SimError::DesignChecks(findings));
389        }
390        settings.method.validate()?;
391        if !(settings.max_time_s.is_finite() && settings.max_time_s > 0.0) {
392            return Err(SimError::Domain {
393                what: "time cap",
394                value: settings.max_time_s,
395            });
396        }
397        rail.validate()?;
398        let (rocket, assembly) = laid_out.into_assembly(configuration_id)?;
399        let aero = AeroModel::new(&assembly.layout)?;
400        // No separation yet, so a motor lit by one has no time.
401        let ignition_s = assembly.ignition_times_s(|_| None);
402        let guides = Guides::of(&assembly);
403        let travel = guides.exit_travel_m(rail.length_m);
404        if travel <= 0.0 {
405            return Err(SimError::Domain {
406                what: "rail travel to exit (the rail is shorter than the aft end's lead on the last guide)",
407                value: travel,
408            });
409        }
410        Ok(Self {
411            vehicle: Vehicle::lit(assembly, aero, ignition_s)?,
412            environment,
413            rail,
414            guides,
415            settings,
416            user_events: Vec::new(),
417            devices: Vec::new(),
418            trigger_times_s: Vec::new(),
419            separations: Vec::new(),
420            separation_times_s: Vec::new(),
421            ejections: Vec::new(),
422            ejection_times_s: Vec::new(),
423            shifts: Vec::new(),
424            releases: Vec::new(),
425            release_parts: Releases::default(),
426            release_times_s: Vec::new(),
427            rocket,
428            configuration_id: configuration_id.to_owned(),
429            aero_overridden: false,
430            recovery_held: false,
431            tip_off: false,
432        })
433    }
434
435    /// Flies tip-off as a phase of its own: once the guide ahead of the aft-most one has left
436    /// the rail, the rocket slides on along the rail, free to pitch and yaw about its last guide
437    /// with roll held, until that guide leaves too ([`Phase::TipOff`]; the equations are
438    /// [`crate::rail`]'s, `docs/physics/flight.md`). It leaves the rail turning. Without this
439    /// the rocket is guided to its last guide and leaves with no angular velocity.
440    ///
441    /// A design with fewer than two guides at different stations has no such stretch, and flies
442    /// as it does without this. On a rail so short that only the last guide starts on it, the
443    /// rocket pivots from liftoff.
444    ///
445    /// The phase is held code to code against RocketPy's on thirteen designs
446    /// (`validation/reports/tip-off-model.md`); no flight checks it.
447    #[must_use]
448    pub fn with_tip_off(mut self) -> Self {
449        self.tip_off = true;
450        self
451    }
452
453    /// Whether the flight has a tip-off phase.
454    #[must_use]
455    pub fn tip_off(&self) -> bool {
456        self.tip_off
457    }
458
459    /// Flies another tool's `C_D0(M)` table instead of the drag buildup, and instead of any drag
460    /// model ([`Simulation::with_drag_model`]). A negative coefficient where the flight meets one
461    /// stops it with [`hpr_aero::AeroError::Domain`].
462    #[must_use]
463    pub fn with_drag_table(mut self, table: DragTable) -> Self {
464        self.vehicle.aero = self.vehicle.aero.clone().with_drag_table(table);
465        self.aero_overridden = true;
466        self
467    }
468
469    /// Flies a drag model of your own instead of the drag buildup, and instead of any drag table
470    /// ([`hpr_aero::custom`]). The model gives the zero-lift drag coefficient on the rocket's
471    /// reference area, not rescaled; the flight scales it for the angle of attack, and the
472    /// normal force, center of pressure, roll and damping stay HPR Sim's. A model's own errors reach
473    /// the caller as [`SimError::Aero`] around [`hpr_aero::AeroError::DragModel`]. Like a table,
474    /// the model is the whole stack's: a flight with a powered separation refuses it at the
475    /// separation, since the sustainer would fly on without it.
476    ///
477    /// # Examples
478    ///
479    /// Valetudo with a drag coefficient of 0.45 at every speed:
480    ///
481    /// ```
482    /// use hpr_aero::{AeroError, DragModel, DragQuery};
483    /// use hpr_core::geodesy::Geodetic;
484    /// use hpr_design::Rocket;
485    /// use hpr_sim::{Environment, EventKind, FlightSettings, Rail, Simulation};
486    ///
487    /// #[derive(Debug)]
488    /// struct Constant(f64);
489    ///
490    /// impl DragModel for Constant {
491    ///     fn zero_lift_drag(&self, _query: &DragQuery<'_>) -> Result<f64, AeroError> {
492    ///         Ok(self.0)
493    ///     }
494    /// }
495    ///
496    /// let rocket: Rocket = serde_json::from_str(include_str!(
497    ///     "../../../validation/designs/rocketpy-valetudo.json"
498    /// ))?;
499    /// let site = Geodetic::from_degrees(32.99, -106.97, 1400.0)?;
500    /// // The apogee's height with a constant drag coefficient `cd`.
501    /// let apogee_m = |cd: f64| -> Result<f64, Box<dyn std::error::Error>> {
502    ///     let flight = Simulation::new(
503    ///         &rocket,
504    ///         "example",
505    ///         Environment::standard(site)?,
506    ///         Rail::vertical(3.0),
507    ///         FlightSettings::default(),
508    ///     )?
509    ///     .with_drag_model(Constant(cd))
510    ///     .run(&mut ())?;
511    ///     let apogee = flight.event(EventKind::Apogee).ok_or("no apogee")?;
512    ///     Ok(apogee.sample.cg_enu_m.z)
513    /// };
514    /// assert!(apogee_m(0.9)? < apogee_m(0.45)?);
515    /// # Ok::<(), Box<dyn std::error::Error>>(())
516    /// ```
517    #[must_use]
518    pub fn with_drag_model(self, model: impl DragModel + 'static) -> Self {
519        self.with_shared_drag_model(Arc::new(model))
520    }
521
522    /// As [`Simulation::with_drag_model`], with a model already shared, as when one model flies
523    /// many simulations.
524    #[must_use]
525    pub fn with_shared_drag_model(mut self, model: Arc<dyn DragModel>) -> Self {
526        self.vehicle.aero = self.vehicle.aero.clone().with_shared_drag_model(model);
527        self.aero_overridden = true;
528        self
529    }
530
531    /// Multiplies the rocket's zero-lift drag coefficient by `scale`, whatever gives it: HPR Sim's
532    /// buildup, a drag table or a drag model ([`hpr_aero::AeroModel::with_drag_scale`]). Unlike
533    /// a table or a model it is not the whole stack's: a sustainer lit at a powered separation
534    /// keeps the same scale. Recovery devices' drag is their own and is not scaled. A Monte Carlo
535    /// run disperses drag this way (`hpr_analysis::montecarlo`).
536    ///
537    /// # Errors
538    ///
539    /// [`SimError::Aero`] for a scale that is negative or not finite.
540    pub fn with_drag_scale(mut self, scale: f64) -> Result<Self, SimError> {
541        self.vehicle.aero = self.vehicle.aero.clone().with_drag_scale(scale)?;
542        Ok(self)
543    }
544
545    /// Scales the structure's mass and inertia by `scale`, the motors' left as they are: a design
546    /// that weighs other than its parts say, for a fit to a log (`hpr_forensics::fit`). It leaves
547    /// the center of mass where it is. It is the whole stack's: a part that comes away in flight, a
548    /// stage or a recovery section, keeps its own mass as laid out, so it holds until the flight
549    /// first splits. Under a [`Simulation::with_mass_history`] it scales only the inertia, the
550    /// history giving the mass.
551    ///
552    /// # Errors
553    ///
554    /// [`SimError::Domain`] for a scale that isn't positive and finite.
555    pub fn with_structure_mass_scale(mut self, scale: f64) -> Result<Self, SimError> {
556        if !(scale.is_finite() && scale > 0.0) {
557            return Err(SimError::Domain {
558                what: "structure mass scale",
559                value: scale,
560            });
561        }
562        let structure = &mut self.vehicle.assembly.layout.structure;
563        structure.mass_kg *= scale;
564        structure.inertia_kg_m2 *= scale;
565        Ok(self)
566    }
567
568    /// Flies `history`'s thrust in place of the motors' ([`crate::histories`]): along the axis, at
569    /// the mean of the lit motors' nozzle exits, not corrected again for the air's pressure. The
570    /// motors still set the burnout, the base area a burning motor frees and the mass flow behind
571    /// jet damping. For sizing a difference from another tool, as a drag table is
572    /// ([ADR-349][adr-349]), not a model.
573    ///
574    /// # Errors
575    ///
576    /// [`SimError::History`] for a flight with no motor lit by a known time, for the thrust to
577    /// act at, and for one with a separation, ejections, mass shifts or releases, whose parts a
578    /// history doesn't give. The builders that add those refuse them once a history is given, so
579    /// they can come in any order.
580    ///
581    /// [adr-349]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0349-m2-3c6-in-four-the-public-nose-probe-first.md
582    pub fn with_thrust_history(mut self, history: ThrustHistory) -> Result<Self, SimError> {
583        Self::takes_history("thrust", self.parts(), self.moves_parts())?;
584        let Some(nozzle_m) = self.vehicle.lit_nozzle_mean_m() else {
585            return Err(SimError::History {
586                history: "thrust",
587                why: "the flight has no motor lit by a known time, at whose nozzle it would act",
588            });
589        };
590        self.vehicle.histories.nozzle_m = nozzle_m;
591        self.vehicle.histories.thrust = Some(history);
592        Ok(self)
593    }
594
595    /// Flies `history`'s mass and center of mass in place of the design's
596    /// ([`crate::histories`]): the inertia about the center of mass stays the design's, moved to
597    /// the nose tip with the history's mass and center. For sizing a difference from another
598    /// tool ([ADR-349][adr-349]), not a model. Beside a
599    /// [`Simulation::with_structure_mass_scale`], the scale then changes only the inertia.
600    ///
601    /// # Errors
602    ///
603    /// [`SimError::History`] for a flight with a separation, ejections, mass shifts or releases,
604    /// whose parts a history doesn't give. The builders that add those refuse them once a history
605    /// is given, so they can come in any order.
606    ///
607    /// [adr-349]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/decisions/0349-m2-3c6-in-four-the-public-nose-probe-first.md
608    pub fn with_mass_history(mut self, history: MassHistory) -> Result<Self, SimError> {
609        Self::takes_history("mass", self.parts(), self.moves_parts())?;
610        self.vehicle.histories.mass = Some(history);
611        Ok(self)
612    }
613
614    /// The thrust and mass histories flown in place of the flight's own, if given.
615    #[must_use]
616    pub fn histories(&self) -> (Option<&ThrustHistory>, Option<&MassHistory>) {
617        let histories = &self.vehicle.histories;
618        (histories.thrust.as_ref(), histories.mass.as_ref())
619    }
620
621    /// Whether the flight moves or releases a part.
622    fn moves_parts(&self) -> bool {
623        !self.shifts.is_empty() || !self.releases.is_empty()
624    }
625
626    /// The refusal of a `history` in a flight that splits (`parts`) or moves or releases a part
627    /// (`moves`).
628    fn takes_history(history: &'static str, parts: bool, moves: bool) -> Result<(), SimError> {
629        if parts {
630            return Err(SimError::History {
631                history,
632                why: "the flight splits, by a separation or an ejection, and a history is the \
633                      whole stack's, with no part's own",
634            });
635        }
636        if moves {
637            return Err(SimError::History {
638                history,
639                why: "the flight moves or releases a part, and a history is the whole stack's \
640                      mass, with no part's own",
641            });
642        }
643        Ok(())
644    }
645
646    /// The refusal of a split (`parts`) or a moved or released part (`moves`) once a history is
647    /// given.
648    fn check_no_history(&self, parts: bool, moves: bool) -> Result<(), SimError> {
649        match &self.vehicle.histories {
650            h if h.thrust.is_some() => Self::takes_history("thrust", parts, moves),
651            h if h.mass.is_some() => Self::takes_history("mass", parts, moves),
652            _ => Ok(()),
653        }
654    }
655
656    /// Keeps the aft base's whole drag while a motor burns, as OpenRocket 24.12 does, instead of
657    /// taking the burning motor's cross-section off it
658    /// ([`hpr_aero::AeroModel::with_full_base_drag_under_power`]). A sustainer lit at a powered
659    /// separation keeps the same rule. For sizing a difference from OpenRocket, not a better model
660    /// ([ADR-097][adr-097]).
661    ///
662    /// [adr-097]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-097-a-cause-in-the-drag-sized-by-hpr-flying-openrockets-drag-2026-09-28
663    #[must_use]
664    pub fn with_full_base_drag_under_power(mut self) -> Self {
665        self.vehicle.aero = self.vehicle.aero.clone().with_full_base_drag_under_power();
666        self
667    }
668
669    /// Flies another tool's normal force and center of pressure, against Mach number and angle of
670    /// attack, instead of HPR Sim's own ([`hpr_aero::NormalForceTable`], read from a RASAero II
671    /// export). The table sets the static normal force at the center of mass's airflow; the pitch
672    /// and yaw damping stay HPR Sim's, from the airspeed the rotation adds at each component, since a
673    /// table has none (the decision record on normal-force overrides, [ADR-032][adr-032]). The
674    /// flight still refuses Mach 5 and faster, where HPR Sim's components, which give that damping,
675    /// end.
676    ///
677    /// [adr-032]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-032-normal-force-overrides-from-rasaero-ii-the-static-force-replaced-hprs-damping-kept-2026-09-19
678    ///
679    /// # Errors
680    ///
681    /// [`SimError::Aero`] around [`hpr_aero::AeroError::Domain`] for a center of pressure in the
682    /// table outside the rocket ([`hpr_aero::AeroModel::with_normal_force_table`]).
683    ///
684    /// # Examples
685    ///
686    /// Valetudo from a 3 m rail on a small export with invented numbers: 9 per radian, and the
687    /// center of pressure 55 inches from the nose tip.
688    ///
689    /// ```
690    /// use hpr_aero::NormalForceTable;
691    /// use hpr_core::geodesy::Geodetic;
692    /// use hpr_design::Rocket;
693    /// use hpr_sim::{Environment, EventKind, FlightSettings, Rail, Simulation};
694    ///
695    /// let rocket: Rocket = serde_json::from_str(include_str!(
696    ///     "../../../validation/designs/rocketpy-valetudo.json"
697    /// ))?;
698    /// // The text of a RASAero II export; a program would read it from the file.
699    /// let export = "Mach,Alpha,CN,CN Potential,CP\n\
700    ///               0,0,0,0,55\n\
701    ///               1,0,0,0,55\n\
702    ///               0,2,0.314159,0.314159,55\n\
703    ///               1,2,0.314159,0.314159,55\n";
704    /// // On RASAero II's reference, the body's largest section, which hpr rescales to the
705    /// // rocket's reference area.
706    /// let table = NormalForceTable::from_rasaero_csv(export)?;
707    /// let site = Geodetic::from_degrees(32.99, -106.97, 1400.0)?;
708    /// let simulation = Simulation::new(
709    ///     &rocket,
710    ///     "example",
711    ///     Environment::standard(site)?,
712    ///     Rail::vertical(3.0),
713    ///     FlightSettings::default(),
714    /// )?
715    /// .with_normal_force_table(table)?;
716    /// let flight = simulation.run(&mut ())?;
717    /// assert!(flight.event(EventKind::Apogee).is_some());
718    /// # Ok::<(), Box<dyn std::error::Error>>(())
719    /// ```
720    pub fn with_normal_force_table(mut self, table: NormalForceTable) -> Result<Self, SimError> {
721        self.vehicle.aero = self.vehicle.aero.clone().with_normal_force_table(table)?;
722        self.aero_overridden = true;
723        Ok(self)
724    }
725
726    /// Adds a user event, checked during free flight and the descent.
727    #[must_use]
728    pub fn with_event(mut self, event: UserEvent) -> Self {
729        self.user_events.push(event);
730        self
731    }
732
733    /// Flies with these recovery devices, in the order given: a device's index in this list names
734    /// it in [`EventKind`] and in [`crate::recovery::Device::released_by`].
735    ///
736    /// # Errors
737    ///
738    /// [`SimError::Domain`] for a device whose drag area, lag, inflation, trigger or release index
739    /// is outside its domain, or whose trigger names a motor that isn't there or has no ejection
740    /// delay in seconds.
741    pub fn with_recovery(mut self, devices: Vec<Device>) -> Result<Self, SimError> {
742        self.trigger_times_s = recovery::plan(
743            &devices,
744            &self.vehicle.assembly.motors,
745            self.vehicle.ignition_s(),
746        )?;
747        if self.parts() {
748            // Already given a separation or ejections, so the bodies are known; otherwise the
749            // check waits for them, and for the flight, so that the builders work in any order.
750            check_bodies(&devices, self.body_count(), false)?;
751        }
752        self.devices = devices;
753        Ok(self)
754    }
755
756    /// The recovery devices.
757    #[must_use]
758    pub fn recovery(&self) -> &[Device] {
759        &self.devices
760    }
761
762    /// Flies with a separation: at its trigger the stack comes apart at the stage boundary, and
763    /// each body descends under its own devices ([`crate::recovery::Separation`]); or, when the
764    /// nose's body still has a motor to burn, it flies on as a sustainer and the aft body
765    /// descends. The same as [`Self::with_separations`] with this one alone.
766    ///
767    /// Call this after [`Self::with_recovery`]: it checks the devices against the bodies.
768    ///
769    /// # Errors
770    ///
771    /// [`SimError::Domain`] if the design has no stage aft of the split, if a body carries no
772    /// device (the descent has no airframe drag, so it would fall as if in a vacuum), if the
773    /// trigger is out of its domain, or if its time is known and an aft body's motor burns past
774    /// it (but for a lit motor a powered separation drops burning when it says so,
775    /// [`Separation::drops_burning`]), or if it is timed from a motor with no ignition known
776    /// before the flight, so that it could never fire; [`SimError::Parting`] if an ejection
777    /// already given parts at its stage boundary. The same checks run again if [`Self::with_recovery`] is called afterwards, so the
778    /// builders can be given in any order. A device on a body that nothing makes is refused when
779    /// the flight starts, since an ejection given later can make it.
780    pub fn with_separation(self, separation: Separation) -> Result<Self, SimError> {
781        self.with_separations(vec![separation])
782    }
783
784    /// Flies with several separations, in the order they fire, each at a stage boundary further
785    /// forward than the one before: a stack that drops its stages one at a time under power, as
786    /// a three-stage rocket does. Separation `k` makes body `k + 1`, the stages between its
787    /// boundary and the one before it (or the tail); body 0 keeps the nose. With more than one,
788    /// each must leave the nose's body a motor to burn, so that it flies on as a sustainer and the
789    /// part behind descends ([`crate::recovery::Separation`]); a lone separation may also end the
790    /// ascent, as [`Self::with_separation`] says. An empty list flies none.
791    ///
792    /// Call this after [`Self::with_recovery`]: it checks the devices against the bodies.
793    ///
794    /// # Errors
795    ///
796    /// As [`Self::with_separation`], for each separation; [`SimError::Domain`] as well if the
797    /// boundaries don't move forward in the order given, or if two of the times known before the
798    /// flight come in the other order; [`SimError::Unsupported`] for more than one separation in
799    /// a flight with ejections, whose pieces a sustainer's cut design doesn't track. In flight, a
800    /// separation that leaves nothing ahead of it to burn, in a flight with more than one, is an
801    /// error, as is one that fires before the separation ahead of it in the list.
802    pub fn with_separations(mut self, separations: Vec<Separation>) -> Result<Self, SimError> {
803        if !separations.is_empty() {
804            self.check_no_history(true, false)?;
805            self.check_no_moving_parts()?;
806        }
807        let stages = self.vehicle.assembly.layout.stages.len();
808        for (index, separation) in separations.iter().enumerate() {
809            if separation.stages_of(1, stages).is_none() {
810                return Err(SimError::Domain {
811                    what: "stage boundary of a separation (there is no stage aft of it)",
812                    value: separation.after_stage as f64,
813                });
814            }
815            if index > 0 && separation.after_stage >= separations[index - 1].after_stage {
816                return Err(SimError::Domain {
817                    what: "stage boundary of a separation (each must be forward of the one \
818                           before it, as the stack drops its stages from the tail)",
819                    value: separation.after_stage as f64,
820                });
821            }
822            let dropped = Separation::stages_of_body(&separations[..=index], index + 1, stages);
823            if !dropped.is_some_and(|(first, last)| {
824                hangs_together(&self.vehicle.assembly.layout.stages, first, last)
825            }) {
826                return Err(SimError::Domain {
827                    what: "stage boundary of a separation (its dropped stages must hang together: \
828                           a parallel stage hung on a kept stage can't go with one behind)",
829                    value: separation.after_stage as f64,
830                });
831            }
832        }
833        if separations.len() > 1 && !self.ejections.is_empty() {
834            return Err(Self::separations_and_ejections());
835        }
836        if !self.ejections.is_empty() {
837            // Its boundary may be a joint an ejection parts at too.
838            Pieces::new(
839                &self.rocket,
840                &self.vehicle.assembly,
841                &separations,
842                &self.ejections,
843            )?;
844        }
845        if !self.devices.is_empty() && !separations.is_empty() {
846            // With the devices already given they are checked now; given afterwards they are
847            // checked then, and either way again when the flight starts.
848            check_bodies(
849                &self.devices,
850                1 + separations.len() + self.ejections.len(),
851                false,
852            )?;
853        }
854        let mut times_s = Vec::with_capacity(separations.len());
855        for &separation in &separations {
856            if let Trigger::Altitude {
857                height_above_ground_m,
858            } = separation.trigger
859                && !(height_above_ground_m.is_finite() && height_above_ground_m > 0.0)
860            {
861                return Err(SimError::Domain {
862                    what: "height above the launch site at which the stack separates, m",
863                    value: height_above_ground_m,
864                });
865            }
866            let time_s = recovery::trigger_time_s(
867                separation.trigger,
868                &self.vehicle.assembly.motors,
869                self.vehicle.ignition_s(),
870            )?;
871            if let Some(time_s) = time_s {
872                // A body's mass is held constant through its descent. For a trigger whose time is
873                // known now, say so now rather than in the middle of a flight.
874                let powered = separation.powered_at(&self.vehicle.assembly, time_s);
875                self.check_aft_body_spent(separation, self.vehicle.ignition_s(), time_s, powered)?;
876            }
877            if let (None, Trigger::MotorDelay { motor } | Trigger::Burnout { motor, .. }) =
878                (time_s, separation.trigger)
879            {
880                // Timed from a motor with no ignition known before the flight: one lit by a
881                // separation, or one that never lights. It would never fire, and the stack would
882                // land whole. (A `Time` always has its time.)
883                return Err(SimError::Domain {
884                    what: "index of the motor a separation is timed from (it has no ignition time \
885                           before the separation, so the separation could never fire)",
886                    value: motor as f64,
887                });
888            }
889            if let (Some(time_s), Some(before_s)) = (
890                time_s,
891                times_s.iter().rev().find_map(|time: &Option<f64>| *time),
892            ) && time_s < before_s
893            {
894                return Err(SimError::Domain {
895                    what: "time of a separation, s (it comes before the separation ahead of it \
896                           in the list, which drops the stages behind it)",
897                    value: time_s,
898                });
899            }
900            times_s.push(time_s);
901        }
902        self.separation_times_s = times_s;
903        self.separations = separations;
904        Ok(self)
905    }
906
907    /// Flies with ejections: at each one's trigger a piece leaves the airframe, at the joint aft of
908    /// a body component or as a payload from inside it, and each body flies on to its own landing
909    /// under its own devices ([`crate::Ejection`]). With a separation as well, the separation's aft
910    /// body is body 1 and ejection `k` makes body `k + 2`; without one, ejection `k` makes body
911    /// `k + 1`. A flight with more than one separation takes none.
912    ///
913    /// Call this after [`Self::with_recovery`]: it checks the devices against the bodies. The
914    /// builders can be given in any order, and the checks run again when the flight starts.
915    ///
916    /// # Errors
917    ///
918    /// [`SimError::Parting`] for a parting the design can't make; [`SimError::Domain`] if a body
919    /// carries no device, if a trigger or impulse is out of its domain, if its time is known and a
920    /// motor burns past it, or if it is timed from a motor with no ignition known before the
921    /// flight; [`SimError::Unsupported`] with more than one separation. A device on a body that
922    /// nothing makes, and a pushed payload in the nose's piece, are
923    /// refused when the flight starts. In flight, an ejection that fires while a motor burns, or
924    /// ahead of a separation that would light one, is an error, and so are a powered separation in
925    /// a flight with ejections and a pushed payload whose section's forward joint hasn't parted.
926    pub fn with_ejections(mut self, ejections: Vec<Ejection>) -> Result<Self, SimError> {
927        if !ejections.is_empty() {
928            self.check_no_history(true, false)?;
929            self.check_no_moving_parts()?;
930            if self.separations.len() > 1 {
931                return Err(Self::separations_and_ejections());
932            }
933        }
934        Pieces::new(
935            &self.rocket,
936            &self.vehicle.assembly,
937            &self.separations,
938            &ejections,
939        )?;
940        let bodies = 1 + self.separations.len() + ejections.len();
941        if !self.devices.is_empty() && !ejections.is_empty() {
942            check_bodies(&self.devices, bodies, false)?;
943        }
944        let mut times_s = Vec::with_capacity(ejections.len());
945        for ejection in &ejections {
946            if let Trigger::Altitude {
947                height_above_ground_m,
948            } = ejection.trigger
949                && !(height_above_ground_m.is_finite() && height_above_ground_m > 0.0)
950            {
951                return Err(SimError::Domain {
952                    what: "height above the launch site at which a piece is ejected, m",
953                    value: height_above_ground_m,
954                });
955            }
956            if !(ejection.impulse_n_s.is_finite() && ejection.impulse_n_s >= 0.0) {
957                return Err(SimError::Domain {
958                    what: "impulse of an ejection, N·s (zero or more: it pushes the two sides \
959                           apart)",
960                    value: ejection.impulse_n_s,
961                });
962            }
963            let time_s = recovery::trigger_time_s(
964                ejection.trigger,
965                &self.vehicle.assembly.motors,
966                self.vehicle.ignition_s(),
967            )?;
968            if let Some(time_s) = time_s {
969                // Every body is a point mass of constant mass once the airframe parts.
970                self.check_spent(self.vehicle.ignition_s(), time_s)?;
971            }
972            if let (None, Trigger::MotorDelay { motor } | Trigger::Burnout { motor, .. }) =
973                (time_s, ejection.trigger)
974            {
975                return Err(SimError::Domain {
976                    what: "index of the motor an ejection is timed from (it has no ignition time \
977                           before the flight, so the ejection could never fire)",
978                    value: motor as f64,
979                });
980            }
981            times_s.push(time_s);
982        }
983        self.ejections = ejections;
984        self.ejection_times_s = times_s;
985        Ok(self)
986    }
987
988    /// The ejections, in the order given.
989    #[must_use]
990    pub fn ejections(&self) -> &[Ejection] {
991        &self.ejections
992    }
993
994    /// Flies with parts that move along the airframe ([`MassShift`]), in the order given: a
995    /// shift's index in this list names it in [`EventKind::Shift`]. A shift with a trigger known
996    /// before the flight (a time, or a motor's burnout or delay) starts then; the flight watches
997    /// for the apogee and for a height, descending, as it does for a recovery device's.
998    ///
999    /// # Errors
1000    ///
1001    /// [`SimError::Shift`] for a part that can't move ([`MassShift`] says which);
1002    /// [`SimError::Domain`] for a travel, duration or trigger outside its domain, or a trigger on
1003    /// a motor with no ignition known before the flight, which could never fire (a shift that
1004    /// starts before the rocket leaves the rail is refused by [`Self::run`] when it comes);
1005    /// [`SimError::Unsupported`] with a separation or ejections, whose pieces are fixed before the
1006    /// flight with every part where the design puts it.
1007    pub fn with_shifts(mut self, shifts: Vec<MassShift>) -> Result<Self, SimError> {
1008        if !shifts.is_empty() {
1009            self.check_no_history(false, true)?;
1010        }
1011        if !shifts.is_empty() && self.parts() {
1012            return Err(Self::shifts_and_partings());
1013        }
1014        if !shifts.is_empty() && !self.releases.is_empty() {
1015            return Err(Self::releases_and_shifts());
1016        }
1017        let mut starts_s = Vec::with_capacity(shifts.len());
1018        for shift in &shifts {
1019            starts_s.push(self.planned_s(shift.trigger, &SHIFT_WORDS)?);
1020        }
1021        self.vehicle.shifts =
1022            Shifts::new(&self.rocket, &self.vehicle.assembly, &shifts, &starts_s)?;
1023        self.shifts = shifts;
1024        Ok(self)
1025    }
1026
1027    /// The mass shifts, in the order given.
1028    #[must_use]
1029    pub fn shifts(&self) -> &[MassShift] {
1030        &self.shifts
1031    }
1032
1033    /// Flies with parts released in flight ([`MassRelease`]), in the order given: a release's
1034    /// index in this list names it in [`EventKind::MassRelease`] and in
1035    /// [`FlightResult::released`]. A release with a trigger known before the flight (a time, or a
1036    /// motor's burnout or delay) comes then; the flight watches for the apogee and for a height,
1037    /// descending, as it does for a recovery device's.
1038    ///
1039    /// # Errors
1040    ///
1041    /// [`SimError::MassRelease`] for a part that can't be released ([`MassRelease`] says which);
1042    /// [`SimError::Domain`] for a drag area or trigger outside its domain, or a trigger on a
1043    /// motor with no ignition known before the flight, which could never fire (a release that
1044    /// comes before the rocket leaves the rail is refused by [`Self::run`] when it comes);
1045    /// [`SimError::Unsupported`] with a separation, ejections or mass shifts, whose parts are
1046    /// fixed before the flight with every part where the design puts it.
1047    pub fn with_releases(mut self, releases: Vec<MassRelease>) -> Result<Self, SimError> {
1048        if !releases.is_empty() {
1049            self.check_no_history(false, true)?;
1050        }
1051        if !releases.is_empty() && (self.parts() || !self.shifts.is_empty()) {
1052            return Err(Self::releases_and_shifts());
1053        }
1054        let mut times_s = Vec::with_capacity(releases.len());
1055        for release in &releases {
1056            times_s.push(self.planned_s(release.trigger, &RELEASE_WORDS)?);
1057        }
1058        self.release_parts = Releases::new(&self.rocket, &self.vehicle.assembly, &releases)?;
1059        self.release_times_s = times_s;
1060        self.releases = releases;
1061        Ok(self)
1062    }
1063
1064    /// The releases, in the order given.
1065    #[must_use]
1066    pub fn releases(&self) -> &[MassRelease] {
1067        &self.releases
1068    }
1069
1070    /// The time a shift's or a release's `trigger` gives before the flight, if it gives one,
1071    /// refusing a trigger outside its domain in `words`. The checks are a device's; the errors
1072    /// that name a device are put in `words`.
1073    fn planned_s(&self, trigger: Trigger, words: &TriggerWords) -> Result<Option<f64>, SimError> {
1074        if let Trigger::Altitude {
1075            height_above_ground_m,
1076        } = trigger
1077            && !(height_above_ground_m.is_finite() && height_above_ground_m > 0.0)
1078        {
1079            return Err(SimError::Domain {
1080                what: words.height,
1081                value: height_above_ground_m,
1082            });
1083        }
1084        let time_s = recovery::trigger_time_s(
1085            trigger,
1086            &self.vehicle.assembly.motors,
1087            self.vehicle.ignition_s(),
1088        )
1089        .map_err(|error| match error {
1090            SimError::Domain { what, value } => SimError::Domain {
1091                what: match what {
1092                    "deployment time after launch, s" => words.time,
1093                    "index of the motor whose delay fires a device" => words.delay_motor,
1094                    "the motor firing a device has no ejection delay in seconds (it is plugged, \
1095                     or its delay is unset)" => words.no_delay,
1096                    other => other,
1097                },
1098                value,
1099            },
1100            other => other,
1101        })?;
1102        if let (None, Trigger::MotorDelay { motor } | Trigger::Burnout { motor, .. }) =
1103            (time_s, trigger)
1104        {
1105            return Err(SimError::Domain {
1106                what: words.never,
1107                value: motor as f64,
1108            });
1109        }
1110        Ok(time_s)
1111    }
1112
1113    /// The stack's mass properties at `t_s` as `flight` flew it: the design's, its motors burned
1114    /// to `t_s`, with each part that moves where it was then. `flight` must be a flight of this
1115    /// simulation; nothing checks that it is. A shift whose trigger is known before the flight (a
1116    /// time, or a motor's burnout or delay) starts then, whether or not `flight` got that far; one
1117    /// the flight watched for starts where `flight` records it ([`EventKind::Shift`]), and hasn't
1118    /// started if it doesn't. A part released at or before `t_s` is gone: its release came when
1119    /// its trigger's time is known before the flight, and otherwise where `flight` records it
1120    /// ([`EventKind::MassRelease`]). They are the whole stack's, in body axes about its center of
1121    /// mass, before any separation (and a flight with a separation has no shifts or releases).
1122    /// A mass history ([`Self::with_mass_history`]) gives the mass and the center of mass's
1123    /// axial place in their stead, the inertia staying the design's.
1124    #[must_use]
1125    pub fn mass_properties(&self, flight: &FlightResult, t_s: f64) -> hpr_design::MassProperties {
1126        let mut shifts = self.vehicle.shifts.clone();
1127        for index in 0..self.shifts.len() {
1128            if let Some(event) = flight.event(EventKind::Shift(index)) {
1129                shifts.start(index, event.sample.time_s);
1130            }
1131        }
1132        let mut gone: Vec<(f64, usize)> = (0..self.releases.len())
1133            .filter_map(|index| {
1134                self.release_times_s[index]
1135                    .or_else(|| {
1136                        flight
1137                            .event(EventKind::MassRelease(index))
1138                            .map(|event| event.sample.time_s)
1139                    })
1140                    .filter(|&time_s| time_s <= t_s)
1141                    .map(|time_s| (time_s, index))
1142            })
1143            .collect();
1144        // Taken out in the order the flight takes them, so the sums are the ones it flew.
1145        gone.sort_by(|a, b| a.0.total_cmp(&b.0));
1146        let assembly = &self.vehicle.assembly;
1147        let structure = gone
1148            .iter()
1149            .fold(assembly.layout.structure, |structure, &(_, index)| {
1150                structure.without_part(self.release_parts.part(index))
1151            });
1152        let whole = assembly.mass_properties_lit_on(structure, t_s, self.vehicle.ignition_s());
1153        let mut flown = shifts.apply(whole, t_s);
1154        if let Some(history) = &self.vehicle.histories.mass {
1155            flown.mass_kg = history.mass_kg(t_s);
1156            flown.cg_m.z = -history.cg_aft_of_nose_m(t_s);
1157        }
1158        flown
1159    }
1160
1161    /// The stack's apogee at `sample`: its event, and the trigger of each of the stack's own
1162    /// devices waiting for it, whose deployment becomes a stop time (below `cap`).
1163    fn reach_apogee(
1164        &self,
1165        sample: Sample,
1166        run: &mut Run,
1167        (stops, cap): (&mut Vec<f64>, f64),
1168        events: &mut Vec<FlightEvent>,
1169        observer: &mut dyn Observer,
1170    ) {
1171        let mut record = |kind: EventKind| {
1172            let event = FlightEvent { kind, sample };
1173            observer.event(&event);
1174            events.push(event);
1175        };
1176        record(EventKind::Apogee);
1177        let t = sample.time_s;
1178        for device in 0..self.devices.len() {
1179            // Only the stack's own: a body's device waits for its body, which finds its own
1180            // apogee.
1181            if !self.recovery_held
1182                && self.devices[device].trigger == Trigger::Apogee
1183                && run.pending(device)
1184                && self.acts_before_separation(device)
1185            {
1186                let deploy_s = run.trigger(&self.devices, device, t);
1187                insert_stop(stops, deploy_s, cap);
1188                record(EventKind::Trigger(device));
1189            }
1190        }
1191    }
1192
1193    /// Refuses a separation or ejections in a flight with mass shifts or releases.
1194    fn check_no_moving_parts(&self) -> Result<(), SimError> {
1195        if !self.releases.is_empty() {
1196            Err(Self::releases_and_shifts())
1197        } else if self.shifts.is_empty() {
1198            Ok(())
1199        } else {
1200            Err(Self::shifts_and_partings())
1201        }
1202    }
1203
1204    /// The refusal of mass releases with a separation, ejections or mass shifts.
1205    fn releases_and_shifts() -> SimError {
1206        SimError::Unsupported {
1207            what: "a mass release in a flight with a separation, ejections or mass shifts (their \
1208                   parts are fixed before the flight, where the design puts them)",
1209        }
1210    }
1211
1212    /// The refusal of several separations with ejections.
1213    fn separations_and_ejections() -> SimError {
1214        SimError::Unsupported {
1215            what: "ejections in a flight with more than one separation (a sustainer flies a cut \
1216                   design, not the pieces the ejections were given for)",
1217        }
1218    }
1219
1220    /// The refusal of mass shifts with a separation or ejections.
1221    fn shifts_and_partings() -> SimError {
1222        SimError::Unsupported {
1223            what: "a mass shift in a flight with a separation or ejections (its pieces are fixed \
1224                   before the flight, where the design puts them)",
1225        }
1226    }
1227
1228    /// The drag area of piece `piece` tumbling on its own, for a device on the body it leads:
1229    /// [`crate::recovery::DeviceDrag::tumbling`]'s model over the piece's own body components and
1230    /// fin sets. Piece 0 is the nose's, the separation makes piece 1, and each ejection the next
1231    /// ([`crate::Ejection`]), so piece `k` leads body `k`. Call it after [`Self::with_ejections`]
1232    /// and [`Self::with_separation`], which fix the pieces.
1233    ///
1234    /// It is the piece's own area only: a body that still carries another section, until that
1235    /// section's own parting, tumbles with its lead piece's area. The model was fitted to whole
1236    /// model rockets tumbling, so a lone nose cone is outside its fit: see the recovery page's
1237    /// [tumble section](https://hpr.fusionspace.co/physics/recovery.html#tumble).
1238    ///
1239    /// # Errors
1240    ///
1241    /// [`SimError::Domain`] for a piece the airframe doesn't part into, a payload (it has no
1242    /// body tube or fin of its own), and as [`crate::recovery::DeviceDrag::tumbling`].
1243    pub fn tumbling_piece(&self, piece: usize) -> Result<recovery::DeviceDrag, SimError> {
1244        Pieces::new(
1245            &self.rocket,
1246            &self.vehicle.assembly,
1247            &self.separations,
1248            &self.ejections,
1249        )?
1250        .tumbling(piece, &self.vehicle.assembly)
1251    }
1252
1253    /// Refuses an ejection at `t_s` while any motor lit at `ignition_s` burns: once the airframe
1254    /// parts, every body is a point mass of constant mass.
1255    fn check_spent(&self, ignition_s: &[Option<f64>], t_s: f64) -> Result<(), SimError> {
1256        for (placed, ignition) in self.vehicle.assembly.motors.iter().zip(ignition_s) {
1257            if let Some(ignition_s) = ignition {
1258                let burnout_s = ignition_s + placed.mounted.motor.burnout_time_s();
1259                if burnout_s > t_s {
1260                    return Err(SimError::Domain {
1261                        what: "time of an ejection (every motor must have burned out by then; \
1262                               this is when one of them does)",
1263                        value: burnout_s,
1264                    });
1265                }
1266            }
1267        }
1268        Ok(())
1269    }
1270
1271    /// Refuses a separation at `t_s` while a motor of its aft body, lit at `ignition_s`, burns or
1272    /// is still to light: that body descends as a point mass of constant mass. A `powered`
1273    /// separation, whose nose body has a motor burning or lighting then, may drop a motor still
1274    /// burning when it says so ([`Separation::drops_burning`], ADR-172): the body's descent leaves
1275    /// out the thrust that motor had left ([`BodyFlight::impulse_left_n_s`]). A motor still to
1276    /// light is refused either way.
1277    fn check_aft_body_spent(
1278        &self,
1279        separation: Separation,
1280        ignition_s: &[Option<f64>],
1281        t_s: f64,
1282        powered: bool,
1283    ) -> Result<(), SimError> {
1284        for (placed, ignition) in self.vehicle.assembly.motors.iter().zip(ignition_s) {
1285            if placed.stage <= separation.after_stage {
1286                continue;
1287            }
1288            if let Some(ignition_s) = ignition {
1289                let burnout_s = ignition_s + placed.mounted.motor.burnout_time_s();
1290                let dropped_burning = separation.drops_burning && powered && *ignition_s < t_s;
1291                if burnout_s > t_s && !dropped_burning {
1292                    return Err(SimError::Domain {
1293                        what: "time of a separation (the aft body's motors must have burned out \
1294                               by then; this is when one of them does)",
1295                        value: burnout_s,
1296                    });
1297                }
1298            }
1299        }
1300        Ok(())
1301    }
1302
1303    /// The first separation, if the flight has one.
1304    #[must_use]
1305    pub fn separation(&self) -> Option<Separation> {
1306        self.separations.first().copied()
1307    }
1308
1309    /// The separations, in the order they fire.
1310    #[must_use]
1311    pub fn separations(&self) -> &[Separation] {
1312        &self.separations
1313    }
1314
1315    /// The assembled design.
1316    #[must_use]
1317    pub fn assembly(&self) -> &hpr_design::Assembly {
1318        &self.vehicle.assembly
1319    }
1320
1321    /// The aerodynamic model.
1322    #[must_use]
1323    pub fn aero(&self) -> &AeroModel {
1324        &self.vehicle.aero
1325    }
1326
1327    /// The vehicles `result`, a flight of this simulation, flew in six degrees of freedom, in
1328    /// order: the launch stack, then the sustainer each powered separation handed the flight to,
1329    /// its models built again as the flight built them ([`FlownVehicle`]). A separation is one of
1330    /// `result`'s [`EventKind::Separation`] events, the `k`-th being [`Self::separations`]`[k]`;
1331    /// every one is powered but a last one that ended the flight ([`Termination::Separated`]),
1332    /// after which the bodies fall as points. Each motor's ignition time counts a motor lit by a
1333    /// separation from that separation's event.
1334    ///
1335    /// # Errors
1336    ///
1337    /// [`SimError::Domain`] if `result` has more separations than this simulation, and the errors
1338    /// of building a sustainer's models.
1339    pub fn flown_vehicles(&self, result: &FlightResult) -> Result<Vec<FlownVehicle<'_>>, SimError> {
1340        let separated_s: Vec<f64> = result
1341            .events
1342            .iter()
1343            .filter(|event| event.kind == EventKind::Separation)
1344            .map(|event| event.sample.time_s)
1345            .collect();
1346        if separated_s.len() > self.separations.len() {
1347            return Err(SimError::Domain {
1348                what: "count of separations in a flight's events (more than its simulation has: \
1349                       the flight is another simulation's)",
1350                value: separated_s.len() as f64,
1351            });
1352        }
1353        let powered = if result.termination == Termination::Separated {
1354            separated_s.len().saturating_sub(1)
1355        } else {
1356            separated_s.len()
1357        };
1358        let lit = self.vehicle.assembly.ignition_times_s(|stage| {
1359            self.separations
1360                .iter()
1361                .zip(&separated_s)
1362                .find(|(separation, _)| separation.after_stage == stage)
1363                .map(|(_, &at_s)| at_s)
1364        });
1365        let mut vehicles = vec![FlownVehicle {
1366            assembly: Cow::Borrowed(&self.vehicle.assembly),
1367            aero: Cow::Borrowed(&self.vehicle.aero),
1368            ignition_s: lit.clone(),
1369            from_s: None,
1370            until_s: separated_s[..powered].first().copied(),
1371        }];
1372        for (index, &at_s) in separated_s[..powered].iter().enumerate() {
1373            let model = Sustainer::of(
1374                &self.rocket,
1375                &self.configuration_id,
1376                &self.vehicle.assembly,
1377                self.separations[index],
1378            )?;
1379            vehicles.push(FlownVehicle {
1380                ignition_s: model.motors.iter().map(|&motor| lit[motor]).collect(),
1381                assembly: Cow::Owned(model.assembly),
1382                aero: Cow::Owned(model.aero),
1383                from_s: Some(at_s),
1384                until_s: separated_s[..powered].get(index + 1).copied(),
1385            });
1386        }
1387        Ok(vehicles)
1388    }
1389
1390    /// Takes `other`'s supersonic table for this flight's aerodynamic model where the two would
1391    /// build the same table ([`AeroModel::share_supersonic_table`]), so that it is built once for
1392    /// both: for many flights of one airframe, as a Monte Carlo run's. `other` is usually
1393    /// another simulation's [`Simulation::aero`]. The flight is unchanged, bit for bit. A
1394    /// sustainer's model, built at a powered separation, still builds its own table every
1395    /// flight. Returns `true` if the table is now shared.
1396    pub fn share_supersonic_table(&mut self, other: &AeroModel) -> bool {
1397        self.vehicle.aero.share_supersonic_table(other)
1398    }
1399
1400    /// The rail guides.
1401    #[must_use]
1402    pub fn guides(&self) -> Guides {
1403        self.guides
1404    }
1405
1406    /// The simulation on other guides than its design's: for a test of what the driver does
1407    /// with guide geometry no design can give it.
1408    #[cfg(test)]
1409    pub(crate) fn with_guides(mut self, guides: Guides) -> Self {
1410        self.guides = guides;
1411        self
1412    }
1413
1414    /// The rail.
1415    #[must_use]
1416    pub fn rail(&self) -> Rail {
1417        self.rail
1418    }
1419
1420    /// The environment.
1421    #[must_use]
1422    pub fn environment(&self) -> &Environment {
1423        &self.environment
1424    }
1425
1426    /// The settings.
1427    #[must_use]
1428    pub fn settings(&self) -> FlightSettings {
1429        self.settings
1430    }
1431
1432    /// The state at ignition: on the rail, aft end at its foot, at rest.
1433    #[must_use]
1434    pub fn initial_state(&self) -> State {
1435        let attitude = self.rail.attitude();
1436        State {
1437            position_enu_m: self.rail.direction_enu() * self.guides.aft_station_m,
1438            velocity_enu_m_s: DVec3::ZERO,
1439            attitude,
1440            body_rate_rad_s: DVec3::ZERO,
1441        }
1442    }
1443
1444    /// This simulation with its recovery charges held: the stack's devices never fire, so it
1445    /// coasts through its apogee as if every delay were long. A separation that lights a motor
1446    /// ahead of it still happens, and a separated body's devices act as they would; one that
1447    /// doesn't is held with the charges, and so is a mass shift or release fired by a motor's
1448    /// delay: the charge that would fire it doesn't. User events, which can't be copied, are left
1449    /// out.
1450    pub(crate) fn with_recovery_held(&self) -> Self {
1451        let on_charge = |trigger: Trigger| matches!(trigger, Trigger::MotorDelay { .. });
1452        let mut vehicle = self.vehicle.clone();
1453        for (index, shift) in self.shifts.iter().enumerate() {
1454            if on_charge(shift.trigger) {
1455                vehicle.shifts.hold(index);
1456            }
1457        }
1458        Self {
1459            vehicle,
1460            environment: self.environment.clone(),
1461            rail: self.rail,
1462            guides: self.guides,
1463            settings: self.settings,
1464            user_events: Vec::new(),
1465            devices: self.devices.clone(),
1466            // No charge fires, so none of their times is a stop.
1467            trigger_times_s: vec![None; self.devices.len()],
1468            separations: self.separations.clone(),
1469            separation_times_s: self.separation_times_s.clone(),
1470            ejections: self.ejections.clone(),
1471            ejection_times_s: self.ejection_times_s.clone(),
1472            shifts: self.shifts.clone(),
1473            releases: self.releases.clone(),
1474            release_parts: self.release_parts.clone(),
1475            release_times_s: self
1476                .releases
1477                .iter()
1478                .zip(&self.release_times_s)
1479                .map(|(release, time)| time.filter(|_| !on_charge(release.trigger)))
1480                .collect(),
1481            rocket: self.rocket.clone(),
1482            configuration_id: self.configuration_id.clone(),
1483            aero_overridden: self.aero_overridden,
1484            recovery_held: true,
1485            tip_off: self.tip_off,
1486        }
1487    }
1488
1489    /// Flies from ignition on the pad until the flight ends.
1490    ///
1491    /// # Errors
1492    ///
1493    /// [`SimError`] from the models or the integrator (other than the step limit, which is a
1494    /// [`Termination`]), or from the observer. The checks that wait for every builder run here
1495    /// too: a device on a body nothing makes, and a pushed payload in the nose's piece
1496    /// ([`Self::with_ejections`]). A mass shift that starts, or a mass release that comes, before
1497    /// the rocket leaves the rail is [`SimError::Domain`] ([`Self::with_shifts`],
1498    /// [`Self::with_releases`]), as is a release that steps the rest's center of mass below the
1499    /// ground while it climbs, and a separation or ejection whose time is known before the flight
1500    /// and comes before the rocket leaves the rail ([`Self::with_separations`],
1501    /// [`Self::with_ejections`]).
1502    pub fn run(&self, observer: &mut dyn Observer) -> Result<FlightResult, SimError> {
1503        self.fly(0.0, self.initial_state(), Phase::Pad, observer)
1504    }
1505
1506    /// Flies freely from `state` at `t0_s` seconds after launch, as after a rail exit or from a
1507    /// restart: the motors burn as their curves say at that time.
1508    ///
1509    /// # Errors
1510    ///
1511    /// As [`Self::run`].
1512    pub fn run_free(
1513        &self,
1514        t0_s: f64,
1515        state: State,
1516        observer: &mut dyn Observer,
1517    ) -> Result<FlightResult, SimError> {
1518        self.fly(t0_s, state, Phase::Free, observer)
1519    }
1520
1521    /// The sample at `(t, y)` in `phase` during the interval `window`, with `drag_area_m2` of
1522    /// recovery devices open.
1523    fn sample(
1524        &self,
1525        vehicle: &Vehicle,
1526        phase: Phase,
1527        window: (f64, f64),
1528        t: f64,
1529        y: &[f64; STATE_LEN],
1530        drag_area_m2: f64,
1531    ) -> Result<Sample, SimError> {
1532        let evaluation = self.evaluate(vehicle, phase, window, t, y, drag_area_m2)?;
1533        Ok(sample_of(phase, t, y, &evaluation))
1534    }
1535
1536    /// [`Self::evaluate`] under `conditions`, written over `out` (left as it was on an error).
1537    fn evaluate_into(
1538        &self,
1539        vehicle: &Vehicle,
1540        conditions: Conditions,
1541        t: f64,
1542        y: &[f64; STATE_LEN],
1543        out: &mut Evaluation,
1544    ) -> Result<(), SimError> {
1545        vehicle.evaluate_into(
1546            &self.environment,
1547            self.rail.friction_coefficient,
1548            conditions,
1549            t,
1550            y,
1551            out,
1552        )
1553    }
1554
1555    /// Where the rocket pivots during tip-off, and the rail's line: `None` without guides.
1556    fn pivot(&self) -> Option<Pivot> {
1557        self.guides.pivot_station_m.map(|station_m| Pivot {
1558            point_m: DVec3::new(0.0, 0.0, -station_m),
1559            rail_enu: self.rail.direction_enu(),
1560        })
1561    }
1562
1563    /// The travel along the rail at which tip-off begins, and its pivot, if the flight asks for
1564    /// tip-off and the design has a guide ahead of its last one that leaves the rail before it.
1565    fn tip_off_start(&self) -> Option<(f64, Pivot)> {
1566        if !self.tip_off {
1567            return None;
1568        }
1569        let travel_m = self.guides.tip_off_travel_m(self.rail.length_m)?;
1570        (travel_m < self.guides.exit_travel_m(self.rail.length_m))
1571            .then_some(travel_m)
1572            .zip(self.pivot())
1573    }
1574
1575    /// What an evaluation in `phase` needs.
1576    fn conditions(&self, phase: Phase, window: (f64, f64), drag_area_m2: f64) -> Conditions {
1577        Conditions {
1578            phase,
1579            window,
1580            drag_area_m2,
1581            pivot: if phase == Phase::TipOff {
1582                self.pivot()
1583            } else {
1584                None
1585            },
1586        }
1587    }
1588
1589    fn evaluate(
1590        &self,
1591        vehicle: &Vehicle,
1592        phase: Phase,
1593        window: (f64, f64),
1594        t: f64,
1595        y: &[f64; STATE_LEN],
1596        drag_area_m2: f64,
1597    ) -> Result<Evaluation, SimError> {
1598        vehicle.evaluate(
1599            &self.environment,
1600            self.rail.friction_coefficient,
1601            self.conditions(phase, window, drag_area_m2),
1602            t,
1603            y,
1604        )
1605    }
1606
1607    fn fly(
1608        &self,
1609        t0: f64,
1610        state: State,
1611        start_phase: Phase,
1612        observer: &mut dyn Observer,
1613    ) -> Result<FlightResult, SimError> {
1614        if !t0.is_finite() || t0 < 0.0 || t0 >= self.settings.max_time_s {
1615            return Err(SimError::Domain {
1616                what: "start time (must be from ignition and before the time cap)",
1617                value: t0,
1618            });
1619        }
1620        // The builders can be given in either order, and the last one wins, so the devices and
1621        // the bodies are checked against each other here as well.
1622        check_bodies(&self.devices, self.body_count(), true)?;
1623        if self
1624            .ejections
1625            .iter()
1626            .any(|ejection| ejection.impulse_n_s > 0.0)
1627        {
1628            Pieces::new(
1629                &self.rocket,
1630                &self.vehicle.assembly,
1631                &self.separations,
1632                &self.ejections,
1633            )?
1634            .check_pushed_payloads(&self.ejections)?;
1635        }
1636        // Which parts have left; one that left before the flight's start isn't recorded, and the
1637        // stack starts without it.
1638        let mut released: Vec<bool> = self
1639            .release_times_s
1640            .iter()
1641            .map(|time| time.is_some_and(|time_s| time_s < t0))
1642            .collect();
1643        // The stack once a part has left it.
1644        let mut lightened: Option<Vehicle> = released.contains(&true).then(|| {
1645            let mut stack = self.vehicle.clone();
1646            // In the order they left, as the flight would have taken them out.
1647            let mut gone: Vec<(f64, usize)> = (0..released.len())
1648                .filter_map(|index| Some((self.release_times_s[index]?, index)))
1649                .filter(|&(_, index)| released[index])
1650                .collect();
1651            gone.sort_by(|a, b| a.0.total_cmp(&b.0));
1652            for (_, index) in gone {
1653                lighten(&mut stack.assembly, self.release_parts.part(index));
1654            }
1655            stack
1656        });
1657        if start_phase == Phase::Free {
1658            let height = self
1659                .evaluate(
1660                    lightened.as_ref().unwrap_or(&self.vehicle),
1661                    Phase::Free,
1662                    (t0, t0),
1663                    t0,
1664                    &state.to_array(),
1665                    0.0,
1666                )?
1667                .height_above_ground_m;
1668            if height <= 0.0 {
1669                return Err(SimError::Domain {
1670                    what: "starting height of the center of mass above the ground",
1671                    value: height,
1672                });
1673            }
1674        }
1675        let mut integrator = Integrator::new(self.settings.method, t0, state.to_array())?
1676            .with_step_limit(self.settings.step_limit);
1677        let cap = self.settings.max_time_s;
1678        // What a powered separation changes: the trigger and ignition times that count from it,
1679        // the vehicle flying, and the booster's descent.
1680        let mut trigger_times_s = self.trigger_times_s.clone();
1681        let mut ignition_s = self.vehicle.ignition_s().to_vec();
1682        let mut ignited: Vec<bool> = ignition_s
1683            .iter()
1684            .map(|ignition| ignition.is_some_and(|time| time <= t0))
1685            .collect();
1686        let mut sustainer: Option<Vehicle> = None;
1687        // The stack once a shift the flight watched for has started, with its start set.
1688        let mut shifted: Option<Vehicle> = None;
1689        // Which shifts have started; one that started before the flight's start isn't recorded.
1690        let mut shift_started: Vec<bool> = (0..self.shifts.len())
1691            .map(|index| {
1692                self.vehicle
1693                    .shifts
1694                    .start_s(index)
1695                    .is_some_and(|start_s| start_s < t0)
1696            })
1697            .collect();
1698        let mut released_flights: Vec<ReleasedFlight> = Vec::new();
1699        // How many separations have fired under power, so the next to come is
1700        // `separations[staged]`, and when each did.
1701        let mut staged = 0;
1702        let mut staged_at_s: Vec<f64> = Vec::new();
1703        let mut booster: Vec<BodyFlight> = Vec::new();
1704        let mut stops = self.vehicle.thrust_knots_s();
1705        stops.push(cap);
1706        stops.extend(trigger_times_s.iter().flatten().copied());
1707        stops.extend(self.separation_times_s.iter().flatten().copied());
1708        stops.extend(self.ejection_times_s.iter().flatten().copied());
1709        stops.extend(self.vehicle.shifts.knots_s());
1710        stops.extend(self.release_times_s.iter().flatten().copied());
1711        stops.retain(|t| *t <= cap);
1712        stops.sort_by(f64::total_cmp);
1713        stops.dedup();
1714        let mut burnout_s = self.vehicle.burnout_s();
1715        let rail_origin = state.position_enu_m;
1716        let exit_travel_m = self.guides.exit_travel_m(self.rail.length_m);
1717        // Tip-off, if the flight has it: the travel where it begins, the pivot, and where the
1718        // pivot started.
1719        let tip_off = self.tip_off_start().map(|(travel_m, pivot)| TipOff {
1720            travel_m,
1721            pivot_m: pivot.point_m,
1722            pivot_origin: rail_origin + self.rail.attitude().mul_vec3(pivot.point_m),
1723            along: pivot.rail_enu,
1724        });
1725        // The phase of a rocket that moves on the rail: guided, or past where its last guide
1726        // holds it alone.
1727        let on_rail = |y: &[f64; STATE_LEN]| match &tip_off {
1728            Some(tip_off) if tip_off.pivot_travel_m(y) >= tip_off.travel_m => Phase::TipOff,
1729            _ => Phase::Rail,
1730        };
1731
1732        let mut phase = start_phase;
1733        // When a device froze the stack's attitude, which says nothing of its axis after that.
1734        let mut frozen_at_s = None;
1735        let mut lifted = start_phase != Phase::Pad;
1736        let mut burnout_recorded = t0 >= burnout_s;
1737        let mut separated = false;
1738        // Whether the stack came apart with nothing left to burn, by a separation or a charge,
1739        // while it still climbed: before its apogee, rising.
1740        let mut climbing = false;
1741        // The splits that have happened, in piece order: the separation, then the ejections.
1742        let mut opened = vec![false; self.body_count() - 1];
1743        // An unpowered separation or an ejection that a held flight skips.
1744        let mut separation_held = false;
1745        let mut events: Vec<FlightEvent> = Vec::new();
1746        let mut run = Run::new(self.devices.len());
1747        let record = |events: &mut Vec<FlightEvent>, observer: &mut dyn Observer, kind, sample| {
1748            let event = FlightEvent { kind, sample };
1749            observer.event(&event);
1750            events.push(event);
1751        };
1752
1753        let termination = loop {
1754            let t = integrator.time_s();
1755            let mut y = *integrator.state();
1756            if t >= cap {
1757                break Termination::TimeCap;
1758            }
1759
1760            // Mass shifts: one whose start is known begins at that stop time; the flight watches
1761            // for the apogee and the heights of the rest, as it does for a device's. A shift
1762            // makes no step in the state, so the integrator carries on.
1763            for (index, started) in shift_started.iter_mut().enumerate() {
1764                if *started {
1765                    continue;
1766                }
1767                let stack = shifted.as_ref().unwrap_or(&self.vehicle);
1768                let window = (t, next_stop(&stops, t, cap));
1769                let area = self.ascent_drag_area_m2(&run, t);
1770                let starts = match stack.shifts.start_s(index) {
1771                    Some(start_s) => t >= start_s,
1772                    None if matches!(phase, Phase::Free | Phase::Descent) => {
1773                        match self.shifts[index].trigger {
1774                            // At or past the apogee, as a device's apogee trigger is.
1775                            Trigger::Apogee => {
1776                                self.evaluate(stack, phase, window, t, &y, area)?
1777                                    .vertical_speed_m_s
1778                                    <= 0.0
1779                            }
1780                            Trigger::Altitude {
1781                                height_above_ground_m,
1782                            } => {
1783                                let e = self.evaluate(stack, phase, window, t, &y, area)?;
1784                                e.vertical_speed_m_s < 0.0
1785                                    && e.height_above_ground_m <= height_above_ground_m
1786                            }
1787                            Trigger::Time { .. }
1788                            | Trigger::MotorDelay { .. }
1789                            | Trigger::Burnout { .. } => false,
1790                        }
1791                    }
1792                    None => false,
1793                };
1794                if !starts {
1795                    continue;
1796                }
1797                if matches!(phase, Phase::Pad | Phase::Rail | Phase::TipOff) {
1798                    // The rail has no stop at its foot: a part thrown aft on the pad could push
1799                    // the rocket up the rail and leave it there.
1800                    return Err(SimError::Domain {
1801                        what: "start time of a mass shift, s (it must start once the rocket has \
1802                               left the rail)",
1803                        value: t,
1804                    });
1805                }
1806                if stack.shifts.start_s(index).is_none() {
1807                    shifted
1808                        .get_or_insert_with(|| self.vehicle.clone())
1809                        .shifts
1810                        .start(index, t);
1811                }
1812                let stack = shifted.as_ref().unwrap_or(&self.vehicle);
1813                for stop_s in stack.shifts.stops_s(index) {
1814                    if stop_s > t {
1815                        insert_stop(&mut stops, stop_s, cap);
1816                    }
1817                }
1818                *started = true;
1819                let window = (t, next_stop(&stops, t, cap));
1820                let sample = self.sample(stack, phase, window, t, &y, area)?;
1821                record(&mut events, observer, EventKind::Shift(index), sample);
1822            }
1823
1824            // Mass releases: one whose time is known comes at that stop time; the flight watches
1825            // for the apogee and the heights of the rest, as it does for a device's. The part
1826            // leaves with the velocity its center had in the airframe, the stack flies on from
1827            // the same state without it, and the part falls on its own. The passes repeat until
1828            // no part leaves, since a release can make the apogee another release waits for.
1829            let mut landed: Option<Sample> = None;
1830            loop {
1831                // The stack as the pass begins, which the apogee and height triggers are judged
1832                // on, so that the parts listed before one don't decide whether it leaves. Past
1833                // the recorded apogee the stack is coming down, whatever a release did to its
1834                // center's speed; with none (a flight started falling) its own speed says.
1835                let apogee_recorded = events.iter().any(|event| event.kind == EventKind::Apogee);
1836                let start = if matches!(phase, Phase::Free | Phase::Descent)
1837                    && released.iter().zip(&self.releases).any(|(gone, release)| {
1838                        !gone
1839                            && matches!(release.trigger, Trigger::Apogee | Trigger::Altitude { .. })
1840                    }) {
1841                    let stack = lightened.as_ref().unwrap_or(&self.vehicle);
1842                    let window = (t, next_stop(&stops, t, cap));
1843                    let area = self.ascent_drag_area_m2(&run, t);
1844                    Some(self.evaluate(stack, phase, window, t, &y, area)?)
1845                } else {
1846                    None
1847                };
1848                let at_apogee = start
1849                    .as_ref()
1850                    .is_some_and(|e| apogee_recorded || e.vertical_speed_m_s <= 0.0);
1851                let descending = start
1852                    .as_ref()
1853                    .is_some_and(|e| apogee_recorded || e.vertical_speed_m_s < 0.0);
1854                // The rocket's vertical speed just before the first part left in this pass.
1855                let mut rising: Option<f64> = None;
1856                for (index, gone) in released.iter_mut().enumerate() {
1857                    if *gone {
1858                        continue;
1859                    }
1860                    let stack = lightened.as_ref().unwrap_or(&self.vehicle);
1861                    let window = (t, next_stop(&stops, t, cap));
1862                    let area = self.ascent_drag_area_m2(&run, t);
1863                    let leaves = match self.release_times_s[index] {
1864                        Some(time_s) => t >= time_s,
1865                        None if matches!(phase, Phase::Free | Phase::Descent) => {
1866                            match self.releases[index].trigger {
1867                                // At the flight's apogee, as a device's apogee trigger is, or
1868                                // past one it didn't see (a flight started falling).
1869                                Trigger::Apogee => at_apogee,
1870                                Trigger::Altitude {
1871                                    height_above_ground_m,
1872                                } => {
1873                                    descending
1874                                        && start.as_ref().is_some_and(|e| {
1875                                            e.height_above_ground_m <= height_above_ground_m
1876                                        })
1877                                }
1878                                Trigger::Time { .. }
1879                                | Trigger::MotorDelay { .. }
1880                                | Trigger::Burnout { .. } => false,
1881                            }
1882                        }
1883                        None => false,
1884                    };
1885                    if !leaves {
1886                        continue;
1887                    }
1888                    if matches!(phase, Phase::Pad | Phase::Rail | Phase::TipOff) {
1889                        // On the pad or the rail the part has nowhere to go.
1890                        return Err(SimError::Domain {
1891                            what: "time of a mass release, s (it must come once the rocket has left \
1892                                   the rail)",
1893                            value: t,
1894                        });
1895                    }
1896                    let sample = self.sample(stack, phase, window, t, &y, area)?;
1897                    record(&mut events, observer, EventKind::MassRelease(index), sample);
1898                    rising.get_or_insert(sample.vertical_speed_m_s);
1899                    // Its center, and the velocity that point had: `v_O + ω × c` in `L` (the body
1900                    // rates are zero in the descent, whose attitude is frozen).
1901                    let part = self.release_parts.part(index);
1902                    let state = State::from_array(&y);
1903                    let omega = if phase == Phase::Free {
1904                        state.body_rate_rad_s
1905                    } else {
1906                        DVec3::ZERO
1907                    };
1908                    let velocity_enu_m_s = state.velocity_enu_m_s
1909                        + state.unit_attitude().mul_vec3(omega.cross(part.cg_m));
1910                    released_flights.push(self.fly_released(
1911                        index,
1912                        t,
1913                        (state.point_enu_m(part.cg_m), velocity_enu_m_s),
1914                        part.mass_kg,
1915                    )?);
1916                    lighten(
1917                        &mut lightened
1918                            .get_or_insert_with(|| self.vehicle.clone())
1919                            .assembly,
1920                        part,
1921                    );
1922                    *gone = true;
1923                }
1924                let (Some(rising), Some(stack)) = (rising, lightened.as_ref()) else {
1925                    break;
1926                };
1927                // The mass steps here, so the integrator starts afresh from the same state: the
1928                // nose tip's, which the stack keeps.
1929                integrator.reset(t, y)?;
1930                let window = (t, next_stop(&stops, t, cap));
1931                let area = self.ascent_drag_area_m2(&run, t);
1932                let sample = self.sample(stack, phase, window, t, &y, area)?;
1933                if sample.height_above_ground_m <= 0.0 {
1934                    if sample.vertical_speed_m_s > 0.0 {
1935                        // Below the ground and climbing: not a landing.
1936                        return Err(SimError::Domain {
1937                            what: "height of the rest's center of mass above the ground after a \
1938                                   mass release, m (it steps below the ground while climbing)",
1939                            value: sample.height_above_ground_m,
1940                        });
1941                    }
1942                    // The rest's center stepped to the ground or below it, which the ground
1943                    // event, a crossing from above, would never see: it has landed.
1944                    landed = Some(sample);
1945                    break;
1946                }
1947                // The rest's center moves at `v_O + ω × cg'`, not as the rocket's did: a part let
1948                // go just before the apogee can leave it already falling, and the apogee the
1949                // flight watches for, its vertical speed falling through zero, is then here.
1950                if rising > 0.0
1951                    && sample.vertical_speed_m_s <= 0.0
1952                    && events.iter().all(|event| event.kind != EventKind::Apogee)
1953                {
1954                    self.reach_apogee(sample, &mut run, (&mut stops, cap), &mut events, observer);
1955                }
1956            }
1957            if let Some(sample) = landed {
1958                record(&mut events, observer, EventKind::GroundHit, sample);
1959                break Termination::GroundHit;
1960            }
1961            let vehicle = sustainer
1962                .as_ref()
1963                .or(shifted.as_ref())
1964                .or(lightened.as_ref())
1965                .unwrap_or(&self.vehicle);
1966
1967            // Motors lit after launch: their ignitions are stop times, so each is found here at
1968            // its own time.
1969            for index in 0..ignition_s.len() {
1970                if !ignited[index] && ignition_s[index].is_some_and(|time| t >= time) {
1971                    ignited[index] = true;
1972                    let window = (t, next_stop(&stops, t, cap));
1973                    let area = self.ascent_drag_area_m2(&run, t);
1974                    let sample = self.sample(vehicle, phase, window, t, &y, area)?;
1975                    record(&mut events, observer, EventKind::Ignition(index), sample);
1976                }
1977            }
1978
1979            // Recovery: fire the charges whose time or height has come, then deploy the devices
1980            // whose lag has run out. A lag of zero deploys in the same pass, and a deployment can
1981            // release another device, so this repeats until nothing more happens. Only the
1982            // devices of body 0 act before a separation: a device meant for another body has a
1983            // drag area computed for that body (a booster's tumbling area, say), which is not a
1984            // model of the whole stack.
1985            while !self.recovery_held
1986                && !self.devices.is_empty()
1987                && matches!(phase, Phase::Free | Phase::Descent)
1988            {
1989                let mut again = false;
1990                let window = (t, next_stop(&stops, t, cap));
1991                let area = self.ascent_drag_area_m2(&run, t);
1992                // One evaluation serves every device in the pass: they all ask about the same
1993                // `(t, y)`. It is only made when a pending device needs the flight's state, and
1994                // it is not one of the integrator's, so `Stats` doesn't count it.
1995                let mut here: Option<Evaluation> = None;
1996                for index in 0..self.devices.len() {
1997                    if !run.pending(index) || !self.acts_before_separation(index) {
1998                        continue;
1999                    }
2000                    // `plan` gives `trigger_times_s` one entry per device, in order.
2001                    let fires = match self.devices[index].trigger {
2002                        Trigger::Time { .. }
2003                        | Trigger::MotorDelay { .. }
2004                        | Trigger::Burnout { .. } => trigger_times_s
2005                            .get(index)
2006                            .copied()
2007                            .flatten()
2008                            .is_some_and(|time| t >= time),
2009                        // At or past the apogee, which is RocketPy's own trigger (`y[5] < 0`)
2010                        // widened to include a flight that starts exactly at its apogee: with
2011                        // `< 0` such a flight has no crossing for the apogee event to find
2012                        // either, and would wait for the next interval. The apogee event fires
2013                        // this too, and whichever comes first wins.
2014                        Trigger::Apogee => {
2015                            let e = cached(&mut here, || {
2016                                self.evaluate(vehicle, phase, window, t, &y, area)
2017                            })?;
2018                            e.vertical_speed_m_s <= 0.0
2019                        }
2020                        Trigger::Altitude {
2021                            height_above_ground_m,
2022                        } => {
2023                            // An altimeter's main setting: descending, at or below the height.
2024                            // A rocket already below it at apogee fires there, as the event on
2025                            // the height never crosses it (RocketPy's numeric trigger). Past the
2026                            // recorded apogee the rocket is descending, even while a part let go
2027                            // there has the rest's center rising for a moment (beyond RocketPy,
2028                            // which has no releases; without one the rule is the same).
2029                            let e = cached(&mut here, || {
2030                                self.evaluate(vehicle, phase, window, t, &y, area)
2031                            })?;
2032                            (e.vertical_speed_m_s < 0.0
2033                                || events.iter().any(|event| event.kind == EventKind::Apogee))
2034                                && e.height_above_ground_m <= height_above_ground_m
2035                        }
2036                    };
2037                    if fires {
2038                        let deploy_s = run.trigger(&self.devices, index, t);
2039                        insert_stop(&mut stops, deploy_s, cap);
2040                        let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2041                        record(&mut events, observer, EventKind::Trigger(index), sample);
2042                        again = true;
2043                    }
2044                }
2045                for index in 0..self.devices.len() {
2046                    if !run.waiting(index)
2047                        || run.deploy_s(index) > t
2048                        || !self.acts_before_separation(index)
2049                    {
2050                        continue;
2051                    }
2052                    if run.released_s(index).is_some_and(|released| released <= t) {
2053                        // Cut away before its own charge fired: the canopy never flies.
2054                        run.abandon(index);
2055                        again = true;
2056                        continue;
2057                    }
2058                    let evaluation = cached(&mut here, || {
2059                        self.evaluate(vehicle, phase, window, t, &y, area)
2060                    })?;
2061                    let full_s = run.deploy(&self.devices, index, t, evaluation.airspeed_m_s);
2062                    insert_stop(&mut stops, full_s, cap);
2063                    if phase != Phase::Descent {
2064                        // The descent is a point mass: the attitude freezes where it deployed and
2065                        // the body rates go, snubbed by the lines and the canopy. The state's
2066                        // velocity is the nose tip's, so it is shifted to keep the center of mass
2067                        // moving as it was: dropping `ω` while holding `v_O` would change the
2068                        // center of mass's momentum with nothing to do it (found in review).
2069                        // Written this way it reads as what it is; the `ṙ_cg` terms cancel, so
2070                        // the net shift is `q(ω × r_cg)`.
2071                        phase = Phase::Descent;
2072                        frozen_at_s = Some(t);
2073                        let mut frozen = State::from_array(&y);
2074                        frozen.velocity_enu_m_s = evaluation.cg_velocity_enu_m_s
2075                            - frozen.unit_attitude().mul_vec3(evaluation.mass.cg_rate_m_s);
2076                        frozen.body_rate_rad_s = DVec3::ZERO;
2077                        y = frozen.to_array();
2078                        integrator.reset(t, y)?;
2079                        here = None;
2080                    }
2081                    let area = self.ascent_drag_area_m2(&run, t);
2082                    let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2083                    record(&mut events, observer, EventKind::Deployment(index), sample);
2084                    again = true;
2085                }
2086                // A release happens when the device that releases it is fully open, which is a
2087                // stop time, so the drag area never dips between a drogue and a filling main.
2088                for index in 0..self.devices.len() {
2089                    if run.release_due(index, t) && self.acts_before_separation(index) {
2090                        run.release(index);
2091                        let area = self.ascent_drag_area_m2(&run, t);
2092                        let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2093                        record(&mut events, observer, EventKind::Release(index), sample);
2094                        again = true;
2095                    }
2096                }
2097                if !again {
2098                    break;
2099                }
2100            }
2101
2102            // A separation or an ejection known to come while the rocket is still on the pad or
2103            // the rail: the stack can't come apart there, and firing it at the rail exit instead
2104            // would be a different flight (#231). Refused, as an early shift or release is.
2105            if self.parts()
2106                && !separation_held
2107                && matches!(phase, Phase::Pad | Phase::Rail | Phase::TipOff)
2108            {
2109                let separations = self.separation_times_s.iter().skip(staged).map(|time_s| {
2110                    (
2111                        time_s,
2112                        "time of a separation, s (it must come once the rocket has left the rail)",
2113                    )
2114                });
2115                let ejections = self.ejection_times_s.iter().map(|time_s| {
2116                    (
2117                        time_s,
2118                        "time of an ejection, s (it must come once the rocket has left the rail)",
2119                    )
2120                });
2121                for (time_s, what) in separations.chain(ejections) {
2122                    if time_s.is_some_and(|time_s| t >= time_s) {
2123                        return Err(SimError::Domain { what, value: t });
2124                    }
2125                }
2126            }
2127
2128            // The separations and the ejections: the same triggers as a device's. When the next
2129            // separation fires with the nose's body still to burn, that body flies on as the
2130            // sustainer and the part behind it descends; otherwise the ascent ends and every body
2131            // flies on as a point mass.
2132            if self.parts()
2133                && (staged < self.separations.len() || (staged == 0 && !self.ejections.is_empty()))
2134                && !separation_held
2135                && matches!(phase, Phase::Free | Phase::Descent)
2136            {
2137                let window = (t, next_stop(&stops, t, cap));
2138                let area = self.ascent_drag_area_m2(&run, t);
2139                let mut here: Option<Evaluation> = None;
2140                let mut fires = |trigger: Trigger, time_s: Option<f64>| -> Result<bool, SimError> {
2141                    Ok(match trigger {
2142                        Trigger::Time { .. }
2143                        | Trigger::MotorDelay { .. }
2144                        | Trigger::Burnout { .. } => time_s.is_some_and(|time| t >= time),
2145                        // At or past the apogee, as a device's apogee trigger is.
2146                        Trigger::Apogee => {
2147                            cached(&mut here, || {
2148                                self.evaluate(vehicle, phase, window, t, &y, area)
2149                            })?
2150                            .vertical_speed_m_s
2151                                <= 0.0
2152                        }
2153                        Trigger::Altitude {
2154                            height_above_ground_m,
2155                        } => {
2156                            let e = cached(&mut here, || {
2157                                self.evaluate(vehicle, phase, window, t, &y, area)
2158                            })?;
2159                            e.vertical_speed_m_s < 0.0
2160                                && e.height_above_ground_m <= height_above_ground_m
2161                        }
2162                    })
2163                };
2164                let pending = self.separations.get(staged).copied();
2165                let separates = match pending {
2166                    Some(separation) => fires(separation.trigger, self.separation_times_s[staged])?,
2167                    None => false,
2168                };
2169                if !separates {
2170                    // One further down the list can't come first: the stages it drops are still
2171                    // held by the ones behind them.
2172                    for later in staged + 1..self.separations.len() {
2173                        if fires(
2174                            self.separations[later].trigger,
2175                            self.separation_times_s[later],
2176                        )? {
2177                            return Err(SimError::Domain {
2178                                what: "time of a separation, s (it fires before the separation \
2179                                       ahead of it in the list, which drops the stages behind it)",
2180                                value: t,
2181                            });
2182                        }
2183                    }
2184                }
2185                let mut ejected = Vec::new();
2186                for (index, ejection) in self.ejections.iter().enumerate() {
2187                    if fires(ejection.trigger, self.ejection_times_s[index])? {
2188                        ejected.push(index);
2189                    }
2190                }
2191                if separates || !ejected.is_empty() {
2192                    // The stack's motors as the separation lights them: one lit by it counts from
2193                    // now. A body's mass is held constant through its descent, so the booster's
2194                    // motors must be spent.
2195                    let mut lit = ignition_s.clone();
2196                    // The separation, when it fires with a motor ahead of it still to burn.
2197                    let mut powered: Option<Separation> = None;
2198                    if let Some(separation) = pending.filter(|_| separates) {
2199                        // A motor lit by an earlier separation counts from that one.
2200                        lit = self.vehicle.assembly.ignition_times_s(|stage| {
2201                            (stage == separation.after_stage).then_some(t).or_else(|| {
2202                                self.separations
2203                                    .iter()
2204                                    .zip(&staged_at_s)
2205                                    .find(|(earlier, _)| earlier.after_stage == stage)
2206                                    .map(|(_, &at_s)| at_s)
2207                            })
2208                        });
2209                        let burning = self.vehicle.assembly.motors.iter().zip(&lit).any(
2210                            |(placed, ignition)| {
2211                                placed.stage <= separation.after_stage
2212                                    && ignition.is_some_and(|ignition| {
2213                                        ignition + placed.mounted.motor.burnout_time_s() > t
2214                                    })
2215                            },
2216                        );
2217                        powered = burning.then_some(separation);
2218                        // Checked before a held flight holds it, so that the delay's flight
2219                        // refuses what the flown one would.
2220                        self.check_aft_body_spent(separation, &lit, t, burning)?;
2221                        if !burning && self.separations.len() > 1 {
2222                            // Once every body is a point mass there is no sustainer left to part
2223                            // again, and the bodies a sustainer already dropped have flown.
2224                            return Err(SimError::Domain {
2225                                what: "time of a separation leaving nothing ahead to burn, \
2226                                       with more than one separation in the flight (each must \
2227                                       hand the flight to a sustainer)",
2228                                value: t,
2229                            });
2230                        }
2231                    }
2232                    if powered.is_some() && !self.ejections.is_empty() {
2233                        // The sustainer flies on a cut design whose components aren't the
2234                        // pieces the ejections were given for.
2235                        return Err(SimError::Domain {
2236                            what: "time of a powered separation in a flight with ejections (the \
2237                                   pieces of a sustainer aren't tracked)",
2238                            value: t,
2239                        });
2240                    }
2241                    if !ejected.is_empty() {
2242                        // Every body is a point mass of constant mass once the airframe parts.
2243                        self.check_spent(&lit, t)?;
2244                        if let Some(separation) = pending.filter(|_| !separates)
2245                            && self
2246                                .vehicle
2247                                .assembly
2248                                .ignition_times_s(|stage| {
2249                                    (stage == separation.after_stage).then_some(t)
2250                                })
2251                                .iter()
2252                                .zip(&lit)
2253                                .any(|(would, is)| would.is_some() && is.is_none())
2254                        {
2255                            return Err(SimError::Domain {
2256                                what: "time of an ejection before the separation that lights a \
2257                                       motor (the pieces would never light it)",
2258                                value: t,
2259                            });
2260                        }
2261                    }
2262                    if self.recovery_held && powered.is_none() {
2263                        // With nothing ahead of it left to burn it is part of the recovery, so it
2264                        // is held with the charges.
2265                        separation_held = true;
2266                        continue;
2267                    }
2268                    let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2269                    if separates {
2270                        record(&mut events, observer, EventKind::Separation, sample);
2271                    }
2272                    for &index in &ejected {
2273                        record(&mut events, observer, EventKind::Ejection(index), sample);
2274                    }
2275                    let Some(separation) = powered else {
2276                        if separates {
2277                            opened[staged] = true;
2278                        }
2279                        climbing = events.iter().all(|event| event.kind != EventKind::Apogee)
2280                            && State::from_array(&y).velocity_enu_m_s.z > 0.0;
2281                        let first = self.separations.len();
2282                        for &index in &ejected {
2283                            opened[first + index] = true;
2284                        }
2285                        ignition_s = lit;
2286                        separated = true;
2287                        break Termination::Separated;
2288                    };
2289                    if phase == Phase::Descent {
2290                        // The descent is a point mass under canopies; a sustainer under thrust
2291                        // is not something it can fly.
2292                        return Err(SimError::Domain {
2293                            what: "time of a separation whose nose body still has a motor to \
2294                                   burn (it comes after a recovery device opened on that body)",
2295                            value: t,
2296                        });
2297                    }
2298                    if self.aero_overridden {
2299                        return Err(SimError::Domain {
2300                            what: "time of a powered separation (a drag table or drag model, \
2301                                   or a normal-force table, is the whole stack's, and the \
2302                                   sustainer has none)",
2303                            value: t,
2304                        });
2305                    }
2306                    // Built only now, so an unpowered separation never needs the cut design.
2307                    let model = Sustainer::of(
2308                        &self.rocket,
2309                        &self.configuration_id,
2310                        &self.vehicle.assembly,
2311                        separation,
2312                    )?;
2313                    let lit_here = model.motors.iter().map(|&index| lit[index]).collect();
2314                    let aero = if self.vehicle.aero.full_base_drag_under_power() {
2315                        model.aero.with_full_base_drag_under_power()
2316                    } else {
2317                        model.aero
2318                    }
2319                    .with_drag_scale(self.vehicle.aero.drag_scale())?;
2320                    let flown = Vehicle::lit(model.assembly, aero, lit_here)?;
2321                    // The part it drops is the next body, flown alone: the nose's flies on, and those
2322                    // dropped before have flown.
2323                    opened[staged] = true;
2324                    booster.extend(self.fly_bodies(
2325                        t,
2326                        &State::from_array(&y),
2327                        &mut run,
2328                        &lit,
2329                        (
2330                            &opened,
2331                            Some(staged + 1),
2332                            frozen_at_s.is_some_and(|frozen_s| frozen_s < t),
2333                        ),
2334                        observer,
2335                    )?);
2336                    // The booster's descent has no airframe drag, and a powered separation comes
2337                    // near the top speed, so a coast to its device would climb as if in a vacuum
2338                    // (twice the sustainer's apogee in review). Its device must open at once.
2339                    let open_at_split = self.devices.iter().enumerate().any(|(index, device)| {
2340                        device.body == staged + 1
2341                            && run.devices[index]
2342                                .deployed_s
2343                                .is_some_and(|deployed_s| deployed_s <= t)
2344                    });
2345                    if !open_at_split {
2346                        return Err(SimError::Domain {
2347                            what: "time of a powered separation (the booster has no airframe \
2348                                   drag, so a device on it must open as it starts flying: \
2349                                   `Time { time_s: 0.0 }`, no lag)",
2350                            value: t,
2351                        });
2352                    }
2353                    trigger_times_s =
2354                        recovery::plan(&self.devices, &self.vehicle.assembly.motors, &lit)?;
2355                    for time in trigger_times_s
2356                        .iter()
2357                        .flatten()
2358                        .copied()
2359                        .chain(flown.thrust_knots_s())
2360                    {
2361                        if time > t {
2362                            insert_stop(&mut stops, time, cap);
2363                        }
2364                    }
2365                    if flown.burnout_s() > t {
2366                        burnout_recorded = false;
2367                    }
2368                    burnout_s = flown.burnout_s();
2369                    ignition_s = lit;
2370                    staged += 1;
2371                    staged_at_s.push(t);
2372                    sustainer = Some(flown);
2373                    // The mass steps here, so the integrator starts afresh from the same state:
2374                    // the nose tip's, which the sustainer keeps.
2375                    integrator.reset(t, y)?;
2376                    continue;
2377                }
2378            }
2379
2380            let next = next_stop(&stops, t, cap);
2381            let window = (t, next);
2382            if phase == Phase::Pad {
2383                if self
2384                    .evaluate(vehicle, Phase::Pad, window, t, &y, 0.0)?
2385                    .rail_force_n
2386                    > 0.0
2387                {
2388                    phase = on_rail(&y);
2389                    lifted = true;
2390                    let sample = self.sample(vehicle, phase, window, t, &y, 0.0)?;
2391                    record(&mut events, observer, EventKind::Liftoff, sample);
2392                } else if t >= burnout_s {
2393                    break if lifted {
2394                        Termination::StalledOnRail
2395                    } else {
2396                        Termination::NoLiftoff
2397                    };
2398                }
2399            }
2400            // Once a part has left, the rest's center sits apart from where the rocket's was, and
2401            // can rise again for a moment after the rocket's apogee: the flight has one.
2402            let apogee_pending = !(released.contains(&true)
2403                && events.iter().any(|event| event.kind == EventKind::Apogee));
2404            let watches = self.watches(
2405                (phase, tip_off.is_some()),
2406                &run,
2407                (
2408                    (!separation_held
2409                        && (staged < self.separations.len() || (staged == 0 && self.parts())))
2410                    .then_some(staged),
2411                    apogee_pending,
2412                ),
2413                (&shift_started, &released),
2414            );
2415            let mut system = PhaseSystem {
2416                simulation: self,
2417                vehicle,
2418                phase,
2419                window,
2420                rail_origin,
2421                exit_travel_m,
2422                tip_off,
2423                canopies: Canopies {
2424                    devices: &self.devices,
2425                    run: &run,
2426                    body: self.parts().then_some(0),
2427                },
2428                watches: &watches,
2429                observer: &mut *observer,
2430                failure: None,
2431                cache: None,
2432                previous: None,
2433            };
2434            let outcome = integrator.advance(&mut system, next);
2435            if let Some(error) = system.failure.take() {
2436                return Err(error);
2437            }
2438            let outcome = match outcome {
2439                Ok(outcome) => outcome,
2440                Err(IntegrationError::StepLimit { .. }) => break Termination::StepLimit,
2441                Err(IntegrationError::Derivative { source, .. }) => return Err(source),
2442                Err(error) => return Err(SimError::Integration(Box::new(error))),
2443            };
2444            let t = integrator.time_s();
2445            let y = *integrator.state();
2446            let area = self.ascent_drag_area_m2(&run, t);
2447            // Burnout is a stop time, but an event can end the step on it first.
2448            if !burnout_recorded && t >= burnout_s {
2449                burnout_recorded = true;
2450                let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2451                record(&mut events, observer, EventKind::Burnout, sample);
2452            }
2453            match outcome {
2454                Advance::Reached => {}
2455                Advance::Events => {
2456                    let fired = integrator.fired_events().to_vec();
2457                    let mut ground = false;
2458                    let mut next_phase = phase;
2459                    for index in fired {
2460                        // `event_count` is `watches.len()`, and the integrator numbers its events
2461                        // by it, so a fired index is always in range.
2462                        match watches[index] {
2463                            Watch::RailExit => {
2464                                next_phase = Phase::Free;
2465                                let sample =
2466                                    self.sample(vehicle, Phase::Free, window, t, &y, area)?;
2467                                record(&mut events, observer, EventKind::RailExit, sample);
2468                            }
2469                            Watch::RailStall => next_phase = Phase::Pad,
2470                            // The last guide leaving, or the rocket stopping, in the same
2471                            // step wins: a rocket already off the rail, or at rest on it, has
2472                            // no last guide to turn about. Were tip-off to win, the exit's
2473                            // watch, already past its zero, would never fire again.
2474                            Watch::TipOff if next_phase == phase => next_phase = Phase::TipOff,
2475                            Watch::TipOff => {}
2476                            Watch::RailForce => {
2477                                next_phase = on_rail(&y);
2478                                lifted = true;
2479                                let sample =
2480                                    self.sample(vehicle, next_phase, window, t, &y, area)?;
2481                                record(&mut events, observer, EventKind::Liftoff, sample);
2482                            }
2483                            // The watch stays armed past the apogee until a part leaves, and can
2484                            // find the same root again a step later (#242): the flight has one.
2485                            Watch::Apogee
2486                                if events.iter().any(|event| event.kind == EventKind::Apogee) => {}
2487                            Watch::Apogee => {
2488                                let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2489                                self.reach_apogee(
2490                                    sample,
2491                                    &mut run,
2492                                    (&mut stops, cap),
2493                                    &mut events,
2494                                    observer,
2495                                );
2496                            }
2497                            Watch::Ground => {
2498                                let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2499                                record(&mut events, observer, EventKind::GroundHit, sample);
2500                                ground = true;
2501                            }
2502                            Watch::Altitude(device) => {
2503                                if !self.recovery_held && run.pending(device) {
2504                                    let deploy_s = run.trigger(&self.devices, device, t);
2505                                    insert_stop(&mut stops, deploy_s, cap);
2506                                    let sample =
2507                                        self.sample(vehicle, phase, window, t, &y, area)?;
2508                                    record(
2509                                        &mut events,
2510                                        observer,
2511                                        EventKind::Trigger(device),
2512                                        sample,
2513                                    );
2514                                }
2515                            }
2516                            Watch::SeparationHeight(_)
2517                            | Watch::EjectionHeight(_)
2518                            | Watch::ShiftHeight(_)
2519                            | Watch::ReleaseHeight(_) => {
2520                                // The separation, ejection, shift or release itself fires at the
2521                                // top of the next pass, which is where its burnout check and its
2522                                // bodies live, where a shift's start is set, and where a part
2523                                // leaves.
2524                            }
2525                            Watch::User(user) => {
2526                                let sample = self.sample(vehicle, phase, window, t, &y, area)?;
2527                                record(&mut events, observer, EventKind::User(user), sample);
2528                            }
2529                        }
2530                    }
2531                    if ground {
2532                        break Termination::GroundHit;
2533                    }
2534                    if next_phase == Phase::Pad && matches!(phase, Phase::Rail | Phase::TipOff) {
2535                        // Stopped on the rail: at rest where it stopped, held as on the pad. A
2536                        // rocket that stops on its last guide alone keeps the angle it has
2537                        // turned to and stops turning.
2538                        let mut at_rest = State::from_array(&y);
2539                        at_rest.velocity_enu_m_s = DVec3::ZERO;
2540                        at_rest.body_rate_rad_s = DVec3::ZERO;
2541                        integrator.reset(t, at_rest.to_array())?;
2542                    }
2543                    phase = next_phase;
2544                }
2545                _ => {}
2546            }
2547        };
2548
2549        let t = integrator.time_s();
2550        let y = *integrator.state();
2551        let vehicle = sustainer
2552            .as_ref()
2553            .or(shifted.as_ref())
2554            .or(lightened.as_ref())
2555            .unwrap_or(&self.vehicle);
2556        let next = next_stop(&stops, t, f64::INFINITY);
2557        let area = self.ascent_drag_area_m2(&run, t);
2558        let final_sample = self.sample(vehicle, phase, (t, next.max(t)), t, &y, area)?;
2559        let bodies = if separated {
2560            let bodies = self.fly_bodies(
2561                t,
2562                &State::from_array(&y),
2563                &mut run,
2564                &ignition_s,
2565                (
2566                    &opened,
2567                    None,
2568                    frozen_at_s.is_some_and(|frozen_s| frozen_s < t),
2569                ),
2570                observer,
2571            )?;
2572            // Each part falls as a point with only its open devices' drag. One parted on the way
2573            // up whose device fired by the split but waits out its lag would climb through the
2574            // lag with no drag at all, as if in a vacuum, where the real part has its airframe's
2575            // (a deployment lag drawn by a Monte Carlo run did, in review): refused by name. A
2576            // device set for the part's own apogee leaves it climbing as before, which the
2577            // `.ork` reader refuses for the part that keeps the nose (ADR-165).
2578            if climbing {
2579                for body in bodies.iter().filter(|body| body.start_sample.time_s == t) {
2580                    let mine = || {
2581                        self.devices
2582                            .iter()
2583                            .enumerate()
2584                            .filter(|(_, device)| device.body == body.body)
2585                            .map(|(index, _)| &run.devices[index])
2586                    };
2587                    let open_at_split = mine()
2588                        .any(|device| device.deployed_s.is_some_and(|deployed_s| deployed_s <= t));
2589                    let lagging = mine().any(|device| {
2590                        device
2591                            .triggered_s
2592                            .is_some_and(|triggered_s| triggered_s <= t)
2593                    });
2594                    if lagging && !open_at_split {
2595                        return Err(SimError::Domain {
2596                            what: "time of a split with nothing left to burn, before \
2597                                   apogee (a device fired by then opens after its lag: the part \
2598                                   would climb through it with no airframe drag)",
2599                            value: t,
2600                        });
2601                    }
2602                }
2603            }
2604            bodies
2605        } else {
2606            booster
2607        };
2608        Ok(FlightResult {
2609            termination,
2610            events,
2611            final_sample,
2612            stats: integrator.stats(),
2613            bodies,
2614            released: released_flights,
2615        })
2616    }
2617
2618    /// Flies the bodies of a stack that came apart at `t` to their landings, with the stack's
2619    /// motors lit at `ignition_s`: `open[split]` says which splits happened (the separations, then
2620    /// the ejections), `only` flies that body alone, the one a powered separation drops while the
2621    /// rest fly on or have already flown, and `frozen`
2622    /// says a device froze the stack's attitude before `t` (one that opens as the stack parts
2623    /// leaves the axis it had then).
2624    ///
2625    /// Each body is a point mass with its own pieces' and motors' mass, starting where its own
2626    /// center of mass was with the velocity that point already had, plus the push of each
2627    /// ejection's impulse on its side. The bodies share the flight's devices and their progress: a
2628    /// device that had already opened stays open on whichever body carries it. A body that parts
2629    /// again on the way down hands the piece that leaves to a body of its own, flown after it.
2630    fn fly_bodies(
2631        &self,
2632        t: f64,
2633        state: &State,
2634        run: &mut Run,
2635        ignition_s: &[Option<f64>],
2636        (open, only, frozen): (&[bool], Option<usize>, bool),
2637        observer: &mut dyn Observer,
2638    ) -> Result<Vec<BodyFlight>, SimError> {
2639        if !self.parts() {
2640            return Ok(Vec::new());
2641        }
2642        let pieces = Pieces::new(
2643            &self.rocket,
2644            &self.vehicle.assembly,
2645            &self.separations,
2646            &self.ejections,
2647        )?;
2648        let mut open = open.to_vec();
2649        open.resize(pieces.count() - 1, false);
2650        let attitude = state.unit_attitude();
2651        // A trigger on a motor the separation lit has its time only now.
2652        let trigger_times_s =
2653            recovery::plan(&self.devices, &self.vehicle.assembly.motors, ignition_s)?;
2654        let leaders = pieces.leaders(&open);
2655        let mut starts = Vec::new();
2656        for body in 0..pieces.count() {
2657            if leaders[body] != body || only.is_some_and(|only| only != body) {
2658                continue;
2659            }
2660            let mass = pieces.mass_properties(
2661                |piece| leaders[piece] == body,
2662                &self.vehicle.assembly,
2663                t,
2664                ignition_s,
2665            );
2666            // Its own center of mass, and the velocity that point had: `v_O + ω × r` in `L`.
2667            let cg_enu_m = state.point_enu_m(mass.cg_m);
2668            let velocity_enu_m_s =
2669                state.velocity_enu_m_s + attitude.mul_vec3(state.body_rate_rad_s.cross(mass.cg_m));
2670            starts.push(Start {
2671                body,
2672                t_s: t,
2673                cg_enu_m,
2674                velocity_enu_m_s,
2675                mass_kg: checked_body_mass(mass.mass_kg)?,
2676            });
2677        }
2678        // Each split that parts the stack here pushes its two sides apart: along the airframe's
2679        // axis while it flies with nothing open, and by its velocity through the air once a
2680        // device has frozen its attitude at some earlier time (ADR-086).
2681        let firing: Vec<usize> = (0..open.len()).filter(|&index| open[index]).collect();
2682        if firing
2683            .iter()
2684            .any(|&index| self.split_impulse_n_s(index) > 0.0)
2685        {
2686            let nose_ward = if frozen {
2687                let (mut kg, mut momentum, mut moment) = (0.0, DVec3::ZERO, DVec3::ZERO);
2688                for start in &starts {
2689                    kg += start.mass_kg;
2690                    momentum += start.velocity_enu_m_s * start.mass_kg;
2691                    moment += start.cg_enu_m * start.mass_kg;
2692                }
2693                let hanging =
2694                    run.hung_before(&self.devices, |index| self.acts_before_separation(index), t);
2695                self.nose_ward_enu(moment / kg, momentum / kg, hanging)?
2696            } else {
2697                attitude.mul_vec3(DVec3::Z)
2698            };
2699            self.push_apart(
2700                (&firing, &pieces, &open, &leaders),
2701                nose_ward,
2702                &mut starts,
2703                t,
2704            )?;
2705        }
2706        let mut queue: std::collections::VecDeque<Start> = starts.into();
2707        let mut bodies = Vec::new();
2708        while let Some(start) = queue.pop_front() {
2709            let mut split = Split {
2710                pieces: &pieces,
2711                open: &mut open,
2712                ignition_s,
2713                queue: &mut queue,
2714            };
2715            bodies.push(self.fly_body(start, &mut split, run, &trigger_times_s, observer)?);
2716        }
2717        bodies.sort_by_key(|body| body.body);
2718        Ok(bodies)
2719    }
2720
2721    /// Flies one body as a point mass from its `start` to its landing, parting it on the way
2722    /// down at each of its splits that fires.
2723    fn fly_body(
2724        &self,
2725        start: Start,
2726        split: &mut Split<'_>,
2727        run: &mut Run,
2728        trigger_times_s: &[Option<f64>],
2729        observer: &mut dyn Observer,
2730    ) -> Result<BodyFlight, SimError> {
2731        let Start {
2732            body,
2733            t_s: t0,
2734            cg_enu_m,
2735            velocity_enu_m_s,
2736            mut mass_kg,
2737        } = start;
2738        let impulse_left_n_s = {
2739            let leaders = split.pieces.leaders(split.open);
2740            split.pieces.impulse_left_n_s(
2741                |piece| leaders[piece] == body,
2742                &self.vehicle.assembly,
2743                t0,
2744                split.ignition_s,
2745            )
2746        };
2747        let cap = self.settings.max_time_s;
2748        let start = [
2749            cg_enu_m.x,
2750            cg_enu_m.y,
2751            cg_enu_m.z,
2752            velocity_enu_m_s.x,
2753            velocity_enu_m_s.y,
2754            velocity_enu_m_s.z,
2755        ];
2756        let mut integrator = Integrator::new(self.settings.method, t0, start)?
2757            .with_step_limit(self.settings.step_limit);
2758        // Every time this body's devices already have: their trigger times, and (for a device
2759        // that was triggered, deployed or released before the separation) its deployment, the
2760        // end of its filling and its release. Without these the descent would step straight past
2761        // them (found in review).
2762        let mut stops: Vec<f64> = Vec::new();
2763        for index in 0..self.devices.len() {
2764            if self.devices[index].body != body {
2765                continue;
2766            }
2767            stops.extend(trigger_times_s.get(index).copied().flatten());
2768            stops.extend(run.times_of(index));
2769        }
2770        // And its splits' known times.
2771        let mut leaders = split.pieces.leaders(split.open);
2772        for index in split.pending(&leaders, body) {
2773            stops.extend(self.split(index).1);
2774        }
2775        stops.retain(|time| *time > t0 && *time <= cap);
2776        stops.push(cap);
2777        stops.sort_by(f64::total_cmp);
2778        stops.dedup();
2779        let mut events: Vec<BodyEvent> = Vec::new();
2780        let start_sample = self.body_sample(body, mass_kg, t0, &start, run)?;
2781        if start_sample.height_above_ground_m <= 0.0 {
2782            // The ground event is a falling crossing, so a body that starts below the site would
2783            // integrate underground to the time cap.
2784            return Err(SimError::Domain {
2785                what: "starting height of a separated body's center of mass above the ground",
2786                value: start_sample.height_above_ground_m,
2787            });
2788        }
2789        let mine: Vec<usize> = (0..self.devices.len())
2790            .filter(|index| self.devices[*index].body == body)
2791            .collect();
2792
2793        let termination = loop {
2794            let t = integrator.time_s();
2795            let mut y = *integrator.state();
2796            if t >= cap {
2797                break Termination::TimeCap;
2798            }
2799            // Charges, deployments and releases, as in the main loop.
2800            loop {
2801                let mut again = false;
2802                let sample = self.body_sample(body, mass_kg, t, &y, run)?;
2803                for &index in &mine {
2804                    if !run.pending(index) {
2805                        continue;
2806                    }
2807                    let fires = match self.devices[index].trigger {
2808                        Trigger::Time { .. }
2809                        | Trigger::MotorDelay { .. }
2810                        | Trigger::Burnout { .. } => trigger_times_s
2811                            .get(index)
2812                            .copied()
2813                            .flatten()
2814                            .is_some_and(|time| t >= time),
2815                        Trigger::Apogee => sample.vertical_speed_m_s <= 0.0,
2816                        Trigger::Altitude {
2817                            height_above_ground_m,
2818                        } => {
2819                            sample.vertical_speed_m_s < 0.0
2820                                && sample.height_above_ground_m <= height_above_ground_m
2821                        }
2822                    };
2823                    if fires {
2824                        let deploy_s = run.trigger(&self.devices, index, t);
2825                        insert_stop(&mut stops, deploy_s, cap);
2826                        events.push(BodyEvent {
2827                            kind: EventKind::Trigger(index),
2828                            sample,
2829                            after: None,
2830                        });
2831                        again = true;
2832                    }
2833                }
2834                for &index in &mine {
2835                    if !run.waiting(index) || run.deploy_s(index) > t {
2836                        continue;
2837                    }
2838                    if run.released_s(index).is_some_and(|released| released <= t) {
2839                        run.abandon(index);
2840                        again = true;
2841                        continue;
2842                    }
2843                    let full_s = run.deploy(&self.devices, index, t, sample.airspeed_m_s);
2844                    insert_stop(&mut stops, full_s, cap);
2845                    events.push(BodyEvent {
2846                        kind: EventKind::Deployment(index),
2847                        sample: self.body_sample(body, mass_kg, t, &y, run)?,
2848                        after: None,
2849                    });
2850                    again = true;
2851                }
2852                for &index in &mine {
2853                    if run.release_due(index, t) {
2854                        run.release(index);
2855                        events.push(BodyEvent {
2856                            kind: EventKind::Release(index),
2857                            sample: self.body_sample(body, mass_kg, t, &y, run)?,
2858                            after: None,
2859                        });
2860                        again = true;
2861                    }
2862                }
2863                if !again {
2864                    break;
2865                }
2866            }
2867
2868            // Its splits whose trigger has come part it at once, as the stack parts at the first
2869            // parting: each piece they make starts here, at this body's point and velocity plus
2870            // the pushes on its sides, and is flown after it. Which fire, and the way the pushes
2871            // point, are decided on the body as the pass starts, so neither depends on the order
2872            // the splits were given in (found in review: taking them one at a time let a push
2873            // delay a split, or share one charge's push with pieces another then parted). A split
2874            // that hasn't fired is asked again at the same instant, on the pushed body.
2875            let pending = split.pending(&leaders, body);
2876            let fires = |index: usize, sample: &BodySample| {
2877                let (trigger, time_s, _) = self.split(index);
2878                match trigger {
2879                    Trigger::Time { .. } | Trigger::MotorDelay { .. } | Trigger::Burnout { .. } => {
2880                        time_s.is_some_and(|time| t >= time)
2881                    }
2882                    Trigger::Apogee => sample.vertical_speed_m_s <= 0.0,
2883                    Trigger::Altitude {
2884                        height_above_ground_m,
2885                    } => {
2886                        sample.vertical_speed_m_s < 0.0
2887                            && sample.height_above_ground_m <= height_above_ground_m
2888                    }
2889                }
2890            };
2891            let before = if pending.is_empty() {
2892                None
2893            } else {
2894                Some(self.body_sample(body, mass_kg, t, &y, run)?)
2895            };
2896            let firing: Vec<usize> = before.map_or_else(Vec::new, |before| {
2897                pending
2898                    .iter()
2899                    .copied()
2900                    .filter(|&index| fires(index, &before))
2901                    .collect()
2902            });
2903            if let (Some(before), false) = (before, firing.is_empty()) {
2904                // A separation still to come here lights no motor: an ejection ahead of one that
2905                // would is refused in the ascent.
2906                for &index in &firing {
2907                    split.open[index] = true;
2908                }
2909                leaders = split.pieces.leaders(split.open);
2910                let mass_of = |lead: usize| {
2911                    checked_body_mass(
2912                        split
2913                            .pieces
2914                            .mass_properties(
2915                                |piece| leaders[piece] == lead,
2916                                &self.vehicle.assembly,
2917                                t,
2918                                split.ignition_s,
2919                            )
2920                            .mass_kg,
2921                    )
2922                };
2923                // This body, then the body each split makes, led by the split's piece.
2924                let mut parts = vec![Start {
2925                    body,
2926                    t_s: t,
2927                    cg_enu_m: before.cg_enu_m,
2928                    velocity_enu_m_s: before.cg_velocity_enu_m_s,
2929                    mass_kg: mass_of(body)?,
2930                }];
2931                for &index in &firing {
2932                    parts.push(Start {
2933                        body: index + 1,
2934                        mass_kg: mass_of(index + 1)?,
2935                        ..parts[0]
2936                    });
2937                }
2938                if firing
2939                    .iter()
2940                    .any(|&index| self.split_impulse_n_s(index) > 0.0)
2941                {
2942                    let hanging =
2943                        run.hung_before(&self.devices, |index| self.devices[index].body == body, t);
2944                    let nose_ward =
2945                        self.nose_ward_enu(before.cg_enu_m, before.cg_velocity_enu_m_s, hanging)?;
2946                    let open = &*split.open;
2947                    self.push_apart(
2948                        (&firing, split.pieces, open, &leaders),
2949                        nose_ward,
2950                        &mut parts,
2951                        t,
2952                    )?;
2953                }
2954                mass_kg = parts[0].mass_kg;
2955                y[3] = parts[0].velocity_enu_m_s.x;
2956                y[4] = parts[0].velocity_enu_m_s.y;
2957                y[5] = parts[0].velocity_enu_m_s.z;
2958                let after = self.body_sample(body, mass_kg, t, &y, run)?;
2959                for &index in &firing {
2960                    events.push(BodyEvent {
2961                        kind: self.split(index).2,
2962                        sample: before,
2963                        after: Some(after),
2964                    });
2965                }
2966                split.queue.extend(parts.into_iter().skip(1));
2967                // The mass steps here, and a push steps the velocity, so the integrator starts
2968                // afresh from the new state.
2969                integrator.reset(t, y)?;
2970                continue;
2971            }
2972
2973            let next = next_stop(&stops, t, cap);
2974            // The heights this body watches for: its devices' and its splits'.
2975            let mut watches: Vec<f64> = mine
2976                .iter()
2977                .filter(|index| run.pending(**index))
2978                .filter_map(|index| match self.devices[*index].trigger {
2979                    Trigger::Altitude {
2980                        height_above_ground_m,
2981                    } => Some(height_above_ground_m),
2982                    _ => None,
2983                })
2984                .collect();
2985            for &index in &pending {
2986                if let Trigger::Altitude {
2987                    height_above_ground_m,
2988                } = self.split(index).0
2989                {
2990                    watches.push(height_above_ground_m);
2991                }
2992            }
2993            // Every body watches for its own apogee: an apogee charge on a body separated while
2994            // climbing would never fire without it (found in review), and since the ascent ends
2995            // at the separation this is the only place a staged flight can record a peak.
2996            let apogee = events.iter().all(|event| event.kind != EventKind::Apogee);
2997            let mut system = BodySystem {
2998                simulation: self,
2999                body,
3000                mass_kg,
3001                run,
3002                apogee,
3003                watches: &watches,
3004                observer: &mut *observer,
3005                failure: None,
3006            };
3007            let outcome = integrator.advance(&mut system, next);
3008            if let Some(error) = system.failure.take() {
3009                return Err(error);
3010            }
3011            let outcome = match outcome {
3012                Ok(outcome) => outcome,
3013                Err(IntegrationError::StepLimit { .. }) => break Termination::StepLimit,
3014                Err(IntegrationError::Derivative { source, .. }) => return Err(source),
3015                Err(error) => return Err(SimError::Integration(Box::new(error))),
3016            };
3017            if let Advance::Events = outcome {
3018                let fired = integrator.fired_events().to_vec();
3019                let t = integrator.time_s();
3020                let y = *integrator.state();
3021                if apogee && fired.contains(&1) {
3022                    // The body's own apogee: the ascent's ended at the separation, so this is the
3023                    // only place a staged flight can record one.
3024                    events.push(BodyEvent {
3025                        kind: EventKind::Apogee,
3026                        sample: self.body_sample(body, mass_kg, t, &y, run)?,
3027                        after: None,
3028                    });
3029                }
3030                if fired.contains(&0) {
3031                    events.push(BodyEvent {
3032                        kind: EventKind::GroundHit,
3033                        sample: self.body_sample(body, mass_kg, t, &y, run)?,
3034                        after: None,
3035                    });
3036                    break Termination::GroundHit;
3037                }
3038            }
3039        };
3040
3041        let t = integrator.time_s();
3042        let y = *integrator.state();
3043        let final_sample = self.body_sample(body, mass_kg, t, &y, run)?;
3044        if termination == Termination::GroundHit
3045            && !mine
3046                .iter()
3047                .any(|&index| run.devices[index].deployed_s.is_some())
3048        {
3049            // Every body must carry a device, and its device must actually open: a trigger that
3050            // never becomes true (a timer set after the body lands, say) would
3051            // otherwise drop the body with no drag at all, which is a wrong number rather than a
3052            // missing feature (found in review). A device that opened on the stack before the
3053            // separation counts: its deployment is in the flight's events, not the body's.
3054            return Err(SimError::Domain {
3055                what: "a separated body reached the ground with no device open (its triggers \
3056                       never fired); the body",
3057                value: body as f64,
3058            });
3059        }
3060        let pieces: Vec<usize> = (0..leaders.len())
3061            .filter(|piece| leaders[*piece] == body)
3062            .collect();
3063        Ok(BodyFlight {
3064            body,
3065            stages: split.pieces.stages(|piece| leaders[piece] == body),
3066            pieces,
3067            mass_kg,
3068            start_sample,
3069            termination,
3070            events,
3071            final_sample,
3072            stats: integrator.stats(),
3073            impulse_left_n_s,
3074        })
3075    }
3076
3077    /// One separated body at `(t, y)`, where `y` is its center of mass and that point's velocity.
3078    fn body_sample(
3079        &self,
3080        body: usize,
3081        mass_kg: f64,
3082        t: f64,
3083        y: &[f64; 6],
3084        run: &Run,
3085    ) -> Result<BodySample, SimError> {
3086        self.point_sample(t, y, mass_kg, run.body_drag_area_m2(&self.devices, body, t))
3087    }
3088
3089    /// A point mass of `mass_kg` under drag area `drag_area_m2` at `(t, y)`, where `y` is its
3090    /// position and velocity in the launch frame: a separated body, or a released part.
3091    pub(crate) fn point_sample(
3092        &self,
3093        t: f64,
3094        y: &[f64; 6],
3095        mass_kg: f64,
3096        drag_area_m2: f64,
3097    ) -> Result<BodySample, SimError> {
3098        let cg_enu_m = DVec3::new(y[0], y[1], y[2]);
3099        let velocity_enu_m_s = DVec3::new(y[3], y[4], y[5]);
3100        let frame = self.environment.earth.frame();
3101        let height_above_ground_m =
3102            frame.geodetic_from_enu(cg_enu_m)?.height_m - frame.origin().height_m;
3103        let (up_enu, wind_enu) = self.up_and_wind_enu(cg_enu_m)?;
3104        Ok(BodySample {
3105            time_s: t,
3106            cg_enu_m,
3107            cg_velocity_enu_m_s: velocity_enu_m_s,
3108            height_above_ground_m,
3109            vertical_speed_m_s: up_enu.dot(velocity_enu_m_s),
3110            airspeed_m_s: (velocity_enu_m_s - wind_enu).length(),
3111            recovery_drag_area_m2: drag_area_m2,
3112            mass_kg,
3113        })
3114    }
3115
3116    /// The rates of a point mass of `mass_kg` under drag area `drag_area_m2`, whose position and
3117    /// velocity in the launch frame are `y`: a separated body, or a released part. The equations
3118    /// are the descent phase's (`docs/physics/recovery.md`) with no thrust and no airframe:
3119    /// `m a = −½ ρ (C_D S) |v − w| (v − w) + m (g + a_Coriolis)`.
3120    pub(crate) fn point_mass_derivative(
3121        &self,
3122        y: &[f64; 6],
3123        mass_kg: f64,
3124        drag_area_m2: f64,
3125    ) -> Result<[f64; 6], SimError> {
3126        let velocity_enu_m_s = DVec3::new(y[3], y[4], y[5]);
3127        let drag_enu = self.point_mass_drag_enu_m_s2(y, mass_kg, drag_area_m2)?;
3128        let cg_enu_m = DVec3::new(y[0], y[1], y[2]);
3129        let environment = &self.environment;
3130        let gravity_enu = environment.earth.gravity_enu_mps2(cg_enu_m)?;
3131        let coriolis_enu = environment
3132            .earth
3133            .rotation_acceleration_enu_mps2(velocity_enu_m_s);
3134        let acceleration = drag_enu + gravity_enu + coriolis_enu;
3135        Ok([
3136            velocity_enu_m_s.x,
3137            velocity_enu_m_s.y,
3138            velocity_enu_m_s.z,
3139            acceleration.x,
3140            acceleration.y,
3141            acceleration.z,
3142        ])
3143    }
3144
3145    /// The drag acceleration of a point mass of `mass_kg` under drag area `drag_area_m2` at the
3146    /// state `y` of [`Self::point_mass_derivative`], m/s²: `−½ ρ (C_D S) |v − w| (v − w) / m`, its
3147    /// specific force, as it has no thrust and no airframe. Zero with no drag area, in a vacuum,
3148    /// or at rest in the air.
3149    pub(crate) fn point_mass_drag_enu_m_s2(
3150        &self,
3151        y: &[f64; 6],
3152        mass_kg: f64,
3153        drag_area_m2: f64,
3154    ) -> Result<DVec3, SimError> {
3155        let cg_enu_m = DVec3::new(y[0], y[1], y[2]);
3156        let velocity_enu_m_s = DVec3::new(y[3], y[4], y[5]);
3157        let environment = &self.environment;
3158        let geodetic = environment.earth.frame().geodetic_from_enu(cg_enu_m)?;
3159        let height_msl_m = geodetic.height_m - environment.geoid_undulation_m;
3160        let air = environment.air_at(height_msl_m)?;
3161        let wind_enu = environment.wind_enu_m_s(height_msl_m)?;
3162        let air_velocity = velocity_enu_m_s - wind_enu;
3163        let speed = air_velocity.length();
3164        Ok(
3165            if air.density_kg_m3 > 0.0 && speed > 0.0 && drag_area_m2 > 0.0 {
3166                air_velocity * (-0.5 * air.density_kg_m3 * drag_area_m2 * speed / mass_kg)
3167            } else {
3168                DVec3::ZERO
3169            },
3170        )
3171    }
3172
3173    /// The way the nose of a body with no attitude of its own is taken to point, as a unit vector
3174    /// in the launch frame, for the push of an ejection (ADR-086): a body `hanging` from a device
3175    /// points its forward end against its velocity through the air, toward the device, assumed to
3176    /// have left through that end; any other points its nose along that velocity, as a stable
3177    /// airframe does. Below [`STILL_AIR_M_S`] that velocity is drift or round-off rather
3178    /// than a flight path, and the nose is taken to point up.
3179    fn nose_ward_enu(
3180        &self,
3181        cg_enu_m: DVec3,
3182        velocity_enu_m_s: DVec3,
3183        hanging: bool,
3184    ) -> Result<DVec3, SimError> {
3185        let (up_enu, wind_enu) = self.up_and_wind_enu(cg_enu_m)?;
3186        let through_air = velocity_enu_m_s - wind_enu;
3187        let speed_m_s = through_air.length();
3188        Ok(if speed_m_s < STILL_AIR_M_S {
3189            up_enu
3190        } else if hanging {
3191            -through_air / speed_m_s
3192        } else {
3193            through_air / speed_m_s
3194        })
3195    }
3196
3197    /// The local vertical and the wind at the point `cg_enu_m` of the launch frame.
3198    fn up_and_wind_enu(&self, cg_enu_m: DVec3) -> Result<(DVec3, DVec3), SimError> {
3199        let frame = self.environment.earth.frame();
3200        let geodetic = frame.geodetic_from_enu(cg_enu_m)?;
3201        let up_ecef = DVec3::new(
3202            geodetic.latitude_rad.cos() * geodetic.longitude_rad.cos(),
3203            geodetic.latitude_rad.cos() * geodetic.longitude_rad.sin(),
3204            geodetic.latitude_rad.sin(),
3205        );
3206        let up_enu = frame.ecef_from_enu_rotation().transpose() * up_ecef;
3207        let height_msl_m = geodetic.height_m - self.environment.geoid_undulation_m;
3208        let wind_enu = self.environment.wind_enu_m_s(height_msl_m)?;
3209        Ok((up_enu, wind_enu))
3210    }
3211
3212    /// Whether the airframe can come apart: it has a separation or an ejection.
3213    fn parts(&self) -> bool {
3214        !self.separations.is_empty() || !self.ejections.is_empty()
3215    }
3216
3217    /// How many bodies the airframe can come apart into: one per piece.
3218    fn body_count(&self) -> usize {
3219        1 + self.separations.len() + self.ejections.len()
3220    }
3221
3222    /// Pushes apart the bodies in `parts` (each a body's start, by its lead piece) at the splits
3223    /// `firing`, all parting at `t`: each split's own piece's body takes `±J` along `nose_ward`,
3224    /// `+J` if the piece is forward of the split, and the body on its other side the opposite,
3225    /// each over its own mass, so the momentum is unchanged (ADR-086). `open` says which splits
3226    /// have happened, these among them, and `leaders` gives each piece's body after them.
3227    ///
3228    /// # Errors
3229    ///
3230    /// [`SimError::Domain`] for a pushed payload whose section's forward joint hasn't parted, so
3231    /// that it has no way out forward.
3232    fn push_apart(
3233        &self,
3234        (firing, pieces, open, leaders): (&[usize], &Pieces, &[bool], &[usize]),
3235        nose_ward: DVec3,
3236        parts: &mut [Start],
3237        t: f64,
3238    ) -> Result<(), SimError> {
3239        for &index in firing {
3240            let impulse_n_s = self.split_impulse_n_s(index);
3241            if impulse_n_s == 0.0 {
3242                continue;
3243            }
3244            let piece = index + 1;
3245            if let Some(host) = pieces.host(piece)
3246                && !(host > 0 && open[host - 1])
3247            {
3248                return Err(SimError::Domain {
3249                    what: "time of a pushed payload's ejection (it leaves forward, and the joint \
3250                           forward of the section that carries it has not parted by then)",
3251                    value: t,
3252                });
3253            }
3254            let (other, forward) = pieces.across(piece);
3255            let push = nose_ward * if forward { impulse_n_s } else { -impulse_n_s };
3256            for (lead, push) in [(leaders[piece], push), (leaders[other], -push)] {
3257                let part = parts.iter_mut().find(|part| part.body == lead);
3258                // Both sides of a split that fires here fly: only a sustainer's body is left out,
3259                // and a powered separation is refused with ejections, whose splits alone push.
3260                debug_assert!(part.is_some(), "a pushed body {lead} doesn't fly");
3261                if let Some(part) = part {
3262                    part.velocity_enu_m_s += push / part.mass_kg;
3263                }
3264            }
3265        }
3266        Ok(())
3267    }
3268
3269    /// The impulse of split `split`, in piece order, N·s: an ejection's own, and none for a
3270    /// separation.
3271    fn split_impulse_n_s(&self, split: usize) -> f64 {
3272        match split.checked_sub(self.separations.len()) {
3273            Some(ejection) => self.ejections[ejection].impulse_n_s,
3274            None => 0.0,
3275        }
3276    }
3277
3278    /// Split `split` of the flight, in piece order (the separations first, then the ejections):
3279    /// its trigger, its time when that is known before the flight, and its event.
3280    fn split(&self, split: usize) -> (Trigger, Option<f64>, EventKind) {
3281        match self.separations.get(split) {
3282            Some(separation) => (
3283                separation.trigger,
3284                self.separation_times_s[split],
3285                EventKind::Separation,
3286            ),
3287            None => {
3288                let ejection = split - self.separations.len();
3289                (
3290                    self.ejections[ejection].trigger,
3291                    self.ejection_times_s[ejection],
3292                    EventKind::Ejection(ejection),
3293                )
3294            }
3295        }
3296    }
3297
3298    /// The drag area acting on the stack before it comes apart, m²: body 0's devices, which with
3299    /// no separation or ejection is all of them.
3300    fn ascent_drag_area_m2(&self, run: &Run, t: f64) -> f64 {
3301        if self.parts() {
3302            run.body_drag_area_m2(&self.devices, 0, t)
3303        } else {
3304            run.drag_area_m2(&self.devices, t)
3305        }
3306    }
3307
3308    /// Whether device `index` acts on the stack before it comes apart: only body 0's do.
3309    fn acts_before_separation(&self, index: usize) -> bool {
3310        !self.parts() || self.devices[index].body == 0
3311    }
3312
3313    /// What the integrator watches for in `phase`, in event order.
3314    fn watches(
3315        &self,
3316        (phase, tip_off): (Phase, bool),
3317        run: &Run,
3318        (separation_pending, apogee_pending): (Option<usize>, bool),
3319        (shift_started, released): (&[bool], &[bool]),
3320    ) -> Vec<Watch> {
3321        match phase {
3322            Phase::Pad => vec![Watch::RailForce],
3323            Phase::Rail if tip_off => vec![Watch::RailExit, Watch::RailStall, Watch::TipOff],
3324            Phase::Rail | Phase::TipOff => vec![Watch::RailExit, Watch::RailStall],
3325            Phase::Free | Phase::Descent => {
3326                let mut watches = if apogee_pending {
3327                    vec![Watch::Apogee, Watch::Ground]
3328                } else {
3329                    vec![Watch::Ground]
3330                };
3331                for (index, device) in self.devices.iter().enumerate() {
3332                    if matches!(device.trigger, Trigger::Altitude { .. })
3333                        && run.pending(index)
3334                        && self.acts_before_separation(index)
3335                    {
3336                        watches.push(Watch::Altitude(index));
3337                    }
3338                }
3339                // The next separation's own height, so it is located rather than polled at the
3340                // next boundary that happens to exist.
3341                if let Some((next, Trigger::Altitude { .. })) = separation_pending
3342                    .and_then(|next| Some((next, self.separations.get(next)?.trigger)))
3343                {
3344                    watches.push(Watch::SeparationHeight(next));
3345                }
3346                if separation_pending == Some(0) {
3347                    for (index, ejection) in self.ejections.iter().enumerate() {
3348                        if matches!(ejection.trigger, Trigger::Altitude { .. }) {
3349                            watches.push(Watch::EjectionHeight(index));
3350                        }
3351                    }
3352                }
3353                for (index, shift) in self.shifts.iter().enumerate() {
3354                    if matches!(shift.trigger, Trigger::Altitude { .. })
3355                        && !shift_started.get(index).copied().unwrap_or(true)
3356                    {
3357                        watches.push(Watch::ShiftHeight(index));
3358                    }
3359                }
3360                for (index, release) in self.releases.iter().enumerate() {
3361                    if matches!(release.trigger, Trigger::Altitude { .. })
3362                        && !released.get(index).copied().unwrap_or(true)
3363                    {
3364                        watches.push(Watch::ReleaseHeight(index));
3365                    }
3366                }
3367                watches.extend((0..self.user_events.len()).map(Watch::User));
3368                watches
3369            }
3370        }
3371    }
3372}
3373
3374/// Whether `stages[first..=last]` hang together as one dropped body: each after the first hangs on
3375/// one of them, a parallel stage on the stage it is hung on ([`hpr_design::PlacedStage::hung_on`]),
3376/// an axial stage on the axial stage ahead of it. A separation's boundary drops every stage after
3377/// it, so a parallel stage hung on a stage the nose keeps must not lie behind a stage it drops
3378/// with it (the decision record on parallel stages, [ADR-171][adr-171]).
3379///
3380/// [adr-171]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-171-a-parallel-stage-is-a-pod-set-that-separates-2026-10-05
3381fn hangs_together(stages: &[hpr_design::PlacedStage], first: usize, last: usize) -> bool {
3382    // The axial stage ahead of each stage, found in one pass.
3383    let mut axial_ahead = None;
3384    for (index, stage) in stages.iter().enumerate().take(last + 1) {
3385        let carrier = stage.hung_on.or(axial_ahead);
3386        if index > first && !carrier.is_some_and(|carrier| (first..=last).contains(&carrier)) {
3387            return false;
3388        }
3389        if stage.hung_on.is_none() {
3390            axial_ahead = Some(index);
3391        }
3392    }
3393    true
3394}
3395
3396/// Checks the devices against the `bodies` a separation and ejections make, whichever builder ran
3397/// last: one when there is neither.
3398///
3399/// When the airframe can part, every body needs at least one device, and no device may name a
3400/// body that doesn't exist. Without a parting there is only body 0, so a device that names another
3401/// would have its drag area counted on the whole rocket and never be flown on a body of its own.
3402/// A builder checks only the first (`complete` false): a separation or ejection given after it
3403/// can still make the body a device names, and an ejection's number counts the separation.
3404fn check_bodies(devices: &[Device], bodies: usize, complete: bool) -> Result<(), SimError> {
3405    if let Some(device) = devices
3406        .iter()
3407        .find(|device| complete && device.body >= bodies)
3408    {
3409        return Err(SimError::Domain {
3410            what: if bodies > 1 {
3411                "body a device is attached to (the separation and ejections don't make it)"
3412            } else {
3413                "body a device is attached to (there is no separation or ejection, so there is \
3414                 only body 0)"
3415            },
3416            value: device.body as f64,
3417        });
3418    }
3419    if bodies > 1 {
3420        for body in 0..bodies {
3421            if !devices.iter().any(|device| device.body == body) {
3422                return Err(SimError::Domain {
3423                    what: "recovery devices on a separated body (every body needs one: a descent \
3424                           has no airframe drag)",
3425                    value: body as f64,
3426                });
3427            }
3428        }
3429    }
3430    Ok(())
3431}
3432
3433/// The first stop after `t`, or `cap`.
3434fn next_stop(stops: &[f64], t: f64, cap: f64) -> f64 {
3435    stops.iter().copied().find(|stop| *stop > t).unwrap_or(cap)
3436}
3437
3438/// The evaluation for the recovery scan, made once per pass and reused.
3439fn cached(
3440    cache: &mut Option<Evaluation>,
3441    evaluate: impl FnOnce() -> Result<Evaluation, SimError>,
3442) -> Result<Evaluation, SimError> {
3443    if let Some(evaluation) = cache {
3444        return Ok(*evaluation);
3445    }
3446    let evaluation = evaluate()?;
3447    *cache = Some(evaluation);
3448    Ok(evaluation)
3449}
3450
3451/// Adds `t` to the sorted stop times, unless it is past `cap` or already there.
3452fn insert_stop(stops: &mut Vec<f64>, t: f64, cap: f64) {
3453    if !t.is_finite() || t > cap {
3454        return;
3455    }
3456    match stops.binary_search_by(|stop| stop.total_cmp(&t)) {
3457        Ok(_) => {}
3458        Err(index) => stops.insert(index, t),
3459    }
3460}
3461
3462/// What the integrator watches for, in the order the events are numbered.
3463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3464enum Watch {
3465    /// The pad's force margin rising through zero: liftoff.
3466    RailForce,
3467    /// The travel along the rail reaching the exit travel.
3468    RailExit,
3469    /// The speed along the rail falling through zero: a stall.
3470    RailStall,
3471    /// The travel along the rail reaching where the last guide holds the rocket alone: tip-off
3472    /// begins.
3473    TipOff,
3474    /// The center of mass's height rate falling through zero: apogee.
3475    Apogee,
3476    /// The center of mass reaching the ground, descending.
3477    Ground,
3478    /// A device's deployment height, descending.
3479    Altitude(usize),
3480    /// A separation's height, descending, by its index.
3481    SeparationHeight(usize),
3482    /// An ejection's height, descending, by its index.
3483    EjectionHeight(usize),
3484    /// A mass shift's height, descending, by its index.
3485    ShiftHeight(usize),
3486    /// A mass release's height, descending, by its index.
3487    ReleaseHeight(usize),
3488    /// A user event.
3489    User(usize),
3490}
3491
3492/// Where a body's own flight starts: its number, the time, its center of mass and that point's
3493/// velocity, and its mass.
3494#[derive(Debug, Clone, Copy)]
3495struct Start {
3496    body: usize,
3497    t_s: f64,
3498    cg_enu_m: DVec3,
3499    velocity_enu_m_s: DVec3,
3500    mass_kg: f64,
3501}
3502
3503/// What the bodies' flights share about the airframe's parting: its pieces, which splits have
3504/// happened, the motors' ignitions, and the bodies still to fly.
3505struct Split<'a> {
3506    pieces: &'a Pieces,
3507    open: &'a mut Vec<bool>,
3508    ignition_s: &'a [Option<f64>],
3509    queue: &'a mut std::collections::VecDeque<Start>,
3510}
3511
3512impl Split<'_> {
3513    /// The splits still to happen inside `body`, given each piece's body in `leaders`: those whose
3514    /// piece is still joined to it.
3515    fn pending(&self, leaders: &[usize], body: usize) -> Vec<usize> {
3516        (0..self.open.len())
3517            .filter(|&index| !self.open[index] && leaders[index + 1] == body)
3518            .collect()
3519    }
3520}
3521
3522/// Takes `part` out of `assembly`'s structure: a part released in flight.
3523fn lighten(assembly: &mut hpr_design::Assembly, part: &hpr_design::MassProperties) {
3524    assembly.layout.structure = assembly.layout.structure.without_part(part);
3525}
3526
3527/// A body's mass, refused unless it is finite and positive.
3528fn checked_body_mass(mass_kg: f64) -> Result<f64, SimError> {
3529    if mass_kg.is_finite() && mass_kg > 0.0 {
3530        Ok(mass_kg)
3531    } else {
3532        Err(SimError::Domain {
3533            what: "mass of a separated body, kg",
3534            value: mass_kg,
3535        })
3536    }
3537}
3538
3539/// One separated body as the integrator sees it: a point mass under its open devices' drag area,
3540/// with its center of mass and that point's velocity as the state.
3541///
3542/// The equations are the descent phase's (`docs/physics/recovery.md`) with no thrust and no
3543/// airframe: `m a = −½ ρ (C_D S)(t) |v − w| (v − w) + m (g + a_Coriolis)`.
3544struct BodySystem<'a> {
3545    simulation: &'a Simulation,
3546    body: usize,
3547    mass_kg: f64,
3548    run: &'a Run,
3549    /// Whether the body is watching for its own apogee, which is event 1 when it is.
3550    apogee: bool,
3551    /// The heights this body is watching for, after the apogee: its devices' deployment heights
3552    /// and its splits'.
3553    watches: &'a [f64],
3554    observer: &'a mut dyn Observer,
3555    failure: Option<SimError>,
3556}
3557
3558/// A separated body's accepted step, as an [`Observer`] sees it.
3559struct BodyStepView<'a> {
3560    simulation: &'a Simulation,
3561    body: usize,
3562    mass_kg: f64,
3563    run: &'a Run,
3564    step: &'a Step<6>,
3565}
3566
3567impl crate::recorder::sealed::Sealed for BodyStepView<'_> {}
3568
3569impl BodyStep for BodyStepView<'_> {
3570    fn start_s(&self) -> f64 {
3571        self.step.start_s()
3572    }
3573
3574    fn end_s(&self) -> f64 {
3575        self.step.end_s()
3576    }
3577
3578    fn sample(&self, t_s: f64) -> Result<BodySample, SimError> {
3579        self.simulation.body_sample(
3580            self.body,
3581            self.mass_kg,
3582            t_s,
3583            &self.step.state_at(t_s),
3584            self.run,
3585        )
3586    }
3587
3588    fn acceleration_enu_m_s2(&self, t_s: f64) -> Result<DVec3, SimError> {
3589        let drag_area_m2 = self
3590            .run
3591            .body_drag_area_m2(&self.simulation.devices, self.body, t_s);
3592        let rates = self.simulation.point_mass_derivative(
3593            &self.step.state_at(t_s),
3594            self.mass_kg,
3595            drag_area_m2,
3596        )?;
3597        Ok(DVec3::new(rates[3], rates[4], rates[5]))
3598    }
3599
3600    fn specific_force_enu_m_s2(&self, t_s: f64) -> Result<DVec3, SimError> {
3601        let drag_area_m2 = self
3602            .run
3603            .body_drag_area_m2(&self.simulation.devices, self.body, t_s);
3604        self.simulation.point_mass_drag_enu_m_s2(
3605            &self.step.state_at(t_s),
3606            self.mass_kg,
3607            drag_area_m2,
3608        )
3609    }
3610}
3611
3612impl BodySystem<'_> {
3613    /// The height above the site and the drag acceleration at `(t, y)`.
3614    fn sample(&self, t_s: f64, y: &[f64; 6]) -> Result<BodySample, SimError> {
3615        self.simulation
3616            .body_sample(self.body, self.mass_kg, t_s, y, self.run)
3617    }
3618}
3619
3620impl OdeSystem<6> for BodySystem<'_> {
3621    type Error = SimError;
3622
3623    fn derivative(&mut self, t_s: f64, y: &[f64; 6]) -> Result<[f64; 6], SimError> {
3624        let drag_area_m2 = self
3625            .run
3626            .body_drag_area_m2(&self.simulation.devices, self.body, t_s);
3627        self.simulation
3628            .point_mass_derivative(y, self.mass_kg, drag_area_m2)
3629    }
3630
3631    fn event_count(&self) -> usize {
3632        1 + usize::from(self.apogee) + self.watches.len()
3633    }
3634
3635    fn event_direction(&self, _index: usize) -> Direction {
3636        Direction::Falling
3637    }
3638
3639    fn event_value(&mut self, index: usize, t_s: f64, y: &[f64; 6]) -> f64 {
3640        let sample = match self.sample(t_s, y) {
3641            Ok(sample) => sample,
3642            Err(error) => {
3643                self.failure.get_or_insert(error);
3644                return f64::NAN;
3645            }
3646        };
3647        // The ground, then this body's apogee if it is looking for one, then each watched
3648        // device's deployment height. Every one is a falling crossing, so a device fires on the
3649        // way down only.
3650        if index == 0 {
3651            return sample.height_above_ground_m;
3652        }
3653        if self.apogee && index == 1 {
3654            return sample.vertical_speed_m_s;
3655        }
3656        let watch = index - 1 - usize::from(self.apogee);
3657        self.watches
3658            .get(watch)
3659            .map_or(f64::NAN, |height_m| sample.height_above_ground_m - height_m)
3660    }
3661
3662    fn accept_step(&mut self, step: &Step<6>) -> ControlFlow<()> {
3663        let view = BodyStepView {
3664            simulation: self.simulation,
3665            body: self.body,
3666            mass_kg: self.mass_kg,
3667            run: self.run,
3668            step,
3669        };
3670        match self.observer.body_step(self.body, &view) {
3671            Ok(()) => ControlFlow::Continue(()),
3672            Err(error) => {
3673                self.failure.get_or_insert(error);
3674                ControlFlow::Break(())
3675            }
3676        }
3677    }
3678}
3679
3680/// The recovery devices of a flight and their progress through it.
3681#[derive(Debug, Clone, Copy)]
3682struct Canopies<'a> {
3683    devices: &'a [Device],
3684    run: &'a Run,
3685    /// The body whose devices act, when a separation means only some of them do. `None` is all
3686    /// of them, which is what a flight without a separation has.
3687    body: Option<usize>,
3688}
3689
3690impl Canopies<'_> {
3691    /// The drag area at `t` of the devices that act on what is being flown, m². It has to match
3692    /// the loop's `ascent_drag_area_m2`, because this is what the equations and the recorded rows
3693    /// see.
3694    fn drag_area_m2(&self, t: f64) -> f64 {
3695        match self.body {
3696            Some(body) => self.run.body_drag_area_m2(self.devices, body, t),
3697            None => self.run.drag_area_m2(self.devices, t),
3698        }
3699    }
3700}
3701
3702fn sample_of(phase: Phase, t: f64, y: &[f64; STATE_LEN], e: &Evaluation) -> Sample {
3703    Sample {
3704        time_s: t,
3705        phase,
3706        state: State::from_array(y),
3707        cg_enu_m: e.cg_enu_m,
3708        cg_velocity_enu_m_s: e.cg_velocity_enu_m_s,
3709        height_above_ground_m: e.height_above_ground_m,
3710        vertical_speed_m_s: e.vertical_speed_m_s,
3711        acceleration_enu_m_s2: e.acceleration_enu_m_s2,
3712        specific_force_enu_m_s2: e.specific_force_enu_m_s2,
3713        airspeed_m_s: e.airspeed_m_s,
3714        mach: e.mach,
3715        angle_of_attack_rad: e.angle_of_attack_rad,
3716        dynamic_pressure_pa: e.dynamic_pressure_pa,
3717        axial_coefficient: e.axial_coefficient,
3718        thrust_n: e.thrust_n,
3719        mass_kg: e.mass.mass_kg,
3720        recovery_drag_area_m2: e.recovery_drag_area_m2,
3721    }
3722}
3723
3724/// Where tip-off begins and what it turns about.
3725#[derive(Debug, Clone, Copy)]
3726struct TipOff {
3727    /// The travel along the rail at which the last guide holds the rocket alone, m.
3728    travel_m: f64,
3729    /// The pivot in body axes, m from the nose tip.
3730    pivot_m: DVec3,
3731    /// Where the pivot started, in `L`, m.
3732    pivot_origin: DVec3,
3733    /// The unit vector along the rail, up, in `L`.
3734    along: DVec3,
3735}
3736
3737impl TipOff {
3738    /// How far the pivot has moved along the rail, m. While the rocket is guided this is the
3739    /// nose tip's travel; once it turns, only the pivot keeps to the rail's line.
3740    fn pivot_travel_m(&self, y: &[f64; STATE_LEN]) -> f64 {
3741        (State::from_array(y).point_enu_m(self.pivot_m) - self.pivot_origin).dot(self.along)
3742    }
3743
3744    /// The pivot's speed along the rail, m/s.
3745    fn pivot_speed_m_s(&self, y: &[f64; STATE_LEN]) -> f64 {
3746        let state = State::from_array(y);
3747        let velocity = state.velocity_enu_m_s
3748            + state
3749                .unit_attitude()
3750                .mul_vec3(state.body_rate_rad_s.cross(self.pivot_m));
3751        velocity.dot(self.along)
3752    }
3753}
3754
3755/// One phase over one interval, as the integrator sees it.
3756struct PhaseSystem<'a> {
3757    simulation: &'a Simulation,
3758    vehicle: &'a Vehicle,
3759    phase: Phase,
3760    window: (f64, f64),
3761    rail_origin: DVec3,
3762    exit_travel_m: f64,
3763    /// Tip-off's start and pivot, if the flight has the phase.
3764    tip_off: Option<TipOff>,
3765    canopies: Canopies<'a>,
3766    watches: &'a [Watch],
3767    observer: &'a mut dyn Observer,
3768    /// An error from an event function or the observer, returned after the integrator stops.
3769    failure: Option<SimError>,
3770    /// The last evaluation: the integrator evaluates the derivative at a step's end before the
3771    /// events there.
3772    cache: Option<(f64, [f64; STATE_LEN], Evaluation)>,
3773    /// The cache as the last accepted step left it: that step's end, which is the next step's
3774    /// start, where the observers ask again. The integrator's stages have replaced the cache by the
3775    /// time the next step is accepted.
3776    previous: Option<(f64, [f64; STATE_LEN], Evaluation)>,
3777}
3778
3779impl PhaseSystem<'_> {
3780    /// The evaluation at `(t, y)`, from the cache when it holds that state. A reference, not a
3781    /// copy: an evaluation is a few hundred bytes, and the integrator asks for one at every
3782    /// stage and event check.
3783    fn evaluation(&mut self, t: f64, y: &[f64; STATE_LEN]) -> Result<&Evaluation, SimError> {
3784        if !matches!(&self.cache, Some((ct, cy, _)) if *ct == t && cy == y) {
3785            let drag_area_m2 = self.canopies.drag_area_m2(t);
3786            match &mut self.cache {
3787                // Overwritten in place; `out` is untouched on an error, so the entry stays the
3788                // evaluation of the state it names.
3789                Some((ct, cy, out)) => {
3790                    let conditions =
3791                        self.simulation
3792                            .conditions(self.phase, self.window, drag_area_m2);
3793                    self.simulation
3794                        .evaluate_into(self.vehicle, conditions, t, y, out)?;
3795                    *ct = t;
3796                    *cy = *y;
3797                }
3798                slot @ None => {
3799                    let evaluation = self.simulation.evaluate(
3800                        self.vehicle,
3801                        self.phase,
3802                        self.window,
3803                        t,
3804                        y,
3805                        drag_area_m2,
3806                    )?;
3807                    *slot = Some((t, *y, evaluation));
3808                }
3809            }
3810        }
3811        let Some((_, _, evaluation)) = &self.cache else {
3812            // An invariant, not an input: a hit found the cache full, and a miss filled it above
3813            // or returned the evaluation's error.
3814            unreachable!("the evaluation cache is filled just above")
3815        };
3816        Ok(evaluation)
3817    }
3818
3819    /// An event value, or NaN with the error kept for the caller.
3820    fn or_fail(&mut self, value: Result<f64, SimError>) -> f64 {
3821        match value {
3822            Ok(value) => value,
3823            Err(error) => {
3824                self.failure.get_or_insert(error);
3825                f64::NAN
3826            }
3827        }
3828    }
3829}
3830
3831impl OdeSystem<STATE_LEN> for PhaseSystem<'_> {
3832    type Error = SimError;
3833
3834    fn derivative(&mut self, t_s: f64, y: &[f64; STATE_LEN]) -> Result<[f64; STATE_LEN], SimError> {
3835        self.evaluation(t_s, y).map(|e| e.derivative)
3836    }
3837
3838    fn event_count(&self) -> usize {
3839        self.watches.len()
3840    }
3841
3842    fn event_direction(&self, index: usize) -> Direction {
3843        match self.watches.get(index) {
3844            Some(Watch::RailForce | Watch::RailExit | Watch::TipOff) => Direction::Rising,
3845            Some(
3846                Watch::RailStall
3847                | Watch::Apogee
3848                | Watch::Ground
3849                | Watch::Altitude(_)
3850                | Watch::SeparationHeight(_)
3851                | Watch::EjectionHeight(_)
3852                | Watch::ShiftHeight(_)
3853                | Watch::ReleaseHeight(_),
3854            ) => Direction::Falling,
3855            Some(Watch::User(user)) => self
3856                .simulation
3857                .user_events
3858                .get(*user)
3859                .map_or(Direction::Either, |event| event.direction),
3860            None => Direction::Either,
3861        }
3862    }
3863
3864    fn event_value(&mut self, index: usize, t_s: f64, y: &[f64; STATE_LEN]) -> f64 {
3865        let state = State::from_array(y);
3866        let Some(watch) = self.watches.get(index).copied() else {
3867            return f64::NAN;
3868        };
3869        match watch {
3870            // In tip-off the pivot keeps to the rail's line, and the nose tip does not.
3871            Watch::RailExit | Watch::RailStall if self.phase == Phase::TipOff => {
3872                match (&self.tip_off, watch) {
3873                    (Some(tip_off), Watch::RailExit) => {
3874                        tip_off.pivot_travel_m(y) - self.exit_travel_m
3875                    }
3876                    (Some(tip_off), _) => tip_off.pivot_speed_m_s(y),
3877                    (None, _) => f64::NAN,
3878                }
3879            }
3880            Watch::RailExit => {
3881                let along = self.simulation.rail.direction_enu();
3882                (state.position_enu_m - self.rail_origin).dot(along) - self.exit_travel_m
3883            }
3884            Watch::RailStall => state
3885                .velocity_enu_m_s
3886                .dot(self.simulation.rail.direction_enu()),
3887            Watch::TipOff => match &self.tip_off {
3888                Some(tip_off) => {
3889                    let along = self.simulation.rail.direction_enu();
3890                    (state.position_enu_m - self.rail_origin).dot(along) - tip_off.travel_m
3891                }
3892                None => f64::NAN,
3893            },
3894            Watch::Apogee => {
3895                let value = self.evaluation(t_s, y).map(|e| e.vertical_speed_m_s);
3896                self.or_fail(value)
3897            }
3898            Watch::Ground => {
3899                let value = self.evaluation(t_s, y).map(|e| e.height_above_ground_m);
3900                self.or_fail(value)
3901            }
3902            Watch::Altitude(device) => {
3903                let height_m = match self.simulation.devices.get(device).map(|d| d.trigger) {
3904                    Some(Trigger::Altitude {
3905                        height_above_ground_m,
3906                    }) => height_above_ground_m,
3907                    _ => return f64::NAN,
3908                };
3909                let value = self
3910                    .evaluation(t_s, y)
3911                    .map(|e| e.height_above_ground_m - height_m);
3912                self.or_fail(value)
3913            }
3914            Watch::SeparationHeight(_)
3915            | Watch::EjectionHeight(_)
3916            | Watch::ShiftHeight(_)
3917            | Watch::ReleaseHeight(_) => {
3918                let trigger = match watch {
3919                    Watch::EjectionHeight(index) => {
3920                        self.simulation.ejections.get(index).map(|e| e.trigger)
3921                    }
3922                    Watch::ShiftHeight(index) => {
3923                        self.simulation.shifts.get(index).map(|s| s.trigger)
3924                    }
3925                    Watch::ReleaseHeight(index) => {
3926                        self.simulation.releases.get(index).map(|r| r.trigger)
3927                    }
3928                    Watch::SeparationHeight(index) => {
3929                        self.simulation.separations.get(index).map(|s| s.trigger)
3930                    }
3931                    _ => None,
3932                };
3933                let height_m = match trigger {
3934                    Some(Trigger::Altitude {
3935                        height_above_ground_m,
3936                    }) => height_above_ground_m,
3937                    _ => return f64::NAN,
3938                };
3939                let value = self
3940                    .evaluation(t_s, y)
3941                    .map(|e| e.height_above_ground_m - height_m);
3942                self.or_fail(value)
3943            }
3944            Watch::User(user) => {
3945                let phase = self.phase;
3946                let value = self.evaluation(t_s, y).map(|e| sample_of(phase, t_s, y, e));
3947                match value {
3948                    Ok(sample) => self
3949                        .simulation
3950                        .user_events
3951                        .get(user)
3952                        .map_or(f64::NAN, |event| (event.function)(&sample)),
3953                    Err(error) => self.or_fail(Err(error)),
3954                }
3955            }
3956            Watch::RailForce => {
3957                let value = self.evaluation(t_s, y).map(|e| e.rail_force_n);
3958                self.or_fail(value)
3959            }
3960        }
3961    }
3962
3963    fn accept_step(&mut self, step: &Step<STATE_LEN>) -> ControlFlow<()> {
3964        let view = StepView {
3965            simulation: self.simulation,
3966            vehicle: self.vehicle,
3967            phase: self.phase,
3968            window: self.window,
3969            canopies: self.canopies,
3970            step,
3971            memo: Default::default(),
3972            held: self.cache.as_ref(),
3973            previous: self.previous.as_ref(),
3974        };
3975        let flow = self.observer.step(&view);
3976        self.previous.clone_from(&self.cache);
3977        match flow {
3978            Ok(()) => ControlFlow::Continue(()),
3979            Err(error) => {
3980                self.failure.get_or_insert(error);
3981                ControlFlow::Break(())
3982            }
3983        }
3984    }
3985}
3986
3987#[cfg(test)]
3988thread_local! {
3989    /// Set by tests to evaluate every instant afresh, as before the step's memo, so a test can
3990    /// compare the two paths bit for bit.
3991    pub(crate) static STEP_MEMO_OFF: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3992}
3993
3994/// An accepted step as the observer sees it.
3995struct StepView<'a> {
3996    simulation: &'a Simulation,
3997    vehicle: &'a Vehicle,
3998    phase: Phase,
3999    window: (f64, f64),
4000    canopies: Canopies<'a>,
4001    step: &'a Step<STATE_LEN>,
4002    /// The step's evaluations by time, so a sample and a stability at one instant share one:
4003    /// within a step the evaluation is a function of the time alone. The first four times asked
4004    /// (the observers ask for three: the step's start, middle and end) are kept; later ones are
4005    /// evaluated afresh. Read in place, as an evaluation is a few hundred bytes.
4006    memo: [std::cell::OnceCell<(u64, Evaluation)>; 4],
4007    /// The integrator's last evaluation, used when a time and its state are bit for bit the
4008    /// ones it holds: a step's end, which the integrator evaluates before the events there. With
4009    /// both integrators it always holds the step's end, so today the time alone decides; the state
4010    /// is compared too, so a change to the integrator can't hand over another state's evaluation.
4011    held: Option<&'a (f64, [f64; STATE_LEN], Evaluation)>,
4012    /// The evaluation the integrator held when the step before was accepted: its end, this step's
4013    /// start. Used on the same terms as `held`, the time and the state bit for bit.
4014    previous: Option<&'a (f64, [f64; STATE_LEN], Evaluation)>,
4015}
4016
4017impl StepView<'_> {
4018    /// The vehicle's evaluation at `t_s` on this step's dense output, from the memo if it has one.
4019    /// Borrowed from the memo (no 600-byte copy out) unless every slot is taken.
4020    fn evaluation(&self, t_s: f64) -> Result<EvaluationRef<'_>, SimError> {
4021        let key = t_s.to_bits();
4022        #[cfg(test)]
4023        let shared = !STEP_MEMO_OFF.with(std::cell::Cell::get);
4024        #[cfg(not(test))]
4025        let shared = true;
4026        let mut free = None;
4027        if shared {
4028            for slot in &self.memo {
4029                match slot.get() {
4030                    Some((k, e)) if *k == key => return Ok(EvaluationRef::Shared(e)),
4031                    Some(_) => {}
4032                    None => {
4033                        free = Some(slot);
4034                        break;
4035                    }
4036                }
4037            }
4038        }
4039        let y = self.step.state_at(t_s);
4040        let same =
4041            |held: &[f64; STATE_LEN]| held.iter().zip(&y).all(|(a, b)| a.to_bits() == b.to_bits());
4042        let reused = [self.held, self.previous]
4043            .into_iter()
4044            .flatten()
4045            .find(|(ht, hy, _)| shared && ht.to_bits() == key && same(hy));
4046        if let (Some(slot), Some((_, _, he))) = (free, reused) {
4047            return Ok(EvaluationRef::Shared(&slot.get_or_init(|| (key, *he)).1));
4048        }
4049        let e = match reused {
4050            Some((_, _, he)) => *he,
4051            None => self.simulation.evaluate(
4052                self.vehicle,
4053                self.phase,
4054                self.window,
4055                t_s,
4056                &y,
4057                self.canopies.drag_area_m2(t_s),
4058            )?,
4059        };
4060        if let Some(slot) = free {
4061            // Empty when found, and nothing else fills it in between: the set can't fail.
4062            return Ok(EvaluationRef::Shared(&slot.get_or_init(|| (key, e)).1));
4063        }
4064        Ok(EvaluationRef::Owned(Box::new(e)))
4065    }
4066}
4067
4068/// An evaluation read in place from the step's memo, or owned when the memo is full.
4069enum EvaluationRef<'a> {
4070    Shared(&'a Evaluation),
4071    Owned(Box<Evaluation>),
4072}
4073
4074impl std::ops::Deref for EvaluationRef<'_> {
4075    type Target = Evaluation;
4076    fn deref(&self) -> &Evaluation {
4077        match self {
4078            Self::Shared(e) => e,
4079            Self::Owned(e) => e,
4080        }
4081    }
4082}
4083
4084impl FlightStep for StepView<'_> {
4085    fn phase(&self) -> Phase {
4086        self.phase
4087    }
4088
4089    fn start_s(&self) -> f64 {
4090        self.step.start_s()
4091    }
4092
4093    fn end_s(&self) -> f64 {
4094        self.step.end_s()
4095    }
4096
4097    fn state_at(&self, t_s: f64) -> State {
4098        State::from_array(&self.step.state_at(t_s))
4099    }
4100
4101    fn sample(&self, t_s: f64) -> Result<Sample, SimError> {
4102        let evaluation = self.evaluation(t_s)?;
4103        Ok(sample_of(
4104            self.phase,
4105            t_s,
4106            &self.step.state_at(t_s),
4107            &evaluation,
4108        ))
4109    }
4110
4111    fn stability(&self, t_s: f64) -> Result<Stability, SimError> {
4112        let e = self.evaluation(t_s)?;
4113        crate::metrics::stability(
4114            &self.vehicle.aero,
4115            t_s,
4116            e.height_above_ground_m,
4117            e.dynamic_pressure_pa,
4118            -e.mass.cg_m.z,
4119            e.mach,
4120        )
4121    }
4122}