Skip to main content

hpr_sim/
rail.rs

1//! The launch rail: its direction, length and friction, and where a design's rail buttons or launch
2//! lugs leave it.
3//!
4//! The rocket starts with its aft end (the aft-most point of its body, of any part on its outside,
5//! fin tips and pods included, or of its nozzle exits) at the foot of the rail, its axis along
6//! the rail. It is guided, with one degree of freedom along the rail, until the aft edge of its
7//! aft-most guide passes the top of the rail. A rocket with no rail buttons or lugs is guided
8//! until its aft end passes the top, as from a tower.
9//!
10//! Once the guide ahead of the aft-most one is off the rail, a real rocket is held by one guide
11//! alone and gravity and the wind turn it about that guide: tip-off. A flight that asks for it
12//! ([`crate::Simulation::with_tip_off`]) flies that as a phase of its own (`pivot_motion`, in this module):
13//! the rocket slides on along the rail, free to pitch and yaw about its last guide with roll
14//! held, until that guide leaves too. Without it the rocket stays guided to its last guide and
15//! leaves the rail with no angular velocity.
16//!
17//! Friction is Coulomb friction, `μ |N|`, with `N` the rail's reaction perpendicular to the rail:
18//! the component of gravity, the aerodynamic force and the variable-mass terms across the rocket's
19//! axis. It opposes the motion along the rail, and on the pad it holds the rocket until the force
20//! along the rail exceeds it.
21//!
22//! Method: `docs/physics/flight.md`.
23
24use hpr_core::frames::LaunchAngles;
25use hpr_core::{DMat3, DQuat, DVec3};
26use hpr_design::{Assembly, Part};
27use serde::{Deserialize, Serialize};
28
29use crate::error::SimError;
30
31/// A launch rail.
32#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct Rail {
35    /// The rail's length from its foot, where the rocket's aft end starts, to its top, m.
36    pub length_m: f64,
37    /// The heading of the rail, clockwise from true north, rad (`frames::LaunchAngles`).
38    pub azimuth_rad: f64,
39    /// The rail's angle above the horizon, rad (`π/2` is vertical).
40    pub elevation_rad: f64,
41    /// The rocket's roll on the rail: the turn of `x_B` about the rail axis, rad.
42    pub roll_rad: f64,
43    /// The Coulomb friction coefficient between the guides and the rail. There is no default
44    /// value in the sources; zero means a frictionless rail.
45    pub friction_coefficient: f64,
46}
47
48impl Rail {
49    /// A frictionless vertical rail of length `length_m`.
50    #[must_use]
51    pub fn vertical(length_m: f64) -> Self {
52        Self {
53            length_m,
54            azimuth_rad: 0.0,
55            elevation_rad: std::f64::consts::FRAC_PI_2,
56            roll_rad: 0.0,
57            friction_coefficient: 0.0,
58        }
59    }
60
61    /// Checks the length, angles and friction.
62    ///
63    /// # Errors
64    ///
65    /// [`SimError::Domain`] for a non-positive length, a negative friction coefficient, an
66    /// elevation outside `(0, π/2]` or a non-finite angle.
67    pub fn validate(&self) -> Result<(), SimError> {
68        let checks = [
69            ("rail length", self.length_m, self.length_m > 0.0),
70            (
71                "rail friction coefficient",
72                self.friction_coefficient,
73                self.friction_coefficient >= 0.0,
74            ),
75            (
76                "rail elevation",
77                self.elevation_rad,
78                self.elevation_rad > 0.0 && self.elevation_rad <= std::f64::consts::FRAC_PI_2,
79            ),
80            ("rail azimuth", self.azimuth_rad, true),
81            ("rail roll", self.roll_rad, true),
82        ];
83        for (what, value, ok) in checks {
84            if !value.is_finite() || !ok {
85                return Err(SimError::Domain { what, value });
86            }
87        }
88        Ok(())
89    }
90
91    /// The rocket's attitude on the rail.
92    #[must_use]
93    pub fn attitude(&self) -> DQuat {
94        LaunchAngles {
95            azimuth_rad: self.azimuth_rad,
96            elevation_rad: self.elevation_rad,
97            roll_rad: self.roll_rad,
98        }
99        .to_quaternion()
100    }
101
102    /// The unit vector along the rail, up, in the launch frame.
103    #[must_use]
104    pub fn direction_enu(&self) -> DVec3 {
105        self.attitude().mul_vec3(DVec3::Z)
106    }
107}
108
109/// Where a design meets the rail, as stations (m aft of the nose tip).
110#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
111pub struct Guides {
112    /// The rocket's aft end, which starts at the foot of the rail: the aft-most point of its body,
113    /// of every part on its outside (a fin's tip trailing edge where a swept fin reaches past the
114    /// tube, a tube fin's or a pod's aft end) and of its nozzle exits. The rocket stands on that
115    /// point (the decision record on the rail, [ADR-011][adr-011]; #1254).
116    ///
117    /// [adr-011]: https://github.com/nrdptel/fusionspace-eridanus/blob/main/docs/DECISIONS.md#adr-011-rigid-body-flight-equations-of-motion-aerodynamic-coupling-rail-phases-and-termination-2026-09-17
118    pub aft_station_m: f64,
119    /// The aft edge of the forward-most guide (a rail button's aft edge, or a lug's aft end), or
120    /// `None` without guides.
121    pub first_guide_station_m: Option<f64>,
122    /// The aft edge of the aft-most guide, or `None` without guides.
123    pub last_guide_station_m: Option<f64>,
124    /// The aft edge of the guide next ahead of the aft-most one, or `None` with fewer than two
125    /// guides at different stations. Once it passes the top of the rail the aft-most guide holds
126    /// the rocket alone, and tip-off begins.
127    #[serde(default)]
128    pub next_guide_station_m: Option<f64>,
129    /// The middle of the aft-most guide (a button's center, a lug's midpoint), where the rocket
130    /// pivots during tip-off, or `None` without guides.
131    #[serde(default)]
132    pub pivot_station_m: Option<f64>,
133}
134
135impl Guides {
136    /// The guides of an assembled design: every rail button of every row (each `outer_diameter`
137    /// long, `spacing` apart) and every launch lug (each `length` long).
138    #[must_use]
139    pub fn of(assembly: &Assembly) -> Self {
140        let body_aft = assembly.layout.length_m;
141        // Every body component (a pod's too) and every part on the outside, as far aft as it
142        // reaches: a fin set by its outline, not its root chord. A part with no copies isn't
143        // there. Internal parts aren't counted (a design check warns when one runs past its
144        // parent's end); a motor reaches out by its nozzle.
145        let outside_aft = assembly
146            .layout
147            .components
148            .iter()
149            .filter(|c| (c.part.is_body() || c.part.is_external()) && !c.copies.is_empty())
150            .map(|c| match &c.part {
151                Part::FinSet(fins) => c.fore_station_m + fins.planform.aft_extent_m(),
152                _ => c.aft_station_m(),
153            })
154            .fold(body_aft, f64::max);
155        let aft_station_m = assembly
156            .motors
157            .iter()
158            .map(|motor| motor.nozzle_station_m())
159            .fold(outside_aft, f64::max);
160        let mut first: Option<f64> = None;
161        // The aft-most guide's aft edge and its length, and the aft edge of the one next ahead.
162        let mut last: Option<(f64, f64)> = None;
163        let mut next: Option<f64> = None;
164        for component in &assembly.layout.components {
165            let (count, spacing, extent) = match &component.part {
166                Part::RailButton(button) => {
167                    (button.count, button.spacing_m, button.outer_diameter_m)
168                }
169                Part::LaunchLug(lug) => (lug.count, lug.spacing_m, lug.length_m),
170                _ => continue,
171            };
172            for k in 0..count {
173                let aft_edge = component.fore_station_m + f64::from(k) * spacing + extent;
174                first = Some(first.map_or(aft_edge, |f| f.min(aft_edge)));
175                match last {
176                    Some((edge, _)) if aft_edge > edge + SAME_GUIDE_M => {
177                        next = Some(edge);
178                        last = Some((aft_edge, extent));
179                    }
180                    Some((edge, _)) if aft_edge < edge - SAME_GUIDE_M => {
181                        next = Some(next.map_or(aft_edge, |n| n.max(aft_edge)));
182                    }
183                    // A guide at the aft-most one's station (a second row beside it) leaves
184                    // with it: the two are one guide here, and the aft-most edge of the two is
185                    // the guide's.
186                    Some((edge, kept)) => last = Some((edge.max(aft_edge), kept)),
187                    None => last = Some((aft_edge, extent)),
188                }
189            }
190        }
191        Self {
192            aft_station_m,
193            first_guide_station_m: first,
194            last_guide_station_m: last.map(|(edge, _)| edge),
195            next_guide_station_m: next,
196            pivot_station_m: last.map(|(edge, extent)| edge - 0.5 * extent),
197        }
198    }
199
200    /// How far the rocket travels along a rail of `rail_length_m` before its last guide leaves the
201    /// top: `L − (s_aft − s_guide)`, with the aft end standing in for the guide without guides.
202    #[must_use]
203    pub fn exit_travel_m(&self, rail_length_m: f64) -> f64 {
204        let guide = self.last_guide_station_m.unwrap_or(self.aft_station_m);
205        rail_length_m - (self.aft_station_m - guide)
206    }
207
208    /// How far the rocket travels before its first guide leaves the top.
209    #[must_use]
210    pub fn first_guide_exit_travel_m(&self, rail_length_m: f64) -> f64 {
211        let guide = self.first_guide_station_m.unwrap_or(self.aft_station_m);
212        rail_length_m - (self.aft_station_m - guide)
213    }
214
215    /// How far the rocket travels before its last guide holds it alone, where tip-off begins:
216    /// the guide next ahead of the last one leaving the top, `L − (s_aft − s_next)`. `None`
217    /// with fewer than two guides at different stations: one guide, or a tower, has no such
218    /// stretch.
219    #[must_use]
220    pub fn tip_off_travel_m(&self, rail_length_m: f64) -> Option<f64> {
221        self.next_guide_station_m
222            .map(|guide| rail_length_m - (self.aft_station_m - guide))
223    }
224}
225
226/// How close two guides' aft edges are, m, for the two to count as one guide that leaves the
227/// rail at once: a micron. Two rows of buttons at one nominal station can reach the layout
228/// through different sums and land a few ulps apart; a stretch that short on the "last" of them
229/// alone is rounding, not tip-off.
230const SAME_GUIDE_M: f64 = 1e-6;
231
232/// What a rocket on its last guide alone needs besides the free equations: where it pivots and
233/// the line the pivot keeps to.
234#[derive(Debug, Clone, Copy, PartialEq)]
235pub(crate) struct Pivot {
236    /// The pivot in body axes, m from the nose tip: on the axis at the last guide's middle.
237    pub(crate) point_m: DVec3,
238    /// The unit vector along the rail, up, in the launch frame.
239    pub(crate) rail_enu: DVec3,
240}
241
242/// The motion of a rocket that slides along the rail on its last guide alone, free to pitch and
243/// yaw about that guide with roll held: tip-off.
244///
245/// The free equations of motion ([`crate::dynamics`]) give the nose tip's acceleration `a` and
246/// the angular acceleration `ω̇` the rocket would have with nothing holding it. The guide adds
247/// what keeps it on the rail: a force `F` on the pivot `p`, square to the rail, and a moment
248/// `τ z_B` about the long axis. With `d = p − r` the pivot from the center of mass, each changes
249/// the motion by
250///
251/// ```text
252/// Δω̇  = I_c⁻¹ (d × F + τ z_B)
253/// Δa_p = F/m + Δω̇ × d            (the pivot's acceleration)
254/// Δa   = F/m − Δω̇ × r            (the nose tip's)
255/// ```
256///
257/// and the three unknowns, `F`'s two parts across the rail and `τ`, are fixed by three
258/// conditions: the pivot's acceleration `a + ω̇ × p + ω × (ω × p)` has no part across the rail
259/// (two), and the rocket's angular acceleration has none about its long axis (one). The three
260/// equations are linear, with a symmetric positive-definite matrix.
261///
262/// Friction is the rail's Coulomb friction on that force: `μ |F|` on the pivot along the rail,
263/// against the sliding (`sliding` is the sign of the pivot's speed up the rail). It turns the
264/// rocket slightly, which changes `F`; with `x₀` the frictionless solution, `c` the conditions'
265/// response to a unit force against the sliding and `u = J⁻¹ c`, the solution is `x₀ − μρu` with
266/// `ρ = |F|` the non-negative root of `(1 − μ²|u_F|²) ρ² + 2μ (x₀·u)_F ρ − |x₀|_F² = 0`, where
267/// the subscript keeps the force's two parts.
268///
269/// Source: the reaction-wrench form of RocketPy's tip-off phase (`Flight.udot_rail2`, its pull
270/// request #920, MIT; `THIRD-PARTY-NOTICES.md`), written for this crate's equations about the
271/// nose tip; the friction term is this crate's rail friction carried over. On a body of fixed
272/// mass with no thrust and no air it reduces to a pendulum's `ω̇ = m g r cos θ / (I + m r²)`.
273/// Method and a worked example: `docs/physics/flight.md`.
274///
275/// Returns the nose tip's acceleration and the angular acceleration, both in body axes.
276///
277/// # Errors
278///
279/// [`SimError::Domain`] if the inertia about the center of mass has no inverse, or the
280/// conditions' matrix none, or the friction coefficient is so large that the rocket would jam on
281/// its guide (`μ |u_F| ≥ 1`).
282pub(crate) fn pivot_motion(
283    (mass_kg, cg_m, inertia_cg): (f64, DVec3, DMat3),
284    body_rate_rad_s: DVec3,
285    (free_acceleration, free_angular_acceleration): (DVec3, DVec3),
286    (pivot_m, rail_body): (DVec3, DVec3),
287    (friction_coefficient, sliding): (f64, f64),
288) -> Result<(DVec3, DVec3), SimError> {
289    let positive = |what: &'static str, value: f64| {
290        if value.is_finite() && value > 0.0 {
291            Ok(value)
292        } else {
293            Err(SimError::Domain { what, value })
294        }
295    };
296    positive(
297        "determinant of the inertia about the center of mass",
298        inertia_cg.determinant(),
299    )?;
300    let inverse_inertia = inertia_cg.inverse();
301    let (r, p, omega) = (cg_m, pivot_m, body_rate_rad_s);
302    let d = p - r;
303    // Two unit vectors across the rail, in body axes: the first from the body axis least along
304    // the rail.
305    let n = rail_body.normalize();
306    let (ax, ay, az) = (n.x.abs(), n.y.abs(), n.z.abs());
307    let helper = if az <= ax && az <= ay {
308        DVec3::Z
309    } else if ay <= ax {
310        DVec3::Y
311    } else {
312        DVec3::X
313    };
314    let e1 = n.cross(helper).normalize();
315    let e2 = n.cross(e1);
316    // What a force on the pivot and a moment about the long axis change: the angular
317    // acceleration, and the three conditions.
318    let turn = |force: DVec3, roll_moment: f64| {
319        inverse_inertia * (d.cross(force) + DVec3::Z * roll_moment)
320    };
321    let conditions = |force: DVec3, roll_moment: f64| {
322        let angular = turn(force, roll_moment);
323        let pivot = force / mass_kg + angular.cross(d);
324        DVec3::new(pivot.dot(e1), pivot.dot(e2), angular.z)
325    };
326    let jacobian = DMat3::from_cols(
327        conditions(e1, 0.0),
328        conditions(e2, 0.0),
329        conditions(DVec3::ZERO, 1.0),
330    );
331    positive(
332        "determinant of the tip-off conditions",
333        jacobian.determinant(),
334    )?;
335    let inverse = jacobian.inverse();
336    let pivot_free =
337        free_acceleration + free_angular_acceleration.cross(p) + omega.cross(omega.cross(p));
338    let unheld = DVec3::new(
339        pivot_free.dot(e1),
340        pivot_free.dot(e2),
341        free_angular_acceleration.z,
342    );
343    let frictionless = inverse * -unheld;
344    // Friction: a force on the pivot against its sliding, as large as μ times the force across.
345    let against = n * -sliding;
346    let mut solution = frictionless;
347    let mut friction_n = 0.0;
348    if friction_coefficient > 0.0 {
349        let mu = friction_coefficient;
350        let u = inverse * conditions(against, 0.0);
351        let (x0, u2) = (frictionless.truncate(), u.truncate());
352        let lead = positive(
353            "room before the rocket jams on its last guide, 1 − μ²|u|² (the rail friction \
354             coefficient is too large for tip-off)",
355            1.0 - mu * mu * u2.length_squared(),
356        )?;
357        let b = mu * x0.dot(u2);
358        let across = ((b * b + lead * x0.length_squared()).sqrt() - b) / lead;
359        friction_n = mu * across;
360        solution = frictionless - u * friction_n;
361    }
362    let force = e1 * solution.x + e2 * solution.y + against * friction_n;
363    let change = turn(force, solution.z);
364    let angular = free_angular_acceleration + change;
365    let acceleration = free_acceleration + force / mass_kg - change.cross(r);
366    // Roll is held: the solved component is rounding, and is dropped so it can't build up.
367    Ok((acceleration, DVec3::new(angular.x, angular.y, 0.0)))
368}
369
370#[cfg(test)]
371mod tests;