stable-flight 0.3.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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! Guidance for multirotors such as the QuadCopter X: waypoint navigation and pilot-stick
//! interpretation, feeding [`CopterStabilizer`](crate::stabilizers::copter::CopterStabilizer).
//!
//! | Control input | Setpoint |
//! |---|---|
//! | [`ControlInput::Rate`] | [`Setpoint::Rate`], sticks passed through; the heading-hold target follows the vehicle |
//! | [`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 |
//! | [`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) |
//! | [`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 |
//! | [`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 |
//! | [`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 |
//!
//! Piloted inputs mark their setpoint [`idle`](crate::AttitudeSetpoint::idle) while the
//! throttle is at or below [`idle_throttle`](CopterGuidanceConfig::idle_throttle) (or NaN), as ArduPilot spools to ground idle on
//! `throttle_zero` in its piloted modes (`ModeStabilize::run`). Waypoint and
//! land setpoints never are: there's no land detector to tell a touchdown
//! ([#395](https://github.com/wboayue/stable-flight/issues/395)).
//!
//! [`ThrustLimits`] bound the thrust while flying (all off by default): a floor, a sink guard
//! for piloted flight, and a ceiling on the tilt boost. A tailsitter's control surfaces need
//! the propwash, a sink turns the airflow against it, and differential thrust needs headroom.
//!
//! Switching modes doesn't jump the heading: attitude, absolute-attitude, waypoint, and land
//! flight share one heading-hold target, and rate flight keeps it on the vehicle's heading.
//! Waypoint flight slews that target along the leg, from where the leg began to its waypoint,
//! as ArduPilot's and PX4's defaults face the next waypoint (`WP_YAW_BEHAVIOR`,
//! `ArduCopter/config.h`; `MPC_YAW_MODE`, PX4 `FlightTaskAuto::_set_heading_from_mode`), so a
//! leg behind the vehicle isn't flown tail first. The leg's direction, not the bearing from the
//! vehicle, keeps a braking overshoot or a hold drifting in wind from turning the nose around.
//! The
//! altitude and lateral loops start fresh each time waypoint or land flight is entered, with
//! the altitude target starting from the vehicle's altitude.

use core::f32::consts::{FRAC_PI_4, PI};

use crate::estimation::wind::WindConfig;
use crate::nalgebra::UnitQuaternion;
use crate::{GRAVITY, Vec2, WindEstimate};

use crate::commanders::touchdown::DESCENDING_MPS;
use crate::commanders::waypoint::DEFAULT_ACCEPTANCE_RADIUS_M;
use crate::controllers::*;
use crate::controllers::{check, check_limit, check_positive, check_tilt, check_unit_interval};
use crate::{
    AbsoluteAttitudeCommand, AbsoluteRateCommand, AttitudeCommand, AttitudeSetpoint,
    BodyRateSetpoint, Configurable, ControlInput, FlightRegime, Guidance, LandCommand,
    RateSetpoint, Saturation, Setpoint, VehicleState, WaypointCommand,
};

use super::rate_divider::RateDivider;
use crate::math::{
    all_finite, assert_dt, cap_magnitude, guard_sink, saturate_throttle, saturate_unit,
    shaped_closing_speed, tilt_boost, wrap_angle,
};
use hover_wind::HoverWind;
use leg_heading::LegHeading;

mod hover_wind;
mod leg_heading;
mod params;
#[cfg(test)]
mod tests;
mod wind_heading;

/// Default [`CopterGuidanceConfig::stick_yaw_rate_radps`]: 1 rad/s (~57°/s).
pub const DEFAULT_STICK_YAW_RATE_RADPS: f32 = 1.0;

/// Default [`CopterGuidanceConfig::max_tilt_rad`]: 27°, leaving thrust headroom to climb while
/// translating (60% of the default 45° stabilizer limit).
pub const DEFAULT_MAX_TILT_RAD: f32 = 27.0_f32.to_radians();

/// Default [`CopterGuidanceConfig::max_stick_angles_rad`] per axis: 45°, the default stabilizer
/// limit, so full stick is full tilt.
pub const DEFAULT_MAX_STICK_ANGLE_RAD: f32 = FRAC_PI_4;

/// Default [`CopterGuidanceConfig::navigation_period_s`]: 50 Hz, a fifth of the usual 250 Hz
/// inner loop.
pub const DEFAULT_NAVIGATION_PERIOD_S: f32 = 0.02;

/// Default [`CopterGuidanceConfig::max_descent_mps`]: fast enough for the figure-eight's
/// descending half (up to about 3 m/s at 7 m/s cruise).
pub const DEFAULT_MAX_DESCENT_MPS: f32 = 3.0;

/// Default [`CopterGuidanceConfig::descent_accel_mps2`]: ArduPilot's waypoint vertical
/// acceleration limit, `WP_ACC_Z` (`libraries/AC_WPNav/AC_WPNav.cpp`).
pub const DEFAULT_DESCENT_ACCEL_MPS2: f32 = 1.0;

/// Default [`CopterGuidanceConfig::climb_decel_mps2`]: ArduPilot's quadplane vertical
/// acceleration limit, `Q_PILOT_ACCEL_Z`, which it sheds a tailsitter's climb at after a
/// handover (`QuadPlane::run_z_controller`). On the sim tailsitter handed over
/// 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
/// 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).
pub const DEFAULT_CLIMB_DECEL_MPS2: f32 = 2.5;

/// Default [`CopterGuidanceConfig::waypoint_yaw_radps`]: 60°/s, ArduPilot's waypoint yaw slew
/// (`ATC_RATE_WPY_MAX`, `libraries/AC_AttitudeControl/AC_AttitudeControl.h`) and PX4's
/// (`MPC_YAWRAUTO_MAX`).
pub const DEFAULT_WAYPOINT_YAW_RADPS: f32 = 60.0_f32.to_radians();

/// Default [`CopterGuidanceConfig::heading_rate_radps`]: the waypoint yaw slew, 60°/s, which
/// ArduPilot also turns to a commanded yaw at (`ATC_RATE_WPY_MAX`).
pub const DEFAULT_HEADING_RATE_RADPS: f32 = DEFAULT_WAYPOINT_YAW_RADPS;

/// Default [`CopterGuidanceConfig::waypoint_yaw_min_leg_m`]: the waypoint follower's
/// [`DEFAULT_ACCEPTANCE_RADIUS_M`], since a shorter leg is reached as it begins; PX4 likewise
/// holds its yaw inside the acceptance radius (`FlightTaskAuto::_set_heading_from_mode`).
pub const DEFAULT_WAYPOINT_YAW_MIN_LEG_M: f32 = DEFAULT_ACCEPTANCE_RADIUS_M;

/// Default [`CopterGuidanceConfig::heading_yield_rad`]: 30°. On the sim quadplane, 20°–45°
/// all yield to the fin in 5 and 11 m/s winds and none yields in a calm 180° turn (#452).
pub const DEFAULT_HEADING_YIELD_RAD: f32 = 30.0_f32.to_radians();

/// Default [`CopterGuidanceConfig::heading_yield_rate_radps`]: 0.1 rad/s (about 6°/s), under
/// the turn rate toward the target and over a vehicle held off by its fin (#452).
pub const DEFAULT_HEADING_YIELD_RATE_RADPS: f32 = 0.1;

/// Default [`CopterGuidanceConfig::heading_yield_s`]: 1 s. On the sim quadplane taking off in
/// 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
/// in a headwind) (#431).
pub const DEFAULT_HEADING_YIELD_S: f32 = 1.0;

/// Default [`CopterGuidanceConfig::airborne_height_m`]: 1 m.
pub const DEFAULT_AIRBORNE_HEIGHT_M: f32 = 1.0;

/// Default [`CopterGuidanceConfig::land_speed_mps`], as PX4's `MPC_LAND_SPEED`.
pub const DEFAULT_LAND_SPEED_MPS: f32 = 0.7;

/// Default [`CopterGuidanceConfig::idle_throttle`]: 0.05.
pub const DEFAULT_IDLE_THROTTLE: f32 = 0.05;

/// Default [`CopterGuidanceConfig::altitude_leash_m`]: 1 m, which keeps a tailsitter handed
/// over still climbing near `max_descent_mps` instead of sinking past it (#400).
pub const DEFAULT_ALTITUDE_LEASH_M: f32 = 1.0;

/// Default [`CopterGuidanceConfig::feedforward_hold_band_mps`]: 0.3 m/s. With no band, the sim
/// eXplora's autotune designed its pitch rate 31% under RealFlight's; at 0.5 m/s the sim
/// tailsitter's steady-wind hold left its band. The eXplora's worst 25 m leg at 1.5 or 3 m/s
/// 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
/// feedforward (#609).
pub const DEFAULT_FEEDFORWARD_HOLD_BAND_MPS: f32 = 0.3;

/// Default [`CopterGuidanceConfig::wind_heading_from_wind_rad`]: 80°, a wingtip into the wind
/// 10° short of square. Descending 60 → 20 m in RealFlight's 2 m/s wind, the eXplora's pitch
/// swung up to 9.3–12.7° off its setpoint square on, and 4.9–6.0° at 78–80°; at about 65° it
/// pinned its tilt cap (#470).
pub const DEFAULT_WIND_HEADING_FROM_WIND_RAD: f32 = 80.0_f32.to_radians();

/// Default [`CopterGuidanceConfig::wind_heading_max_sd_rad`]: 15°, which off the 80° target
/// reaches the 65° where the RealFlight eXplora pinned its tilt cap (#470).
pub const DEFAULT_WIND_HEADING_MAX_SD_RAD: f32 = 15.0_f32.to_radians();

/// Default [`CopterGuidanceConfig::wind_heading_deadband_rad`]: 10°; the estimate's direction
/// wanders within 3.3° of RealFlight's wind (#473).
pub const DEFAULT_WIND_HEADING_DEADBAND_RAD: f32 = 10.0_f32.to_radians();

/// Configuration for [CopterGuidance]: the altitude and lateral position loops and the
/// waypoint-flight limits.
///
/// Plain data: [`CopterGuidance::new`] validates it ([`validate`](Self::validate)), and the
/// guidance passes the loop configs to its controllers every tick.
///
/// # Examples
///
/// ```
/// use stable_flight::controllers::Gains;
/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
///
/// let mut config = CopterGuidanceConfig::default();
/// config.altitude.gains = Gains { p: 2.0, i: 0.2, d: 0.1 };
/// config.altitude.hover_thrust = 0.45; // airframe-specific
/// let guidance = CopterGuidance::new(config);
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CopterGuidanceConfig {
    /// Altitude loop: altitude error (m) → vertical acceleration (m/s²), fed to the thrust law
    /// with gravity and tilt compensation. Its `hover_thrust` defaults to
    /// [`DEFAULT_HOVER_THRUST`].
    pub altitude: AltitudeControllerConfig,
    /// Lateral loop: horizontal position error (m) → velocity (m/s, capped at the waypoint's
    /// `cruise_speed_mps`) → acceleration (m/s²), flown as a tilt of `atan(|a| / g)` toward it.
    pub lateral: LateralControllerConfig,
    /// Seconds between runs of the lateral position loop; its roll/pitch output is held in
    /// between. `0.0` runs it every tick. Rounded to the nearest tick (at a 4 ms loop, 20 ms
    /// is every 5th tick); each run steps over the actual elapsed time. The altitude loop runs
    /// every tick, since its tilt compensation needs the current attitude. Must be
    /// non-negative and finite. Defaults to [`DEFAULT_NAVIGATION_PERIOD_S`].
    pub navigation_period_s: f32,
    /// Largest waypoint-flight tilt in radians, in `(0, π/2)`. Caps the magnitude of the
    /// combined roll/pitch request, so a far waypoint can't ask for full tilt while the
    /// altitude loop also wants full climb. It limits the request, not the achieved tilt: the
    /// attitude loop can overshoot it briefly, and the stabilizer's own `max_angles_rad` still
    /// applies. Piloted attitude flight is not capped. Defaults to [`DEFAULT_MAX_TILT_RAD`].
    pub max_tilt_rad: f32,
    /// Roll and pitch in radians that full stick (±1) commands in piloted attitude flight;
    /// the stick scales linearly. The stabilizer saturates to its own `max_angles_rad`, so a
    /// larger value only reaches that limit sooner. Must be non-negative and finite. Defaults
    /// to [`DEFAULT_MAX_STICK_ANGLE_RAD`] on both axes.
    pub max_stick_angles_rad: Vec2,
    /// Rate, in rad/s, at which full yaw stick (±1) slews the heading-hold target in piloted
    /// attitude flight; the stick scales linearly. Higher: a quicker turn on the stick, the
    /// yaw loop lagging further behind the target. Must be non-negative and finite. Defaults to
    /// [`DEFAULT_STICK_YAW_RATE_RADPS`].
    pub stick_yaw_rate_radps: f32,
    /// A piloted throttle (stick, rate, or absolute-attitude thrust) at or below this is idle,
    /// as is NaN: [`ThrustLimits::min_thrust`] and the sink guard don't raise it, so the motors
    /// can idle on the ground and the pilot can still cut them, and the setpoint is marked
    /// [`idle`](crate::AttitudeSetpoint::idle), so the stabilizer clears its integrals. Higher:
    /// more of the stick's bottom left unfloored. In `[0, 1)`. Defaults to
    /// [`DEFAULT_IDLE_THROTTLE`].
    pub idle_throttle: f32,
    /// Fastest descent waypoint flight asks for, in m/s: a target below the vehicle is
    /// approached by an altitude target lowered at up to this rate, so a low waypoint descends
    /// instead of cutting thrust. Climbs aren't limited. It limits the target, not the achieved
    /// rate: the vehicle can exceed it briefly while catching up. Must be positive and finite.
    /// Defaults to [`DEFAULT_MAX_DESCENT_MPS`].
    pub max_descent_mps: f32,
    /// Acceleration a waypoint descent's target starts and ends with, in m/s², and a land's
    /// starts with: the target's descent rate rises by at most this much per second, and a
    /// waypoint descent's shrinks toward the waypoint so this much deceleration stops it
    /// there, and is 0 on it.
    /// Within `descent_accel_mps2 / P²` of the waypoint (P the altitude loop's, as ArduPilot
    /// shapes with its vertical position P) the rate is linear in the gap instead, so retuning
    /// that P moves where the braking changes shape. Must be positive and finite. Defaults to
    /// [`DEFAULT_DESCENT_ACCEL_MPS2`].
    pub descent_accel_mps2: f32,
    /// Descent rate of a land ([`ControlInput::Land`]), in m/s. Must be finite and above the
    /// touchdown detector's [`DESCENDING_MPS`] (0.2 m/s), so the detector sees the descent and
    /// the land ends in a disarm. Defaults to [`DEFAULT_LAND_SPEED_MPS`].
    pub land_speed_mps: f32,
    /// Deceleration, in m/s², at which a waypoint or land target latched while the vehicle
    /// climbs sheds that climb. The target starts moving up at the vehicle's climb rate (a
    /// sink starts it at rest, as ArduPilot's tailsitter does,
    /// `AC_PosControl::D_init_controller_no_descent`), so the altitude loop doesn't cut thrust
    /// to stop the climb at once: on a tailsitter handed over from a back transition, that cut
    /// let the climb die and the hover fall past the descent limit (#462). Higher: stops the
    /// climb lower, cuts more thrust doing it; a climb of v rises about v² / (2 · this) further.
    /// Must be positive and finite. Defaults to [`DEFAULT_CLIMB_DECEL_MPS2`].
    pub climb_decel_mps2: f32,
    /// How far, in meters, a descending altitude target (waypoint or land) may run below the
    /// vehicle. A vehicle still climbing when the descent begins, as a tailsitter handed over
    /// from a back transition, then gets at most `P · leash` of the altitude loop's downward
    /// pull, so it sinks near `max_descent_mps` instead of past it. Once the ground stops a
    /// landing vehicle, the altitude loop settles on a thrust below hover instead of winding
    /// down toward none. Higher: a harder pull down when the vehicle lags its target. Must be
    /// positive and finite. Defaults to [`DEFAULT_ALTITUDE_LEASH_M`].
    pub altitude_leash_m: f32,
    /// Rate, in rad/s, at which waypoint flight turns the heading-hold target to the leg's
    /// direction, the shorter way round; `0` holds the heading the leg began with, unless
    /// [yielded](Self::heading_yield_s). A leg runs
    /// from where the vehicle was when waypoint flight began or the waypoint changed, to the
    /// waypoint. The vehicle translates while it turns. Land flight holds the heading (or turns
    /// it with [`wind_heading_min_mps`](Self::wind_heading_min_mps)).
    /// Must be non-negative and finite. Defaults to [`DEFAULT_WAYPOINT_YAW_RADPS`].
    pub waypoint_yaw_radps: f32,
    /// Rate, in rad/s, at which waypoint flight turns the heading-hold target to a waypoint's
    /// [`heading_rad`](WaypointCommand::heading_rad), the shorter way round. Must be positive
    /// and finite. Defaults to [`DEFAULT_HEADING_RATE_RADPS`].
    pub heading_rate_radps: f32,
    /// Shortest leg, in meters horizontally when it begins, whose direction waypoint flight
    /// turns to; a shorter one (a hold, a waypoint that moves with the vehicle) keeps the
    /// heading. A change applies from the next leg. Must be
    /// non-negative and finite. Defaults to [`DEFAULT_WAYPOINT_YAW_MIN_LEG_M`].
    pub waypoint_yaw_min_leg_m: f32,
    /// Heading error, in radians, past which waypoint flight counts the heading as stuck while
    /// the vehicle yaws toward the heading-hold target at under
    /// [`heading_yield_rate_radps`](Self::heading_yield_rate_radps). Must be non-negative and
    /// finite. Defaults to [`DEFAULT_HEADING_YIELD_RAD`].
    pub heading_yield_rad: f32,
    /// Yaw rate toward the heading-hold target, in rad/s, below which a heading off it by more
    /// than [`heading_yield_rad`](Self::heading_yield_rad) is stuck. A vehicle turning to its
    /// target yaws toward it faster; one held off by its fin doesn't yaw, or yaws away.
    /// Higher: a slow turn can count as stuck and yield. Must be non-negative and finite.
    /// Defaults to [`DEFAULT_HEADING_YIELD_RATE_RADPS`].
    pub heading_yield_rate_radps: f32,
    /// Seconds the heading stays stuck before waypoint flight yields it: the heading-hold
    /// target then follows the vehicle's heading until the waypoint changes, so a quadplane's
    /// fin swinging the nose into the wind isn't fought for good (#431). `0` never yields.
    /// Must be non-negative and finite. Defaults to [`DEFAULT_HEADING_YIELD_S`].
    pub heading_yield_s: f32,
    /// Least wind, in m/s, that turns the heading-hold target to put a wingtip into the wind
    /// (the vehicle's `x` axis, a tailsitter's belly,
    /// [`wind_heading_from_wind_rad`](Self::wind_heading_from_wind_rad) off where it comes
    /// from) while holding a waypoint or landing, at `heading_rate_radps`. The side is the one
    /// nearer the heading when first picked; the wind estimate ([`wind`](Self::wind)) turns it
    /// only when its direction is known within
    /// [`wind_heading_max_sd_rad`](Self::wind_heading_max_sd_rad), and moves it only past
    /// [`wind_heading_deadband_rad`](Self::wind_heading_deadband_rad). A waypoint's
    /// [`heading_rad`](WaypointCommand::heading_rad) wins, and legs longer than
    /// `waypoint_yaw_min_leg_m` keep their own heading until within that of the waypoint.
    /// `0` turns nothing. Must be non-negative and finite. Defaults to `0`.
    pub wind_heading_min_mps: f32,
    /// Angle, in radians, between the heading [`wind_heading_min_mps`](Self::wind_heading_min_mps)
    /// turns to and where the wind comes from: `π/2` puts a wingtip square into it, less keeps
    /// some of the wind on the belly. In `[0, π]`. Defaults to
    /// [`DEFAULT_WIND_HEADING_FROM_WIND_RAD`].
    pub wind_heading_from_wind_rad: f32,
    /// Most uncertainty in the wind estimate's direction, in radians, that still turns the
    /// heading to it. Higher: turns on a less certain estimate, possibly to a heading off the
    /// wind by this much. Must be non-negative and finite. Defaults to
    /// [`DEFAULT_WIND_HEADING_MAX_SD_RAD`].
    pub wind_heading_max_sd_rad: f32,
    /// Least change, in radians, in the wind's wingtip heading that moves a latched one.
    /// Higher: fewer turns chasing the estimate's wander, a heading further off the wind
    /// before it moves. Must be non-negative and finite. Defaults to
    /// [`DEFAULT_WIND_HEADING_DEADBAND_RAD`].
    pub wind_heading_deadband_rad: f32,
    /// Thrust floor, sink guard, and tilt-boost ceiling; all off by default.
    pub thrust: ThrustLimits,
    /// Height, in meters, above the altitude primed on the ground past which the vehicle is
    /// airborne and the wind estimate updates: on the ground the air's push is lost in contact
    /// forces and would read as calm. Higher: the estimate starts later in the climb. Must be
    /// non-negative and finite. Defaults to [`DEFAULT_AIRBORNE_HEIGHT_M`].
    pub airborne_height_m: f32,
    /// Commanded speed, in m/s, under which a hold's corrections stay, left to the lateral loop
    /// by the drag feedforward: the feedforward models the drag of the commanded velocity past
    /// it. Fed forward, those corrections stiffen the hold. Higher: more of a leg's drag left
    /// to the loop's I term, which carries it past the waypoint when the vehicle stops. Must be
    /// non-negative and finite. Defaults to [`DEFAULT_FEEDFORWARD_HOLD_BAND_MPS`].
    pub feedforward_hold_band_mps: f32,
    /// The wind estimator's drag model and noises; off by default (no drag coefficients).
    pub wind: WindConfig,
}

/// Bounds on [`CopterGuidance`]'s thrust while flying, for an airframe whose control comes
/// from the propwash (a tailsitter). The defaults bound nothing.
///
/// # Examples
///
/// ```
/// use stable_flight::guidance::copter::{CopterGuidanceConfig, ThrustLimits};
///
/// let config = CopterGuidanceConfig {
///     thrust: ThrustLimits { min_thrust: 0.65, sink_limit_mps: 1.0, sink_gain: 0.15, max_boost_thrust: 0.9 },
///     ..Default::default()
/// };
/// assert!(config.validate().is_ok());
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ThrustLimits {
    /// Least linear thrust while flying, in `[0, 1)`; `0` (the default) is none. It keeps air
    /// over a tailsitter's control surfaces, whose authority comes from the propwash: at low
    /// throttle the elevons can't hold the nose up. ArduPilot's tailsitters floor the motors
    /// the same way (`Q_TAILSIT_MIN_VO`, `ArduPlane/tailsitter.cpp`, applied by
    /// `AP_MotorsTailsitter` only once spooled up). Every setpoint's thrust is raised to it,
    /// after the tilt boost (so even inverted), except a piloted throttle at or below
    /// [`idle_throttle`](CopterGuidanceConfig::idle_throttle), which passes through. Waypoint and land flight always get it. Set it
    /// below the altitude loop's `hover_thrust`, or waypoint flight can't descend and a land
    /// never touches down.
    pub min_thrust: f32,
    /// Sink rate, in m/s, beyond which piloted flight (attitude, rate, or absolute attitude,
    /// above [`idle_throttle`](CopterGuidanceConfig::idle_throttle)) gets more thrust: [`sink_gain`](Self::sink_gain) per m/s of
    /// sink past it, on top of the stick (and floor). Direct throttle can't hold a descent
    /// rate, and a tailsitter sinking a few m/s has air flowing up against its propwash, which
    /// takes the elevons' authority and drops the nose. Waypoint and land flight limit
    /// their own descents ([`CopterGuidanceConfig::max_descent_mps`]). Must be non-negative
    /// and finite; `0` (the default) disables it.
    pub sink_limit_mps: f32,
    /// Thrust added per m/s of sink past [`sink_limit_mps`](Self::sink_limit_mps), in s/m.
    /// Must be non-negative and finite. Defaults to 0.
    pub sink_gain: f32,
    /// Most thrust the attitude-mode tilt boost may raise the stick to, in `(0, 1]`. A stick
    /// above it passes through; the boost doesn't push past it, so a tilted vehicle keeps
    /// motor headroom for the moments (a tailsitter rolling on differential thrust).
    /// Defaults to 1 (no ceiling).
    pub max_boost_thrust: f32,
}

impl Default for ThrustLimits {
    /// No floor, no sink guard, and no boost ceiling.
    fn default() -> Self {
        ThrustLimits {
            min_thrust: 0.0,
            sink_limit_mps: 0.0,
            sink_gain: 0.0,
            max_boost_thrust: 1.0,
        }
    }
}

impl ThrustLimits {
    /// Checks that `min_thrust` is in `[0, 1)`, that `sink_limit_mps` and `sink_gain` are
    /// non-negative and finite, and that `max_boost_thrust` is in `(0, 1]`.
    pub fn validate(&self) -> Result<(), InvalidConfig> {
        check(
            "min_thrust",
            (0.0..1.0).contains(&self.min_thrust),
            "in [0, 1)",
        )?;
        check_limit("sink_limit_mps", self.sink_limit_mps)?;
        check_limit("sink_gain", self.sink_gain)?;
        check_unit_interval("max_boost_thrust", self.max_boost_thrust)
    }
}

impl Default for CopterGuidanceConfig {
    /// The controller defaults (flight-checked on RealFlight's QuadCopterX), a 50 Hz lateral
    /// loop, a 27° waypoint tilt cap, 45° at full stick, a 3 m/s descent limit, a climb under
    /// way when a descent starts shed at 2.5 m/s², a 0.7 m/s land, waypoint legs over 3 m
    /// turned to face along them at 60°/s, a waypoint's heading turned to at 60°/s, the
    /// 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
    /// of 0.05, a 1 m altitude leash, no wind heading (80° off the wind when on), the wind
    /// estimated from 1 m up, a 0.3 m/s feedforward hold band, no thrust floor or sink guard,
    /// and no boost ceiling.
    fn default() -> Self {
        CopterGuidanceConfig {
            altitude: AltitudeControllerConfig::default(),
            lateral: LateralControllerConfig::default(),
            navigation_period_s: DEFAULT_NAVIGATION_PERIOD_S,
            max_tilt_rad: DEFAULT_MAX_TILT_RAD,
            max_stick_angles_rad: Vec2::new(
                DEFAULT_MAX_STICK_ANGLE_RAD,
                DEFAULT_MAX_STICK_ANGLE_RAD,
            ),
            stick_yaw_rate_radps: DEFAULT_STICK_YAW_RATE_RADPS,
            idle_throttle: DEFAULT_IDLE_THROTTLE,
            max_descent_mps: DEFAULT_MAX_DESCENT_MPS,
            descent_accel_mps2: DEFAULT_DESCENT_ACCEL_MPS2,
            land_speed_mps: DEFAULT_LAND_SPEED_MPS,
            climb_decel_mps2: DEFAULT_CLIMB_DECEL_MPS2,
            altitude_leash_m: DEFAULT_ALTITUDE_LEASH_M,
            waypoint_yaw_radps: DEFAULT_WAYPOINT_YAW_RADPS,
            heading_rate_radps: DEFAULT_HEADING_RATE_RADPS,
            waypoint_yaw_min_leg_m: DEFAULT_WAYPOINT_YAW_MIN_LEG_M,
            heading_yield_rad: DEFAULT_HEADING_YIELD_RAD,
            heading_yield_rate_radps: DEFAULT_HEADING_YIELD_RATE_RADPS,
            heading_yield_s: DEFAULT_HEADING_YIELD_S,
            wind_heading_min_mps: 0.0,
            wind_heading_from_wind_rad: DEFAULT_WIND_HEADING_FROM_WIND_RAD,
            wind_heading_max_sd_rad: DEFAULT_WIND_HEADING_MAX_SD_RAD,
            wind_heading_deadband_rad: DEFAULT_WIND_HEADING_DEADBAND_RAD,
            thrust: ThrustLimits::default(),
            airborne_height_m: DEFAULT_AIRBORNE_HEIGHT_M,
            feedforward_hold_band_mps: DEFAULT_FEEDFORWARD_HOLD_BAND_MPS,
            wind: WindConfig::default(),
        }
    }
}

impl CopterGuidanceConfig {
    /// Checks both loop configs ([`AltitudeControllerConfig::validate`],
    /// [`LateralControllerConfig::validate`]; errors carry the loop as their `section`), the
    /// thrust limits ([`ThrustLimits::validate`], section `thrust`), that
    /// `navigation_period_s`, `max_stick_angles_rad`, and `stick_yaw_rate_radps` are
    /// non-negative and finite, that `idle_throttle` is in `[0, 1)`, that `max_tilt_rad` is in
    /// `(0, π/2)`, that `max_descent_mps`, `descent_accel_mps2`, `climb_decel_mps2`,
    /// `altitude_leash_m`, and `heading_rate_radps` are positive and finite, that
    /// `land_speed_mps` is finite and above [`DESCENDING_MPS`], that
    /// `wind_heading_from_wind_rad` is in `[0, π]`, and that `waypoint_yaw_radps`,
    /// `waypoint_yaw_min_leg_m`, `heading_yield_rad`, `heading_yield_rate_radps`, `heading_yield_s`,
    /// `wind_heading_min_mps`, `wind_heading_max_sd_rad`, `wind_heading_deadband_rad`,
    /// `airborne_height_m`, and `feedforward_hold_band_mps` are non-negative and finite.
    ///
    /// # Examples
    ///
    /// ```
    /// use stable_flight::guidance::copter::CopterGuidanceConfig;
    ///
    /// let mut config = CopterGuidanceConfig::default();
    /// assert!(config.validate().is_ok());
    /// config.altitude.hover_thrust = 1.5;
    /// assert_eq!(config.validate().unwrap_err().to_string(), "altitude.hover_thrust must be in (0, 1]");
    /// ```
    pub fn validate(&self) -> Result<(), InvalidConfig> {
        self.altitude
            .validate()
            .map_err(|e| e.in_section("altitude"))?;
        self.lateral
            .validate()
            .map_err(|e| e.in_section("lateral"))?;
        check_limit("navigation_period_s", self.navigation_period_s)?;
        check_limit("max_stick_angles_rad.x", self.max_stick_angles_rad.x)?;
        check_limit("max_stick_angles_rad.y", self.max_stick_angles_rad.y)?;
        check_limit("stick_yaw_rate_radps", self.stick_yaw_rate_radps)?;
        check(
            "idle_throttle",
            (0.0..1.0).contains(&self.idle_throttle),
            "in [0, 1)",
        )?;
        check_tilt("max_tilt_rad", self.max_tilt_rad)?;
        check_positive("max_descent_mps", self.max_descent_mps)?;
        check_positive("descent_accel_mps2", self.descent_accel_mps2)?;
        check_positive("climb_decel_mps2", self.climb_decel_mps2)?;
        check_positive("altitude_leash_m", self.altitude_leash_m)?;
        check(
            "land_speed_mps",
            self.land_speed_mps > DESCENDING_MPS && self.land_speed_mps.is_finite(),
            "above the touchdown detector's DESCENDING_MPS and finite",
        )?;
        check_limit("waypoint_yaw_radps", self.waypoint_yaw_radps)?;
        check_positive("heading_rate_radps", self.heading_rate_radps)?;
        check_limit("waypoint_yaw_min_leg_m", self.waypoint_yaw_min_leg_m)?;
        check_limit("heading_yield_rad", self.heading_yield_rad)?;
        check_limit("heading_yield_rate_radps", self.heading_yield_rate_radps)?;
        check_limit("heading_yield_s", self.heading_yield_s)?;
        check_limit("wind_heading_min_mps", self.wind_heading_min_mps)?;
        check(
            "wind_heading_from_wind_rad",
            (0.0..=PI).contains(&self.wind_heading_from_wind_rad),
            "in [0, π]",
        )?;
        check_limit("wind_heading_max_sd_rad", self.wind_heading_max_sd_rad)?;
        check_limit("wind_heading_deadband_rad", self.wind_heading_deadband_rad)?;
        check_limit("airborne_height_m", self.airborne_height_m)?;
        check_limit("feedforward_hold_band_mps", self.feedforward_hold_band_mps)?;
        self.thrust.validate().map_err(|e| e.in_section("thrust"))?;
        self.wind.validate().map_err(|e| e.in_section("wind"))
    }
}

/// Copter guidance: altitude and lateral position loops for waypoints, heading along the leg,
/// and heading hold for piloted attitude flight.
///
/// # Examples
///
/// ```
/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
/// use stable_flight::{
///     AttitudeCommand, ControlInput, FlightRegime, Guidance, Setpoint, VehicleState,
/// };
///
/// let mut guidance = CopterGuidance::new(CopterGuidanceConfig::default());
/// let state = VehicleState { heading_rad: 1.0, ..Default::default() };
/// guidance.prime(&state);
///
/// let input = ControlInput::Attitude(AttitudeCommand { throttle: 0.5, ..Default::default() });
/// let Setpoint::Attitude(setpoint) = guidance.guide(0.004, FlightRegime::Copter, &input, &state) else {
///     unreachable!("attitude commands yield attitude setpoints");
/// };
/// assert!((setpoint.heading_rad - 1.0).abs() < 1e-6); // holds the primed heading
/// assert_eq!(setpoint.thrust, 0.5);
/// ```
pub struct CopterGuidance {
    /// Loop configs and limits, passed into the controllers every tick.
    config: CopterGuidanceConfig,

    altitude: AltitudeController,
    lateral: LateralController,
    /// Where the altitude loop is steered, in meters: the waypoint's altitude, or on the way
    /// down to it, slewed at the descent limit and leashed `altitude_leash_m` below the
    /// vehicle. `None` until waypoint or land flight latches it from the vehicle's altitude.
    altitude_target_m: Option<f32>,
    /// How fast the altitude target last descended, in m/s, negative while it climbs (0 when
    /// level). Latched from the vehicle's climb, then raised toward the descent rate: at
    /// `climb_decel_mps2` while negative, at `descent_accel_mps2` from 0.
    descent_speed_mps: f32,

    /// Heading-hold target for attitude, absolute-attitude, waypoint, and land commands.
    heading: f32,
    /// Turns the heading-hold target along the waypoint leg, or yields it.
    leg_heading: LegHeading,

    /// Paces the lateral loop.
    lateral_rate: RateDivider,
    /// The lateral loop's last roll/pitch in radians, held between its runs.
    tilt_rad: Vec2,
    /// The held tilt was capped at `max_tilt_rad` when the lateral loop last ran.
    tilt_capped: bool,
    /// The lateral loop's last acceleration request in m/s², before the tilt cap. While
    /// `tilt_capped`, the loop's integral is held against it on the next run.
    requested_accel_mps2: Vec2,

    /// What the last `guide` call clipped.
    saturation: Saturation,

    /// Estimates the wind while airborne and not paused.
    wind: HoverWind,
}

impl CopterGuidance {
    /// Creates a new [CopterGuidance] with the specified configuration.
    ///
    /// # Panics
    ///
    /// If `config` is invalid ([`CopterGuidanceConfig::validate`]).
    pub fn new(config: CopterGuidanceConfig) -> Self {
        if let Err(error) = config.validate() {
            panic!("invalid CopterGuidanceConfig: {error}");
        }
        CopterGuidance {
            config,
            altitude: AltitudeController::default(),
            lateral: LateralController::default(),
            altitude_target_m: None,
            descent_speed_mps: 0.0,

            heading: 0.0,
            leg_heading: LegHeading::default(),

            lateral_rate: RateDivider::default(),
            tilt_rad: Vec2::zeros(),
            tilt_capped: false,
            requested_accel_mps2: Vec2::zeros(),
            saturation: Saturation::default(),
            wind: HoverWind::default(),
        }
    }

    /// Pauses (or resumes) the wind estimate's updates, keeping the estimate: for a VTOL's
    /// guidance while it flies outside hover (a transition, or pusher thrust along the body),
    /// where the drag model doesn't hold.
    pub(crate) fn set_wind_paused(&mut self, paused: bool) {
        self.wind.set_paused(paused);
    }
}

impl Configurable for CopterGuidance {
    type Config = CopterGuidanceConfig;

    fn config(&self) -> &CopterGuidanceConfig {
        &self.config
    }

    /// Validates with [`CopterGuidanceConfig::validate`]. The heading-hold target and the
    /// lateral loop's timing are kept; a new `navigation_period_s` applies from the next tick,
    /// and the held waypoint tilt is re-capped to a lowered `max_tilt_rad` at once.
    fn set_config(&mut self, config: CopterGuidanceConfig) -> Result<(), InvalidConfig> {
        config.validate()?;
        let old = &self.config;
        self.altitude
            .rescale_integral(&old.altitude, &config.altitude);
        self.lateral.rescale_integral(&old.lateral, &config.lateral);
        self.config = config;
        if self.tilt_rad.norm() > config.max_tilt_rad {
            self.tilt_capped = true;
        }
        self.tilt_rad = cap_magnitude(self.tilt_rad, config.max_tilt_rad);
        Ok(())
    }
}

impl Guidance for CopterGuidance {
    fn guide(
        &mut self,
        dt: f32,
        _regime: FlightRegime,
        input: &ControlInput,
        estimated_state: &VehicleState,
    ) -> Setpoint {
        assert_dt(dt);
        self.saturation = Saturation::default();
        self.wind.update(
            dt,
            &self.config.wind,
            self.config.airborne_height_m,
            estimated_state,
        );

        if !matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_)) {
            // The position loops are idle: clear them so re-entering waypoint mode starts
            // fresh, runs the lateral loop at once instead of holding a stale tilt, carries no
            // integral from an earlier leg, and starts its altitude target from the vehicle.
            self.altitude = AltitudeController::default();
            self.lateral = LateralController::default();
            self.requested_accel_mps2 = Vec2::zeros();
            self.altitude_target_m = None;
            self.descent_speed_mps = 0.0;
            self.lateral_rate.reset();
        }
        if !matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_)) {
            self.leg_heading.reset();
        }

        match input {
            ControlInput::Attitude(attitude_command) => {
                Setpoint::Attitude(self.attitude_setpoint(dt, attitude_command, estimated_state))
            }
            ControlInput::Rate(rate_command) => {
                self.follow_heading(estimated_state);
                let mut setpoint: RateSetpoint = rate_command.into();
                (setpoint.thrust, setpoint.idle) = self.hold_piloted(
                    rate_command.throttle,
                    setpoint.thrust,
                    estimated_state.velocity_mps.z,
                );
                Setpoint::Rate(setpoint)
            }
            ControlInput::Waypoint(waypoint_command) => {
                Setpoint::Attitude(self.navigate(dt, waypoint_command, estimated_state))
            }
            ControlInput::AbsoluteAttitude(command) => {
                Setpoint::Attitude(self.absolute_attitude_setpoint(command, estimated_state))
            }
            ControlInput::Land(command) => {
                Setpoint::Attitude(self.land(dt, command, estimated_state))
            }
            ControlInput::AbsoluteRate(command) => {
                Setpoint::BodyRate(self.absolute_rate_setpoint(command, estimated_state))
            }
        }
    }

    /// Clears the altitude and lateral controller state, the altitude target and its descent,
    /// the leg, and any held waypoint tilt, and latches the current heading as the yaw-hold
    /// target. Primed on the ground (no more than
    /// [`airborne_height_m`](CopterGuidanceConfig::airborne_height_m) above the last
    /// ground altitude, or never primed), it also latches the ground altitude and forgets the
    /// wind; primed in the air (a VTOL back in hover), it keeps both. Re-armed on ground more
    /// than `airborne_height_m` above where it was last primed, it counts as airborne and
    /// feeds the wind estimate from the ground until liftoff.
    fn prime(&mut self, state: &VehicleState) {
        self.wind.prime(self.config.airborne_height_m, state);
        self.altitude = AltitudeController::default();
        self.lateral = LateralController::default();
        self.altitude_target_m = None;
        self.descent_speed_mps = 0.0;
        self.heading = state.heading_rad;
        self.leg_heading.reset();
        self.lateral_rate.reset();
        self.tilt_rad = Vec2::zeros();
        self.tilt_capped = false;
        self.requested_accel_mps2 = Vec2::zeros();
        self.saturation = Saturation::default();
    }

    /// `tilt` when the waypoint tilt request was capped at
    /// [`max_tilt_rad`](CopterGuidanceConfig::max_tilt_rad) (held with the tilt between
    /// lateral-loop runs), and `thrust` when the altitude loop's thrust, attitude mode's
    /// boosted throttle, or an absolute attitude's thrust was clipped to `[0, 1]`, held at
    /// [`max_boost_thrust`](ThrustLimits::max_boost_thrust), raised to
    /// [`min_thrust`](ThrustLimits::min_thrust), or raised by the sink guard. A tilt
    /// beyond the stabilizer's limit in an absolute attitude is the stabilizer's to flag.
    fn saturation(&self) -> Saturation {
        self.saturation
    }

    /// The wind, estimated from the drag model in
    /// [`wind`](CopterGuidanceConfig::wind) on every tick more than
    /// [`airborne_height_m`](CopterGuidanceConfig::airborne_height_m)
    /// above the altitude primed on the ground, the vehicle's frame taken as the thrust frame
    /// (a tailsitter's hover view under [`View`](crate::View)), except while a VTOL's guidance
    /// flies outside hover; `None` before the first update, or without drag coefficients.
    fn wind(&self) -> Option<WindEstimate> {
        self.wind.estimate()
    }
}

impl CopterGuidance {
    /// Scales the roll/pitch sticks to radians, boosts throttle for the measured tilt, and
    /// slews the heading-hold target with the yaw stick.
    fn attitude_setpoint(
        &mut self,
        dt: f32,
        attitude_command: &AttitudeCommand,
        estimated_state: &VehicleState,
    ) -> AttitudeSetpoint {
        // Commands from input devices can be out of range or NaN; saturate rather than panic
        // (see `crate::math`).
        let yaw = saturate_unit(attitude_command.yaw);
        let max_stick = self.config.max_stick_angles_rad;
        self.set_heading_target(
            self.heading + yaw * self.config.stick_yaw_rate_radps * dt,
            estimated_state,
        );

        // Angle boost: hold the vertical thrust the stick asks for while tilted, as the
        // altitude loop does (at most 2× past 60°, none when inverted), up to
        // `max_boost_thrust`. Saturated to [0, 1]; NaN means none.
        let throttle = attitude_command.throttle;
        let boosted = self.boost(throttle, &estimated_state.attitude);
        let boosted = self.clip_thrust(boosted);
        let (thrust, idle) = self.hold_piloted(throttle, boosted, estimated_state.velocity_mps.z);

        AttitudeSetpoint {
            roll_rad: saturate_unit(attitude_command.roll) * max_stick.x,
            pitch_rad: saturate_unit(attitude_command.pitch) * max_stick.y,
            heading_rad: self.heading,
            thrust,
            transition: false,
            idle,
        }
    }

    /// Rate flight: tracks the vehicle so attitude or waypoint flight holds the heading it has
    /// when rate flight ends, not the one it had when rate flight began.
    fn follow_heading(&mut self, estimated_state: &VehicleState) {
        if estimated_state.heading_rad.is_finite() {
            self.heading = wrap_angle(estimated_state.heading_rad);
        }
    }

    /// Flies absolute rates as given, with the thrust saturated (not boosted).
    fn absolute_rate_setpoint(
        &mut self,
        command: &AbsoluteRateCommand,
        estimated_state: &VehicleState,
    ) -> BodyRateSetpoint {
        self.follow_heading(estimated_state);
        let mut setpoint = BodyRateSetpoint::from(command);
        (setpoint.thrust, setpoint.idle) = self.hold_absolute(command.thrust, estimated_state);
        setpoint
    }

    /// Flies an absolute attitude: the heading becomes the heading-hold target, so stick
    /// flight afterward keeps it.
    fn absolute_attitude_setpoint(
        &mut self,
        command: &AbsoluteAttitudeCommand,
        estimated_state: &VehicleState,
    ) -> AttitudeSetpoint {
        // A non-finite heading holds the current target.
        let target_rad = if command.heading_rad.is_finite() {
            command.heading_rad
        } else {
            self.heading
        };
        self.set_heading_target(target_rad, estimated_state);
        let (thrust, idle) = self.hold_absolute(command.thrust, estimated_state);
        AttitudeSetpoint {
            roll_rad: command.roll_rad,
            pitch_rad: command.pitch_rad,
            heading_rad: self.heading,
            thrust,
            transition: false,
            idle,
        }
    }

    /// Sets the heading-hold target to `target_rad`, wrapped.
    fn set_heading_target(&mut self, target_rad: f32, estimated_state: &VehicleState) {
        // Wrapped so sustained yaw input can't grow the target without bound; the yaw
        // controller works on the wrapped error either way.
        let target = wrap_angle(target_rad);
        if target.is_finite() {
            self.heading = target;
        } else if estimated_state.heading_rad.is_finite() {
            // A NaN target (e.g. primed from a NaN estimate) would otherwise disable heading
            // hold for good; re-latch from the current estimate once it's valid.
            self.heading = wrap_angle(estimated_state.heading_rad);
        }
    }

    /// Flies toward the waypoint, turning the heading-hold target to the waypoint's heading
    /// (`heading_rate_radps`), along the leg (`waypoint_yaw_radps`), or yielding it
    /// (`heading_yield_s`): the lateral loop gives roll/pitch (once per navigation period, held
    /// in between) and the altitude loop gives thrust (every tick), toward an altitude target
    /// that descends no faster than `max_descent_mps`, speeding up and braking at
    /// `descent_accel_mps2`, and no further than `altitude_leash_m` below the vehicle.
    fn navigate(
        &mut self,
        dt: f32,
        waypoint_command: &WaypointCommand,
        estimated_state: &VehicleState,
    ) -> AttitudeSetpoint {
        let target = self.descend_toward(
            dt,
            waypoint_command.altitude_m,
            estimated_state.position_m.z,
            estimated_state.velocity_mps.z,
        );
        let wind = self.wind.estimate();
        let heading_rad = self.leg_heading.target_rad(
            dt,
            &self.config,
            self.heading,
            waypoint_command,
            wind.as_ref(),
            estimated_state,
        );
        self.set_heading_target(heading_rad, estimated_state);
        self.fly_to(dt, waypoint_command, target, estimated_state)
    }

    /// Lands at the command's position: flies there as to a waypoint, heading held or turned to
    /// a wingtip into the wind (`wind_heading_min_mps`), with an altitude target
    /// that keeps descending at `land_speed_mps`, leashed `altitude_leash_m` below the vehicle.
    /// The descent starts and speeds up to it as a waypoint descent does
    /// ([`descent_start_m`](Self::descent_start_m),
    /// [`ramped_descent_mps`](Self::ramped_descent_mps)): stepping to it cut the RealFlight
    /// eXplora's thrust from 0.89 to 0.76 in one tick (#476).
    fn land(
        &mut self,
        dt: f32,
        land_command: &LandCommand,
        estimated_state: &VehicleState,
    ) -> AttitudeSetpoint {
        let altitude_m = estimated_state.position_m.z;
        let start_m = self.descent_start_m(altitude_m, estimated_state.velocity_mps.z);
        let speed_mps = self.ramped_descent_mps(dt, self.config.land_speed_mps);
        // With nothing latched, the NaN target holds hover.
        let target_m = start_m.map_or(f32::NAN, |start_m| {
            lowered(
                start_m,
                speed_mps * dt,
                altitude_m,
                self.config.altitude_leash_m,
            )
        });
        self.altitude_target_m = Some(target_m).filter(|t| t.is_finite());
        // With nothing latched nothing descends, so a waypoint descent next starts from rest.
        self.descent_speed_mps = if self.altitude_target_m.is_some() {
            speed_mps
        } else {
            0.0
        };
        let waypoint = WaypointCommand {
            position_m: land_command.position_m,
            ..Default::default()
        };
        let target = AltitudeTarget {
            altitude_m: target_m,
            velocity_mps: -speed_mps,
        };
        let wind = self.wind.estimate();
        let heading_rad = self.leg_heading.land_target_rad(
            dt,
            &self.config,
            self.heading,
            wind.as_ref(),
            estimated_state,
        );
        self.set_heading_target(heading_rad, estimated_state);
        self.fly_to(dt, &waypoint, target, estimated_state)
    }

    /// The altitude loop's target on the way to `waypoint_m`: the waypoint itself when it is
    /// above the latched target or the target reaches it, otherwise the latched target moved
    /// by [`descent_rate_mps`](Self::descent_rate_mps) of its height above the waypoint (and
    /// leashed), with the new target's rate fed forward. That rate starts at the vehicle's
    /// climb ([`descent_start_m`](Self::descent_start_m)) and rises from the last tick's by at most
    /// [`ramped_descent_mps`](Self::ramped_descent_mps)'s step, so a descent starts without a
    /// thrust step: an instant 1.5 m/s cut the RealFlight eXplora's thrust from 0.85 to its
    /// 0.65 floor in 0.25 s and dropped its nose 10° (#417). It falls to 0 at the waypoint, so
    /// the target, its feedforward, and the thrust stay continuous where the waypoint takes
    /// over: arriving, and where the leash puts the target on the waypoint (#445).
    fn descend_toward(
        &mut self,
        dt: f32,
        waypoint_m: f32,
        altitude_m: f32,
        climb_mps: f32,
    ) -> AltitudeTarget {
        let level = AltitudeTarget {
            altitude_m: waypoint_m,
            velocity_mps: 0.0,
        };
        let Some(start_m) = self.descent_start_m(altitude_m, climb_mps) else {
            self.descent_speed_mps = 0.0;
            return level;
        };
        let rate_mps = self.ramped_descent_mps(dt, self.descent_rate_mps(start_m - waypoint_m));
        let step_m = lowered(
            start_m,
            rate_mps * dt,
            altitude_m,
            self.config.altitude_leash_m,
        );
        // `<` is false for NaN: a non-finite waypoint passes through, and the altitude loop
        // holds hover on it.
        let target = if waypoint_m < step_m {
            AltitudeTarget {
                altitude_m: step_m,
                velocity_mps: -self.descent_rate_mps(step_m - waypoint_m).min(rate_mps),
            }
        } else {
            level
        };
        self.descent_speed_mps = -target.velocity_mps;
        self.altitude_target_m = Some(target.altitude_m).filter(|t| t.is_finite());
        target
    }

    /// Where a descent's target moves from: the latched altitude target, or with none latched
    /// the vehicle's `altitude_m`, the target's speed then started at the vehicle's
    /// `climb_mps` (up positive), so the target rises with the vehicle instead of holding below
    /// it; a sink, or an unknown climb, starts it at rest. `None` until there is a finite
    /// altitude to descend from; the altitude loop holds hover on a non-finite estimate
    /// meanwhile (input policy).
    fn descent_start_m(&mut self, altitude_m: f32, climb_mps: f32) -> Option<f32> {
        if self.altitude_target_m.is_some() {
            return self.altitude_target_m;
        }
        if !altitude_m.is_finite() {
            return None;
        }
        // `max` drops a NaN climb: the target starts at rest.
        self.descent_speed_mps = -climb_mps.max(0.0);
        Some(altitude_m)
    }

    /// `limit_mps`, or less while the target sheds a climb or speeds up to it: at most the
    /// last tick's speed plus `climb_decel_mps2 · dt` while climbing, `descent_accel_mps2 · dt`
    /// from level. A slower limit takes over at once, which only adds thrust.
    fn ramped_descent_mps(&self, dt: f32, limit_mps: f32) -> f32 {
        let accel_mps2 = if self.descent_speed_mps < 0.0 {
            self.config.climb_decel_mps2
        } else {
            self.config.descent_accel_mps2
        };
        limit_mps.min(self.descent_speed_mps + accel_mps2 * dt)
    }

    /// The descent rate toward a waypoint `height_m` below the target, in m/s: what
    /// `descent_accel_mps2` can stop on the waypoint, linear at the altitude loop's P near it
    /// ([`shaped_closing_speed`]), at most `max_descent_mps`; 0 at or below it and for NaN.
    /// Near the waypoint the target closes the gap with time constant 1/P, so it eases onto
    /// the waypoint rather than reaching it in a step.
    fn descent_rate_mps(&self, height_m: f32) -> f32 {
        let config = &self.config;
        shaped_closing_speed(height_m, config.altitude.gains.p, config.descent_accel_mps2)
            .min(config.max_descent_mps)
    }

    /// Flies toward the waypoint's position and the altitude `target`, holding the heading-hold
    /// target.
    fn fly_to(
        &mut self,
        dt: f32,
        waypoint_command: &WaypointCommand,
        target: AltitudeTarget,
        estimated_state: &VehicleState,
    ) -> AttitudeSetpoint {
        self.set_heading_target(self.heading, estimated_state);
        let tilt_rad = self.tilt_toward(dt, waypoint_command, estimated_state);

        let linear_thrust = self.altitude.control(
            &self.config.altitude,
            dt,
            target,
            AltitudeEstimate {
                altitude_m: estimated_state.position_m.z,
                velocity_mps: estimated_state.velocity_mps.z,
                attitude: estimated_state.attitude,
            },
        );

        // The altitude loop clamps its thrust to [0, 1]; landing on a bound means it clipped.
        self.saturation.thrust = linear_thrust <= 0.0 || linear_thrust >= 1.0;
        self.saturation.tilt = self.tilt_capped;

        AttitudeSetpoint {
            roll_rad: tilt_rad.x,
            pitch_rad: tilt_rad.y,
            heading_rad: self.heading,
            thrust: self.floor_thrust(linear_thrust),
            transition: false,
            // Never ground idle: the altitude loop's zero is a vehicle in the air shedding
            // climb. TODO(#395): idle once a land detector reports a touchdown.
            idle: false,
        }
    }

    /// Saturates a thrust request to `[0, 1]` (NaN means none), flagging `thrust` when it
    /// was outside.
    fn clip_thrust(&mut self, thrust: f32) -> f32 {
        // `|=`: the boost may have flagged it already this tick.
        self.saturation.thrust |= !(0.0..=1.0).contains(&thrust) && !thrust.is_nan();
        saturate_throttle(thrust)
    }

    /// The stick `throttle` boosted for the measured tilt, held at or below
    /// `max_boost_thrust` unless the stick itself is above it; flags `thrust` when held.
    fn boost(&mut self, throttle: f32, attitude: &UnitQuaternion<f32>) -> f32 {
        let boosted = throttle * tilt_boost(attitude);
        // `max` ignores a NaN throttle, and `>` is false for a NaN boost: NaN passes through.
        let ceiling = self.config.thrust.max_boost_thrust.max(throttle);
        if boosted > ceiling {
            self.saturation.thrust = true;
            ceiling
        } else {
            boosted
        }
    }

    /// An absolute command's `thrust`, saturated to `[0, 1]` (not boosted), then held as a
    /// piloted throttle ([`hold_piloted`](Self::hold_piloted)), and whether it is idle.
    fn hold_absolute(&mut self, thrust: f32, estimated_state: &VehicleState) -> (f32, bool) {
        let clipped = self.clip_thrust(thrust);
        self.hold_piloted(thrust, clipped, estimated_state.velocity_mps.z)
    }

    /// The piloted `thrust` and whether the pilot's `throttle` is idle (at or below
    /// `idle_throttle`, or NaN): an idle throttle passes `thrust` through; any other is
    /// raised to `min_thrust`, then gets the sink guard for the vertical speed `climb_mps` (up
    /// positive).
    fn hold_piloted(&mut self, throttle: f32, thrust: f32, climb_mps: f32) -> (f32, bool) {
        if throttle > self.config.idle_throttle {
            let floored = self.floor_thrust(thrust);
            (self.guard_sink(floored, climb_mps), false)
        } else {
            (thrust, true)
        }
    }

    /// [`guard_sink`] with the configured limit and gain, flagging `thrust` when it acts.
    fn guard_sink(&mut self, thrust: f32, climb_mps: f32) -> f32 {
        let limits = &self.config.thrust;
        let Some(raised) = guard_sink(thrust, climb_mps, limits.sink_limit_mps, limits.sink_gain)
        else {
            return thrust;
        };
        self.saturation.thrust = true;
        raised
    }

    /// Raises `thrust` to `min_thrust`, flagging `thrust` when it does.
    fn floor_thrust(&mut self, thrust: f32) -> f32 {
        let min_thrust = self.config.thrust.min_thrust;
        if thrust < min_thrust {
            self.saturation.thrust = true;
            min_thrust
        } else {
            thrust
        }
    }

    /// Roll/pitch in radians toward the waypoint from the lateral loop, run when
    /// [`lateral_rate`](Self::lateral_rate) is due and held otherwise.
    fn tilt_toward(
        &mut self,
        dt: f32,
        waypoint_command: &WaypointCommand,
        estimated_state: &VehicleState,
    ) -> Vec2 {
        let Some(step) = self.lateral_rate.due(dt, self.config.navigation_period_s) else {
            return self.tilt_rad;
        };

        let target = LateralTarget {
            position_m: waypoint_command.position_m,
            velocity_mps: waypoint_command.velocity_mps.unwrap_or_else(Vec2::zeros),
            max_speed_mps: waypoint_command.cruise_speed_mps,
        };
        let estimate = LateralEstimate {
            position_m: estimated_state.position_m.xy(),
            velocity_mps: estimated_state.velocity_mps.xy(),
        };
        let heading_rad = estimated_state.heading_rad;

        // A non-finite target or estimate gets level for this tick only (input policy). The
        // loop doesn't run, so the neutral output isn't held for a period and the next tick
        // retries over the combined time.
        let error = target.position_m - estimate.position_m;
        if !(all_finite(&error)
            && all_finite(&target.velocity_mps)
            && all_finite(&estimate.velocity_mps)
            && heading_rad.is_finite())
        {
            self.tilt_capped = false;
            return Vec2::zeros();
        }

        let limit_mps2 = if self.tilt_capped {
            self.requested_accel_mps2
        } else {
            Vec2::zeros()
        };
        let wind_mps = self
            .wind
            .estimate()
            .map_or(Vec2::zeros(), |w| w.velocity_mps);
        let accel_mps2 =
            self.lateral
                .control(&self.config.lateral, step, target, estimate, limit_mps2)
                + drag_feedforward_mps2(
                    &self.config.wind,
                    self.config.feedforward_hold_band_mps,
                    self.lateral.commanded_velocity_mps(),
                    wind_mps,
                    heading_rad,
                );
        self.requested_accel_mps2 = accel_mps2;
        let requested = tilt_for_acceleration(accel_mps2, heading_rad);
        self.tilt_capped = requested.norm() > self.config.max_tilt_rad;
        self.tilt_rad = cap_magnitude(requested, self.config.max_tilt_rad);
        self.lateral_rate.ran();
        self.tilt_rad
    }
}

/// Roll/pitch in radians, at `heading_rad`, that points thrust to give horizontal
/// acceleration `accel_mps2` (north, east) at constant altitude: a tilt of `atan(|a| / g)`
/// toward it. Ahead is nose down (negative pitch), to the right is right roll. The tilt is a
/// vector of that length, split between the axes, exact for single-axis requests and close for
/// diagonal ones at waypoint tilts. A non-finite acceleration or heading gives level.
fn tilt_for_acceleration(accel_mps2: Vec2, heading_rad: f32) -> Vec2 {
    let accel_norm = accel_mps2.norm();
    if !accel_norm.is_finite() || accel_norm == 0.0 || !heading_rad.is_finite() {
        return Vec2::zeros();
    }
    let tilt_rad = libm::atanf(accel_norm / GRAVITY);
    // Rotate (north, east) into (ahead, right) of the heading.
    let (sin, cos) = (libm::sinf(heading_rad), libm::cosf(heading_rad));
    let ahead = accel_mps2.x * cos + accel_mps2.y * sin;
    let right = -accel_mps2.x * sin + accel_mps2.y * cos;
    Vec2::new(right, -ahead) * (tilt_rad / accel_norm)
}

/// The acceleration, in m/s² (north, east), that holds off the drag `wind`'s model puts on a
/// leg's speed: the lateral loop's commanded velocity `commanded_mps` past
/// `hold_band_mps`, through air moving at `wind_mps` (both north, east), facing
/// `heading_rad`; on a hold, that is the wind's drag alone. Fed forward, so the lateral loop's
/// I term trims only what the model misses: learned by the I instead, a leg's drag stays wound
/// up when the vehicle stops and carries it past the waypoint (#609). Zero without a drag
/// model.
fn drag_feedforward_mps2(
    wind: &WindConfig,
    hold_band_mps: f32,
    commanded_mps: Vec2,
    wind_mps: Vec2,
    heading_rad: f32,
) -> Vec2 {
    let speed_mps = commanded_mps.norm();
    let leg_mps = if speed_mps > hold_band_mps {
        commanded_mps * ((speed_mps - hold_band_mps) / speed_mps)
    } else {
        Vec2::zeros()
    };
    let air_mps = leg_mps - wind_mps;
    // (north, east) into (ahead, right) of the heading, the thrust frame's `x` and `y` level,
    // and the push back out.
    let (sin, cos) = (libm::sinf(heading_rad), libm::cosf(heading_rad));
    let air_body_mps = Vec2::new(
        air_mps.x * cos + air_mps.y * sin,
        -air_mps.x * sin + air_mps.y * cos,
    );
    let push_body_mps2 = -wind.drag_mps2(air_body_mps);
    Vec2::new(
        push_body_mps2.x * cos - push_body_mps2.y * sin,
        push_body_mps2.x * sin + push_body_mps2.y * cos,
    )
}

/// A descent target `start_m` lowered by `step_m`, but no further than `leash_m` below the
/// vehicle's `altitude_m`. `f32::max` ignores a NaN side: a NaN altitude keeps
/// lowering a latched target.
fn lowered(start_m: f32, step_m: f32, altitude_m: f32, leash_m: f32) -> f32 {
    (start_m - step_m).max(altitude_m - leash_m)
}