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::AbsoluteRate`] | [`Setpoint::BodyRate`]: rates passed through (the stabilizer saturates them); the heading-hold target follows the vehicle; thrust saturated to `[0, 1]`, not boosted |
8//! | [`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) |
9//! | [`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 |
10//! | [`ControlInput::Waypoint`] | [`Setpoint::Attitude`]: lateral position → velocity (shaped at [`max_accel_mps2`](crate::controllers::LateralControllerConfig::max_accel_mps2) when set, braking onto the waypoint along a braking curve) → acceleration → roll/pitch (every [`navigation_period_s`](CopterGuidanceConfig::navigation_period_s)), altitude loop → thrust (every tick), heading turned to the waypoint's [`heading_rad`](WaypointCommand::heading_rad) at [`heading_rate_radps`](CopterGuidanceConfig::heading_rate_radps) when set, otherwise along the leg at [`waypoint_yaw_radps`](CopterGuidanceConfig::waypoint_yaw_radps) (held on a leg shorter than [`waypoint_yaw_min_leg_m`](CopterGuidanceConfig::waypoint_yaw_min_leg_m)), or on station turned to put a wingtip into the wind when [`wind_heading_min_mps`](CopterGuidanceConfig::wind_heading_min_mps) is set; descents slewed at up to [`max_descent_mps`](CopterGuidanceConfig::max_descent_mps), starting from the vehicle's climb (shed at [`climb_decel_mps2`](CopterGuidanceConfig::climb_decel_mps2)) or from hover, speeding up and braking to stop on the waypoint at [`descent_accel_mps2`](CopterGuidanceConfig::descent_accel_mps2), at most [`ALTITUDE_LEASH_M`] below the vehicle |
11//! | [`ControlInput::Land`] | [`Setpoint::Attitude`]: as a waypoint at the land position, heading held (or turned to a wingtip into the wind, as on station), with an altitude target that keeps descending at [`land_speed_mps`](CopterGuidanceConfig::land_speed_mps), starting as a waypoint descent does and speeding up to it at [`descent_accel_mps2`](CopterGuidanceConfig::descent_accel_mps2), at most [`ALTITUDE_LEASH_M`] below the vehicle |
12//!
13//! Piloted inputs mark their setpoint [`idle`](crate::AttitudeSetpoint::idle) while the
14//! throttle is at or below [`IDLE_THROTTLE`] (or NaN), as ArduPilot spools to ground idle on
15//! `throttle_zero` in its piloted modes (`ArduCopter/mode_stabilize.cpp:19-40`). Waypoint and
16//! land setpoints never are: there's no land detector to tell a touchdown
17//! ([#395](https://github.com/wboayue/stable-flight/issues/395)).
18//!
19//! [`ThrustLimits`] bound the thrust while flying (all off by default): a floor, a sink guard
20//! for piloted flight, and a ceiling on the tilt boost. A tailsitter's control surfaces need
21//! the propwash, a sink turns the airflow against it, and differential thrust needs headroom.
22//!
23//! Switching modes doesn't jump the heading: attitude, absolute-attitude, waypoint, and land
24//! flight share one heading-hold target, and rate flight keeps it on the vehicle's heading.
25//! Waypoint flight slews that target along the leg, from where the leg began to its waypoint,
26//! as ArduPilot's and PX4's defaults face the next waypoint (`WP_YAW_BEHAVIOR`,
27//! `ArduCopter/config.h:468`; `MPC_YAW_MODE`, PX4 `FlightTaskAuto.cpp:571-628`), so a leg
28//! behind the vehicle isn't flown tail first. The leg's direction, not the bearing from the
29//! vehicle, keeps a braking overshoot or a hold drifting in wind from turning the nose around.
30//! The
31//! altitude and lateral loops start fresh each time waypoint or land flight is entered, with
32//! the altitude target starting from the vehicle's altitude.
33
34use core::f32::consts::FRAC_PI_4;
35
36use crate::estimation::wind::WindConfig;
37use crate::nalgebra::UnitQuaternion;
38use crate::{GRAVITY, Vec2, WindEstimate};
39
40use crate::commanders::touchdown::DESCENDING_MPS;
41use crate::commanders::waypoint::DEFAULT_ACCEPTANCE_RADIUS_M;
42use crate::controllers::*;
43use crate::controllers::{check, check_limit, check_positive, check_tilt, check_unit_interval};
44use crate::{
45    AbsoluteAttitudeCommand, AbsoluteRateCommand, AttitudeCommand, AttitudeSetpoint,
46    BodyRateSetpoint, Configurable, ControlInput, FlightRegime, Guidance, LandCommand,
47    RateSetpoint, Saturation, Setpoint, VehicleState, WaypointCommand,
48};
49
50use super::rate_divider::RateDivider;
51use crate::math::{
52    all_finite, assert_dt, cap_magnitude, guard_sink, saturate_throttle, saturate_unit,
53    shaped_closing_speed, tilt_boost, wrap_angle,
54};
55use hover_wind::HoverWind;
56use leg_heading::LegHeading;
57
58mod hover_wind;
59mod leg_heading;
60mod params;
61#[cfg(test)]
62mod tests;
63mod wind_heading;
64
65/// Heading-hold target slew rate at full yaw stick, in rad/s (~57°/s).
66const HEADING_SLEW_RATE: f32 = 1.0;
67
68/// Default [`CopterGuidanceConfig::max_tilt_rad`]: 27°, leaving thrust headroom to climb while
69/// translating (60% of the default 45° stabilizer limit).
70pub const DEFAULT_MAX_TILT_RAD: f32 = 27.0_f32.to_radians();
71
72/// Default [`CopterGuidanceConfig::max_stick_angles_rad`] per axis: 45°, the default stabilizer
73/// limit, so full stick is full tilt.
74pub const DEFAULT_MAX_STICK_ANGLE_RAD: f32 = FRAC_PI_4;
75
76/// Default [`CopterGuidanceConfig::navigation_period_s`]: 50 Hz, a fifth of the usual 250 Hz
77/// inner loop.
78pub const DEFAULT_NAVIGATION_PERIOD_S: f32 = 0.02;
79
80/// Default [`CopterGuidanceConfig::max_descent_mps`]: fast enough for the figure-eight's
81/// descending half (up to about 3 m/s at 7 m/s cruise).
82pub const DEFAULT_MAX_DESCENT_MPS: f32 = 3.0;
83
84/// Default [`CopterGuidanceConfig::descent_accel_mps2`]: ArduPilot's waypoint vertical
85/// acceleration limit, `WP_ACC_Z` (`libraries/AC_WPNav/AC_WPNav.cpp:14`).
86pub const DEFAULT_DESCENT_ACCEL_MPS2: f32 = 1.0;
87
88/// Default [`CopterGuidanceConfig::climb_decel_mps2`]: ArduPilot's quadplane vertical
89/// acceleration limit, `Q_PILOT_ACCEL_Z`, which it sheds a tailsitter's climb at after a
90/// handover (`ArduPlane/quadplane.cpp:64`, `:1008-1016`). On the sim tailsitter handed over
91/// at +3.4 m/s with a 1.5 m/s descent limit, it sank 1.61 m/s and rose 2.6 m; 1 m/s² rose
92/// 6.1 m (33 m at +8.1 m/s), g sank 1.75 m/s, and a target starting at rest 1.98 m/s (#462).
93pub const DEFAULT_CLIMB_DECEL_MPS2: f32 = 2.5;
94
95/// Default [`CopterGuidanceConfig::waypoint_yaw_radps`]: 60°/s, ArduPilot's waypoint yaw slew
96/// (`ATC_RATE_WPY_MAX`, `libraries/AC_AttitudeControl/AC_AttitudeControl.h:21`) and PX4's
97/// (`MPC_YAWRAUTO_MAX`, `multicopter_autonomous_params.yaml:21-42`).
98pub const DEFAULT_WAYPOINT_YAW_RADPS: f32 = 60.0_f32.to_radians();
99
100/// Default [`CopterGuidanceConfig::heading_rate_radps`]: the waypoint yaw slew, 60°/s, which
101/// ArduPilot also turns to a commanded yaw at (`ATC_RATE_WPY_MAX`).
102pub const DEFAULT_HEADING_RATE_RADPS: f32 = DEFAULT_WAYPOINT_YAW_RADPS;
103
104/// Default [`CopterGuidanceConfig::waypoint_yaw_min_leg_m`]: the waypoint follower's
105/// [`DEFAULT_ACCEPTANCE_RADIUS_M`], since a shorter leg is reached as it begins; PX4 likewise
106/// holds its yaw inside the acceptance radius (`FlightTaskAuto.cpp:608-628`).
107pub const DEFAULT_WAYPOINT_YAW_MIN_LEG_M: f32 = DEFAULT_ACCEPTANCE_RADIUS_M;
108
109/// Default [`CopterGuidanceConfig::heading_yield_rad`]: 30°. On the sim quadplane, 20°–45°
110/// all yield to the fin in 5 and 11 m/s winds and none yields in a calm 180° turn (#452).
111pub const DEFAULT_HEADING_YIELD_RAD: f32 = 30.0_f32.to_radians();
112
113/// Default [`CopterGuidanceConfig::heading_yield_s`]: 1 s. On the sim quadplane taking off in
114/// an 8 m/s crosswind it reaches 29 m in 15.2 s (14.9 s at 0.5 s, 21.9 s never yielding; 13.8 s
115/// in a headwind) (#431).
116pub const DEFAULT_HEADING_YIELD_S: f32 = 1.0;
117
118/// Height, in meters, above the altitude primed on the ground past which the vehicle is
119/// airborne and the wind estimate updates: on the ground the air's push is lost in contact
120/// forces and would read as calm.
121pub const AIRBORNE_HEIGHT_M: f32 = 1.0;
122
123/// Default [`CopterGuidanceConfig::land_speed_mps`], as PX4's `MPC_LAND_SPEED`.
124pub const DEFAULT_LAND_SPEED_MPS: f32 = 0.7;
125
126/// A piloted throttle (stick, rate, or absolute-attitude thrust) at or below this is idle:
127/// [`ThrustLimits::min_thrust`] and the sink guard don't raise it, so the motors can idle on the ground
128/// and the pilot can still cut them, and the setpoint is marked
129/// [`idle`](crate::AttitudeSetpoint::idle), so the stabilizer clears its integrals.
130pub const IDLE_THROTTLE: f32 = 0.05;
131
132/// How far, in meters, a descending altitude target (waypoint or land) may run below the
133/// vehicle. A vehicle still climbing when the descent begins, as a tailsitter handed over from
134/// a back transition, then gets at most `P · leash` of the loop's downward pull, so it sinks
135/// near `max_descent_mps` instead of past it (#400). Once the ground stops a landing vehicle,
136/// the altitude loop settles on a thrust below hover instead of winding down toward none.
137pub const ALTITUDE_LEASH_M: f32 = 1.0;
138
139/// Configuration for [CopterGuidance]: the altitude and lateral position loops and the
140/// waypoint-flight limits.
141///
142/// Plain data: [`CopterGuidance::new`] validates it ([`validate`](Self::validate)), and the
143/// guidance passes the loop configs to its controllers every tick.
144///
145/// # Examples
146///
147/// ```
148/// use stable_flight::controllers::Gains;
149/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
150///
151/// let mut config = CopterGuidanceConfig::default();
152/// config.altitude.gains = Gains { p: 2.0, i: 0.2, d: 0.1 };
153/// config.altitude.hover_thrust = 0.45; // airframe-specific
154/// let guidance = CopterGuidance::new(config);
155/// ```
156#[derive(Clone, Copy, Debug, PartialEq)]
157pub struct CopterGuidanceConfig {
158    /// Altitude loop: altitude error (m) → vertical acceleration (m/s²), fed to the thrust law
159    /// with gravity and tilt compensation. Its `hover_thrust` defaults to
160    /// [`DEFAULT_HOVER_THRUST`].
161    pub altitude: AltitudeControllerConfig,
162    /// Lateral loop: horizontal position error (m) → velocity (m/s, capped at the waypoint's
163    /// `cruise_speed_mps`) → acceleration (m/s²), flown as a tilt of `atan(|a| / g)` toward it.
164    pub lateral: LateralControllerConfig,
165    /// Seconds between runs of the lateral position loop; its roll/pitch output is held in
166    /// between. `0.0` runs it every tick. Rounded to the nearest tick (at a 4 ms loop, 20 ms
167    /// is every 5th tick); each run steps over the actual elapsed time. The altitude loop runs
168    /// every tick, since its tilt compensation needs the current attitude. Must be
169    /// non-negative and finite. Defaults to [`DEFAULT_NAVIGATION_PERIOD_S`].
170    pub navigation_period_s: f32,
171    /// Largest waypoint-flight tilt in radians, in `(0, π/2)`. Caps the magnitude of the
172    /// combined roll/pitch request, so a far waypoint can't ask for full tilt while the
173    /// altitude loop also wants full climb. It limits the request, not the achieved tilt: the
174    /// attitude loop can overshoot it briefly, and the stabilizer's own `max_angles_rad` still
175    /// applies. Piloted attitude flight is not capped. Defaults to [`DEFAULT_MAX_TILT_RAD`].
176    pub max_tilt_rad: f32,
177    /// Roll and pitch in radians that full stick (±1) commands in piloted attitude flight;
178    /// the stick scales linearly. The stabilizer saturates to its own `max_angles_rad`, so a
179    /// larger value only reaches that limit sooner. Must be non-negative and finite. Defaults
180    /// to [`DEFAULT_MAX_STICK_ANGLE_RAD`] on both axes.
181    pub max_stick_angles_rad: Vec2,
182    /// Fastest descent waypoint flight asks for, in m/s: a target below the vehicle is
183    /// approached by an altitude target lowered at up to this rate, so a low waypoint descends
184    /// instead of cutting thrust. Climbs aren't limited. It limits the target, not the achieved
185    /// rate: the vehicle can exceed it briefly while catching up. Must be positive and finite.
186    /// Defaults to [`DEFAULT_MAX_DESCENT_MPS`].
187    pub max_descent_mps: f32,
188    /// Acceleration a waypoint descent's target starts and ends with, in m/s², and a land's
189    /// starts with: the target's descent rate rises by at most this much per second, and a
190    /// waypoint descent's shrinks toward the waypoint so this much deceleration stops it
191    /// there, and is 0 on it.
192    /// Within `descent_accel_mps2 / P²` of the waypoint (P the altitude loop's, as ArduPilot
193    /// shapes with its vertical position P) the rate is linear in the gap instead, so retuning
194    /// that P moves where the braking changes shape. Must be positive and finite. Defaults to
195    /// [`DEFAULT_DESCENT_ACCEL_MPS2`].
196    pub descent_accel_mps2: f32,
197    /// Descent rate of a land ([`ControlInput::Land`]), in m/s. Must be finite and above the
198    /// touchdown detector's [`DESCENDING_MPS`] (0.2 m/s), so the detector sees the descent and
199    /// the land ends in a disarm. Defaults to [`DEFAULT_LAND_SPEED_MPS`].
200    pub land_speed_mps: f32,
201    /// Deceleration, in m/s², at which a waypoint or land target latched while the vehicle
202    /// climbs sheds that climb. The target starts moving up at the vehicle's climb rate (a
203    /// sink starts it at rest, as ArduPilot's tailsitter does, `AC_PosControl.cpp:849-863`),
204    /// so the altitude loop doesn't cut thrust to stop the climb at once: on a tailsitter
205    /// handed over from a back transition, that cut let the climb die and the hover fall
206    /// past the descent limit (#462). Higher: stops the climb lower, cuts more thrust doing
207    /// it; a climb of v rises about v² / (2 · this) further. Must be positive and finite.
208    /// Defaults to [`DEFAULT_CLIMB_DECEL_MPS2`].
209    pub climb_decel_mps2: f32,
210    /// Rate, in rad/s, at which waypoint flight turns the heading-hold target to the leg's
211    /// direction, the shorter way round; `0` holds the heading the leg began with, unless
212    /// [yielded](Self::heading_yield_s). A leg runs
213    /// from where the vehicle was when waypoint flight began or the waypoint changed, to the
214    /// waypoint. The vehicle translates while it turns. Land flight holds the heading (or turns
215    /// it with [`wind_heading_min_mps`](Self::wind_heading_min_mps)).
216    /// Must be non-negative and finite. Defaults to [`DEFAULT_WAYPOINT_YAW_RADPS`].
217    pub waypoint_yaw_radps: f32,
218    /// Rate, in rad/s, at which waypoint flight turns the heading-hold target to a waypoint's
219    /// [`heading_rad`](WaypointCommand::heading_rad), the shorter way round. Must be positive
220    /// and finite. Defaults to [`DEFAULT_HEADING_RATE_RADPS`].
221    pub heading_rate_radps: f32,
222    /// Shortest leg, in meters horizontally when it begins, whose direction waypoint flight
223    /// turns to; a shorter one (a hold, a waypoint that moves with the vehicle) keeps the
224    /// heading. A change applies from the next leg. Must be
225    /// non-negative and finite. Defaults to [`DEFAULT_WAYPOINT_YAW_MIN_LEG_M`].
226    pub waypoint_yaw_min_leg_m: f32,
227    /// Heading error, in radians, past which waypoint flight counts the heading as stuck while
228    /// the vehicle yaws toward the heading-hold target at under 0.1 rad/s. Must be
229    /// non-negative and finite. Defaults to [`DEFAULT_HEADING_YIELD_RAD`].
230    pub heading_yield_rad: f32,
231    /// Seconds the heading stays stuck before waypoint flight yields it: the heading-hold
232    /// target then follows the vehicle's heading until the waypoint changes, so a quadplane's
233    /// fin swinging the nose into the wind isn't fought for good (#431). `0` never yields.
234    /// Must be non-negative and finite. Defaults to [`DEFAULT_HEADING_YIELD_S`].
235    pub heading_yield_s: f32,
236    /// Least wind, in m/s, that turns the heading-hold target to put a wingtip into the wind
237    /// (the vehicle's `x` axis, a tailsitter's belly, 80° off where it comes from, 10° short
238    /// of square) while holding a waypoint or landing, at `heading_rate_radps`. The side is
239    /// the one nearer the heading when first picked; the wind estimate ([`wind`](Self::wind))
240    /// turns it only when its direction is known within 15°, and moves it only past 10°. A waypoint's
241    /// [`heading_rad`](WaypointCommand::heading_rad) wins, and legs longer than
242    /// `waypoint_yaw_min_leg_m` keep their own heading until within that of the waypoint.
243    /// `0` turns nothing. Must be non-negative and finite. Defaults to `0`.
244    pub wind_heading_min_mps: f32,
245    /// Thrust floor, sink guard, and tilt-boost ceiling; all off by default.
246    pub thrust: ThrustLimits,
247    /// The wind estimator's drag model and noises; off by default (no drag coefficients).
248    pub wind: WindConfig,
249}
250
251/// Bounds on [`CopterGuidance`]'s thrust while flying, for an airframe whose control comes
252/// from the propwash (a tailsitter). The defaults bound nothing.
253///
254/// # Examples
255///
256/// ```
257/// use stable_flight::guidance::copter::{CopterGuidanceConfig, ThrustLimits};
258///
259/// let config = CopterGuidanceConfig {
260///     thrust: ThrustLimits { min_thrust: 0.65, sink_limit_mps: 1.0, sink_gain: 0.15, max_boost_thrust: 0.9 },
261///     ..Default::default()
262/// };
263/// assert!(config.validate().is_ok());
264/// ```
265#[derive(Clone, Copy, Debug, PartialEq)]
266pub struct ThrustLimits {
267    /// Least linear thrust while flying, in `[0, 1)`; `0` (the default) is none. It keeps air
268    /// over a tailsitter's control surfaces, whose authority comes from the propwash: at low
269    /// throttle the elevons can't hold the nose up. ArduPilot's tailsitters floor the motors
270    /// the same way (`Q_TAILSIT_MIN_VO`, `ArduPlane/tailsitter.cpp`, applied by
271    /// `AP_MotorsTailsitter` only once spooled up). Every setpoint's thrust is raised to it,
272    /// after the tilt boost (so even inverted), except a piloted throttle at or below
273    /// [`IDLE_THROTTLE`], which passes through. Waypoint and land flight always get it. Set it
274    /// below the altitude loop's `hover_thrust`, or waypoint flight can't descend and a land
275    /// never touches down.
276    pub min_thrust: f32,
277    /// Sink rate, in m/s, beyond which piloted flight (attitude, rate, or absolute attitude,
278    /// above [`IDLE_THROTTLE`]) gets more thrust: [`sink_gain`](Self::sink_gain) per m/s of
279    /// sink past it, on top of the stick (and floor). Direct throttle can't hold a descent
280    /// rate, and a tailsitter sinking a few m/s has air flowing up against its propwash, which
281    /// takes the elevons' authority and drops the nose. Waypoint and land flight limit
282    /// their own descents ([`CopterGuidanceConfig::max_descent_mps`]). Must be non-negative
283    /// and finite; `0` (the default) disables it.
284    pub sink_limit_mps: f32,
285    /// Thrust added per m/s of sink past [`sink_limit_mps`](Self::sink_limit_mps), in s/m.
286    /// Must be non-negative and finite. Defaults to 0.
287    pub sink_gain: f32,
288    /// Most thrust the attitude-mode tilt boost may raise the stick to, in `(0, 1]`. A stick
289    /// above it passes through; the boost doesn't push past it, so a tilted vehicle keeps
290    /// motor headroom for the moments (a tailsitter rolling on differential thrust).
291    /// Defaults to 1 (no ceiling).
292    pub max_boost_thrust: f32,
293}
294
295impl Default for ThrustLimits {
296    /// No floor, no sink guard, and no boost ceiling.
297    fn default() -> Self {
298        ThrustLimits {
299            min_thrust: 0.0,
300            sink_limit_mps: 0.0,
301            sink_gain: 0.0,
302            max_boost_thrust: 1.0,
303        }
304    }
305}
306
307impl ThrustLimits {
308    /// Checks that `min_thrust` is in `[0, 1)`, that `sink_limit_mps` and `sink_gain` are
309    /// non-negative and finite, and that `max_boost_thrust` is in `(0, 1]`.
310    pub fn validate(&self) -> Result<(), InvalidConfig> {
311        check(
312            "min_thrust",
313            (0.0..1.0).contains(&self.min_thrust),
314            "in [0, 1)",
315        )?;
316        check_limit("sink_limit_mps", self.sink_limit_mps)?;
317        check_limit("sink_gain", self.sink_gain)?;
318        check_unit_interval("max_boost_thrust", self.max_boost_thrust)
319    }
320}
321
322impl Default for CopterGuidanceConfig {
323    /// The controller defaults (flight-checked on RealFlight's QuadCopterX), a 50 Hz lateral
324    /// loop, a 27° waypoint tilt cap, 45° at full stick, a 3 m/s descent limit, a climb under
325    /// way when a descent starts shed at 2.5 m/s², a 0.7 m/s land, waypoint legs over 3 m
326    /// turned to face along them at 60°/s, a waypoint's heading turned to at 60°/s, the
327    /// heading yielded after 1 s stuck over 30° off, no thrust floor or sink guard, and no
328    /// boost ceiling.
329    fn default() -> Self {
330        CopterGuidanceConfig {
331            altitude: AltitudeControllerConfig::default(),
332            lateral: LateralControllerConfig::default(),
333            navigation_period_s: DEFAULT_NAVIGATION_PERIOD_S,
334            max_tilt_rad: DEFAULT_MAX_TILT_RAD,
335            max_stick_angles_rad: Vec2::new(
336                DEFAULT_MAX_STICK_ANGLE_RAD,
337                DEFAULT_MAX_STICK_ANGLE_RAD,
338            ),
339            max_descent_mps: DEFAULT_MAX_DESCENT_MPS,
340            descent_accel_mps2: DEFAULT_DESCENT_ACCEL_MPS2,
341            land_speed_mps: DEFAULT_LAND_SPEED_MPS,
342            climb_decel_mps2: DEFAULT_CLIMB_DECEL_MPS2,
343            waypoint_yaw_radps: DEFAULT_WAYPOINT_YAW_RADPS,
344            heading_rate_radps: DEFAULT_HEADING_RATE_RADPS,
345            waypoint_yaw_min_leg_m: DEFAULT_WAYPOINT_YAW_MIN_LEG_M,
346            heading_yield_rad: DEFAULT_HEADING_YIELD_RAD,
347            heading_yield_s: DEFAULT_HEADING_YIELD_S,
348            wind_heading_min_mps: 0.0,
349            thrust: ThrustLimits::default(),
350            wind: WindConfig::default(),
351        }
352    }
353}
354
355impl CopterGuidanceConfig {
356    /// Checks both loop configs ([`AltitudeControllerConfig::validate`],
357    /// [`LateralControllerConfig::validate`]; errors carry the loop as their `section`), the
358    /// thrust limits ([`ThrustLimits::validate`], section `thrust`), that
359    /// `navigation_period_s` and `max_stick_angles_rad` are non-negative and finite, that
360    /// `max_tilt_rad` is in `(0, π/2)`, that `max_descent_mps`, `descent_accel_mps2`,
361    /// `climb_decel_mps2`, and `heading_rate_radps` are positive and finite, that
362    /// `land_speed_mps` is finite and above [`DESCENDING_MPS`], and that `waypoint_yaw_radps`,
363    /// `waypoint_yaw_min_leg_m`, `heading_yield_rad`, `heading_yield_s`, and
364    /// `wind_heading_min_mps` are non-negative and finite.
365    ///
366    /// # Examples
367    ///
368    /// ```
369    /// use stable_flight::guidance::copter::CopterGuidanceConfig;
370    ///
371    /// let mut config = CopterGuidanceConfig::default();
372    /// assert!(config.validate().is_ok());
373    /// config.altitude.hover_thrust = 1.5;
374    /// assert_eq!(config.validate().unwrap_err().to_string(), "altitude.hover_thrust must be in (0, 1]");
375    /// ```
376    pub fn validate(&self) -> Result<(), InvalidConfig> {
377        self.altitude
378            .validate()
379            .map_err(|e| e.in_section("altitude"))?;
380        self.lateral
381            .validate()
382            .map_err(|e| e.in_section("lateral"))?;
383        check_limit("navigation_period_s", self.navigation_period_s)?;
384        check_limit("max_stick_angles_rad.x", self.max_stick_angles_rad.x)?;
385        check_limit("max_stick_angles_rad.y", self.max_stick_angles_rad.y)?;
386        check_tilt("max_tilt_rad", self.max_tilt_rad)?;
387        check_positive("max_descent_mps", self.max_descent_mps)?;
388        check_positive("descent_accel_mps2", self.descent_accel_mps2)?;
389        check_positive("climb_decel_mps2", self.climb_decel_mps2)?;
390        check(
391            "land_speed_mps",
392            self.land_speed_mps > DESCENDING_MPS && self.land_speed_mps.is_finite(),
393            "above the touchdown detector's DESCENDING_MPS and finite",
394        )?;
395        check_limit("waypoint_yaw_radps", self.waypoint_yaw_radps)?;
396        check_positive("heading_rate_radps", self.heading_rate_radps)?;
397        check_limit("waypoint_yaw_min_leg_m", self.waypoint_yaw_min_leg_m)?;
398        check_limit("heading_yield_rad", self.heading_yield_rad)?;
399        check_limit("heading_yield_s", self.heading_yield_s)?;
400        check_limit("wind_heading_min_mps", self.wind_heading_min_mps)?;
401        self.thrust.validate().map_err(|e| e.in_section("thrust"))?;
402        self.wind.validate().map_err(|e| e.in_section("wind"))
403    }
404}
405
406/// Copter guidance: altitude and lateral position loops for waypoints, heading along the leg,
407/// and heading hold for piloted attitude flight.
408///
409/// # Examples
410///
411/// ```
412/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
413/// use stable_flight::{
414///     AttitudeCommand, ControlInput, FlightRegime, Guidance, Setpoint, VehicleState,
415/// };
416///
417/// let mut guidance = CopterGuidance::new(CopterGuidanceConfig::default());
418/// let state = VehicleState { heading_rad: 1.0, ..Default::default() };
419/// guidance.prime(&state);
420///
421/// let input = ControlInput::Attitude(AttitudeCommand { throttle: 0.5, ..Default::default() });
422/// let Setpoint::Attitude(setpoint) = guidance.guide(0.004, FlightRegime::Copter, &input, &state) else {
423///     unreachable!("attitude commands yield attitude setpoints");
424/// };
425/// assert!((setpoint.heading_rad - 1.0).abs() < 1e-6); // holds the primed heading
426/// assert_eq!(setpoint.thrust, 0.5);
427/// ```
428pub struct CopterGuidance {
429    /// Loop configs and limits, passed into the controllers every tick.
430    config: CopterGuidanceConfig,
431
432    altitude: AltitudeController,
433    lateral: LateralController,
434    /// Where the altitude loop is steered, in meters: the waypoint's altitude, or on the way
435    /// down to it, slewed at the descent limit and leashed [`ALTITUDE_LEASH_M`] below the
436    /// vehicle. `None` until waypoint or land flight latches it from the vehicle's altitude.
437    altitude_target_m: Option<f32>,
438    /// How fast the altitude target last descended, in m/s, negative while it climbs (0 when
439    /// level). Latched from the vehicle's climb, then raised toward the descent rate: at
440    /// `climb_decel_mps2` while negative, at `descent_accel_mps2` from 0.
441    descent_speed_mps: f32,
442
443    /// Heading-hold target for attitude, absolute-attitude, waypoint, and land commands.
444    heading: f32,
445    /// Turns the heading-hold target along the waypoint leg, or yields it.
446    leg_heading: LegHeading,
447
448    /// Paces the lateral loop.
449    lateral_rate: RateDivider,
450    /// The lateral loop's last roll/pitch in radians, held between its runs.
451    tilt_rad: Vec2,
452    /// The held tilt was capped at `max_tilt_rad` when the lateral loop last ran.
453    tilt_capped: bool,
454    /// The lateral loop's last acceleration request in m/s², before the tilt cap. While
455    /// `tilt_capped`, the loop's integral is held against it on the next run.
456    requested_accel_mps2: Vec2,
457
458    /// What the last `guide` call clipped.
459    saturation: Saturation,
460
461    /// Estimates the wind while airborne and not paused.
462    wind: HoverWind,
463}
464
465impl CopterGuidance {
466    /// Creates a new [CopterGuidance] with the specified configuration.
467    ///
468    /// # Panics
469    ///
470    /// If `config` is invalid ([`CopterGuidanceConfig::validate`]).
471    pub fn new(config: CopterGuidanceConfig) -> Self {
472        if let Err(error) = config.validate() {
473            panic!("invalid CopterGuidanceConfig: {error}");
474        }
475        CopterGuidance {
476            config,
477            altitude: AltitudeController::default(),
478            lateral: LateralController::default(),
479            altitude_target_m: None,
480            descent_speed_mps: 0.0,
481
482            heading: 0.0,
483            leg_heading: LegHeading::default(),
484
485            lateral_rate: RateDivider::default(),
486            tilt_rad: Vec2::zeros(),
487            tilt_capped: false,
488            requested_accel_mps2: Vec2::zeros(),
489            saturation: Saturation::default(),
490            wind: HoverWind::default(),
491        }
492    }
493
494    /// Pauses (or resumes) the wind estimate's updates, keeping the estimate: for a VTOL's
495    /// guidance while it flies outside hover (a transition, or pusher thrust along the body),
496    /// where the drag model doesn't hold.
497    pub(crate) fn set_wind_paused(&mut self, paused: bool) {
498        self.wind.set_paused(paused);
499    }
500}
501
502impl Configurable for CopterGuidance {
503    type Config = CopterGuidanceConfig;
504
505    fn config(&self) -> &CopterGuidanceConfig {
506        &self.config
507    }
508
509    /// Validates with [`CopterGuidanceConfig::validate`]. The heading-hold target and the
510    /// lateral loop's timing are kept; a new `navigation_period_s` applies from the next tick,
511    /// and the held waypoint tilt is re-capped to a lowered `max_tilt_rad` at once.
512    fn set_config(&mut self, config: CopterGuidanceConfig) -> Result<(), InvalidConfig> {
513        config.validate()?;
514        let old = &self.config;
515        self.altitude
516            .rescale_integral(&old.altitude, &config.altitude);
517        self.lateral.rescale_integral(&old.lateral, &config.lateral);
518        self.config = config;
519        if self.tilt_rad.norm() > config.max_tilt_rad {
520            self.tilt_capped = true;
521        }
522        self.tilt_rad = cap_magnitude(self.tilt_rad, config.max_tilt_rad);
523        Ok(())
524    }
525}
526
527impl Guidance for CopterGuidance {
528    fn guide(
529        &mut self,
530        dt: f32,
531        _regime: FlightRegime,
532        input: &ControlInput,
533        estimated_state: &VehicleState,
534    ) -> Setpoint {
535        assert_dt(dt);
536        self.saturation = Saturation::default();
537        self.wind.update(dt, &self.config.wind, estimated_state);
538
539        if !matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_)) {
540            // The position loops are idle: clear them so re-entering waypoint mode starts
541            // fresh, runs the lateral loop at once instead of holding a stale tilt, carries no
542            // integral from an earlier leg, and starts its altitude target from the vehicle.
543            self.altitude = AltitudeController::default();
544            self.lateral = LateralController::default();
545            self.requested_accel_mps2 = Vec2::zeros();
546            self.altitude_target_m = None;
547            self.descent_speed_mps = 0.0;
548            self.lateral_rate.reset();
549        }
550        if !matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_)) {
551            self.leg_heading.reset();
552        }
553
554        match input {
555            ControlInput::Attitude(attitude_command) => {
556                Setpoint::Attitude(self.attitude_setpoint(dt, attitude_command, estimated_state))
557            }
558            ControlInput::Rate(rate_command) => {
559                self.follow_heading(estimated_state);
560                let mut setpoint: RateSetpoint = rate_command.into();
561                (setpoint.thrust, setpoint.idle) = self.hold_piloted(
562                    rate_command.throttle,
563                    setpoint.thrust,
564                    estimated_state.velocity_mps.z,
565                );
566                Setpoint::Rate(setpoint)
567            }
568            ControlInput::Waypoint(waypoint_command) => {
569                Setpoint::Attitude(self.navigate(dt, waypoint_command, estimated_state))
570            }
571            ControlInput::AbsoluteAttitude(command) => {
572                Setpoint::Attitude(self.absolute_attitude_setpoint(command, estimated_state))
573            }
574            ControlInput::Land(command) => {
575                Setpoint::Attitude(self.land(dt, command, estimated_state))
576            }
577            ControlInput::AbsoluteRate(command) => {
578                Setpoint::BodyRate(self.absolute_rate_setpoint(command, estimated_state))
579            }
580        }
581    }
582
583    /// Clears the altitude and lateral controller state, the altitude target and its descent,
584    /// the leg, and any held waypoint tilt, and latches the current heading as the yaw-hold
585    /// target. Primed on the ground (no more than [`AIRBORNE_HEIGHT_M`] above the last
586    /// ground altitude, or never primed), it also latches the ground altitude and forgets the
587    /// wind; primed in the air (a VTOL back in hover), it keeps both. Re-armed on ground more
588    /// than [`AIRBORNE_HEIGHT_M`] above where it was last primed, it counts as airborne and
589    /// feeds the wind estimate from the ground until liftoff.
590    fn prime(&mut self, state: &VehicleState) {
591        self.wind.prime(state);
592        self.altitude = AltitudeController::default();
593        self.lateral = LateralController::default();
594        self.altitude_target_m = None;
595        self.descent_speed_mps = 0.0;
596        self.heading = state.heading_rad;
597        self.leg_heading.reset();
598        self.lateral_rate.reset();
599        self.tilt_rad = Vec2::zeros();
600        self.tilt_capped = false;
601        self.requested_accel_mps2 = Vec2::zeros();
602        self.saturation = Saturation::default();
603    }
604
605    /// `tilt` when the waypoint tilt request was capped at
606    /// [`max_tilt_rad`](CopterGuidanceConfig::max_tilt_rad) (held with the tilt between
607    /// lateral-loop runs), and `thrust` when the altitude loop's thrust, attitude mode's
608    /// boosted throttle, or an absolute attitude's thrust was clipped to `[0, 1]`, held at
609    /// [`max_boost_thrust`](ThrustLimits::max_boost_thrust), raised to
610    /// [`min_thrust`](ThrustLimits::min_thrust), or raised by the sink guard. A tilt
611    /// beyond the stabilizer's limit in an absolute attitude is the stabilizer's to flag.
612    fn saturation(&self) -> Saturation {
613        self.saturation
614    }
615
616    /// The wind, estimated from the drag model in
617    /// [`wind`](CopterGuidanceConfig::wind) on every tick more than [`AIRBORNE_HEIGHT_M`]
618    /// above the altitude primed on the ground, the vehicle's frame taken as the thrust frame
619    /// (a tailsitter's hover view under [`View`](crate::View)), except while a VTOL's guidance
620    /// flies outside hover; `None` before the first update, or without drag coefficients.
621    fn wind(&self) -> Option<WindEstimate> {
622        self.wind.estimate()
623    }
624}
625
626impl CopterGuidance {
627    /// Scales the roll/pitch sticks to radians, boosts throttle for the measured tilt, and
628    /// slews the heading-hold target with the yaw stick.
629    fn attitude_setpoint(
630        &mut self,
631        dt: f32,
632        attitude_command: &AttitudeCommand,
633        estimated_state: &VehicleState,
634    ) -> AttitudeSetpoint {
635        // Commands from input devices can be out of range or NaN; saturate rather than panic
636        // (see `crate::math`).
637        let yaw = saturate_unit(attitude_command.yaw);
638        let max_stick = self.config.max_stick_angles_rad;
639        self.set_heading_target(self.heading + yaw * HEADING_SLEW_RATE * dt, estimated_state);
640
641        // Angle boost: hold the vertical thrust the stick asks for while tilted, as the
642        // altitude loop does (at most 2× past 60°, none when inverted), up to
643        // `max_boost_thrust`. Saturated to [0, 1]; NaN means none.
644        let throttle = attitude_command.throttle;
645        let boosted = self.boost(throttle, &estimated_state.attitude);
646        let boosted = self.clip_thrust(boosted);
647        let (thrust, idle) = self.hold_piloted(throttle, boosted, estimated_state.velocity_mps.z);
648
649        AttitudeSetpoint {
650            roll_rad: saturate_unit(attitude_command.roll) * max_stick.x,
651            pitch_rad: saturate_unit(attitude_command.pitch) * max_stick.y,
652            heading_rad: self.heading,
653            thrust,
654            transition: false,
655            idle,
656        }
657    }
658
659    /// Rate flight: tracks the vehicle so attitude or waypoint flight holds the heading it has
660    /// when rate flight ends, not the one it had when rate flight began.
661    fn follow_heading(&mut self, estimated_state: &VehicleState) {
662        if estimated_state.heading_rad.is_finite() {
663            self.heading = wrap_angle(estimated_state.heading_rad);
664        }
665    }
666
667    /// Flies absolute rates as given, with the thrust saturated (not boosted).
668    fn absolute_rate_setpoint(
669        &mut self,
670        command: &AbsoluteRateCommand,
671        estimated_state: &VehicleState,
672    ) -> BodyRateSetpoint {
673        self.follow_heading(estimated_state);
674        let mut setpoint = BodyRateSetpoint::from(command);
675        (setpoint.thrust, setpoint.idle) = self.hold_absolute(command.thrust, estimated_state);
676        setpoint
677    }
678
679    /// Flies an absolute attitude: the heading becomes the heading-hold target, so stick
680    /// flight afterward keeps it.
681    fn absolute_attitude_setpoint(
682        &mut self,
683        command: &AbsoluteAttitudeCommand,
684        estimated_state: &VehicleState,
685    ) -> AttitudeSetpoint {
686        // A non-finite heading holds the current target.
687        let target_rad = if command.heading_rad.is_finite() {
688            command.heading_rad
689        } else {
690            self.heading
691        };
692        self.set_heading_target(target_rad, estimated_state);
693        let (thrust, idle) = self.hold_absolute(command.thrust, estimated_state);
694        AttitudeSetpoint {
695            roll_rad: command.roll_rad,
696            pitch_rad: command.pitch_rad,
697            heading_rad: self.heading,
698            thrust,
699            transition: false,
700            idle,
701        }
702    }
703
704    /// Sets the heading-hold target to `target_rad`, wrapped.
705    fn set_heading_target(&mut self, target_rad: f32, estimated_state: &VehicleState) {
706        // Wrapped so sustained yaw input can't grow the target without bound; the yaw
707        // controller works on the wrapped error either way.
708        let target = wrap_angle(target_rad);
709        if target.is_finite() {
710            self.heading = target;
711        } else if estimated_state.heading_rad.is_finite() {
712            // A NaN target (e.g. primed from a NaN estimate) would otherwise disable heading
713            // hold for good; re-latch from the current estimate once it's valid.
714            self.heading = wrap_angle(estimated_state.heading_rad);
715        }
716    }
717
718    /// Flies toward the waypoint, turning the heading-hold target to the waypoint's heading
719    /// (`heading_rate_radps`), along the leg (`waypoint_yaw_radps`), or yielding it
720    /// (`heading_yield_s`): the lateral loop gives roll/pitch (once per navigation period, held
721    /// in between) and the altitude loop gives thrust (every tick), toward an altitude target
722    /// that descends no faster than `max_descent_mps`, speeding up and braking at
723    /// `descent_accel_mps2`, and no further than [`ALTITUDE_LEASH_M`] below the vehicle.
724    fn navigate(
725        &mut self,
726        dt: f32,
727        waypoint_command: &WaypointCommand,
728        estimated_state: &VehicleState,
729    ) -> AttitudeSetpoint {
730        let target = self.descend_toward(
731            dt,
732            waypoint_command.altitude_m,
733            estimated_state.position_m.z,
734            estimated_state.velocity_mps.z,
735        );
736        let wind = self.wind.estimate();
737        let heading_rad = self.leg_heading.target_rad(
738            dt,
739            &self.config,
740            self.heading,
741            waypoint_command,
742            wind.as_ref(),
743            estimated_state,
744        );
745        self.set_heading_target(heading_rad, estimated_state);
746        self.fly_to(dt, waypoint_command, target, estimated_state)
747    }
748
749    /// Lands at the command's position: flies there as to a waypoint, heading held or turned to
750    /// a wingtip into the wind (`wind_heading_min_mps`), with an altitude target
751    /// that keeps descending at `land_speed_mps`, leashed [`ALTITUDE_LEASH_M`] below the vehicle.
752    /// The descent starts and speeds up to it as a waypoint descent does
753    /// ([`descent_start_m`](Self::descent_start_m),
754    /// [`ramped_descent_mps`](Self::ramped_descent_mps)): stepping to it cut the RealFlight
755    /// eXplora's thrust from 0.89 to 0.76 in one tick (#476).
756    fn land(
757        &mut self,
758        dt: f32,
759        land_command: &LandCommand,
760        estimated_state: &VehicleState,
761    ) -> AttitudeSetpoint {
762        let altitude_m = estimated_state.position_m.z;
763        let start_m = self.descent_start_m(altitude_m, estimated_state.velocity_mps.z);
764        let speed_mps = self.ramped_descent_mps(dt, self.config.land_speed_mps);
765        // With nothing latched, the NaN target holds hover.
766        let target_m = start_m.map_or(f32::NAN, |start_m| {
767            lowered(start_m, speed_mps * dt, altitude_m)
768        });
769        self.altitude_target_m = Some(target_m).filter(|t| t.is_finite());
770        // With nothing latched nothing descends, so a waypoint descent next starts from rest.
771        self.descent_speed_mps = if self.altitude_target_m.is_some() {
772            speed_mps
773        } else {
774            0.0
775        };
776        let waypoint = WaypointCommand {
777            position_m: land_command.position_m,
778            ..Default::default()
779        };
780        let target = AltitudeTarget {
781            altitude_m: target_m,
782            velocity_mps: -speed_mps,
783        };
784        let wind = self.wind.estimate();
785        let heading_rad = self.leg_heading.land_target_rad(
786            dt,
787            &self.config,
788            self.heading,
789            wind.as_ref(),
790            estimated_state,
791        );
792        self.set_heading_target(heading_rad, estimated_state);
793        self.fly_to(dt, &waypoint, target, estimated_state)
794    }
795
796    /// The altitude loop's target on the way to `waypoint_m`: the waypoint itself when it is
797    /// above the latched target or the target reaches it, otherwise the latched target moved
798    /// by [`descent_rate_mps`](Self::descent_rate_mps) of its height above the waypoint (and
799    /// leashed), with the new target's rate fed forward. That rate starts at the vehicle's
800    /// climb ([`descent_start_m`](Self::descent_start_m)) and rises from the last tick's by at most
801    /// [`ramped_descent_mps`](Self::ramped_descent_mps)'s step, so a descent starts without a
802    /// thrust step: an instant 1.5 m/s cut the RealFlight eXplora's thrust from 0.85 to its
803    /// 0.65 floor in 0.25 s and dropped its nose 10° (#417). It falls to 0 at the waypoint, so
804    /// the target, its feedforward, and the thrust stay continuous where the waypoint takes
805    /// over: arriving, and where the leash puts the target on the waypoint (#445).
806    fn descend_toward(
807        &mut self,
808        dt: f32,
809        waypoint_m: f32,
810        altitude_m: f32,
811        climb_mps: f32,
812    ) -> AltitudeTarget {
813        let level = AltitudeTarget {
814            altitude_m: waypoint_m,
815            velocity_mps: 0.0,
816        };
817        let Some(start_m) = self.descent_start_m(altitude_m, climb_mps) else {
818            self.descent_speed_mps = 0.0;
819            return level;
820        };
821        let rate_mps = self.ramped_descent_mps(dt, self.descent_rate_mps(start_m - waypoint_m));
822        let step_m = lowered(start_m, rate_mps * dt, altitude_m);
823        // `<` is false for NaN: a non-finite waypoint passes through, and the altitude loop
824        // holds hover on it.
825        let target = if waypoint_m < step_m {
826            AltitudeTarget {
827                altitude_m: step_m,
828                velocity_mps: -self.descent_rate_mps(step_m - waypoint_m).min(rate_mps),
829            }
830        } else {
831            level
832        };
833        self.descent_speed_mps = -target.velocity_mps;
834        self.altitude_target_m = Some(target.altitude_m).filter(|t| t.is_finite());
835        target
836    }
837
838    /// Where a descent's target moves from: the latched altitude target, or with none latched
839    /// the vehicle's `altitude_m`, the target's speed then started at the vehicle's
840    /// `climb_mps` (up positive), so the target rises with the vehicle instead of holding below
841    /// it; a sink, or an unknown climb, starts it at rest. `None` until there is a finite
842    /// altitude to descend from; the altitude loop holds hover on a non-finite estimate
843    /// meanwhile (input policy).
844    fn descent_start_m(&mut self, altitude_m: f32, climb_mps: f32) -> Option<f32> {
845        if self.altitude_target_m.is_some() {
846            return self.altitude_target_m;
847        }
848        if !altitude_m.is_finite() {
849            return None;
850        }
851        // `max` drops a NaN climb: the target starts at rest.
852        self.descent_speed_mps = -climb_mps.max(0.0);
853        Some(altitude_m)
854    }
855
856    /// `limit_mps`, or less while the target sheds a climb or speeds up to it: at most the
857    /// last tick's speed plus `climb_decel_mps2 · dt` while climbing, `descent_accel_mps2 · dt`
858    /// from level. A slower limit takes over at once, which only adds thrust.
859    fn ramped_descent_mps(&self, dt: f32, limit_mps: f32) -> f32 {
860        let accel_mps2 = if self.descent_speed_mps < 0.0 {
861            self.config.climb_decel_mps2
862        } else {
863            self.config.descent_accel_mps2
864        };
865        limit_mps.min(self.descent_speed_mps + accel_mps2 * dt)
866    }
867
868    /// The descent rate toward a waypoint `height_m` below the target, in m/s: what
869    /// `descent_accel_mps2` can stop on the waypoint, linear at the altitude loop's P near it
870    /// ([`shaped_closing_speed`]), at most `max_descent_mps`; 0 at or below it and for NaN.
871    /// Near the waypoint the target closes the gap with time constant 1/P, so it eases onto
872    /// the waypoint rather than reaching it in a step.
873    fn descent_rate_mps(&self, height_m: f32) -> f32 {
874        let config = &self.config;
875        shaped_closing_speed(height_m, config.altitude.gains.p, config.descent_accel_mps2)
876            .min(config.max_descent_mps)
877    }
878
879    /// Flies toward the waypoint's position and the altitude `target`, holding the heading-hold
880    /// target.
881    fn fly_to(
882        &mut self,
883        dt: f32,
884        waypoint_command: &WaypointCommand,
885        target: AltitudeTarget,
886        estimated_state: &VehicleState,
887    ) -> AttitudeSetpoint {
888        self.set_heading_target(self.heading, estimated_state);
889        let tilt_rad = self.tilt_toward(dt, waypoint_command, estimated_state);
890
891        let linear_thrust = self.altitude.control(
892            &self.config.altitude,
893            dt,
894            target,
895            AltitudeEstimate {
896                altitude_m: estimated_state.position_m.z,
897                velocity_mps: estimated_state.velocity_mps.z,
898                attitude: estimated_state.attitude,
899            },
900        );
901
902        // The altitude loop clamps its thrust to [0, 1]; landing on a bound means it clipped.
903        self.saturation.thrust = linear_thrust <= 0.0 || linear_thrust >= 1.0;
904        self.saturation.tilt = self.tilt_capped;
905
906        AttitudeSetpoint {
907            roll_rad: tilt_rad.x,
908            pitch_rad: tilt_rad.y,
909            heading_rad: self.heading,
910            thrust: self.floor_thrust(linear_thrust),
911            transition: false,
912            // Never ground idle: the altitude loop's zero is a vehicle in the air shedding
913            // climb. TODO(#395): idle once a land detector reports a touchdown.
914            idle: false,
915        }
916    }
917
918    /// Saturates a thrust request to `[0, 1]` (NaN means none), flagging `thrust` when it
919    /// was outside.
920    fn clip_thrust(&mut self, thrust: f32) -> f32 {
921        // `|=`: the boost may have flagged it already this tick.
922        self.saturation.thrust |= !(0.0..=1.0).contains(&thrust) && !thrust.is_nan();
923        saturate_throttle(thrust)
924    }
925
926    /// The stick `throttle` boosted for the measured tilt, held at or below
927    /// `max_boost_thrust` unless the stick itself is above it; flags `thrust` when held.
928    fn boost(&mut self, throttle: f32, attitude: &UnitQuaternion<f32>) -> f32 {
929        let boosted = throttle * tilt_boost(attitude);
930        // `max` ignores a NaN throttle, and `>` is false for a NaN boost: NaN passes through.
931        let ceiling = self.config.thrust.max_boost_thrust.max(throttle);
932        if boosted > ceiling {
933            self.saturation.thrust = true;
934            ceiling
935        } else {
936            boosted
937        }
938    }
939
940    /// An absolute command's `thrust`, saturated to `[0, 1]` (not boosted), then held as a
941    /// piloted throttle ([`hold_piloted`](Self::hold_piloted)), and whether it is idle.
942    fn hold_absolute(&mut self, thrust: f32, estimated_state: &VehicleState) -> (f32, bool) {
943        let clipped = self.clip_thrust(thrust);
944        self.hold_piloted(thrust, clipped, estimated_state.velocity_mps.z)
945    }
946
947    /// The piloted `thrust` and whether the pilot's `throttle` is idle (at or below
948    /// [`IDLE_THROTTLE`], or NaN): an idle throttle passes `thrust` through; any other is
949    /// raised to `min_thrust`, then gets the sink guard for the vertical speed `climb_mps` (up
950    /// positive).
951    fn hold_piloted(&mut self, throttle: f32, thrust: f32, climb_mps: f32) -> (f32, bool) {
952        if throttle > IDLE_THROTTLE {
953            let floored = self.floor_thrust(thrust);
954            (self.guard_sink(floored, climb_mps), false)
955        } else {
956            (thrust, true)
957        }
958    }
959
960    /// [`guard_sink`] with the configured limit and gain, flagging `thrust` when it acts.
961    fn guard_sink(&mut self, thrust: f32, climb_mps: f32) -> f32 {
962        let limits = &self.config.thrust;
963        let Some(raised) = guard_sink(thrust, climb_mps, limits.sink_limit_mps, limits.sink_gain)
964        else {
965            return thrust;
966        };
967        self.saturation.thrust = true;
968        raised
969    }
970
971    /// Raises `thrust` to `min_thrust`, flagging `thrust` when it does.
972    fn floor_thrust(&mut self, thrust: f32) -> f32 {
973        let min_thrust = self.config.thrust.min_thrust;
974        if thrust < min_thrust {
975            self.saturation.thrust = true;
976            min_thrust
977        } else {
978            thrust
979        }
980    }
981
982    /// Roll/pitch in radians toward the waypoint from the lateral loop, run when
983    /// [`lateral_rate`](Self::lateral_rate) is due and held otherwise.
984    fn tilt_toward(
985        &mut self,
986        dt: f32,
987        waypoint_command: &WaypointCommand,
988        estimated_state: &VehicleState,
989    ) -> Vec2 {
990        let Some(step) = self.lateral_rate.due(dt, self.config.navigation_period_s) else {
991            return self.tilt_rad;
992        };
993
994        let target = LateralTarget {
995            position_m: waypoint_command.position_m,
996            velocity_mps: waypoint_command.velocity_mps.unwrap_or_else(Vec2::zeros),
997            max_speed_mps: waypoint_command.cruise_speed_mps,
998        };
999        let estimate = LateralEstimate {
1000            position_m: estimated_state.position_m.xy(),
1001            velocity_mps: estimated_state.velocity_mps.xy(),
1002        };
1003        let heading_rad = estimated_state.heading_rad;
1004
1005        // A non-finite target or estimate gets level for this tick only (input policy). The
1006        // loop doesn't run, so the neutral output isn't held for a period and the next tick
1007        // retries over the combined time.
1008        let error = target.position_m - estimate.position_m;
1009        if !(all_finite(&error)
1010            && all_finite(&target.velocity_mps)
1011            && all_finite(&estimate.velocity_mps)
1012            && heading_rad.is_finite())
1013        {
1014            self.tilt_capped = false;
1015            return Vec2::zeros();
1016        }
1017
1018        let limit_mps2 = if self.tilt_capped {
1019            self.requested_accel_mps2
1020        } else {
1021            Vec2::zeros()
1022        };
1023        let accel_mps2 =
1024            self.lateral
1025                .control(&self.config.lateral, step, target, estimate, limit_mps2);
1026        self.requested_accel_mps2 = accel_mps2;
1027        let requested = tilt_for_acceleration(accel_mps2, heading_rad);
1028        self.tilt_capped = requested.norm() > self.config.max_tilt_rad;
1029        self.tilt_rad = cap_magnitude(requested, self.config.max_tilt_rad);
1030        self.lateral_rate.ran();
1031        self.tilt_rad
1032    }
1033}
1034
1035/// Roll/pitch in radians, at `heading_rad`, that points thrust to give horizontal
1036/// acceleration `accel_mps2` (north, east) at constant altitude: a tilt of `atan(|a| / g)`
1037/// toward it. Ahead is nose down (negative pitch), to the right is right roll. The tilt is a
1038/// vector of that length, split between the axes, exact for single-axis requests and close for
1039/// diagonal ones at waypoint tilts. A non-finite acceleration or heading gives level.
1040fn tilt_for_acceleration(accel_mps2: Vec2, heading_rad: f32) -> Vec2 {
1041    let accel_norm = accel_mps2.norm();
1042    if !accel_norm.is_finite() || accel_norm == 0.0 || !heading_rad.is_finite() {
1043        return Vec2::zeros();
1044    }
1045    let tilt_rad = libm::atanf(accel_norm / GRAVITY);
1046    // Rotate (north, east) into (ahead, right) of the heading.
1047    let (sin, cos) = (libm::sinf(heading_rad), libm::cosf(heading_rad));
1048    let ahead = accel_mps2.x * cos + accel_mps2.y * sin;
1049    let right = -accel_mps2.x * sin + accel_mps2.y * cos;
1050    Vec2::new(right, -ahead) * (tilt_rad / accel_norm)
1051}
1052
1053/// A descent target `start_m` lowered by `step_m`, but no further than [`ALTITUDE_LEASH_M`]
1054/// below the vehicle's `altitude_m`. `f32::max` ignores a NaN side: a NaN altitude keeps
1055/// lowering a latched target.
1056fn lowered(start_m: f32, step_m: f32, altitude_m: f32) -> f32 {
1057    (start_m - step_m).max(altitude_m - ALTITUDE_LEASH_M)
1058}