Skip to main content

stable_flight/guidance/vtol/
quadplane.rs

1//! [`QuadPlaneGuidance`]: hover and plane guidance under one [`LiftTransition`].
2
3use super::{
4    FallbackHold, ForwardThrust, ForwardThrustConfig, LiftTransition, LiftTransitionConfig,
5    LiftTransitionStep, OffNoseSpeed, OffNoseSpeedConfig, ThrustHandoff,
6};
7use crate::controllers::InvalidConfig;
8use crate::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
9use crate::guidance::plane::{PlaneGuidance, PlaneGuidanceConfig};
10use crate::math::{DEG, bank_rad, saturate_symmetric, saturate_throttle};
11use crate::params::{ParamError, Params, locate};
12use crate::{
13    AttitudeSetpoint, BlendSetpoint, Configurable, ControlInput, FlightMode, FlightModeReport,
14    FlightRegime, Guidance, ModeRefusal, PlaneSetpoint, Saturation, Setpoint, VehicleState,
15    WaypointCommand, WindEstimate,
16};
17
18mod deceleration;
19#[cfg(test)]
20mod tests;
21
22use deceleration::BackDeceleration;
23
24/// [`QuadPlaneGuidance`] settings: its two guidances', the transition's, forward thrust's, and
25/// the off-nose speed cut's.
26#[derive(Clone, Copy, Debug, Default, PartialEq)]
27pub struct QuadPlaneGuidanceConfig {
28    /// Hover guidance, on the lift rotors.
29    pub hover: CopterGuidanceConfig,
30    /// Wing-borne guidance, on the surfaces and pusher.
31    pub plane: PlaneGuidanceConfig,
32    /// The transition between them, its pusher, handoff blend, and roll limit.
33    pub transition: LiftTransitionConfig,
34    /// The pusher in copter flight; off by default.
35    pub forward: ForwardThrustConfig,
36    /// The waypoint speed cut in copter flight while the nose is off the waypoint; on by
37    /// default.
38    pub off_nose: OffNoseSpeedConfig,
39}
40
41impl QuadPlaneGuidanceConfig {
42    /// `Ok` when each part validates.
43    ///
44    /// # Errors
45    ///
46    /// The first part's [`InvalidConfig`], in its section (`hover`, `plane`, `transition`,
47    /// `forward`, `off_nose`).
48    pub fn validate(&self) -> Result<(), InvalidConfig> {
49        self.hover.validate().map_err(|e| e.in_section("hover"))?;
50        self.plane.validate().map_err(|e| e.in_section("plane"))?;
51        self.transition
52            .validate()
53            .map_err(|e| e.in_section("transition"))?;
54        self.forward
55            .validate()
56            .map_err(|e| e.in_section("forward"))?;
57        self.off_nose
58            .validate()
59            .map_err(|e| e.in_section("off_nose"))
60    }
61}
62
63/// Guidance for a lift+cruise VTOL (quadplane): [`CopterGuidance`] on the lift rotors and
64/// [`PlaneGuidance`] on the surfaces and pusher, with a [`LiftTransition`] choosing between
65/// them and trading the lift across the transitions. The vehicle stays level throughout, so
66/// there's no [`View`](crate::View).
67///
68/// Each tick:
69///
70/// 1. The requested regime is the command's, except that [`ControlInput::Land`] asks for
71///    `Copter`: it lands as a copter, transitioning back first.
72/// 2. The transition steps, unless the bank is past
73///    [`roll_limit_rad`](LiftTransitionConfig::roll_limit_rad) in a transition: then it's cut
74///    short ([`LiftTransition::cut_short`]).
75/// 3. The mode picks the setpoint:
76///
77///    | Mode | Setpoint |
78///    |---|---|
79///    | `Copter` | hover guidance, on the command's input; after a fallback, until `Copter` is requested, a waypoint as a hover where copter flight took over; on a waypoint or land with [`ForwardThrust`] on, [`Setpoint::Blend`] at lift share 1: the hover's attitude with its nose-down pitch held to the limit, the plane side at that roll and pitch, the pusher on the rest |
80///    | `ToPlane` | [`Setpoint::Blend`]: both sides wings level at the plane guidance's pitch for the command, within ArduPilot's transition limits; hover holding the altitude the transition began at, heading held; the pusher on the plane guidance's thrust, rising at most [`pusher_slew_per_s`](LiftTransitionConfig::pusher_slew_per_s), up to [`forward_thrust`](LiftTransitionConfig::forward_thrust); the step's lift share |
81///    | `Plane` | plane guidance, on the command's input |
82///    | `ToCopter` | [`Setpoint::Blend`]: both sides wings level, the nose up to slow it ([`back_decel_mps2`](LiftTransitionConfig::back_decel_mps2)); hover holding the altitude the back transition began at, heading held; the pusher stopped; the step's lift share |
83///
84///    The hover side holds altitude with the copter's altitude loop (ArduPilot holds it through
85///    its airspeed wait, `SLT_Transition::update`). Going forward the pusher and pitch are the
86///    plane's, as ArduPilot flies its throttle and pitch from the plane controller with pitch
87///    held to 0 below 3 m/s of ground speed,
88///    ±[`forward_pitch_max_rad`](LiftTransitionConfig::forward_pitch_max_rad) while waiting,
89///    and twice it plus 2° on the ramp (`SLT_Transition::set_FW_roll_pitch`): its airspeed
90///    loop keeps the lift ramp from overspeeding, and its altitude loop trims the wing. Going
91///    back the pusher stops (PX4's `Standard::update_transition_state`) and the nose comes up
92///    while it slows less than `back_decel_mps2`, at most about 17° (PX4's back-transition
93///    deceleration, `FlightTaskTransition::computeBackTransitionTiltSetpoint`; ArduPilot
94///    decelerates at its `Q_TRANS_DECEL`): drag alone left the Alia at 31 m/s on its 28 s
95///    timeout (#496).
96///
97/// 4. A side that starts flying is primed: the plane guidance as the forward transition
98///    begins and again entering `Plane` (through the transition its total energy control flies
99///    from no airspeed, and only its thrust is used), the hover guidance as the back transition
100///    begins. Entering `Plane`, the
101///    pusher's thrust blends from where it was over
102///    [`handoff_s`](LiftTransitionConfig::handoff_s) ([`ThrustHandoff`]).
103///
104///    Forward thrust flies only position-controlled input, as ArduPilot's `Q_FWD_THR_USE` 1
105///    (`QuadPlane::get_vfwd_method`): sticks keep the pilot's tilt. A waypoint in
106///    `Copter` reaches the hover guidance with its speed cut while the nose is off it
107///    ([`OffNoseSpeed`]); land flies uncut, since it lands where the vehicle already is.
108///
109/// Pair it with a [`QuadPlaneStabilizer`](crate::stabilizers::vtol::QuadPlaneStabilizer).
110/// Params chain the parts' (`GUID_*`, `PGUID_*`, `TRAN_*`, `FWD_*`, `OFFNOSE_*`).
111///
112/// # Examples
113///
114/// ```
115/// use stable_flight::guidance::vtol::{QuadPlaneGuidance, QuadPlaneGuidanceConfig};
116/// use stable_flight::{
117///     AttitudeCommand, ControlInput, FlightMode, FlightRegime, Guidance, Setpoint, Vec3,
118///     VehicleState,
119/// };
120///
121/// let mut guidance = QuadPlaneGuidance::new(QuadPlaneGuidanceConfig::default());
122/// guidance.prime(&VehicleState::default());
123///
124/// let sticks = ControlInput::Attitude(AttitudeCommand { throttle: 0.6, ..Default::default() });
125/// let high = VehicleState { position_m: Vec3::new(0.0, 0.0, 20.0), ..Default::default() };
126/// let setpoint = guidance.guide(0.01, FlightRegime::Plane, &sticks, &high);
127/// let Setpoint::Blend(blend) = setpoint else { panic!("{setpoint:?}") };
128/// assert_eq!(blend.lift_share, 1.0); // the lift rotors hold it up while the pusher spins up
129/// assert_eq!(guidance.flight_mode().unwrap().mode, FlightMode::ToPlane);
130/// ```
131pub struct QuadPlaneGuidance {
132    config: QuadPlaneGuidanceConfig,
133    hover: CopterGuidance,
134    plane: PlaneGuidance,
135    transition: LiftTransition,
136    forward: ForwardThrust,
137    off_nose: OffNoseSpeed,
138    handoff: ThrustHandoff,
139    fallback_hold: FallbackHold,
140    deceleration: BackDeceleration,
141    /// The mode the last tick flew.
142    mode: FlightMode,
143    /// The pusher's linear thrust on the last tick.
144    pusher_thrust: f32,
145    /// The altitude a transition holds, latched as it begins, in m.
146    hold_altitude_m: f32,
147}
148
149/// Added to the forward pitch limit before it doubles on the lift ramp, in rad: ArduPilot's
150/// `2 (Q_TRAN_PIT_MAX + 1°)` (`SLT_Transition::set_FW_roll_pitch`).
151const RAMP_PITCH_MARGIN_RAD: f32 = 1.0 * DEG;
152
153/// Below this ground speed the forward transition holds pitch at 0, in m/s: until then the
154/// ground speed is too small to fly from (ArduPilot's `SLT_Transition::set_FW_roll_pitch`).
155const LEVEL_BELOW_MPS: f32 = 3.0;
156
157impl QuadPlaneGuidance {
158    /// Guidance with `config`, in `Copter`.
159    ///
160    /// # Panics
161    ///
162    /// If `config` is invalid ([`QuadPlaneGuidanceConfig::validate`]).
163    pub fn new(config: QuadPlaneGuidanceConfig) -> Self {
164        if let Err(error) = config.validate() {
165            panic!("invalid QuadPlaneGuidanceConfig: {error}");
166        }
167        QuadPlaneGuidance {
168            config,
169            hover: CopterGuidance::new(config.hover),
170            plane: PlaneGuidance::new(config.plane),
171            transition: LiftTransition::new(config.transition),
172            forward: ForwardThrust::new(config.forward),
173            off_nose: OffNoseSpeed::new(config.off_nose),
174            handoff: ThrustHandoff::new(config.transition.handoff_s),
175            fallback_hold: FallbackHold::default(),
176            deceleration: BackDeceleration::default(),
177            mode: FlightMode::Copter,
178            pusher_thrust: 0.0,
179            hold_altitude_m: f32::NAN,
180        }
181    }
182
183    /// This tick's step: the transition cut short if it has banked past the limit, else
184    /// stepped.
185    fn step(
186        &mut self,
187        dt: f32,
188        requested: FlightRegime,
189        state: &VehicleState,
190    ) -> LiftTransitionStep {
191        let transitioning = matches!(self.mode, FlightMode::ToPlane | FlightMode::ToCopter);
192        // `>` is false for NaN: an unknown attitude leaves it to the timeouts.
193        let rolled_over = transitioning
194            && bank_rad(&state.attitude).abs() > self.config.transition.roll_limit_rad;
195        if rolled_over {
196            self.transition.cut_short(ModeRefusal::RollError)
197        } else {
198            self.transition.update(dt, requested, state)
199        }
200    }
201
202    /// Readies the side that starts flying as the mode changes from the last tick's to `to`.
203    fn enter(&mut self, to: FlightMode, state: &VehicleState) {
204        match to {
205            FlightMode::ToPlane => {
206                self.plane.prime(state);
207                self.hold_altitude_m = state.position_m.z;
208                self.pusher_thrust = 0.0;
209            }
210            FlightMode::Plane => {
211                // Fresh either way: out of the back transition it hasn't flown, and out of the
212                // forward one its energy control flew from no airspeed, its demands and
213                // integrals filled by a transition that only took its pusher thrust (the
214                // X-Plane Alia dove 90 m at full nose-down on them, #454). The pusher's
215                // thrust carries over in the handoff below.
216                self.plane.prime(state);
217                self.handoff = ThrustHandoff::new(self.config.transition.handoff_s);
218                self.handoff.start(self.pusher_thrust);
219            }
220            FlightMode::ToCopter if self.mode == FlightMode::Plane => {
221                self.hover.prime(state);
222                self.hold_altitude_m = state.position_m.z;
223                self.deceleration.reset();
224            }
225            _ => {}
226        }
227    }
228
229    /// The hover side through a transition: the hover guidance holding
230    /// [`hold_altitude_m`](Self::hold_altitude_m) where the vehicle is, wings level at
231    /// `pitch_rad`. The waypoint moves with the vehicle at its own velocity, so the lateral loop
232    /// asks for nothing, and its tilt is replaced anyway. Flying it as a waypoint keeps the
233    /// altitude loop's state continuous with waypoint flight on either side of a transition.
234    fn hold_level(&mut self, dt: f32, pitch_rad: f32, state: &VehicleState) -> AttitudeSetpoint {
235        let hold = ControlInput::Waypoint(WaypointCommand {
236            position_m: state.position_m.xy(),
237            velocity_mps: Some(state.velocity_mps.xy()),
238            altitude_m: self.hold_altitude_m,
239            cruise_speed_mps: 0.0,
240            heading_rad: None,
241        });
242        match self.hover.guide(dt, FlightRegime::Copter, &hold, state) {
243            Setpoint::Attitude(setpoint) => AttitudeSetpoint {
244                roll_rad: 0.0,
245                pitch_rad,
246                ..setpoint
247            },
248            _ => unreachable!("copter guidance flies a waypoint as an attitude"),
249        }
250    }
251
252    /// `input` for the wing through the forward transition: a waypoint's altitude replaced by
253    /// [`hold_altitude_m`](Self::hold_altitude_m), the one the lift rotors hold, so the wing
254    /// pitches for level flight and carries the weight as the lift ramps out. Toward a lower
255    /// altitude the wing would pitch nose down while the lift rotors hold, enter plane flight
256    /// sinking and unloaded, and stall pulling out: the sim Alia sank at 19 m/s (#491). A climb
257    /// or descent starts once the wing is flying. PX4 raises the transition pitch toward
258    /// `FW_PSP_OFF` as the blend proceeds, whatever the altitude
259    /// (`Standard::update_transition_state`). Other inputs pass through.
260    fn at_held_altitude(&self, input: &ControlInput) -> ControlInput {
261        match input {
262            ControlInput::Waypoint(waypoint) => ControlInput::Waypoint(WaypointCommand {
263                altitude_m: self.hold_altitude_m,
264                ..*waypoint
265            }),
266            _ => *input,
267        }
268    }
269
270    /// The parts whose params chain, in order.
271    fn parts(&self) -> [&dyn Params; 5] {
272        [
273            &self.hover,
274            &self.plane,
275            &self.transition,
276            &self.forward,
277            &self.off_nose,
278        ]
279    }
280
281    /// [`parts`](Self::parts), mutably, in the same order.
282    fn parts_mut(&mut self) -> [&mut dyn Params; 5] {
283        [
284            &mut self.hover,
285            &mut self.plane,
286            &mut self.transition,
287            &mut self.forward,
288            &mut self.off_nose,
289        ]
290    }
291
292    /// Copter flight: the hover guidance on `input`, a waypoint's speed cut while the nose is
293    /// off it ([`OffNoseSpeed`]), its nose-down pitch handed to the pusher on a waypoint or
294    /// land while [`ForwardThrust`] is on.
295    fn copter(&mut self, dt: f32, input: &ControlInput, state: &VehicleState) -> Setpoint {
296        let cut;
297        let flown = match input {
298            ControlInput::Waypoint(waypoint) => {
299                cut = ControlInput::Waypoint(self.off_nose.cap(waypoint, state));
300                &cut
301            }
302            _ => input,
303        };
304        let setpoint = self.hover.guide(dt, FlightRegime::Copter, flown, state);
305        let positioned = matches!(input, ControlInput::Waypoint(_) | ControlInput::Land(_));
306        let (true, Setpoint::Attitude(hover)) = (positioned && self.forward.enabled(), setpoint)
307        else {
308            self.pusher_thrust = 0.0;
309            return setpoint;
310        };
311        let split = self.forward.split(hover.pitch_rad);
312        self.pusher_thrust = split.thrust;
313        Setpoint::Blend(BlendSetpoint {
314            hover: AttitudeSetpoint {
315                pitch_rad: split.pitch_rad,
316                ..hover
317            },
318            plane: PlaneSetpoint {
319                roll_rad: hover.roll_rad,
320                pitch_rad: split.pitch_rad,
321                thrust: split.thrust,
322                ..PlaneSetpoint::default()
323            },
324            lift_share: 1.0,
325        })
326    }
327
328    /// Copies the parts' configs back after a param write, so [`Configurable::config`] stays
329    /// the one view of them.
330    fn sync_config(&mut self) {
331        self.config = QuadPlaneGuidanceConfig {
332            hover: *self.hover.config(),
333            plane: *self.plane.config(),
334            transition: *self.transition.config(),
335            forward: *self.forward.config(),
336            off_nose: *self.off_nose.config(),
337        };
338    }
339}
340
341/// The forward transition's pitch limit, up or down: ArduPilot's transition limits, 0 below
342/// [`LEVEL_BELOW_MPS`] of ground speed, then `max_rad` while the lift rotors carry it all,
343/// `2 (max_rad + 1°)` on the ramp (`SLT_Transition::set_FW_roll_pitch`).
344fn forward_pitch_limit_rad(max_rad: f32, lift_share: f32, state: &VehicleState) -> f32 {
345    if lift_share < 1.0 {
346        2.0 * (max_rad + RAMP_PITCH_MARGIN_RAD)
347    } else if state.velocity_mps.xy().norm_squared() >= LEVEL_BELOW_MPS * LEVEL_BELOW_MPS {
348        max_rad
349    } else {
350        0.0
351    }
352}
353
354/// The forward transition's pitch: the plane guidance's for the command (its altitude loop on
355/// a waypoint, toward the altitude the transition holds; the stick in stabilized flight; 0 for
356/// rates), within `limit_rad` either way.
357fn forward_pitch_rad(wing: &Setpoint, limit_rad: f32) -> f32 {
358    let Setpoint::Plane(plane) = wing else {
359        return 0.0;
360    };
361    saturate_symmetric(plane.pitch_rad, limit_rad)
362}
363
364impl Guidance for QuadPlaneGuidance {
365    fn guide(
366        &mut self,
367        dt: f32,
368        regime: FlightRegime,
369        input: &ControlInput,
370        state: &VehicleState,
371    ) -> Setpoint {
372        let requested = if matches!(input, ControlInput::Land(_)) {
373            FlightRegime::Copter
374        } else {
375            regime
376        };
377        let step = self.step(dt, requested, state);
378        if step.mode != self.mode {
379            self.enter(step.mode, state);
380        }
381        // The drag model needs all thrust along the lift rotors' axis: no transition, and no
382        // pusher thrust on the last tick, which this tick's state still carries.
383        self.hover
384            .set_wind_paused(step.mode != FlightMode::Copter || self.pusher_thrust > 0.0);
385        let transition = self.config.transition;
386
387        let setpoint = match step.mode {
388            FlightMode::ToPlane => {
389                let wing_input = self.at_held_altitude(input);
390                // The plane guidance's energy control flies within the transition's limits, so
391                // its pitch integral stops where the pitch does
392                // (`SLT_Transition::set_FW_roll_pitch`).
393                let limit_rad = forward_pitch_limit_rad(
394                    transition.forward_pitch_max_rad,
395                    step.lift_share,
396                    state,
397                );
398                let wing = self.plane.guide_capped(
399                    dt,
400                    FlightRegime::Plane,
401                    &wing_input,
402                    state,
403                    Some(limit_rad),
404                );
405                let rising = self.pusher_thrust + transition.pusher_slew_per_s * dt;
406                self.pusher_thrust = saturate_throttle(wing.thrust())
407                    .min(rising)
408                    .min(transition.forward_thrust);
409                let pitch_rad = forward_pitch_rad(&wing, limit_rad);
410                Setpoint::Blend(BlendSetpoint {
411                    hover: self.hold_level(dt, pitch_rad, state),
412                    plane: PlaneSetpoint {
413                        pitch_rad,
414                        thrust: self.pusher_thrust,
415                        ..PlaneSetpoint::default()
416                    },
417                    lift_share: step.lift_share,
418                })
419            }
420            FlightMode::Plane => {
421                let setpoint = self.plane.guide(dt, FlightRegime::Plane, input, state);
422                let setpoint = if self.handoff.active() {
423                    setpoint.with_thrust(self.handoff.apply(dt, setpoint.thrust()))
424                } else {
425                    setpoint
426                };
427                self.pusher_thrust = setpoint.thrust();
428                setpoint
429            }
430            FlightMode::ToCopter => {
431                self.pusher_thrust = 0.0;
432                let pitch_rad = self.deceleration.pitch_rad(
433                    dt,
434                    state,
435                    transition.back_decel_mps2,
436                    transition.back_decel_i,
437                );
438                Setpoint::Blend(BlendSetpoint {
439                    hover: self.hold_level(dt, pitch_rad, state),
440                    plane: PlaneSetpoint {
441                        pitch_rad,
442                        ..PlaneSetpoint::default()
443                    },
444                    lift_share: step.lift_share,
445                })
446            }
447            _ => {
448                let fallen_back = self.transition.fallen_back();
449                let flown = self.fallback_hold.input(fallen_back, input, state);
450                self.copter(dt, &flown, state)
451            }
452        };
453        self.mode = step.mode;
454        setpoint
455    }
456
457    /// Primes both guidances and the transition (back to `Copter`), and ends any blend.
458    fn prime(&mut self, state: &VehicleState) {
459        self.hover.prime(state);
460        self.plane.prime(state);
461        self.transition.prime(state);
462        self.handoff = ThrustHandoff::new(self.config.transition.handoff_s);
463        self.fallback_hold.clear();
464        self.deceleration.reset();
465        self.mode = FlightMode::Copter;
466        self.pusher_thrust = 0.0;
467        self.hold_altitude_m = f32::NAN;
468    }
469
470    /// The side that flew the last tick: plane in `Plane`, hover otherwise (its altitude loop
471    /// flies the transitions).
472    fn saturation(&self) -> Saturation {
473        match self.mode {
474            FlightMode::Plane => self.plane.saturation(),
475            _ => self.hover.saturation(),
476        }
477    }
478
479    /// The transition's report.
480    fn flight_mode(&self) -> Option<FlightModeReport> {
481        Some(self.transition.report())
482    }
483
484    /// The hover guidance's, updated while it flies.
485    fn wind(&self) -> Option<WindEstimate> {
486        self.hover.wind()
487    }
488}
489
490impl Configurable for QuadPlaneGuidance {
491    type Config = QuadPlaneGuidanceConfig;
492
493    fn config(&self) -> &QuadPlaneGuidanceConfig {
494        &self.config
495    }
496
497    /// Validates the whole config first, then hands each part its own.
498    fn set_config(&mut self, config: QuadPlaneGuidanceConfig) -> Result<(), InvalidConfig> {
499        config.validate()?;
500        self.hover.set_config(config.hover)?;
501        self.plane.set_config(config.plane)?;
502        self.transition.set_config(config.transition)?;
503        self.forward.set_config(config.forward)?;
504        self.off_nose.set_config(config.off_nose)?;
505        self.config = config;
506        Ok(())
507    }
508}
509
510/// The parts' params, chained: hover (`GUID_*`), plane (`PGUID_*`), transition (`TRAN_*`),
511/// forward thrust (`FWD_*`), off-nose speed (`OFFNOSE_*`).
512impl Params for QuadPlaneGuidance {
513    fn param_count(&self) -> usize {
514        self.parts().iter().map(|part| part.param_count()).sum()
515    }
516
517    fn param_name(&self, index: usize) -> Option<&'static str> {
518        let (part, i) = locate(&self.parts(), index)?;
519        self.parts()[part].param_name(i)
520    }
521
522    fn param_at(&self, index: usize) -> Option<f32> {
523        let (part, i) = locate(&self.parts(), index)?;
524        self.parts()[part].param_at(i)
525    }
526
527    fn set_param_at(&mut self, index: usize, value: f32) -> Result<(), ParamError> {
528        let (part, i) = locate(&self.parts(), index).ok_or(ParamError::Unknown)?;
529        let result = self.parts_mut()[part].set_param_at(i, value);
530        self.sync_config();
531        result
532    }
533}