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