Skip to main content

stable_flight/controllers/
attitude.rs

1use core::f32::consts::FRAC_PI_4;
2
3use crate::Vec2;
4
5use super::derivative::DerivativeState;
6use super::{Gains, InvalidConfig, check_limit, rescale_integral};
7use crate::math::{assert_dt, clamp_symmetric, clamp_symmetric_each, saturate_symmetric};
8
9/// Configures the attitude controller for a vehicle.
10/// Defines PID gains, maximum angles, and maximum angular rates for roll and pitch control.
11/// Yaw is typically handled separately by a dedicated yaw controller.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct AttitudeControllerConfig {
14    /// PID gains for roll and pitch control (Kp, Ki, Kd).
15    pub gains: Gains,
16
17    /// Maximum angles in radians for roll (x) and pitch (y) (e.g., π/4 = 45°).
18    /// Limits the vehicle's tilt in each axis.
19    pub max_angles_rad: Vec2,
20
21    /// Maximum absolute value of the integrated angle error, in rad·s, per axis.
22    /// Prevents integral windup by limiting error accumulation.
23    pub max_integral: f32,
24
25    /// Maximum angular rates in radians/second for roll (x) and pitch (y).
26    /// Limits the output rates sent to the rate controller.
27    pub max_rate_radps: Vec2,
28}
29
30impl Default for AttitudeControllerConfig {
31    /// Untuned starting values (45° tilt, 2 rad/s rate cap); airframes override them with
32    /// flight-checked sets.
33    fn default() -> Self {
34        Self {
35            gains: Gains {
36                p: 3.0,
37                i: 0.001,
38                d: 1.0,
39            },
40            max_angles_rad: Vec2::new(FRAC_PI_4, FRAC_PI_4), // 45° for roll and pitch
41            max_integral: 100.0,
42            max_rate_radps: Vec2::new(2.0, 2.0), // 2 rad/s (~114°/s) for roll and pitch
43        }
44    }
45}
46
47impl AttitudeControllerConfig {
48    /// Checks the config: `max_angles_rad`, `max_rate_radps`, and `max_integral` must be
49    /// non-negative and finite.
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// use stable_flight::controllers::AttitudeControllerConfig;
55    /// use stable_flight::Vec2;
56    ///
57    /// assert!(AttitudeControllerConfig::default().validate().is_ok());
58    /// let bad = AttitudeControllerConfig {
59    ///     max_angles_rad: Vec2::new(-1.0, 0.5),
60    ///     ..Default::default()
61    /// };
62    /// assert!(bad.validate().is_err());
63    /// ```
64    pub fn validate(&self) -> Result<(), InvalidConfig> {
65        check_limit("max_angles_rad.x", self.max_angles_rad.x)?;
66        check_limit("max_angles_rad.y", self.max_angles_rad.y)?;
67        check_limit("max_rate_radps.x", self.max_rate_radps.x)?;
68        check_limit("max_rate_radps.y", self.max_rate_radps.y)?;
69        check_limit("max_integral", self.max_integral)
70    }
71}
72
73/// Roll/pitch angle PID loop: turns roll/pitch setpoints in radians into body-rate setpoints for the
74/// [`BodyRateController`](super::BodyRateController).
75///
76/// It holds only state (integral and derivative history); gains and limits come from the
77/// [`AttitudeControllerConfig`] passed to each [`control`](Self::control) call, so they can
78/// change between ticks without resetting the state.
79#[derive(Clone, Debug, Default, PartialEq)]
80pub struct AttitudeController {
81    integrated_error: Vec2, // Accumulated error (roll, pitch)
82    /// Previous error for the derivative term; empty on the first tick and after a gap.
83    derivative: DerivativeState<Vec2>,
84}
85
86impl AttitudeController {
87    /// Computes desired angular rates to achieve target roll and pitch angles.
88    ///
89    /// Uses a PID controller to convert angle errors into angular rates (rad/s)
90    /// for the rate control loop. Input angles are clamped to
91    /// [-max_angles_rad.x, max_angles_rad.x] for roll and [-max_angles_rad.y, max_angles_rad.y] for pitch.
92    /// Output rates are clamped to [-max_rate_radps.x, max_rate_radps.x] for roll and
93    /// [-max_rate_radps.y, max_rate_radps.y] for pitch.
94    ///
95    /// # Arguments
96    /// * `config` - Gains and limits; assumed valid ([`AttitudeControllerConfig::validate`]).
97    ///   An invalid limit does not panic: a negative or NaN limit acts as 0.
98    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
99    /// * `desired_angles_rad` - Target roll/pitch in radians. Values beyond `max_angles_rad`
100    ///   saturate to it, and NaN is treated as 0 (level).
101    /// * `estimated_angles_rad` - Current roll/pitch angles in radians
102    ///
103    /// # Returns
104    /// Desired angular rates (roll rate, pitch rate) in radians/second,
105    /// clamped to configured max_rate_radps limits
106    ///
107    /// # Panics
108    ///
109    /// If `dt` is not positive and finite.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use stable_flight::controllers::{AttitudeController, AttitudeControllerConfig};
115    /// use stable_flight::Vec2;
116    ///
117    /// let config = AttitudeControllerConfig::default();
118    /// let mut controller = AttitudeController::default();
119    /// let dt = 0.004;
120    /// let desired_angles_rad = Vec2::new(0.4, -0.15); // roll right, pitch down
121    /// let estimated_angles_rad = Vec2::new(0.1, 0.0); // current roll/pitch in radians
122    ///
123    /// let angular_rates = controller.control(&config, dt, desired_angles_rad, estimated_angles_rad);
124    /// assert!(angular_rates.x > 0.0 && angular_rates.y < 0.0);
125    /// ```
126    pub fn control(
127        &mut self,
128        config: &AttitudeControllerConfig,
129        dt: f32,
130        desired_angles_rad: Vec2,
131        estimated_angles_rad: Vec2,
132    ) -> Vec2 {
133        assert_dt(dt);
134
135        // Outer loops and pilots can ask for more than full tilt, or NaN; saturate to the
136        // configured limit rather than panic the flight loop.
137        let desired_angles_rad = Vec2::new(
138            saturate_symmetric(desired_angles_rad.x, config.max_angles_rad.x),
139            saturate_symmetric(desired_angles_rad.y, config.max_angles_rad.y),
140        );
141
142        // Calculate error (setpoint - actual)
143        let error = desired_angles_rad - estimated_angles_rad;
144
145        // A non-finite error (NaN/∞ estimate) yields no rate command and never enters the
146        // integral or derivative history (see `crate::math` for the policy).
147        if !(error.x.is_finite() && error.y.is_finite()) {
148            self.derivative.forget();
149            return Vec2::zeros();
150        }
151
152        // Derivative term: rate of change of error (skipped on the first tick after a gap)
153        let error_derivative = self.derivative.step(error, dt);
154
155        // Integral term with anti-windup
156        self.integrated_error =
157            clamp_symmetric_each(self.integrated_error + dt * error, config.max_integral);
158
159        // PID calculation: Kp×error + Ki×∫error + Kd×d(error)/dt
160        let Gains { p, i, d } = config.gains;
161        let rates = p * error + i * self.integrated_error + d * error_derivative;
162
163        // Scale output to configured maximum rates
164        Vec2::new(
165            clamp_symmetric(rates.x, config.max_rate_radps.x),
166            clamp_symmetric(rates.y, config.max_rate_radps.y),
167        )
168    }
169
170    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
171    /// tick's I term picks up where the last left off (`rescale_integral`).
172    pub(crate) fn rescale_integral(
173        &mut self,
174        old: &AttitudeControllerConfig,
175        new: &AttitudeControllerConfig,
176    ) {
177        let (old_i, new_i) = (old.gains.i, new.gains.i);
178        self.integrated_error = self
179            .integrated_error
180            .map(|e| rescale_integral(e, old_i, new_i));
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    fn gains(p: f32, i: f32, d: f32) -> AttitudeControllerConfig {
189        AttitudeControllerConfig {
190            gains: Gains { p, i, d },
191            ..AttitudeControllerConfig::default()
192        }
193    }
194
195    #[test]
196    fn default_is_zeroed_state() {
197        let controller = AttitudeController::default();
198
199        assert_eq!(controller.integrated_error, Vec2::zeros());
200        assert_eq!(controller.derivative, DerivativeState::default());
201    }
202
203    /// A fresh controller has no previous error, so D alone gives nothing on the first tick.
204    #[test]
205    fn first_tick_has_no_derivative_kick() {
206        let mut controller = AttitudeController::default();
207        let rates = controller.control(
208            &gains(0.0, 0.0, 0.5),
209            0.1,
210            Vec2::new(0.3, -0.2),
211            Vec2::zeros(),
212        );
213        assert_eq!(rates, Vec2::zeros());
214    }
215
216    #[test]
217    fn validate_rejects_negative_or_non_finite_limits() {
218        let default = AttitudeControllerConfig::default();
219        let (angles, rates) = (default.max_angles_rad, default.max_rate_radps);
220        // (max_angles_rad, max_rate_radps, max_integral, offending field)
221        let cases = [
222            (Vec2::new(-1.0, angles.y), rates, 1.0, "max_angles_rad.x"),
223            (Vec2::new(angles.x, -1.0), rates, 1.0, "max_angles_rad.y"),
224            (angles, Vec2::new(-1.0, rates.y), 1.0, "max_rate_radps.x"),
225            (angles, Vec2::new(rates.x, -1.0), 1.0, "max_rate_radps.y"),
226            (angles, rates, -1.0, "max_integral"),
227        ];
228        assert!(default.validate().is_ok());
229        for (max_angles_rad, max_rate_radps, max_integral, field) in cases {
230            let config = AttitudeControllerConfig {
231                max_angles_rad,
232                max_rate_radps,
233                max_integral,
234                ..default
235            };
236            assert_eq!(config.validate().map_err(|e| e.field), Err(field));
237        }
238    }
239
240    /// An invalid limit fails `validate` but `control` stays panic-free: the limit acts as 0.
241    #[test]
242    fn invalid_limits_give_neutral_output_without_panicking() {
243        for bad in [-1.0, f32::NAN] {
244            let config = AttitudeControllerConfig {
245                max_angles_rad: Vec2::new(bad, bad),
246                max_rate_radps: Vec2::new(bad, bad),
247                max_integral: bad,
248                ..AttitudeControllerConfig::default()
249            };
250            let mut controller = AttitudeController::default();
251            let rates = controller.control(&config, 0.1, Vec2::new(1.0, -1.0), Vec2::new(0.2, 0.0));
252
253            assert_eq!(rates, Vec2::zeros(), "limit {bad}");
254            assert_eq!(controller.integrated_error, Vec2::zeros(), "limit {bad}");
255        }
256    }
257
258    #[test]
259    fn test_control_zero_error() {
260        let mut controller = AttitudeController::default();
261
262        let rates = controller.control(
263            &AttitudeControllerConfig::default(),
264            0.1,
265            Vec2::zeros(),
266            Vec2::zeros(),
267        );
268
269        assert_eq!(rates, Vec2::zeros()); // No error, no rate output
270        assert_eq!(controller.integrated_error, Vec2::zeros()); // No integral buildup
271    }
272
273    #[test]
274    fn test_control_proportional_response() {
275        let config = gains(2.0, 0.0, 0.0);
276        let mut controller = AttitudeController::default();
277        let dt = 0.1;
278        let desired_angles = Vec2::new(1.0, -1.0); // Beyond 45°: saturates to the max
279
280        let rates = controller.control(&config, dt, desired_angles, Vec2::zeros());
281
282        let expected_error = Vec2::new(FRAC_PI_4, -FRAC_PI_4); // 45° in radians
283        let expected_rates = config.gains.p * expected_error;
284        assert!((rates.x - expected_rates.x).abs() < 1e-6);
285        assert!((rates.y - expected_rates.y).abs() < 1e-6);
286        assert_eq!(controller.integrated_error, dt * expected_error);
287    }
288
289    #[test]
290    fn test_control_rate_clamping() {
291        let config = AttitudeControllerConfig {
292            max_rate_radps: Vec2::new(2.0, 2.0),
293            ..gains(100.0, 0.0, 0.0) // High P gain to exceed max_rate_radps
294        };
295
296        let rates =
297            AttitudeController::default().control(&config, 0.1, Vec2::new(1.0, 1.0), Vec2::zeros());
298
299        assert_eq!(rates, Vec2::new(2.0, 2.0)); // Clamped to max_rate_radps
300    }
301
302    #[test]
303    fn test_control_integral_buildup() {
304        let config = gains(1.0, 1.0, 0.0);
305        let mut controller = AttitudeController::default();
306        let dt = 0.1;
307        let desired_angles = Vec2::new(0.5, 0.5);
308
309        controller.control(&config, dt, desired_angles, Vec2::zeros());
310        let rates2 = controller.control(&config, dt, desired_angles, Vec2::zeros());
311
312        let error = desired_angles;
313        let expected_integral = dt * 2.0 * error; // Two steps
314        assert_eq!(controller.integrated_error, expected_integral);
315        let expected_rates = 1.0 * error + 1.0 * expected_integral; // P + I terms
316        assert!((rates2.x - expected_rates.x).abs() < 1e-6);
317        assert!((rates2.y - expected_rates.y).abs() < 1e-6);
318    }
319
320    #[test]
321    fn test_control_integral_clamping() {
322        let config = AttitudeControllerConfig {
323            max_integral: 1.0,         // Low limit for testing
324            ..gains(0.0, 8000.0, 0.0)  // High I to hit max_integral
325        };
326        let mut controller = AttitudeController::default();
327        let dt = 2.0; // Large dt to quickly reach max_integral
328
329        let rates = controller.control(&config, dt, Vec2::new(1.0, 1.0), Vec2::zeros());
330
331        assert_eq!(controller.integrated_error, Vec2::new(1.0, 1.0)); // Clamped to max_integral
332        assert_eq!(rates, Vec2::new(2.0, 2.0));
333    }
334
335    /// A gain change between ticks applies on the next tick and keeps the integral; a shrunk
336    /// `max_integral` clamps the existing integral.
337    #[test]
338    fn config_change_between_ticks_keeps_state() {
339        let mut controller = AttitudeController::default();
340        controller.control(
341            &gains(0.0, 1.0, 0.0),
342            1.0,
343            Vec2::new(1.0, 0.0),
344            Vec2::zeros(),
345        );
346        let integral = controller.integrated_error;
347
348        let rates = controller.control(&gains(0.0, 2.0, 0.0), 0.1, Vec2::zeros(), Vec2::zeros());
349        assert_eq!(controller.integrated_error, integral);
350        approx::assert_relative_eq!(rates.x, 2.0 * integral.x);
351
352        let shrunk = AttitudeControllerConfig {
353            max_integral: 0.1,
354            ..gains(0.0, 1.0, 0.0)
355        };
356        controller.control(&shrunk, 0.1, Vec2::zeros(), Vec2::zeros());
357        assert_eq!(controller.integrated_error.x, 0.1);
358    }
359
360    #[test]
361    fn test_control_derivative_response() {
362        let config = gains(0.0, 0.0, 0.5);
363        let mut controller = AttitudeController::default();
364        let dt = 0.1;
365        let desired_angles = Vec2::new(1.0, 1.0); // saturates to 45°
366        let estimated_angles2 = Vec2::new(0.5 * FRAC_PI_4, 0.5 * FRAC_PI_4);
367
368        controller.control(&config, dt, desired_angles, Vec2::zeros());
369        let rates2 = controller.control(&config, dt, desired_angles, estimated_angles2);
370
371        let error1 = Vec2::new(FRAC_PI_4, FRAC_PI_4);
372        let error2 = error1 - estimated_angles2;
373        let derivative = (error2 - error1) / dt;
374        let expected_rates = config.gains.d * derivative;
375        assert!((rates2.x - expected_rates.x).abs() < 1e-6);
376        assert!((rates2.y - expected_rates.y).abs() < 1e-6);
377    }
378
379    #[test]
380    #[should_panic(expected = "dt must be positive and finite")]
381    fn zero_dt_panics() {
382        AttitudeController::default().control(
383            &AttitudeControllerConfig::default(),
384            0.0,
385            Vec2::zeros(),
386            Vec2::zeros(),
387        );
388    }
389
390    #[test]
391    fn out_of_range_or_nan_desired_angles_saturate_instead_of_panicking() {
392        let config = AttitudeControllerConfig::default();
393        let max = FRAC_PI_4; // default max_angles_rad
394        // (requested angles in rad, equivalent in-range request)
395        let cases = [
396            (Vec2::new(2.0, 0.0), Vec2::new(max, 0.0)),
397            (Vec2::new(0.0, -4.6), Vec2::new(0.0, -max)),
398            (Vec2::new(-1.5, 3.0), Vec2::new(-max, max)),
399            (Vec2::new(f32::NAN, 0.5), Vec2::new(0.0, 0.5)),
400            (
401                Vec2::new(f32::INFINITY, f32::NEG_INFINITY),
402                Vec2::new(max, -max),
403            ),
404        ];
405        for (requested, equivalent) in cases {
406            let rates =
407                AttitudeController::default().control(&config, 0.1, requested, Vec2::zeros());
408            let expected =
409                AttitudeController::default().control(&config, 0.1, equivalent, Vec2::zeros());
410            assert!(
411                rates.x.is_finite() && rates.y.is_finite(),
412                "{requested:?} gave non-finite rates {rates:?}"
413            );
414            approx::assert_relative_eq!(rates.x, expected.x);
415            approx::assert_relative_eq!(rates.y, expected.y);
416        }
417    }
418
419    #[test]
420    fn nan_estimate_does_not_poison_later_ticks() {
421        let config = AttitudeControllerConfig::default();
422        let mut controller = AttitudeController::default();
423        let desired = Vec2::new(0.5, -0.5);
424
425        let during = controller.control(&config, 0.1, desired, Vec2::new(f32::NAN, 0.0));
426        assert!(during == Vec2::zeros(), "NaN estimate gave {during:?}");
427        assert!(controller.integrated_error == Vec2::zeros());
428
429        // First finite tick after the gap: P + I only (no derivative from the pre-gap error).
430        let after_nan = controller.control(&config, 0.1, desired, Vec2::zeros());
431        let error = desired;
432        let Gains { p, i, .. } = config.gains;
433        let expected = p * error + i * (0.1 * error);
434        approx::assert_relative_eq!(after_nan.x, expected.x.clamp(-2.0, 2.0));
435        approx::assert_relative_eq!(after_nan.y, expected.y.clamp(-2.0, 2.0));
436    }
437}