stable-flight 0.2.0

no_std autopilot core for Stable Flight: copter, plane, tailsitter, and quadplane guidance and stabilizers, waypoint navigation, failsafe, autotune, mixers, and the per-tick flight loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
use core::f32::consts::FRAC_PI_2;

use approx::assert_relative_eq;
use assert2::check;
use nalgebra::{Quaternion, UnitQuaternion};

use super::*;
use crate::{Vec2, Vec3};

const DT: f32 = 0.01;
/// Height that clears the default `min_height_m`.
const CLEAR_M: f32 = 10.0;

/// A state with the nose `tilt_deg` from vertical, `height_m` above the arming point (at 0),
/// and `airspeed_mps`.
fn state(tilt_deg: f32, height_m: f32, airspeed_mps: Option<f32>) -> VehicleState {
    VehicleState {
        position_m: Vec3::new(0.0, 0.0, height_m),
        attitude: UnitQuaternion::from_euler_angles(0.0, FRAC_PI_2 - tilt_deg.to_radians(), 0.0),
        airspeed_mps,
        ..Default::default()
    }
}

fn hover() -> VehicleState {
    state(0.0, CLEAR_M, None)
}

/// A primed transition with the default config, armed at altitude 0.
fn primed() -> Transition {
    primed_with(TransitionConfig::default())
}

fn primed_with(config: TransitionConfig) -> Transition {
    let mut transition = Transition::new(config);
    transition.prime(&state(0.0, 0.0, None));
    transition
}

/// `transition` driven into `Plane` (forward transition completed).
fn in_plane() -> Transition {
    let mut transition = primed();
    transition.update(DT, FlightRegime::Plane, &hover());
    let step = transition.update(DT, FlightRegime::Plane, &state(50.0, CLEAR_M, None));
    assert!(step.mode == FlightMode::Plane && step.handoff);
    transition
}

/// Each row of the mode table from a single tick: (name, starting transition, request,
/// state, mode, handoff, refusal).
#[test]
fn follows_the_mode_table() {
    let in_to_plane = || {
        let mut transition = primed();
        transition.update(DT, FlightRegime::Plane, &hover());
        transition
    };
    let in_to_copter = || {
        let mut transition = in_plane();
        transition.update(DT, FlightRegime::Copter, &state(80.0, CLEAR_M, None));
        transition
    };
    type Make = fn() -> Transition;
    type Row = (
        &'static str,
        Make,
        FlightRegime,
        VehicleState,
        FlightMode,
        bool,
        Option<ModeRefusal>,
    );
    let cases: [Row; 12] = [
        (
            "copter stays",
            primed,
            FlightRegime::Copter,
            hover(),
            FlightMode::Copter,
            false,
            None,
        ),
        (
            "too low",
            primed,
            FlightRegime::Plane,
            state(0.0, 4.0, None),
            FlightMode::Copter,
            false,
            Some(ModeRefusal::BelowMinAltitude),
        ),
        (
            "NaN altitude",
            primed,
            FlightRegime::Plane,
            state(0.0, f32::NAN, None),
            FlightMode::Copter,
            false,
            Some(ModeRefusal::BelowMinAltitude),
        ),
        (
            "forward starts",
            primed,
            FlightRegime::Plane,
            hover(),
            FlightMode::ToPlane,
            false,
            None,
        ),
        (
            "forward aborts",
            in_to_plane,
            FlightRegime::Copter,
            hover(),
            FlightMode::Copter,
            false,
            None,
        ),
        (
            "forward ramps",
            in_to_plane,
            FlightRegime::Plane,
            state(30.0, CLEAR_M, None),
            FlightMode::ToPlane,
            false,
            None,
        ),
        (
            "forward completes",
            in_to_plane,
            FlightRegime::Plane,
            state(46.0, CLEAR_M, None),
            FlightMode::Plane,
            true,
            None,
        ),
        (
            "plane stays",
            in_plane,
            FlightRegime::Plane,
            state(85.0, CLEAR_M, None),
            FlightMode::Plane,
            false,
            None,
        ),
        (
            "back starts",
            in_plane,
            FlightRegime::Copter,
            state(85.0, CLEAR_M, None),
            FlightMode::ToCopter,
            false,
            None,
        ),
        (
            "back aborts",
            in_to_copter,
            FlightRegime::Plane,
            state(70.0, CLEAR_M, None),
            FlightMode::Plane,
            false,
            None,
        ),
        (
            "back ramps",
            in_to_copter,
            FlightRegime::Copter,
            state(60.0, CLEAR_M, None),
            FlightMode::ToCopter,
            false,
            None,
        ),
        (
            "back completes",
            in_to_copter,
            FlightRegime::Copter,
            state(44.0, CLEAR_M, None),
            FlightMode::Copter,
            true,
            None,
        ),
    ];

    for (name, make, requested, vehicle, mode, handoff, refusal) in cases {
        let mut transition = make();
        let step = transition.update(DT, requested, &vehicle);
        check!(step.mode == mode, "{name}");
        check!(step.handoff == handoff, "{name}");
        check!(
            transition.report() == FlightModeReport { mode, refusal },
            "{name}"
        );
        check!(
            step.tilt_target_rad.is_some()
                == matches!(mode, FlightMode::ToPlane | FlightMode::ToCopter),
            "{name}"
        );
    }
}

/// A standing request ramps the target on every tick without restarting, and completes with
/// exactly one handoff.
#[test]
fn repeated_requests_continue_the_ramp() {
    let mut transition = primed();
    let mut last = -1.0_f32;
    let mut handoffs = 0;
    for tick in 0..200 {
        // The vehicle follows the target a tick late.
        let tilt_deg = last.max(0.0).to_degrees();
        let step = transition.update(DT, FlightRegime::Plane, &state(tilt_deg, CLEAR_M, None));
        handoffs += usize::from(step.handoff);
        let Some(target) = step.tilt_target_rad else {
            break;
        };
        check!(target > last, "tick {tick}");
        last = target;
    }
    check!(transition.report().mode == FlightMode::Plane);
    check!(handoffs == 1);
}

/// The forward ramp starts at the vehicle's tilt, rises at the configured rate, and stops at
/// `forward_max_tilt_rad`; the back ramp falls to zero.
#[test]
fn ramps_from_the_vehicle_tilt_at_the_configured_rate() {
    let config = TransitionConfig::default();
    let mut transition = primed();
    // Already 10° over when the request arrives: the ramp starts there, not at 0.
    let first = transition.update(DT, FlightRegime::Plane, &state(10.0, CLEAR_M, None));
    assert_relative_eq!(
        first.tilt_target_rad.unwrap(),
        10.0_f32.to_radians(),
        epsilon = 1e-5
    );
    // Airspeed below the gate would hold it at max; here it never completes since the vehicle
    // stays at 10°.
    let after = transition.update(0.5, FlightRegime::Plane, &state(10.0, CLEAR_M, None));
    assert_relative_eq!(
        after.tilt_target_rad.unwrap(),
        10.0_f32.to_radians() + config.forward_rate_radps * 0.5,
        epsilon = 1e-5
    );
    let capped = transition.update(5.0, FlightRegime::Plane, &state(10.0, CLEAR_M, None));
    assert_relative_eq!(capped.tilt_target_rad.unwrap(), config.forward_max_tilt_rad);

    let mut transition = in_plane();
    let back = transition.update(DT, FlightRegime::Copter, &state(80.0, CLEAR_M, None));
    assert_relative_eq!(
        back.tilt_target_rad.unwrap(),
        80.0_f32.to_radians(),
        epsilon = 1e-4
    );
    let down = transition.update(5.0, FlightRegime::Copter, &state(80.0, CLEAR_M, None));
    check!(down.tilt_target_rad == Some(0.0));
}

/// With a gate set, the forward transition completes on tilt only once a valid airspeed reaches
/// it; without a valid airspeed (none, NaN, negative), tilt alone completes it.
#[test]
fn forward_completion_waits_on_valid_airspeed() {
    let config = TransitionConfig {
        min_airspeed_mps: 12.0,
        ..Default::default()
    };
    // (airspeed, completes)
    let cases = [
        (Some(11.0), false),
        (Some(12.0), true),
        (None, true),
        (Some(f32::NAN), true),
        (Some(-1.0), true),
    ];
    for (airspeed_mps, completes) in cases {
        let mut transition = primed_with(config);
        transition.update(DT, FlightRegime::Plane, &hover());
        let step = transition.update(DT, FlightRegime::Plane, &state(60.0, CLEAR_M, airspeed_mps));
        check!(
            (step.mode == FlightMode::Plane) == completes,
            "{airspeed_mps:?}"
        );
    }
}

/// A NaN attitude never completes either way: the ramp runs from hover (forward) or level
/// flight (back) and the timeout ends it.
#[test]
fn nan_attitude_waits_for_the_timeout() {
    let nan = VehicleState {
        attitude: UnitQuaternion::new_unchecked(Quaternion::new(f32::NAN, 0.0, 0.0, 0.0)),
        ..hover()
    };
    let mut transition = primed();
    let step = transition.update(DT, FlightRegime::Plane, &nan);
    check!(step.tilt_target_rad == Some(0.0)); // from hover
    check!(transition.update(DT, FlightRegime::Plane, &nan).mode == FlightMode::ToPlane);

    let mut transition = in_plane();
    let step = transition.update(DT, FlightRegime::Copter, &nan);
    check!(step.tilt_target_rad == Some(FRAC_PI_2)); // from level flight
    check!(transition.update(DT, FlightRegime::Copter, &nan).mode == FlightMode::ToCopter);
}

/// A forward transition that runs out of time falls back to copter and stays refused while
/// `Plane` is still requested; a `Copter` request clears it. A back transition that runs out
/// of time completes.
#[test]
fn timeouts_revert_forward_and_complete_back() {
    let config = TransitionConfig {
        timeout_s: 0.35,
        ..Default::default()
    };
    let stuck = state(10.0, CLEAR_M, None);
    let mut transition = primed_with(config);
    transition.update(DT, FlightRegime::Plane, &stuck);
    let modes: Vec<_> = (0..4)
        .map(|_| transition.update(0.1, FlightRegime::Plane, &stuck).mode)
        .collect();
    check!(
        modes
            == [
                FlightMode::ToPlane,
                FlightMode::ToPlane,
                FlightMode::ToPlane,
                FlightMode::Copter
            ]
    );
    let timed_out = FlightModeReport {
        mode: FlightMode::Copter,
        refusal: Some(ModeRefusal::TransitionTimeout),
    };
    check!(transition.report() == timed_out);
    check!(transition.update(DT, FlightRegime::Plane, &stuck).mode == FlightMode::Copter);
    check!(transition.report() == timed_out);

    transition.update(DT, FlightRegime::Copter, &stuck);
    check!(transition.report() == FlightModeReport::default());
    check!(transition.update(DT, FlightRegime::Plane, &stuck).mode == FlightMode::ToPlane);

    let mut transition = in_plane();
    transition.set_config(config).expect("valid");
    let level = state(85.0, CLEAR_M, None);
    transition.update(DT, FlightRegime::Copter, &level);
    let steps: Vec<_> = (0..4)
        .map(|_| transition.update(0.1, FlightRegime::Copter, &level))
        .map(|step| (step.mode, step.handoff))
        .collect();
    check!(
        steps
            == [
                (FlightMode::ToCopter, false),
                (FlightMode::ToCopter, false),
                (FlightMode::ToCopter, false),
                (FlightMode::Copter, true),
            ]
    );
}

/// A standing `Plane` request refused for height starts the transition once the vehicle
/// climbs past `min_height_m`, measured from where it was primed.
#[test]
fn standing_request_starts_once_high_enough() {
    let mut transition = Transition::new(TransitionConfig::default());
    transition.prime(&state(0.0, 100.0, None)); // armed at 100 m above the datum
    // (height above the datum, mode)
    let climb = [
        (100.0, FlightMode::Copter),
        (104.0, FlightMode::Copter),
        (105.0, FlightMode::ToPlane),
    ];
    for (altitude_m, mode) in climb {
        let step = transition.update(DT, FlightRegime::Plane, &state(0.0, altitude_m, None));
        check!(step.mode == mode, "{altitude_m}");
    }
}

/// The plane minimum height in this module's tests, in m above the arming point.
const FLOOR_M: f32 = 20.0;

/// With a plane minimum height, a forward transition needs it to start; plane flight below it
/// falls back to copter, completing the back transition however `Plane` is still requested,
/// and `Plane` stays refused until `Copter` is requested.
#[test]
fn falls_back_below_the_plane_minimum_height() {
    use FlightRegime::{Copter, Plane};
    use ModeRefusal::{BelowMinAltitude, BelowPlaneMinAltitude};
    let mut transition = primed_with(TransitionConfig {
        plane_min_height_m: FLOOR_M,
        ..Default::default()
    });
    // (what, request, tilt, height, mode, refusal, fallen back)
    let ticks = [
        (
            "past TRAN_MIN_HGT, below the floor",
            Plane,
            0.0,
            15.0,
            FlightMode::Copter,
            Some(BelowMinAltitude),
            false,
        ),
        (
            "above the floor",
            Plane,
            0.0,
            30.0,
            FlightMode::ToPlane,
            None,
            false,
        ),
        (
            "completes",
            Plane,
            50.0,
            30.0,
            FlightMode::Plane,
            None,
            false,
        ),
        (
            "plane above the floor",
            Plane,
            90.0,
            21.0,
            FlightMode::Plane,
            None,
            false,
        ),
        (
            "below it",
            Plane,
            90.0,
            19.0,
            FlightMode::ToCopter,
            Some(BelowPlaneMinAltitude),
            true,
        ),
        (
            "back ramp on",
            Plane,
            80.0,
            19.0,
            FlightMode::ToCopter,
            Some(BelowPlaneMinAltitude),
            true,
        ),
        (
            "back completes",
            Plane,
            10.0,
            19.0,
            FlightMode::Copter,
            Some(BelowPlaneMinAltitude),
            true,
        ),
        (
            "high again, still refused",
            Plane,
            0.0,
            30.0,
            FlightMode::Copter,
            Some(BelowPlaneMinAltitude),
            true,
        ),
        (
            "cleared",
            Copter,
            0.0,
            30.0,
            FlightMode::Copter,
            None,
            false,
        ),
        (
            "plane again",
            Plane,
            0.0,
            30.0,
            FlightMode::ToPlane,
            None,
            false,
        ),
    ];
    for (what, request, tilt_deg, height_m, mode, refusal, fallen_back) in ticks {
        let step = transition.update(DT, request, &state(tilt_deg, height_m, None));
        check!(step.mode == mode, "{what}");
        check!(transition.report().refusal == refusal, "{what}");
        check!(transition.fallen_back() == fallen_back, "{what}");
    }
}

/// Plane flight falls back on no height it doesn't know (NaN), and on none at all with the
/// minimum at 0.
#[test]
fn plane_minimum_height_needs_a_known_height_and_a_floor() {
    let mut floored = primed_with(TransitionConfig {
        plane_min_height_m: FLOOR_M,
        ..Default::default()
    });
    floored.update(DT, FlightRegime::Plane, &state(0.0, 30.0, None));
    floored.update(DT, FlightRegime::Plane, &state(50.0, 30.0, None));
    let unknown = state(90.0, f32::NAN, None);
    check!(floored.update(DT, FlightRegime::Plane, &unknown).mode == FlightMode::Plane);

    let mut floorless = in_plane();
    let underground = state(90.0, -100.0, None);
    check!(floorless.update(DT, FlightRegime::Plane, &underground).mode == FlightMode::Plane);
}

/// Without `prime` there is no arming altitude to measure height from: `Plane` is refused.
#[test]
fn unprimed_refuses_plane() {
    let mut transition = Transition::new(TransitionConfig::default());
    let step = transition.update(DT, FlightRegime::Plane, &state(0.0, 1_000.0, None));
    check!(step.mode == FlightMode::Copter);
    check!(transition.report().refusal == Some(ModeRefusal::BelowMinAltitude));
}

/// `prime` returns to copter and clears a timeout, whatever the mode.
#[test]
fn prime_resets_mode_and_timeout() {
    let mut flying = in_plane();
    flying.prime(&hover());
    check!(flying.report() == FlightModeReport::default());

    let mut timed_out = primed_with(TransitionConfig {
        timeout_s: 0.05,
        ..Default::default()
    });
    let stuck = state(10.0, CLEAR_M, None);
    timed_out.update(DT, FlightRegime::Plane, &stuck);
    timed_out.update(0.1, FlightRegime::Plane, &stuck);
    check!(timed_out.report().refusal == Some(ModeRefusal::TransitionTimeout));
    timed_out.prime(&state(0.0, 0.0, None));
    check!(timed_out.update(DT, FlightRegime::Plane, &stuck).mode == FlightMode::ToPlane);
}

/// Each field out of range is named.
#[test]
fn validates_each_config_field() {
    type Break = fn(&mut TransitionConfig);
    let cases: [(Break, &str); 17] = [
        (|c| c.forward_rate_radps = 0.0, "forward_rate_radps"),
        (|c| c.forward_done_rad = 0.0, "forward_done_rad"),
        (|c| c.forward_done_rad = FRAC_PI_2, "forward_done_rad"),
        (|c| c.forward_max_tilt_rad = 0.0, "forward_max_tilt_rad"),
        (|c| c.forward_max_tilt_rad = 1.6, "forward_max_tilt_rad"),
        (|c| c.min_airspeed_mps = -1.0, "min_airspeed_mps"),
        (|c| c.back_rate_radps = f32::NAN, "back_rate_radps"),
        (|c| c.back_done_rad = -0.1, "back_done_rad"),
        (|c| c.timeout_s = 0.0, "timeout_s"),
        (|c| c.min_height_m = f32::INFINITY, "min_height_m"),
        (|c| c.plane_min_height_m = -1.0, "plane_min_height_m"),
        (|c| c.forward_thrust = 1.1, "forward_thrust"),
        (|c| c.back_thrust = f32::NAN, "back_thrust"),
        (|c| c.back_sink_limit_mps = -1.0, "back_sink_limit_mps"),
        (|c| c.back_sink_gain = f32::INFINITY, "back_sink_gain"),
        (|c| c.handoff_s = -0.1, "handoff_s"),
        (|c| c.roll_limit_rad = 0.0, "roll_limit_rad"),
    ];
    check!(TransitionConfig::default().validate().is_ok());
    for (corrupt, field) in cases {
        let mut config = TransitionConfig::default();
        corrupt(&mut config);
        let error = config.validate().expect_err(field);
        check!(error.field == field);

        let mut transition = primed();
        check!(transition.set_config(config).is_err(), "{field}");
        check!(*transition.config() == TransitionConfig::default());
    }
}

#[test]
#[should_panic(expected = "invalid TransitionConfig")]
fn new_panics_on_an_invalid_config() {
    Transition::new(TransitionConfig {
        timeout_s: -1.0,
        ..Default::default()
    });
}

/// A fallback hold passes the input through outside a fallback, and sticks through in one;
/// in place of a waypoint it latches where the vehicle is on the first such tick, holds that
/// point however the vehicle moves, and lets go when the fallback clears (or on `clear`).
#[test]
fn fallback_hold_latches_the_first_fallback_waypoint() {
    let at = |north_m: f32, height_m: f32| VehicleState {
        position_m: Vec3::new(north_m, 0.0, height_m),
        ..Default::default()
    };
    let hold_over = |north_m: f32, altitude_m: f32| {
        ControlInput::Waypoint(WaypointCommand {
            position_m: Vec2::new(north_m, 0.0),
            altitude_m,
            ..Default::default()
        })
    };
    let far = hold_over(6_000.0, 250.0);
    let sticks = ControlInput::Attitude(Default::default());
    let mut hold = FallbackHold::default();
    // (what, fallen back, input, vehicle north and height, input flown)
    let ticks = [
        ("no fallback", false, far, (10.0, 30.0), far),
        ("sticks in a fallback", true, sticks, (15.0, 30.0), sticks),
        (
            "first waypoint",
            true,
            far,
            (20.0, 29.0),
            hold_over(20.0, 29.0),
        ),
        ("held", true, far, (25.0, 28.0), hold_over(20.0, 29.0)),
        ("cleared", false, far, (30.0, 30.0), far),
        (
            "a new fallback",
            true,
            far,
            (40.0, 31.0),
            hold_over(40.0, 31.0),
        ),
    ];
    for (what, fallen_back, input, (north_m, height_m), flown) in ticks {
        let state = at(north_m, height_m);
        check!(hold.input(fallen_back, &input, &state) == flown, "{what}");
    }
    hold.clear();
    check!(hold.input(true, &far, &at(50.0, 32.0)) == hold_over(50.0, 32.0));
}

/// The blend runs linearly from the start value to the demand over the duration, follows a
/// demand that changes mid-blend, then passes the demand through; NaN counts as 0.
#[test]
fn thrust_handoff_blends_then_passes_through() {
    let mut handoff = ThrustHandoff::new(0.4);
    check!(!handoff.active());
    check!(handoff.apply(DT, 0.7) == 0.7);

    handoff.start(0.8);
    check!(handoff.active());
    // (dt, demanded, expected)
    let cases = [
        (0.1, 0.4, 0.7), // a quarter of the way to 0.4
        (0.1, 0.0, 0.4), // half way to a new demand of 0
        (0.1, 0.0, 0.2), // three quarters
        (0.1, 0.0, 0.0), // done
        (0.1, 0.3, 0.3), // passes through
        (0.1, f32::NAN, 0.0),
        (0.1, 1.5, 1.0),
    ];
    for (dt, demanded, expected) in cases {
        assert_relative_eq!(handoff.apply(dt, demanded), expected, epsilon = 1e-5);
    }
    check!(!handoff.active());

    handoff.start(f32::NAN);
    assert_relative_eq!(handoff.apply(0.2, 0.6), 0.3, epsilon = 1e-5);

    let mut instant = ThrustHandoff::new(0.0);
    instant.start(0.9);
    check!(!instant.active());
    check!(instant.apply(DT, 0.2) == 0.2);
}

#[test]
#[should_panic(expected = "invalid ThrustHandoff")]
fn thrust_handoff_panics_on_a_negative_duration() {
    ThrustHandoff::new(-0.1);
}

/// A roll error cuts a transition short: forward is abandoned like a timeout (held until
/// `Copter` is requested), back completes with a handoff; outside a transition nothing changes.
#[test]
fn cut_short_abandons_forward_and_completes_back() {
    let mut transition = primed();
    transition.update(DT, FlightRegime::Plane, &hover());
    let step = transition.cut_short(ModeRefusal::RollError);
    check!((step.mode, step.handoff, step.tilt_target_rad) == (FlightMode::Copter, false, None));
    let refused = FlightModeReport {
        mode: FlightMode::Copter,
        refusal: Some(ModeRefusal::RollError),
    };
    check!(transition.report() == refused);
    check!(transition.update(DT, FlightRegime::Plane, &hover()).mode == FlightMode::Copter);
    check!(transition.report() == refused);
    transition.update(DT, FlightRegime::Copter, &hover());
    check!(transition.update(DT, FlightRegime::Plane, &hover()).mode == FlightMode::ToPlane);

    let mut transition = in_plane();
    transition.update(DT, FlightRegime::Copter, &state(80.0, CLEAR_M, None));
    let step = transition.cut_short(ModeRefusal::RollError);
    check!((step.mode, step.handoff) == (FlightMode::Copter, true));
    check!(transition.report() == FlightModeReport::default());

    for mut transition in [primed(), in_plane()] {
        let before = transition.report().mode;
        let step = transition.cut_short(ModeRefusal::RollError);
        check!((step.mode, step.handoff) == (before, false));
    }
}