Skip to main content

stable_flight/guidance/
copter.rs

1//! Guidance for multirotors such as the QuadCopter X: waypoint navigation and pilot-stick
2//! interpretation, feeding [`CopterStabilizer`](crate::stabilizers::copter::CopterStabilizer).
3//!
4//! | Control input | Setpoint |
5//! |---|---|
6//! | [`ControlInput::Rate`] | [`Setpoint::Rate`], sticks passed through; the heading-hold target follows the vehicle |
7//! | [`ControlInput::Attitude`] | [`Setpoint::Attitude`]: roll/pitch sticks scaled to [`max_stick_angles_rad`](CopterGuidanceConfig::max_stick_angles_rad); yaw stick slews a heading-hold target; throttle boosted by 1/cos(tilt) so tilting doesn't sink (none when inverted) |
8//! | [`ControlInput::AbsoluteAttitude`] | [`Setpoint::Attitude`]: roll/pitch passed through (the stabilizer saturates them); the heading replaces the heading-hold target (NaN holds it); thrust saturated to `[0, 1]`, not boosted |
9//! | [`ControlInput::Waypoint`] | [`Setpoint::Attitude`]: lateral position → velocity → acceleration → roll/pitch (every [`navigation_period_s`](CopterGuidanceConfig::navigation_period_s)), altitude loop → thrust (every tick), heading held; descents slewed at [`max_descent_mps`](CopterGuidanceConfig::max_descent_mps) |
10//! | [`ControlInput::Land`] | [`Setpoint::Attitude`]: as a waypoint at the land position, with an altitude target that keeps descending at [`land_speed_mps`](CopterGuidanceConfig::land_speed_mps), at most [`LAND_LEASH_M`] below the vehicle |
11//!
12//! Switching modes doesn't jump the heading: attitude, absolute-attitude, waypoint, and land
13//! flight share one heading-hold target, and rate flight keeps it on the vehicle's heading. The
14//! altitude and lateral loops start fresh each time waypoint or land flight is entered, with
15//! the altitude target starting from the vehicle's altitude.
16
17use core::f32::consts::FRAC_PI_4;
18
19use crate::{GRAVITY, Vec2};
20
21use crate::commanders::touchdown::DESCENDING_MPS;
22use crate::controllers::*;
23use crate::controllers::{check, check_limit, check_positive, check_tilt};
24use crate::{
25    AbsoluteAttitudeCommand, AttitudeCommand, AttitudeSetpoint, Configurable, ControlInput,
26    Guidance, LandCommand, Saturation, Setpoint, VehicleState, WaypointCommand,
27};
28
29use super::rate_divider::RateDivider;
30use crate::math::{
31    all_finite, assert_dt, cap_magnitude, saturate_throttle, saturate_unit, tilt_boost, wrap_angle,
32};
33
34mod params;
35#[cfg(test)]
36mod tests;
37
38/// Heading-hold target slew rate at full yaw stick, in rad/s (~57°/s).
39const HEADING_SLEW_RATE: f32 = 1.0;
40
41/// Default [`CopterGuidanceConfig::max_tilt_rad`]: 27°, leaving thrust headroom to climb while
42/// translating (60% of the default 45° stabilizer limit).
43pub const DEFAULT_MAX_TILT_RAD: f32 = 27.0_f32.to_radians();
44
45/// Default [`CopterGuidanceConfig::max_stick_angles_rad`] per axis: 45°, the default stabilizer
46/// limit, so full stick is full tilt.
47pub const DEFAULT_MAX_STICK_ANGLE_RAD: f32 = FRAC_PI_4;
48
49/// Default [`CopterGuidanceConfig::navigation_period_s`]: 50 Hz, a fifth of the usual 250 Hz
50/// inner loop.
51pub const DEFAULT_NAVIGATION_PERIOD_S: f32 = 0.02;
52
53/// Default [`CopterGuidanceConfig::max_descent_mps`]: fast enough for the figure-eight's
54/// descending half (up to about 3 m/s at 7 m/s cruise).
55pub const DEFAULT_MAX_DESCENT_MPS: f32 = 3.0;
56
57/// Default [`CopterGuidanceConfig::land_speed_mps`], as PX4's `MPC_LAND_SPEED`.
58pub const DEFAULT_LAND_SPEED_MPS: f32 = 0.7;
59
60/// How far, in meters, a land's altitude target may run below the vehicle. Once the ground
61/// stops the vehicle, the altitude loop then settles on a thrust below hover instead of winding
62/// down toward none.
63pub const LAND_LEASH_M: f32 = 1.0;
64
65/// Configuration for [CopterGuidance]: the altitude and lateral position loops and the
66/// waypoint-flight limits.
67///
68/// Plain data: [`CopterGuidance::new`] validates it ([`validate`](Self::validate)), and the
69/// guidance passes the loop configs to its controllers every tick.
70///
71/// # Examples
72///
73/// ```
74/// use stable_flight::controllers::Gains;
75/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
76///
77/// let mut config = CopterGuidanceConfig::default();
78/// config.altitude.gains = Gains { p: 2.0, i: 0.2, d: 0.1 };
79/// config.altitude.hover_thrust = 0.45; // airframe-specific
80/// let guidance = CopterGuidance::new(config);
81/// ```
82#[derive(Clone, Copy, Debug, PartialEq)]
83pub struct CopterGuidanceConfig {
84    /// Altitude loop: altitude error (m) → vertical acceleration (m/s²), fed to the thrust law
85    /// with gravity and tilt compensation. Its `hover_thrust` defaults to
86    /// [`DEFAULT_HOVER_THRUST`].
87    pub altitude: AltitudeControllerConfig,
88    /// Lateral loop: horizontal position error (m) → velocity (m/s, capped at the waypoint's
89    /// `cruise_speed_mps`) → acceleration (m/s²), flown as a tilt of `atan(|a| / g)` toward it.
90    pub lateral: LateralControllerConfig,
91    /// Seconds between runs of the lateral position loop; its roll/pitch output is held in
92    /// between. `0.0` runs it every tick. Rounded to the nearest tick (at a 4 ms loop, 20 ms
93    /// is every 5th tick); each run steps over the actual elapsed time. The altitude loop runs
94    /// every tick, since its tilt compensation needs the current attitude. Must be
95    /// non-negative and finite. Defaults to [`DEFAULT_NAVIGATION_PERIOD_S`].
96    pub navigation_period_s: f32,
97    /// Largest waypoint-flight tilt in radians, in `(0, π/2)`. Caps the magnitude of the
98    /// combined roll/pitch request, so a far waypoint can't ask for full tilt while the
99    /// altitude loop also wants full climb. It limits the request, not the achieved tilt: the
100    /// attitude loop can overshoot it briefly, and the stabilizer's own `max_angles_rad` still
101    /// applies. Piloted attitude flight is not capped. Defaults to [`DEFAULT_MAX_TILT_RAD`].
102    pub max_tilt_rad: f32,
103    /// Roll and pitch in radians that full stick (±1) commands in piloted attitude flight;
104    /// the stick scales linearly. The stabilizer saturates to its own `max_angles_rad`, so a
105    /// larger value only reaches that limit sooner. Must be non-negative and finite. Defaults
106    /// to [`DEFAULT_MAX_STICK_ANGLE_RAD`] on both axes.
107    pub max_stick_angles_rad: Vec2,
108    /// Fastest descent waypoint flight asks for, in m/s: a target below the vehicle is
109    /// approached by an altitude target lowered at this rate, so a low waypoint descends
110    /// instead of cutting thrust. Climbs aren't limited. It limits the target, not the achieved
111    /// rate: the vehicle can exceed it briefly while catching up. Must be positive and finite.
112    /// Defaults to [`DEFAULT_MAX_DESCENT_MPS`].
113    pub max_descent_mps: f32,
114    /// Descent rate of a land ([`ControlInput::Land`]), in m/s. Must be finite and above the
115    /// touchdown detector's [`DESCENDING_MPS`] (0.2 m/s), so the detector sees the descent and
116    /// the land ends in a disarm. Defaults to [`DEFAULT_LAND_SPEED_MPS`].
117    pub land_speed_mps: f32,
118}
119
120impl Default for CopterGuidanceConfig {
121    /// The controller defaults (flight-checked on RealFlight's QuadCopterX), a 50 Hz lateral
122    /// loop, a 27° waypoint tilt cap, 45° at full stick, a 3 m/s descent limit, and a 0.7 m/s
123    /// land.
124    fn default() -> Self {
125        CopterGuidanceConfig {
126            altitude: AltitudeControllerConfig::default(),
127            lateral: LateralControllerConfig::default(),
128            navigation_period_s: DEFAULT_NAVIGATION_PERIOD_S,
129            max_tilt_rad: DEFAULT_MAX_TILT_RAD,
130            max_stick_angles_rad: Vec2::new(
131                DEFAULT_MAX_STICK_ANGLE_RAD,
132                DEFAULT_MAX_STICK_ANGLE_RAD,
133            ),
134            max_descent_mps: DEFAULT_MAX_DESCENT_MPS,
135            land_speed_mps: DEFAULT_LAND_SPEED_MPS,
136        }
137    }
138}
139
140impl CopterGuidanceConfig {
141    /// Checks both loop configs ([`AltitudeControllerConfig::validate`],
142    /// [`LateralControllerConfig::validate`]; errors carry the loop as their `section`), that
143    /// `navigation_period_s` and `max_stick_angles_rad` are non-negative and finite, that
144    /// `max_tilt_rad` is in `(0, π/2)`, that `max_descent_mps` is positive and finite, and that
145    /// `land_speed_mps` is finite and above [`DESCENDING_MPS`].
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use stable_flight::guidance::copter::CopterGuidanceConfig;
151    ///
152    /// let mut config = CopterGuidanceConfig::default();
153    /// assert!(config.validate().is_ok());
154    /// config.altitude.hover_thrust = 1.5;
155    /// assert_eq!(config.validate().unwrap_err().to_string(), "altitude.hover_thrust must be in (0, 1]");
156    /// ```
157    pub fn validate(&self) -> Result<(), InvalidConfig> {
158        self.altitude
159            .validate()
160            .map_err(|e| e.in_section("altitude"))?;
161        self.lateral
162            .validate()
163            .map_err(|e| e.in_section("lateral"))?;
164        check_limit("navigation_period_s", self.navigation_period_s)?;
165        check_limit("max_stick_angles_rad.x", self.max_stick_angles_rad.x)?;
166        check_limit("max_stick_angles_rad.y", self.max_stick_angles_rad.y)?;
167        check_tilt("max_tilt_rad", self.max_tilt_rad)?;
168        check_positive("max_descent_mps", self.max_descent_mps)?;
169        check(
170            "land_speed_mps",
171            self.land_speed_mps > DESCENDING_MPS && self.land_speed_mps.is_finite(),
172            "above the touchdown detector's DESCENDING_MPS and finite",
173        )
174    }
175}
176
177/// Copter guidance: altitude and lateral position loops for waypoints, and heading hold for
178/// piloted attitude flight.
179///
180/// # Examples
181///
182/// ```
183/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
184/// use stable_flight::{AttitudeCommand, ControlInput, Guidance, Setpoint, VehicleState};
185///
186/// let mut guidance = CopterGuidance::new(CopterGuidanceConfig::default());
187/// let state = VehicleState { heading_rad: 1.0, ..Default::default() };
188/// guidance.prime(&state);
189///
190/// let input = ControlInput::Attitude(AttitudeCommand { throttle: 0.5, ..Default::default() });
191/// let Setpoint::Attitude(setpoint) = guidance.guide(0.004, &input, &state) else {
192///     unreachable!("attitude commands yield attitude setpoints");
193/// };
194/// assert!((setpoint.heading_rad - 1.0).abs() < 1e-6); // holds the primed heading
195/// assert_eq!(setpoint.thrust, 0.5);
196/// ```
197pub struct CopterGuidance {
198    /// Loop configs and limits, passed into the controllers every tick.
199    config: CopterGuidanceConfig,
200
201    altitude: AltitudeController,
202    lateral: LateralController,
203    /// Where the altitude loop is steered, in meters: the waypoint's altitude, or on the way
204    /// down to it, slewed at the descent limit. `None` until waypoint or land flight latches
205    /// it from the vehicle's altitude.
206    altitude_target_m: Option<f32>,
207
208    /// Heading-hold target for attitude, absolute-attitude, waypoint, and land commands.
209    heading: f32,
210
211    /// Paces the lateral loop.
212    lateral_rate: RateDivider,
213    /// The lateral loop's last roll/pitch in radians, held between its runs.
214    tilt_rad: Vec2,
215    /// The held tilt was capped at `max_tilt_rad` when the lateral loop last ran.
216    tilt_capped: bool,
217
218    /// What the last `guide` call clipped.
219    saturation: Saturation,
220}
221
222impl CopterGuidance {
223    /// Creates a new [CopterGuidance] with the specified configuration.
224    ///
225    /// # Panics
226    ///
227    /// If `config` is invalid ([`CopterGuidanceConfig::validate`]).
228    pub fn new(config: CopterGuidanceConfig) -> Self {
229        if let Err(error) = config.validate() {
230            panic!("invalid CopterGuidanceConfig: {error}");
231        }
232        CopterGuidance {
233            config,
234            altitude: AltitudeController::default(),
235            lateral: LateralController::default(),
236            altitude_target_m: None,
237
238            heading: 0.0,
239
240            lateral_rate: RateDivider::default(),
241            tilt_rad: Vec2::zeros(),
242            tilt_capped: false,
243            saturation: Saturation::default(),
244        }
245    }
246}
247
248impl Configurable for CopterGuidance {
249    type Config = CopterGuidanceConfig;
250
251    fn config(&self) -> &CopterGuidanceConfig {
252        &self.config
253    }
254
255    /// Validates with [`CopterGuidanceConfig::validate`]. The heading-hold target and the
256    /// lateral loop's timing are kept; a new `navigation_period_s` applies from the next tick,
257    /// and the held waypoint tilt is re-capped to a lowered `max_tilt_rad` at once.
258    fn set_config(&mut self, config: CopterGuidanceConfig) -> Result<(), InvalidConfig> {
259        config.validate()?;
260        let old = &self.config;
261        self.altitude
262            .rescale_integral(&old.altitude, &config.altitude);
263        self.lateral.rescale_integral(&old.lateral, &config.lateral);
264        self.config = config;
265        if self.tilt_rad.norm() > config.max_tilt_rad {
266            self.tilt_capped = true;
267        }
268        self.tilt_rad = cap_magnitude(self.tilt_rad, config.max_tilt_rad);
269        Ok(())
270    }
271}
272
273impl Guidance for CopterGuidance {
274    fn guide(&mut self, dt: f32, input: &ControlInput, estimated_state: &VehicleState) -> Setpoint {
275        assert_dt(dt);
276        self.saturation = Saturation::default();
277
278        if !matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_)) {
279            // The position loops are idle: clear them so re-entering waypoint mode starts
280            // fresh, runs the lateral loop at once instead of holding a stale tilt, carries no
281            // integral from an earlier leg, and starts its altitude target from the vehicle.
282            self.altitude = AltitudeController::default();
283            self.lateral = LateralController::default();
284            self.altitude_target_m = None;
285            self.lateral_rate.reset();
286        }
287
288        match input {
289            ControlInput::Attitude(attitude_command) => {
290                Setpoint::Attitude(self.attitude_setpoint(dt, attitude_command, estimated_state))
291            }
292            ControlInput::Rate(rate_command) => {
293                // Track the vehicle so attitude or waypoint flight holds the heading it has
294                // when rate flight ends, not the one it had when rate flight began.
295                if estimated_state.heading_rad.is_finite() {
296                    self.heading = wrap_angle(estimated_state.heading_rad);
297                }
298                Setpoint::Rate(rate_command.into())
299            }
300            ControlInput::Waypoint(waypoint_command) => {
301                Setpoint::Attitude(self.navigate(dt, waypoint_command, estimated_state))
302            }
303            ControlInput::AbsoluteAttitude(command) => {
304                Setpoint::Attitude(self.absolute_attitude_setpoint(command, estimated_state))
305            }
306            ControlInput::Land(command) => {
307                Setpoint::Attitude(self.land(dt, command, estimated_state))
308            }
309        }
310    }
311
312    /// Clears the altitude and lateral controller state, the altitude target, and any held
313    /// waypoint tilt, and latches the current heading as the yaw-hold target.
314    fn prime(&mut self, state: &VehicleState) {
315        self.altitude = AltitudeController::default();
316        self.lateral = LateralController::default();
317        self.altitude_target_m = None;
318        self.heading = state.heading_rad;
319        self.lateral_rate.reset();
320        self.tilt_rad = Vec2::zeros();
321        self.tilt_capped = false;
322        self.saturation = Saturation::default();
323    }
324
325    /// `tilt` when the waypoint tilt request was capped at
326    /// [`max_tilt_rad`](CopterGuidanceConfig::max_tilt_rad) (held with the tilt between
327    /// lateral-loop runs), and `thrust` when the altitude loop's thrust, attitude mode's
328    /// boosted throttle, or an absolute attitude's thrust was clipped to `[0, 1]`. A tilt
329    /// beyond the stabilizer's limit in an absolute attitude is the stabilizer's to flag.
330    fn saturation(&self) -> Saturation {
331        self.saturation
332    }
333}
334
335impl CopterGuidance {
336    /// Scales the roll/pitch sticks to radians, boosts throttle for the measured tilt, and
337    /// slews the heading-hold target with the yaw stick.
338    fn attitude_setpoint(
339        &mut self,
340        dt: f32,
341        attitude_command: &AttitudeCommand,
342        estimated_state: &VehicleState,
343    ) -> AttitudeSetpoint {
344        // Commands from input devices can be out of range or NaN; saturate rather than panic
345        // (see `crate::math`).
346        let yaw = saturate_unit(attitude_command.yaw);
347        let max_stick = self.config.max_stick_angles_rad;
348        self.set_heading_target(self.heading + yaw * HEADING_SLEW_RATE * dt, estimated_state);
349
350        AttitudeSetpoint {
351            roll_rad: saturate_unit(attitude_command.roll) * max_stick.x,
352            pitch_rad: saturate_unit(attitude_command.pitch) * max_stick.y,
353            heading_rad: self.heading,
354            // Angle boost: hold the vertical thrust the stick asks for while tilted, as the
355            // altitude loop does (at most 2× past 60°, none when inverted). Saturated to
356            // [0, 1]; NaN means none.
357            thrust: self
358                .clip_thrust(attitude_command.throttle * tilt_boost(&estimated_state.attitude)),
359        }
360    }
361
362    /// Flies an absolute attitude: the heading becomes the heading-hold target, so stick
363    /// flight afterward keeps it.
364    fn absolute_attitude_setpoint(
365        &mut self,
366        command: &AbsoluteAttitudeCommand,
367        estimated_state: &VehicleState,
368    ) -> AttitudeSetpoint {
369        // A non-finite heading holds the current target.
370        let target_rad = if command.heading_rad.is_finite() {
371            command.heading_rad
372        } else {
373            self.heading
374        };
375        self.set_heading_target(target_rad, estimated_state);
376        AttitudeSetpoint {
377            roll_rad: command.roll_rad,
378            pitch_rad: command.pitch_rad,
379            heading_rad: self.heading,
380            thrust: self.clip_thrust(command.thrust),
381        }
382    }
383
384    /// Sets the heading-hold target to `target_rad`, wrapped.
385    fn set_heading_target(&mut self, target_rad: f32, estimated_state: &VehicleState) {
386        // Wrapped so sustained yaw input can't grow the target without bound; the yaw
387        // controller works on the wrapped error either way.
388        let target = wrap_angle(target_rad);
389        if target.is_finite() {
390            self.heading = target;
391        } else if estimated_state.heading_rad.is_finite() {
392            // A NaN target (e.g. primed from a NaN estimate) would otherwise disable heading
393            // hold for good; re-latch from the current estimate once it's valid.
394            self.heading = wrap_angle(estimated_state.heading_rad);
395        }
396    }
397
398    /// Flies toward the waypoint, holding the heading-hold target: the lateral loop gives
399    /// roll/pitch (once per navigation period, held in between) and the altitude loop gives
400    /// thrust (every tick), toward an altitude target that descends no faster than
401    /// `max_descent_mps`.
402    fn navigate(
403        &mut self,
404        dt: f32,
405        waypoint_command: &WaypointCommand,
406        estimated_state: &VehicleState,
407    ) -> AttitudeSetpoint {
408        let target = self.descend_toward(
409            dt,
410            waypoint_command.altitude_m,
411            estimated_state.position_m.z,
412        );
413        self.fly_to(dt, waypoint_command, target, estimated_state)
414    }
415
416    /// Lands at the command's position: flies there as to a waypoint, with an altitude target
417    /// that keeps descending at `land_speed_mps`, leashed [`LAND_LEASH_M`] below the vehicle.
418    fn land(
419        &mut self,
420        dt: f32,
421        land_command: &LandCommand,
422        estimated_state: &VehicleState,
423    ) -> AttitudeSetpoint {
424        let altitude_m = estimated_state.position_m.z;
425        let speed_mps = self.config.land_speed_mps;
426        // `f32::max` ignores a NaN side: a NaN altitude keeps lowering a latched target (the
427        // altitude loop holds hover meanwhile). With nothing latched, the NaN target holds hover.
428        let target_m = self
429            .lowered_altitude_target_m(dt, speed_mps, altitude_m)
430            .map_or(f32::NAN, |t| t.max(altitude_m - LAND_LEASH_M));
431        self.altitude_target_m = Some(target_m).filter(|t| t.is_finite());
432        let waypoint = WaypointCommand {
433            position_m: land_command.position_m,
434            ..Default::default()
435        };
436        let target = AltitudeTarget {
437            altitude_m: target_m,
438            velocity_mps: -speed_mps,
439        };
440        self.fly_to(dt, &waypoint, target, estimated_state)
441    }
442
443    /// The altitude loop's target on the way to `waypoint_m`: the waypoint itself when it is
444    /// above the latched target or within one step of it, otherwise the latched target lowered
445    /// by `max_descent_mps · dt`, with that descent rate fed forward.
446    fn descend_toward(&mut self, dt: f32, waypoint_m: f32, altitude_m: f32) -> AltitudeTarget {
447        let max_descent_mps = self.config.max_descent_mps;
448        let level = AltitudeTarget {
449            altitude_m: waypoint_m,
450            velocity_mps: 0.0,
451        };
452        let Some(step_m) = self.lowered_altitude_target_m(dt, max_descent_mps, altitude_m) else {
453            return level;
454        };
455        // `<` is false for NaN: a non-finite waypoint passes through, and the altitude loop
456        // holds hover on it.
457        let target = if waypoint_m < step_m {
458            AltitudeTarget {
459                altitude_m: step_m,
460                velocity_mps: -max_descent_mps,
461            }
462        } else {
463            level
464        };
465        self.altitude_target_m = Some(target.altitude_m).filter(|t| t.is_finite());
466        target
467    }
468
469    /// The latched altitude target, or with none latched the vehicle's `altitude_m`, lowered
470    /// by `rate_mps · dt`. `None` until there is a finite altitude to descend from; the
471    /// altitude loop holds hover on a non-finite estimate meanwhile (input policy).
472    fn lowered_altitude_target_m(&self, dt: f32, rate_mps: f32, altitude_m: f32) -> Option<f32> {
473        self.altitude_target_m
474            .or(Some(altitude_m).filter(|a| a.is_finite()))
475            .map(|start_m| start_m - rate_mps * dt)
476    }
477
478    /// Flies toward the waypoint's position and the altitude `target`, holding the heading-hold
479    /// target.
480    fn fly_to(
481        &mut self,
482        dt: f32,
483        waypoint_command: &WaypointCommand,
484        target: AltitudeTarget,
485        estimated_state: &VehicleState,
486    ) -> AttitudeSetpoint {
487        self.set_heading_target(self.heading, estimated_state);
488        let tilt_rad = self.tilt_toward(dt, waypoint_command, estimated_state);
489
490        let linear_thrust = self.altitude.control(
491            &self.config.altitude,
492            dt,
493            target,
494            AltitudeEstimate {
495                altitude_m: estimated_state.position_m.z,
496                velocity_mps: estimated_state.velocity_mps.z,
497                attitude: estimated_state.attitude,
498            },
499        );
500
501        // The altitude loop clamps its thrust to [0, 1]; landing on a bound means it clipped.
502        self.saturation.thrust = linear_thrust <= 0.0 || linear_thrust >= 1.0;
503        self.saturation.tilt = self.tilt_capped;
504
505        AttitudeSetpoint {
506            roll_rad: tilt_rad.x,
507            pitch_rad: tilt_rad.y,
508            heading_rad: self.heading,
509            thrust: linear_thrust,
510        }
511    }
512
513    /// Saturates a thrust request to `[0, 1]` (NaN means none), flagging `thrust` when it
514    /// was outside.
515    fn clip_thrust(&mut self, thrust: f32) -> f32 {
516        self.saturation.thrust = !(0.0..=1.0).contains(&thrust) && !thrust.is_nan();
517        saturate_throttle(thrust)
518    }
519
520    /// Roll/pitch in radians toward the waypoint from the lateral loop, run when
521    /// [`lateral_rate`](Self::lateral_rate) is due and held otherwise.
522    fn tilt_toward(
523        &mut self,
524        dt: f32,
525        waypoint_command: &WaypointCommand,
526        estimated_state: &VehicleState,
527    ) -> Vec2 {
528        let Some(step) = self.lateral_rate.due(dt, self.config.navigation_period_s) else {
529            return self.tilt_rad;
530        };
531
532        let target = LateralTarget {
533            position_m: waypoint_command.position_m,
534            velocity_mps: waypoint_command.velocity_mps.unwrap_or_else(Vec2::zeros),
535            max_speed_mps: waypoint_command.cruise_speed_mps,
536        };
537        let estimate = LateralEstimate {
538            position_m: estimated_state.position_m.xy(),
539            velocity_mps: estimated_state.velocity_mps.xy(),
540        };
541        let heading_rad = estimated_state.heading_rad;
542
543        // A non-finite target or estimate gets level for this tick only (input policy). The
544        // loop doesn't run, so the neutral output isn't held for a period and the next tick
545        // retries over the combined time.
546        let error = target.position_m - estimate.position_m;
547        if !(all_finite(&error)
548            && all_finite(&target.velocity_mps)
549            && all_finite(&estimate.velocity_mps)
550            && heading_rad.is_finite())
551        {
552            self.tilt_capped = false;
553            return Vec2::zeros();
554        }
555
556        let accel_mps2 = self
557            .lateral
558            .control(&self.config.lateral, step, target, estimate);
559        let requested = tilt_for_acceleration(accel_mps2, heading_rad);
560        self.tilt_capped = requested.norm() > self.config.max_tilt_rad;
561        self.tilt_rad = cap_magnitude(requested, self.config.max_tilt_rad);
562        self.lateral_rate.ran();
563        self.tilt_rad
564    }
565}
566
567/// Roll/pitch in radians, at `heading_rad`, that points thrust to give horizontal
568/// acceleration `accel_mps2` (north, east) at constant altitude: a tilt of `atan(|a| / g)`
569/// toward it. Ahead is nose down (negative pitch), to the right is right roll. The tilt is a
570/// vector of that length, split between the axes, exact for single-axis requests and close for
571/// diagonal ones at waypoint tilts. A non-finite acceleration or heading gives level.
572fn tilt_for_acceleration(accel_mps2: Vec2, heading_rad: f32) -> Vec2 {
573    let accel_norm = accel_mps2.norm();
574    if !accel_norm.is_finite() || accel_norm == 0.0 || !heading_rad.is_finite() {
575        return Vec2::zeros();
576    }
577    let tilt_rad = libm::atanf(accel_norm / GRAVITY);
578    // Rotate (north, east) into (ahead, right) of the heading.
579    let (sin, cos) = (libm::sinf(heading_rad), libm::cosf(heading_rad));
580    let ahead = accel_mps2.x * cos + accel_mps2.y * sin;
581    let right = -accel_mps2.x * sin + accel_mps2.y * cos;
582    Vec2::new(right, -ahead) * (tilt_rad / accel_norm)
583}