Skip to main content

stable_flight/stabilizers/
plane.rs

1//! Fixed-wing stabilization: [`PlaneStabilizer`] tracks a [`Setpoint::Plane`] attitude or a
2//! [`Setpoint::PlaneRate`] body rate with control surfaces, scaled for airspeed.
3//!
4//! | Setpoint | Behavior |
5//! |---|---|
6//! | [`Setpoint::Plane`] | Bank and pitch (saturated to [`max_bank_rad`](PlaneStabilizerConfig::max_bank_rad) / [`max_pitch_rad`](PlaneStabilizerConfig::max_pitch_rad), pitch to ±π/2 for a [`transition`](PlaneSetpoint::transition) ramp) → rate targets = error / time constant, plus the coordinated-turn rates for the current bank and airspeed → rate loop |
7//! | [`Setpoint::PlaneRate`] | Absolute body rates (saturated to [`max_body_rate_radps`](PlaneStabilizerConfig::max_body_rate_radps)) → rate loop, at any attitude: acro, rolls, loops |
8//! | others | Neutral (zero thrust and moments) |
9//!
10//! The structure is PX4's fixed-wing attitude and rate control
11//! (`FixedwingAttitudeControl.cpp`, `FixedwingRateControl.cpp`), described, not copied:
12//!
13//! - The attitude error is the yaw-free part of the reduced attitude error the copter uses:
14//!   the rotation that turns the body `z` axis onto the setpoint's, in body axes, so it's
15//!   defined at any attitude, inverted included.
16//! - A level turn at bank φ and speed V turns at ψ̇ = g·tan φ / V, which in body axes is a pitch
17//!   rate ψ̇·sin φ·cos θ and a yaw rate ψ̇·cos φ·cos θ; both are fed forward so the wing turns
18//!   without slipping or losing its nose, faded out between 70° and 75° of bank (PX4's
19//!   turn-coordination fade).
20//! - The rate loop ([`PlaneRateController`]) scales by airspeed and freezes its integral
21//!   below [`min_airspeed_mps`](PlaneStabilizerConfig::min_airspeed_mps). Without an airspeed
22//!   it assumes trim airspeed (PX4).
23//! - Each axis adds its [`trim`](PlaneRateControllerConfig::trim), the moment the wing needs
24//!   in steady flight, scaled like the feedback (PX4's `TRIM_ROLL`/`_PITCH`/`_YAW`).
25//!
26//! Unlike the copter's, the integrals aren't cleared at zero thrust: gliding is normal flight.
27//! Rate flight (acro, a maneuver) leaves them as it found them: the rate integrals are saved
28//! when a [`Setpoint::PlaneRate`] follows any other setpoint and restored when a
29//! [`Setpoint::Plane`] follows it, so what a roll or loop winds up doesn't carry into the
30//! attitude flight after it.
31//!
32//! # Tuning
33//!
34//! An autotune stage ([`start_probe`](crate::tuning::Tunable::start_probe)) hands one loop to a
35//! [`Probe`](crate::tuning::Probe). Before the loop's controller runs, the probe sees its
36//! [`LoopSignals`](crate::tuning::LoopSignals) and replaces the loop's setpoint (a step, or an
37//! identification's square wave).
38//!
39//! | [`PlaneLoop`] | Setpoint, error |
40//! |---|---|
41//! | `RollRate`, `PitchRate` | desired body rate; desired − measured |
42//! | `Roll`, `Pitch` | saturated bank or pitch; the attitude error on that axis |
43//!
44//! The signals' `saturated` is the axis's moment at full deflection on the last tick: a step
45//! clipped there measures the surfaces' limit, not the loop. An angle step's rate target at the
46//! attitude rate limit isn't a clip: the limit is part of the loop the step measures, and a
47//! 30° roll step asks for more than the default 70°/s at τ 0.4 s.
48//!
49//! - A rate stage flies on attitude and rate setpoints alike; an angle stage only on attitude
50//!   setpoints: a [`Setpoint::PlaneRate`] idles the attitude loops and interrupts it
51//!   ([`ProbeStatus::Interrupted`](crate::tuning::ProbeStatus::Interrupted)).
52//! - Any other setpoint, or a [`transition`](PlaneSetpoint::transition) ramp, interrupts
53//!   either: the plane side isn't flying, or is flying a handoff no step should disturb.
54//! - **Handoff:** when the probe finishes, is stopped, or is interrupted, the loop takes its
55//!   setpoint back on the next tick. The loops have no derivative to reset, and the rate
56//!   integral stays.
57//! - The stage is runtime state, not config; [`prime`](crate::Stabilizer::prime) ends it.
58
59use crate::controllers::{
60    InvalidConfig, PlaneRateController, PlaneRateControllerConfig, check, check_limit,
61    check_positive,
62};
63use crate::math::{
64    DEG, assert_dt, attitude_error, bank_rad, clamp_symmetric, pitch_limit_rad, saturate_rates,
65    saturate_symmetric, thrust_curve,
66};
67use crate::{
68    BodyRateSetpoint, Configurable, ControlOutput, GRAVITY, PlaneSetpoint, Saturation, Setpoint,
69    Stabilizer, Vec2, Vec3, VehicleState,
70};
71
72mod params;
73#[cfg(test)]
74mod tests;
75mod tuning;
76
77pub use tuning::{PlaneAxisGains, PlaneLoop};
78
79/// Bank where turn coordination starts to fade, and where it's gone (PX4's 70°–75°).
80const COORDINATION_FADE_RAD: (f32, f32) = (70.0 * DEG, 75.0 * DEG);
81
82/// [`PlaneStabilizer`] settings.
83#[derive(Clone, Copy, Debug, PartialEq)]
84pub struct PlaneStabilizerConfig {
85    /// The rate loop's gains and integral limit.
86    pub rate: PlaneRateControllerConfig,
87    /// How fast the attitude loops close their error, roll (`x`) and pitch (`y`), in s: the
88    /// rate target is the error divided by it.
89    pub time_constant_s: Vec2,
90    /// Largest roll (`x`) and pitch (`y`) rate the attitude loops ask for, in rad/s.
91    pub max_attitude_rate_radps: Vec2,
92    /// Largest body rate an absolute-rate setpoint gets, per axis, in rad/s.
93    pub max_body_rate_radps: Vec3,
94    /// Largest bank an attitude setpoint gets, in radians.
95    pub max_bank_rad: f32,
96    /// Largest pitch, up or down, an attitude setpoint gets, in radians; a
97    /// [`transition`](PlaneSetpoint::transition) ramp's isn't held to it.
98    pub max_pitch_rad: f32,
99    /// The airspeed the gains are tuned at (scale 1), in m/s; assumed without an airspeed.
100    pub trim_airspeed_mps: f32,
101    /// Below this airspeed the scale stops growing and the rate integrals hold, in m/s.
102    pub min_airspeed_mps: f32,
103    /// Above this airspeed the scale stops shrinking, in m/s.
104    pub max_airspeed_mps: f32,
105    /// Linear throttle → motor command exponent (1 passes throttle through). A tailsitter uses
106    /// its hover stabilizer's, so a handoff keeps motor commands continuous.
107    pub thrust_curve_exponent: f32,
108}
109
110impl Default for PlaneStabilizerConfig {
111    /// PX4's fixed-wing defaults (time constants 0.4 s, attitude rate limits 70°/s roll and
112    /// 60°/s pitch, `fw_att_control_params.yaml`), acro up to 180°/s roll and pitch and 60°/s
113    /// yaw, 50° bank and 30° pitch, airspeeds 10/15/25 m/s, and throttle passed through.
114    /// Placeholders until an airframe is tuned.
115    fn default() -> Self {
116        PlaneStabilizerConfig {
117            rate: PlaneRateControllerConfig::default(),
118            time_constant_s: Vec2::new(0.4, 0.4),
119            max_attitude_rate_radps: Vec2::new(70.0 * DEG, 60.0 * DEG),
120            max_body_rate_radps: Vec3::new(180.0 * DEG, 180.0 * DEG, 60.0 * DEG),
121            max_bank_rad: 50.0 * DEG,
122            max_pitch_rad: 30.0 * DEG,
123            trim_airspeed_mps: 15.0,
124            min_airspeed_mps: 10.0,
125            max_airspeed_mps: 25.0,
126            thrust_curve_exponent: 1.0,
127        }
128    }
129}
130
131impl PlaneStabilizerConfig {
132    /// `Ok` when every field is in range: positive time constants, non-negative rate limits,
133    /// bank and pitch limits in `[0, π]`, positive airspeeds, and a positive thrust exponent.
134    /// Each is checked on its own; the scale clamps the airspeed to `[min, max]` with a `max`
135    /// below `min` read as `min`, so out-of-order airspeeds degrade, not fail.
136    ///
137    /// # Errors
138    ///
139    /// [`InvalidConfig`] naming the first field out of range.
140    pub fn validate(&self) -> Result<(), InvalidConfig> {
141        self.rate.validate().map_err(|e| e.in_section("rate"))?;
142        check_positive("time_constant_s.x", self.time_constant_s.x)?;
143        check_positive("time_constant_s.y", self.time_constant_s.y)?;
144        check_limit("max_attitude_rate_radps.x", self.max_attitude_rate_radps.x)?;
145        check_limit("max_attitude_rate_radps.y", self.max_attitude_rate_radps.y)?;
146        check_limit("max_body_rate_radps.x", self.max_body_rate_radps.x)?;
147        check_limit("max_body_rate_radps.y", self.max_body_rate_radps.y)?;
148        check_limit("max_body_rate_radps.z", self.max_body_rate_radps.z)?;
149        let half_turn = |angle: f32| (0.0..=core::f32::consts::PI).contains(&angle);
150        check(
151            "max_bank_rad",
152            half_turn(self.max_bank_rad),
153            "in [0, π] rad",
154        )?;
155        check(
156            "max_pitch_rad",
157            half_turn(self.max_pitch_rad),
158            "in [0, π] rad",
159        )?;
160        check_positive("trim_airspeed_mps", self.trim_airspeed_mps)?;
161        check_positive("min_airspeed_mps", self.min_airspeed_mps)?;
162        check_positive("max_airspeed_mps", self.max_airspeed_mps)?;
163        check_positive("thrust_curve_exponent", self.thrust_curve_exponent)
164    }
165}
166
167/// A fixed-wing stabilizer: attitude and rate loops on the control surfaces, with turn
168/// coordination and airspeed scaling. See the [module docs](self).
169///
170/// # Examples
171///
172/// ```
173/// use stable_flight::stabilizers::plane::{PlaneStabilizer, PlaneStabilizerConfig};
174/// use stable_flight::{PlaneSetpoint, Setpoint, Stabilizer, VehicleState};
175///
176/// let mut stabilizer = PlaneStabilizer::new(PlaneStabilizerConfig::default());
177/// let bank_right = Setpoint::Plane(PlaneSetpoint {
178///     roll_rad: 0.3,
179///     thrust: 0.6,
180///     ..Default::default()
181/// });
182/// let output = stabilizer.stabilize(0.004, &bank_right, &VehicleState::default());
183/// assert!(output.moments.x > 0.0); // roll right
184/// assert_eq!(output.thrust, 0.6);
185/// ```
186#[derive(Clone, Debug, PartialEq)]
187pub struct PlaneStabilizer {
188    config: PlaneStabilizerConfig,
189    rate: PlaneRateController,
190    /// The rate loop as attitude flight left it, while flying a [`Setpoint::PlaneRate`].
191    attitude_rate: Option<PlaneRateController>,
192    saturation: Saturation,
193    /// The autotune stage, if one was started and not yet stopped.
194    stage: Option<tuning::Stage>,
195    /// The last tick's moments, normalized: what a probe reads as the loop's output.
196    last_moments: Vec3,
197}
198
199impl PlaneStabilizer {
200    /// A stabilizer with `config`.
201    ///
202    /// # Panics
203    ///
204    /// If `config` is invalid ([`PlaneStabilizerConfig::validate`]).
205    pub fn new(config: PlaneStabilizerConfig) -> Self {
206        if let Err(error) = config.validate() {
207            panic!("invalid PlaneStabilizerConfig: {error}");
208        }
209        PlaneStabilizer {
210            config,
211            rate: PlaneRateController::default(),
212            attitude_rate: None,
213            saturation: Saturation::default(),
214            stage: None,
215            last_moments: Vec3::zeros(),
216        }
217    }
218
219    /// Rate targets for an attitude setpoint: the error over the time constant, clamped, plus
220    /// the coordinated-turn rates. A probe on an angle loop replaces its angle first.
221    fn attitude_rates(&mut self, dt: f32, setpoint: &PlaneSetpoint, state: &VehicleState) -> Vec3 {
222        let config = &self.config;
223        let max_pitch_rad = pitch_limit_rad(config.max_pitch_rad, setpoint.transition);
224        // `>` is false for NaN, which saturates to level.
225        self.saturation.tilt = setpoint.roll_rad.abs() > config.max_bank_rad
226            || setpoint.pitch_rad.abs() > max_pitch_rad;
227        let mut angles_rad = [
228            saturate_symmetric(setpoint.roll_rad, config.max_bank_rad),
229            saturate_symmetric(setpoint.pitch_rad, max_pitch_rad),
230        ];
231        let mut error = attitude_error(&state.attitude, angles_rad[0], angles_rad[1], f32::NAN);
232        if self.stage.is_some() {
233            let rates_radps = state.angular_velocity_radps;
234            self.probe_angles(dt, &mut angles_rad, [error.x, error.y], &rates_radps);
235            error = attitude_error(&state.attitude, angles_rad[0], angles_rad[1], f32::NAN);
236        }
237        let config = &self.config;
238        let correction = Vec2::new(
239            clamp_symmetric(
240                error.x / config.time_constant_s.x,
241                config.max_attitude_rate_radps.x,
242            ),
243            clamp_symmetric(
244                error.y / config.time_constant_s.y,
245                config.max_attitude_rate_radps.y,
246            ),
247        );
248        coordinated_turn_radps(state, self.airspeed_mps(state))
249            + Vec3::new(correction.x, correction.y, 0.0)
250    }
251
252    /// Rate targets for an absolute-rate setpoint, saturated (NaN as zero).
253    fn body_rates(&self, setpoint: &BodyRateSetpoint) -> Vec3 {
254        saturate_rates(
255            Vec3::new(
256                setpoint.roll_radps,
257                setpoint.pitch_radps,
258                setpoint.yaw_radps,
259            ),
260            self.config.max_body_rate_radps,
261        )
262    }
263
264    /// The airspeed the loops work with: the state's when valid, clamped to the configured
265    /// range, else trim.
266    fn airspeed_mps(&self, state: &VehicleState) -> f32 {
267        let config = &self.config;
268        state
269            .valid_airspeed_mps()
270            .map_or(config.trim_airspeed_mps, |airspeed_mps| {
271                let max_mps = config.max_airspeed_mps.max(config.min_airspeed_mps);
272                airspeed_mps.clamp(config.min_airspeed_mps, max_mps)
273            })
274    }
275
276    /// The angle of attack, in rad: the pitch less the climb angle through the air, the climb
277    /// rate over [`airspeed_mps`](Self::airspeed_mps) (the air holds no vertical wind). A
278    /// climb angle from the ground track reads the angle of attack wrong in wind: in an 8 m/s
279    /// crosswind the eXplora's ground speed was 6.9 m/s against 13.6 m/s through the air, and
280    /// its pitch fit lost the wing's stiffness (#534).
281    pub(super) fn angle_of_attack_rad(&self, state: &VehicleState) -> f32 {
282        let climb_share = state.velocity_mps.z / self.airspeed_mps(state);
283        state.pitch_rad - libm::asinf(clamp_symmetric(climb_share, 1.0))
284    }
285
286    /// The rate loop at `desired_radps`, scaled for airspeed, and the thrust.
287    fn track(
288        &mut self,
289        dt: f32,
290        desired_radps: Vec3,
291        thrust: f32,
292        state: &VehicleState,
293    ) -> ControlOutput {
294        let mut desired_radps = desired_radps;
295        self.probe_rates(dt, &mut desired_radps, state);
296        let config = &self.config;
297        let scale = config.trim_airspeed_mps / self.airspeed_mps(state);
298        // Without an airspeed there's nothing to hold the integral for.
299        let integrate = state
300            .valid_airspeed_mps()
301            .is_none_or(|airspeed_mps| airspeed_mps >= config.min_airspeed_mps);
302        let moments = self.rate.control(
303            &config.rate,
304            dt,
305            desired_radps,
306            state.angular_velocity_radps,
307            scale,
308            integrate,
309        );
310        let thrust_exponent = config.thrust_curve_exponent;
311        self.last_moments = moments;
312        self.finish_stage();
313        self.saturation.thrust = !(0.0..=1.0).contains(&thrust) && !thrust.is_nan();
314        ControlOutput {
315            thrust: thrust_curve(thrust, thrust_exponent),
316            moments,
317            cruise: None,
318        }
319    }
320}
321
322/// The body rates of a level turn at the vehicle's bank and `airspeed_mps`: ψ̇ = g·tan φ / V,
323/// as pitch rate ψ̇·sin φ·cos θ and yaw rate ψ̇·cos φ·cos θ, read from the rotation matrix's
324/// bottom row (`cos θ sin φ`, `cos θ cos φ`) without Euler angles. Faded out between 70° and
325/// 75° of bank; zero inverted or for a non-finite attitude.
326fn coordinated_turn_radps(state: &VehicleState, airspeed_mps: f32) -> Vec3 {
327    let m = state.attitude.to_rotation_matrix();
328    let (sin_roll_cos_pitch, cos_roll_cos_pitch) = (m[(2, 1)], m[(2, 2)]);
329    let bank_rad = bank_rad(&state.attitude).abs();
330    let (start, end) = COORDINATION_FADE_RAD;
331    let fade = ((end - bank_rad) / (end - start)).clamp(0.0, 1.0);
332    // A NaN bank (non-finite attitude) fades to NaN: no feedforward either.
333    if fade.is_nan() || fade <= 0.0 || !airspeed_mps.is_finite() {
334        return Vec3::zeros();
335    }
336    // ψ̇·cos φ·cos θ = g·sin φ·cos θ / V, and ψ̇·sin φ·cos θ = that · tan φ.
337    let yaw_radps = GRAVITY * sin_roll_cos_pitch / airspeed_mps;
338    let pitch_radps = yaw_radps * sin_roll_cos_pitch / cos_roll_cos_pitch;
339    Vec3::new(0.0, pitch_radps, yaw_radps) * fade
340}
341
342impl Configurable for PlaneStabilizer {
343    type Config = PlaneStabilizerConfig;
344
345    fn config(&self) -> &PlaneStabilizerConfig {
346        &self.config
347    }
348
349    /// Validates with [`PlaneStabilizerConfig::validate`]; the rate integrals, and those saved
350    /// for attitude flight, are rescaled to the new integral gains.
351    fn set_config(&mut self, config: PlaneStabilizerConfig) -> Result<(), InvalidConfig> {
352        config.validate()?;
353        self.rate.rescale_integral(&self.config.rate, &config.rate);
354        if let Some(saved) = &mut self.attitude_rate {
355            saved.rescale_integral(&self.config.rate, &config.rate);
356        }
357        self.config = config;
358        Ok(())
359    }
360}
361
362impl Stabilizer for PlaneStabilizer {
363    /// Flies a [`Setpoint::Plane`] or [`Setpoint::PlaneRate`]; neutral for any other.
364    fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput {
365        assert_dt(dt);
366        self.saturation = Saturation::default();
367        let output = match setpoint {
368            Setpoint::Plane(plane) => {
369                if plane.transition {
370                    self.interrupt_stage();
371                }
372                if let Some(saved) = self.attitude_rate.take() {
373                    self.rate = saved;
374                }
375                let rates = self.attitude_rates(dt, plane, state);
376                self.track(dt, rates, plane.thrust, state)
377            }
378            Setpoint::PlaneRate(rates) => {
379                self.interrupt_angle_stage();
380                if self.attitude_rate.is_none() {
381                    self.attitude_rate = Some(self.rate.clone());
382                }
383                let rates_radps = self.body_rates(rates);
384                self.track(dt, rates_radps, rates.thrust, state)
385            }
386            _ => {
387                self.interrupt_stage();
388                self.last_moments = Vec3::zeros();
389                return ControlOutput::default();
390            }
391        };
392        self.saturation.moments = output.moments.map(|m| m.abs() >= 1.0).into();
393        output
394    }
395
396    /// Clears the rate integrals, those saved for attitude flight, and saturation, and ends
397    /// any autotune stage.
398    fn prime(&mut self, _state: &VehicleState) {
399        self.rate.clear_integral();
400        self.attitude_rate = None;
401        self.saturation = Saturation::default();
402        self.stage = None;
403        self.last_moments = Vec3::zeros();
404    }
405
406    /// `tilt` when an attitude setpoint's bank or pitch was beyond its limit, `thrust` when
407    /// the setpoint's thrust was outside `[0, 1]`, and `moments` per axis at ±1.
408    fn saturation(&self) -> Saturation {
409        self.saturation
410    }
411}