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.
15    pub roll_gains: Gains,
16
17    /// PID gains for pitch.
18    pub pitch_gains: Gains,
19
20    /// Maximum angles in radians for roll (x) and pitch (y) (e.g., π/4 = 45°).
21    /// Limits the vehicle's tilt in each axis.
22    pub max_angles_rad: Vec2,
23
24    /// Maximum absolute value of the integrated angle error, in rad·s, per axis.
25    /// Prevents integral windup by limiting error accumulation.
26    pub max_integral: f32,
27
28    /// Maximum angular rates in radians/second for roll (x) and pitch (y).
29    /// Limits the output rates sent to the rate controller.
30    pub max_rate_radps: Vec2,
31}
32
33impl Default for AttitudeControllerConfig {
34    /// Untuned starting values (45° tilt, 2 rad/s rate cap); airframes override them with
35    /// flight-checked sets.
36    fn default() -> Self {
37        let gains = Gains {
38            p: 3.0,
39            i: 0.001,
40            d: 1.0,
41        };
42        Self {
43            roll_gains: gains,
44            pitch_gains: gains,
45            max_angles_rad: Vec2::new(FRAC_PI_4, FRAC_PI_4), // 45° for roll and pitch
46            max_integral: 100.0,
47            max_rate_radps: Vec2::new(2.0, 2.0), // 2 rad/s (~114°/s) for roll and pitch
48        }
49    }
50}
51
52impl AttitudeControllerConfig {
53    /// Checks the config: `max_angles_rad`, `max_rate_radps`, and `max_integral` must be
54    /// non-negative and finite.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// use stable_flight::controllers::AttitudeControllerConfig;
60    /// use stable_flight::Vec2;
61    ///
62    /// assert!(AttitudeControllerConfig::default().validate().is_ok());
63    /// let bad = AttitudeControllerConfig {
64    ///     max_angles_rad: Vec2::new(-1.0, 0.5),
65    ///     ..Default::default()
66    /// };
67    /// assert!(bad.validate().is_err());
68    /// ```
69    pub fn validate(&self) -> Result<(), InvalidConfig> {
70        check_limit("max_angles_rad.x", self.max_angles_rad.x)?;
71        check_limit("max_angles_rad.y", self.max_angles_rad.y)?;
72        check_limit("max_rate_radps.x", self.max_rate_radps.x)?;
73        check_limit("max_rate_radps.y", self.max_rate_radps.y)?;
74        check_limit("max_integral", self.max_integral)
75    }
76
77    /// Gains per axis: roll, pitch.
78    fn axis_gains(&self) -> [Gains; 2] {
79        [self.roll_gains, self.pitch_gains]
80    }
81}
82
83/// Roll/pitch angle PID loop: turns roll/pitch setpoints in radians into body-rate setpoints for the
84/// [`BodyRateController`](super::BodyRateController).
85///
86/// It holds only state (integral and derivative history); gains and limits come from the
87/// [`AttitudeControllerConfig`] passed to each [`control`](Self::control) call, so they can
88/// change between ticks without resetting the state.
89#[derive(Clone, Debug, Default, PartialEq)]
90pub struct AttitudeController {
91    integrated_error: Vec2, // Accumulated error (roll, pitch)
92    /// Previous error per axis for the derivative term; empty on the first tick and after a
93    /// gap.
94    derivative: [DerivativeState<f32>; 2],
95}
96
97impl AttitudeController {
98    /// Computes desired angular rates to achieve target roll and pitch angles.
99    ///
100    /// Uses a PID controller to convert angle errors into angular rates (rad/s)
101    /// for the rate control loop. Input angles are clamped to
102    /// [-max_angles_rad.x, max_angles_rad.x] for roll and [-max_angles_rad.y, max_angles_rad.y] for pitch.
103    /// Output rates are clamped to [-max_rate_radps.x, max_rate_radps.x] for roll and
104    /// [-max_rate_radps.y, max_rate_radps.y] for pitch.
105    ///
106    /// # Arguments
107    /// * `config` - Gains and limits; assumed valid ([`AttitudeControllerConfig::validate`]).
108    ///   An invalid limit does not panic: a negative or NaN limit acts as 0.
109    /// * `dt` - Time step since the last update in seconds (must be positive and finite).
110    /// * `desired_angles_rad` - Target roll/pitch in radians. Values beyond `max_angles_rad`
111    ///   saturate to it, and NaN is treated as 0 (level).
112    /// * `estimated_angles_rad` - Current roll/pitch angles in radians
113    ///
114    /// # Returns
115    /// Desired angular rates (roll rate, pitch rate) in radians/second,
116    /// clamped to configured max_rate_radps limits
117    ///
118    /// # Panics
119    ///
120    /// If `dt` is not positive and finite.
121    ///
122    /// # Examples
123    ///
124    /// ```
125    /// use stable_flight::controllers::{AttitudeController, AttitudeControllerConfig};
126    /// use stable_flight::Vec2;
127    ///
128    /// let config = AttitudeControllerConfig::default();
129    /// let mut controller = AttitudeController::default();
130    /// let dt = 0.004;
131    /// let desired_angles_rad = Vec2::new(0.4, -0.15); // roll right, pitch down
132    /// let estimated_angles_rad = Vec2::new(0.1, 0.0); // current roll/pitch in radians
133    ///
134    /// let angular_rates = controller.control(&config, dt, desired_angles_rad, estimated_angles_rad);
135    /// assert!(angular_rates.x > 0.0 && angular_rates.y < 0.0);
136    /// ```
137    pub fn control(
138        &mut self,
139        config: &AttitudeControllerConfig,
140        dt: f32,
141        desired_angles_rad: Vec2,
142        estimated_angles_rad: Vec2,
143    ) -> Vec2 {
144        let error = Self::angle_error(config, desired_angles_rad, estimated_angles_rad);
145        self.control_error(config, dt, error, [false; 2])
146    }
147
148    /// The PID of [`control`](Self::control) on an angle error already taken (roll, pitch, in
149    /// radians): for a caller that measures the error itself, e.g. from quaternions. Output
150    /// rates are clamped to `max_rate_radps`; a non-finite error gives zero rates. An axis set
151    /// in `hold_integral` keeps its integral this tick instead of adding its error.
152    ///
153    /// # Panics
154    ///
155    /// If `dt` is not positive and finite.
156    pub(crate) fn control_error(
157        &mut self,
158        config: &AttitudeControllerConfig,
159        dt: f32,
160        error: Vec2,
161        hold_integral: [bool; 2],
162    ) -> Vec2 {
163        assert_dt(dt);
164
165        // A non-finite error (NaN/∞ estimate) yields no rate command and never enters the
166        // integral or derivative history (see `crate::math` for the policy).
167        if !(error.x.is_finite() && error.y.is_finite()) {
168            self.derivative.iter_mut().for_each(DerivativeState::forget);
169            return Vec2::zeros();
170        }
171
172        // Derivative term: rate of change of error (skipped on the first tick after a gap)
173        let error_derivative = Vec2::from_fn(|axis, _| self.derivative[axis].step(error[axis], dt));
174
175        // Integral term with anti-windup
176        let integrated_error =
177            clamp_symmetric_each(self.integrated_error + dt * error, config.max_integral);
178        self.integrated_error = Vec2::from_fn(|axis, _| {
179            if hold_integral[axis] {
180                self.integrated_error[axis]
181            } else {
182                integrated_error[axis]
183            }
184        });
185
186        // PID calculation per axis: Kp×error + Ki×∫error + Kd×d(error)/dt
187        let gains = config.axis_gains();
188        let rates = Vec2::from_fn(|axis, _| {
189            let Gains { p, i, d } = gains[axis];
190            p * error[axis] + i * self.integrated_error[axis] + d * error_derivative[axis]
191        });
192
193        // Scale output to configured maximum rates
194        Vec2::new(
195            clamp_symmetric(rates.x, config.max_rate_radps.x),
196            clamp_symmetric(rates.y, config.max_rate_radps.y),
197        )
198    }
199
200    /// The angle error (setpoint − estimate) the loop acts on, per axis. Outer loops and pilots
201    /// can ask for more than full tilt, or NaN: the setpoint saturates to `max_angles_rad`
202    /// (NaN is level) rather than panic the flight loop.
203    pub(crate) fn angle_error(
204        config: &AttitudeControllerConfig,
205        desired_angles_rad: Vec2,
206        estimated_angles_rad: Vec2,
207    ) -> Vec2 {
208        Self::saturate_setpoint(config.max_angles_rad, desired_angles_rad) - estimated_angles_rad
209    }
210
211    /// `desired_angles_rad` saturated to `max_angles_rad` (roll, pitch), NaN as level.
212    pub(crate) fn saturate_setpoint(max_angles_rad: Vec2, desired_angles_rad: Vec2) -> Vec2 {
213        Vec2::new(
214            saturate_symmetric(desired_angles_rad.x, max_angles_rad.x),
215            saturate_symmetric(desired_angles_rad.y, max_angles_rad.y),
216        )
217    }
218
219    /// Restarts `axis` with no derivative history, keeping its integral. The other axis is
220    /// untouched.
221    pub(crate) fn hand_back(&mut self, axis: usize) {
222        self.derivative[axis] = DerivativeState::default();
223    }
224
225    /// The integrated angle error per axis (roll, pitch), in rad·s.
226    #[cfg(test)]
227    pub(crate) fn integral(&self) -> Vec2 {
228        self.integrated_error
229    }
230
231    /// Zeroes the integral, keeping the derivative history.
232    pub(crate) fn clear_integral(&mut self) {
233        self.integrated_error = Vec2::zeros();
234    }
235
236    /// Rescales the integral for a change of integral gain from `old` to `new`, so the next
237    /// tick's I term picks up where the last left off (`rescale_integral`).
238    pub(crate) fn rescale_integral(
239        &mut self,
240        old: &AttitudeControllerConfig,
241        new: &AttitudeControllerConfig,
242    ) {
243        let (old, new) = (old.axis_gains(), new.axis_gains());
244        self.integrated_error = Vec2::from_fn(|axis, _| {
245            rescale_integral(self.integrated_error[axis], old[axis].i, new[axis].i)
246        });
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    fn gains(p: f32, i: f32, d: f32) -> AttitudeControllerConfig {
255        AttitudeControllerConfig {
256            roll_gains: Gains { p, i, d },
257            pitch_gains: Gains { p, i, d },
258            ..AttitudeControllerConfig::default()
259        }
260    }
261
262    #[test]
263    fn default_is_zeroed_state() {
264        let controller = AttitudeController::default();
265
266        assert_eq!(controller.integrated_error, Vec2::zeros());
267        assert_eq!(controller.derivative, [DerivativeState::default(); 2]);
268    }
269
270    /// A fresh controller has no previous error, so D alone gives nothing on the first tick.
271    #[test]
272    fn first_tick_has_no_derivative_kick() {
273        let mut controller = AttitudeController::default();
274        let rates = controller.control(
275            &gains(0.0, 0.0, 0.5),
276            0.1,
277            Vec2::new(0.3, -0.2),
278            Vec2::zeros(),
279        );
280        assert_eq!(rates, Vec2::zeros());
281    }
282
283    #[test]
284    fn validate_rejects_negative_or_non_finite_limits() {
285        let default = AttitudeControllerConfig::default();
286        let (angles, rates) = (default.max_angles_rad, default.max_rate_radps);
287        // (max_angles_rad, max_rate_radps, max_integral, offending field)
288        let cases = [
289            (Vec2::new(-1.0, angles.y), rates, 1.0, "max_angles_rad.x"),
290            (Vec2::new(angles.x, -1.0), rates, 1.0, "max_angles_rad.y"),
291            (angles, Vec2::new(-1.0, rates.y), 1.0, "max_rate_radps.x"),
292            (angles, Vec2::new(rates.x, -1.0), 1.0, "max_rate_radps.y"),
293            (angles, rates, -1.0, "max_integral"),
294        ];
295        assert!(default.validate().is_ok());
296        for (max_angles_rad, max_rate_radps, max_integral, field) in cases {
297            let config = AttitudeControllerConfig {
298                max_angles_rad,
299                max_rate_radps,
300                max_integral,
301                ..default
302            };
303            assert_eq!(config.validate().map_err(|e| e.field), Err(field));
304        }
305    }
306
307    /// An invalid limit fails `validate` but `control` stays panic-free: the limit acts as 0.
308    #[test]
309    fn invalid_limits_give_neutral_output_without_panicking() {
310        for bad in [-1.0, f32::NAN] {
311            let config = AttitudeControllerConfig {
312                max_angles_rad: Vec2::new(bad, bad),
313                max_rate_radps: Vec2::new(bad, bad),
314                max_integral: bad,
315                ..AttitudeControllerConfig::default()
316            };
317            let mut controller = AttitudeController::default();
318            let rates = controller.control(&config, 0.1, Vec2::new(1.0, -1.0), Vec2::new(0.2, 0.0));
319
320            assert_eq!(rates, Vec2::zeros(), "limit {bad}");
321            assert_eq!(controller.integrated_error, Vec2::zeros(), "limit {bad}");
322        }
323    }
324
325    #[test]
326    fn test_control_zero_error() {
327        let mut controller = AttitudeController::default();
328
329        let rates = controller.control(
330            &AttitudeControllerConfig::default(),
331            0.1,
332            Vec2::zeros(),
333            Vec2::zeros(),
334        );
335
336        assert_eq!(rates, Vec2::zeros()); // No error, no rate output
337        assert_eq!(controller.integrated_error, Vec2::zeros()); // No integral buildup
338    }
339
340    #[test]
341    fn test_control_proportional_response() {
342        let config = gains(2.0, 0.0, 0.0);
343        let mut controller = AttitudeController::default();
344        let dt = 0.1;
345        let desired_angles = Vec2::new(1.0, -1.0); // Beyond 45°: saturates to the max
346
347        let rates = controller.control(&config, dt, desired_angles, Vec2::zeros());
348
349        let expected_error = Vec2::new(FRAC_PI_4, -FRAC_PI_4); // 45° in radians
350        let expected_rates = Vec2::new(
351            config.roll_gains.p * expected_error.x,
352            config.pitch_gains.p * expected_error.y,
353        );
354        assert!((rates.x - expected_rates.x).abs() < 1e-6);
355        assert!((rates.y - expected_rates.y).abs() < 1e-6);
356        assert_eq!(controller.integrated_error, dt * expected_error);
357    }
358
359    #[test]
360    fn test_control_rate_clamping() {
361        let config = AttitudeControllerConfig {
362            max_rate_radps: Vec2::new(2.0, 2.0),
363            ..gains(100.0, 0.0, 0.0) // High P gain to exceed max_rate_radps
364        };
365
366        let rates =
367            AttitudeController::default().control(&config, 0.1, Vec2::new(1.0, 1.0), Vec2::zeros());
368
369        assert_eq!(rates, Vec2::new(2.0, 2.0)); // Clamped to max_rate_radps
370    }
371
372    /// A retune rescales each axis's integral by its own gain change: doubling roll's `i`
373    /// halves roll's integral and leaves pitch's alone.
374    #[test]
375    fn retune_rescales_each_axis_integral_by_its_own_gain() {
376        let old = gains(0.0, 1.0, 0.0);
377        let mut controller = AttitudeController::default();
378        controller.control(&old, 0.1, Vec2::new(0.5, 0.5), Vec2::zeros());
379        let integral = controller.integrated_error;
380
381        let new = AttitudeControllerConfig {
382            roll_gains: Gains {
383                i: 2.0,
384                ..old.roll_gains
385            },
386            ..old
387        };
388        controller.rescale_integral(&old, &new);
389
390        approx::assert_relative_eq!(controller.integrated_error.x, integral.x / 2.0);
391        assert_eq!(controller.integrated_error.y, integral.y);
392    }
393
394    /// Handing back one axis clears its derivative history and keeps its integral; the other
395    /// axis keeps both.
396    #[test]
397    fn hand_back_restarts_one_axis_only() {
398        let config = gains(1.0, 2.0, 0.5);
399        let mut controller = AttitudeController::default();
400        controller.control(&config, 0.1, Vec2::new(0.5, 0.5), Vec2::zeros());
401        let roll_integral = controller.integrated_error.x;
402        let pitch_integral = controller.integrated_error.y;
403        let pitch_derivative = controller.derivative[1];
404
405        controller.hand_back(0);
406
407        assert_eq!(controller.integrated_error.x, roll_integral);
408        assert_eq!(controller.derivative[0], DerivativeState::default());
409        assert_eq!(controller.integrated_error.y, pitch_integral);
410        assert_eq!(controller.derivative[1], pitch_derivative);
411    }
412
413    /// Roll uses `roll_gains` and pitch `pitch_gains`, for each PID term.
414    #[test]
415    fn each_axis_uses_its_own_gains() {
416        let pid = |p, i, d| Gains { p, i, d };
417        // (roll gains, pitch gains, expected first-tick rates for a 0.5 rad error on both axes
418        // over dt 0.1: P·e + I·e·dt, no derivative yet)
419        let cases = [
420            (pid(1.0, 0.0, 0.0), pid(3.0, 0.0, 0.0), Vec2::new(0.5, 1.5)),
421            (pid(0.0, 2.0, 0.0), pid(0.0, 4.0, 0.0), Vec2::new(0.1, 0.2)),
422        ];
423        for (roll_gains, pitch_gains, expected) in cases {
424            let config = AttitudeControllerConfig {
425                roll_gains,
426                pitch_gains,
427                max_rate_radps: Vec2::new(10.0, 10.0),
428                ..AttitudeControllerConfig::default()
429            };
430            let rates = AttitudeController::default().control(
431                &config,
432                0.1,
433                Vec2::new(0.5, 0.5),
434                Vec2::zeros(),
435            );
436            approx::assert_relative_eq!(rates, expected, epsilon = 1e-6);
437        }
438
439        // Derivative: second tick after the error drops by 0.1 rad on both axes.
440        let config = AttitudeControllerConfig {
441            roll_gains: pid(0.0, 0.0, 0.1),
442            pitch_gains: pid(0.0, 0.0, 0.3),
443            max_rate_radps: Vec2::new(10.0, 10.0),
444            ..AttitudeControllerConfig::default()
445        };
446        let mut controller = AttitudeController::default();
447        controller.control(&config, 0.1, Vec2::new(0.5, 0.5), Vec2::zeros());
448        let rates = controller.control(&config, 0.1, Vec2::new(0.5, 0.5), Vec2::new(0.1, 0.1));
449        approx::assert_relative_eq!(rates, Vec2::new(-0.1, -0.3), epsilon = 1e-5);
450    }
451
452    #[test]
453    fn test_control_integral_buildup() {
454        let config = gains(1.0, 1.0, 0.0);
455        let mut controller = AttitudeController::default();
456        let dt = 0.1;
457        let desired_angles = Vec2::new(0.5, 0.5);
458
459        controller.control(&config, dt, desired_angles, Vec2::zeros());
460        let rates2 = controller.control(&config, dt, desired_angles, Vec2::zeros());
461
462        let error = desired_angles;
463        let expected_integral = dt * 2.0 * error; // Two steps
464        assert_eq!(controller.integrated_error, expected_integral);
465        let expected_rates = 1.0 * error + 1.0 * expected_integral; // P + I terms
466        assert!((rates2.x - expected_rates.x).abs() < 1e-6);
467        assert!((rates2.y - expected_rates.y).abs() < 1e-6);
468    }
469
470    #[test]
471    fn test_control_integral_clamping() {
472        let config = AttitudeControllerConfig {
473            max_integral: 1.0,         // Low limit for testing
474            ..gains(0.0, 8000.0, 0.0)  // High I to hit max_integral
475        };
476        let mut controller = AttitudeController::default();
477        let dt = 2.0; // Large dt to quickly reach max_integral
478
479        let rates = controller.control(&config, dt, Vec2::new(1.0, 1.0), Vec2::zeros());
480
481        assert_eq!(controller.integrated_error, Vec2::new(1.0, 1.0)); // Clamped to max_integral
482        assert_eq!(rates, Vec2::new(2.0, 2.0));
483    }
484
485    /// A gain change between ticks applies on the next tick and keeps the integral; a shrunk
486    /// `max_integral` clamps the existing integral.
487    #[test]
488    fn config_change_between_ticks_keeps_state() {
489        let mut controller = AttitudeController::default();
490        controller.control(
491            &gains(0.0, 1.0, 0.0),
492            1.0,
493            Vec2::new(1.0, 0.0),
494            Vec2::zeros(),
495        );
496        let integral = controller.integrated_error;
497
498        let rates = controller.control(&gains(0.0, 2.0, 0.0), 0.1, Vec2::zeros(), Vec2::zeros());
499        assert_eq!(controller.integrated_error, integral);
500        approx::assert_relative_eq!(rates.x, 2.0 * integral.x);
501
502        let shrunk = AttitudeControllerConfig {
503            max_integral: 0.1,
504            ..gains(0.0, 1.0, 0.0)
505        };
506        controller.control(&shrunk, 0.1, Vec2::zeros(), Vec2::zeros());
507        assert_eq!(controller.integrated_error.x, 0.1);
508    }
509
510    #[test]
511    fn test_control_derivative_response() {
512        let config = gains(0.0, 0.0, 0.5);
513        let mut controller = AttitudeController::default();
514        let dt = 0.1;
515        let desired_angles = Vec2::new(1.0, 1.0); // saturates to 45°
516        let estimated_angles2 = Vec2::new(0.5 * FRAC_PI_4, 0.5 * FRAC_PI_4);
517
518        controller.control(&config, dt, desired_angles, Vec2::zeros());
519        let rates2 = controller.control(&config, dt, desired_angles, estimated_angles2);
520
521        let error1 = Vec2::new(FRAC_PI_4, FRAC_PI_4);
522        let error2 = error1 - estimated_angles2;
523        let derivative = (error2 - error1) / dt;
524        let expected_rates = Vec2::new(
525            config.roll_gains.d * derivative.x,
526            config.pitch_gains.d * derivative.y,
527        );
528        assert!((rates2.x - expected_rates.x).abs() < 1e-6);
529        assert!((rates2.y - expected_rates.y).abs() < 1e-6);
530    }
531
532    #[test]
533    #[should_panic(expected = "dt must be positive and finite")]
534    fn zero_dt_panics() {
535        AttitudeController::default().control(
536            &AttitudeControllerConfig::default(),
537            0.0,
538            Vec2::zeros(),
539            Vec2::zeros(),
540        );
541    }
542
543    #[test]
544    fn out_of_range_or_nan_desired_angles_saturate_instead_of_panicking() {
545        let config = AttitudeControllerConfig::default();
546        let max = FRAC_PI_4; // default max_angles_rad
547        // (requested angles in rad, equivalent in-range request)
548        let cases = [
549            (Vec2::new(2.0, 0.0), Vec2::new(max, 0.0)),
550            (Vec2::new(0.0, -4.6), Vec2::new(0.0, -max)),
551            (Vec2::new(-1.5, 3.0), Vec2::new(-max, max)),
552            (Vec2::new(f32::NAN, 0.5), Vec2::new(0.0, 0.5)),
553            (
554                Vec2::new(f32::INFINITY, f32::NEG_INFINITY),
555                Vec2::new(max, -max),
556            ),
557        ];
558        for (requested, equivalent) in cases {
559            let rates =
560                AttitudeController::default().control(&config, 0.1, requested, Vec2::zeros());
561            let expected =
562                AttitudeController::default().control(&config, 0.1, equivalent, Vec2::zeros());
563            assert!(
564                rates.x.is_finite() && rates.y.is_finite(),
565                "{requested:?} gave non-finite rates {rates:?}"
566            );
567            approx::assert_relative_eq!(rates.x, expected.x);
568            approx::assert_relative_eq!(rates.y, expected.y);
569        }
570    }
571
572    #[test]
573    fn nan_estimate_does_not_poison_later_ticks() {
574        let config = AttitudeControllerConfig::default();
575        let mut controller = AttitudeController::default();
576        let desired = Vec2::new(0.5, -0.5);
577
578        let during = controller.control(&config, 0.1, desired, Vec2::new(f32::NAN, 0.0));
579        assert!(during == Vec2::zeros(), "NaN estimate gave {during:?}");
580        assert!(controller.integrated_error == Vec2::zeros());
581
582        // First finite tick after the gap: P + I only (no derivative from the pre-gap error).
583        let after_nan = controller.control(&config, 0.1, desired, Vec2::zeros());
584        let error = desired;
585        let [roll, pitch] = config.axis_gains();
586        let expected = Vec2::new(
587            roll.p * error.x + roll.i * (0.1 * error.x),
588            pitch.p * error.y + pitch.i * (0.1 * error.y),
589        );
590        approx::assert_relative_eq!(after_nan.x, expected.x.clamp(-2.0, 2.0));
591        approx::assert_relative_eq!(after_nan.y, expected.y.clamp(-2.0, 2.0));
592    }
593}