stable_flight/commanders/maneuver/segment.rs
1//! The data a [`ManeuverRunner`] flies: [`Maneuver`]s, their
2//! [`Segment`]s, and the catalog.
3
4use thiserror::Error;
5
6use crate::{Vec3, VehicleState};
7
8use super::Path;
9
10#[cfg(doc)]
11use super::{ManeuverConfig, ManeuverRunner};
12
13/// Most segments a [`Maneuver`] holds: a square loop with point rolls on its lines needs more
14/// than 8.
15pub const MAX_SEGMENTS: usize = 16;
16
17/// Seconds a [`Maneuver::doublet`] pauses after its two halves, so the free response is
18/// recorded before the recovery takes over.
19pub const DOUBLET_PAUSE_S: f32 = 1.0;
20
21/// A [`Maneuver::doublet`]'s half width, in s, when a script gives none.
22pub const DEFAULT_DOUBLET_HALF_S: f32 = 0.5;
23
24/// A body axis.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Axis {
27 /// About body `x`, right wing down positive.
28 Roll,
29 /// About body `y`, nose up positive.
30 Pitch,
31 /// About body `z`, nose right positive.
32 Yaw,
33}
34
35impl Axis {
36 /// The axis as a unit vector in body axes.
37 pub(super) fn unit(self) -> Vec3 {
38 match self {
39 Axis::Roll => Vec3::x(),
40 Axis::Pitch => Vec3::y(),
41 Axis::Yaw => Vec3::z(),
42 }
43 }
44}
45
46/// The body rate a [`Segment::Rotate`] holds, signed: the sign is the direction about the
47/// axis (negative roll is left, negative pitch a push).
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub enum RateLaw {
50 /// A fixed rate, in rad/s.
51 Constant {
52 /// The rate, in rad/s.
53 radps: f32,
54 },
55 /// `V / radius_m` each tick, `V` the airspeed (the ground speed without one): the arc of a
56 /// circle of that radius whatever the speed does over it. Negative curves the other way
57 /// (about pitch, an outside loop).
58 Radius {
59 /// The arc's radius, in m.
60 radius_m: f32,
61 },
62}
63
64impl RateLaw {
65 /// The rate for `state`, in rad/s; NaN without a speed.
66 pub(super) fn radps(self, state: &VehicleState) -> f32 {
67 match self {
68 RateLaw::Constant { radps } => radps,
69 RateLaw::Radius { radius_m } => speed_mps(state) / radius_m,
70 }
71 }
72
73 /// The direction it turns about its axis, `±1`.
74 pub(super) fn direction(self) -> f32 {
75 match self {
76 RateLaw::Constant { radps } => radps.signum(),
77 RateLaw::Radius { radius_m } => radius_m.signum(),
78 }
79 }
80
81 /// Its rate or radius: what must be finite and nonzero.
82 fn value(self) -> f32 {
83 match self {
84 RateLaw::Constant { radps } => radps,
85 RateLaw::Radius { radius_m } => radius_m,
86 }
87 }
88}
89
90/// The speed a maneuver turns at, in m/s: the airspeed, or the ground speed without one.
91pub(super) fn speed_mps(state: &VehicleState) -> f32 {
92 state
93 .valid_airspeed_mps()
94 .unwrap_or_else(|| state.velocity_mps.norm())
95}
96
97/// When a [`Segment::Rotate`] ends.
98#[derive(Clone, Copy, Debug, PartialEq)]
99pub enum SegmentEnd {
100 /// Once it has turned this far in its rate's direction, in rad (positive).
101 Angle {
102 /// The angle, in rad.
103 rad: f32,
104 },
105 /// After this long, in s, whatever the attitude.
106 Duration {
107 /// The time, in s.
108 s: f32,
109 },
110}
111
112/// The thrust a [`Segment`] holds, from the [`ManeuverConfig`].
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum Thrust {
115 /// [`ManeuverConfig::thrust`]: an aerobatic segment's.
116 Maneuver,
117 /// [`ManeuverConfig::cruise_thrust`]: a measurement's, flown as in level flight.
118 Cruise,
119}
120
121/// One step of a [`Maneuver`].
122#[derive(Clone, Copy, Debug, PartialEq)]
123#[non_exhaustive]
124pub enum Segment {
125 /// A body rate about one axis until its end.
126 Rotate {
127 /// The axis it turns about.
128 axis: Axis,
129 /// The rate it holds.
130 rate: RateLaw,
131 /// When it ends.
132 end: SegmentEnd,
133 /// The thrust it holds.
134 thrust: Thrust,
135 /// The path it holds while it turns.
136 path: Path,
137 },
138 /// Zero body rate for a time: the free response after a doublet.
139 Pause {
140 /// The time, in s.
141 duration_s: f32,
142 /// The thrust it holds.
143 thrust: Thrust,
144 },
145}
146
147impl Segment {
148 /// `Err` with what's wrong: a rate or radius that isn't finite and nonzero, an angle or
149 /// duration that isn't positive and finite, or a [`Path::Circle`] without a radius or
150 /// about the roll axis (whose circle has no center off the nose).
151 fn check(&self) -> Result<(), &'static str> {
152 match *self {
153 Segment::Rotate {
154 axis,
155 rate,
156 end,
157 path,
158 ..
159 } => {
160 let value = rate.value();
161 if !(value.is_finite() && value != 0.0) {
162 return Err(match rate {
163 RateLaw::Constant { .. } => "rate not finite and nonzero",
164 RateLaw::Radius { .. } => "radius not finite and nonzero",
165 });
166 }
167 if path == Path::Circle {
168 if !matches!(rate, RateLaw::Radius { .. }) {
169 return Err("circle without a radius");
170 }
171 if axis == Axis::Roll {
172 return Err("circle about the roll axis");
173 }
174 }
175 match end {
176 SegmentEnd::Angle { rad } if !positive(rad) => {
177 Err("angle not positive and finite")
178 }
179 SegmentEnd::Duration { s } if !positive(s) => {
180 Err("duration not positive and finite")
181 }
182 _ => Ok(()),
183 }
184 }
185 Segment::Pause { duration_s, .. } if !positive(duration_s) => {
186 Err("duration not positive and finite")
187 }
188 Segment::Pause { .. } => Ok(()),
189 }
190 }
191}
192
193/// Positive and finite.
194pub(super) fn positive(value: f32) -> bool {
195 value > 0.0 && value.is_finite()
196}
197
198/// A [`Maneuver`] that can't be flown.
199#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
200#[non_exhaustive]
201pub enum ManeuverError {
202 /// No segments.
203 #[error("a maneuver needs a segment")]
204 Empty,
205 /// More than [`MAX_SEGMENTS`].
206 #[error("a maneuver holds at most {max} segments, got {count}", max = MAX_SEGMENTS)]
207 TooManySegments {
208 /// The segments given.
209 count: usize,
210 },
211 /// A segment out of range.
212 #[error("segment {index}: {reason}")]
213 InvalidSegment {
214 /// Its index.
215 index: usize,
216 /// What's wrong with it.
217 reason: &'static str,
218 },
219}
220
221/// A sequence of [`Segment`]s flown in order by a [`ManeuverRunner`]. `Copy` and fixed-size, so
222/// a script or a mission can hold one without allocating.
223///
224/// # Examples
225///
226/// ```
227/// use stable_flight::commanders::maneuver::{
228/// Axis, Maneuver, Path, RateLaw, Segment, SegmentEnd, Thrust,
229/// };
230///
231/// let roll = Maneuver::roll(90.0_f32.to_radians()).expect("a nonzero rate");
232/// assert_eq!(roll.segments().len(), 1);
233///
234/// // An Immelmann: half a loop of 25 m, then half a roll at 90°/s on the line it ends on.
235/// let half_turn = SegmentEnd::Angle { rad: core::f32::consts::PI };
236/// let immelmann = Maneuver::new(&[
237/// Segment::Rotate {
238/// axis: Axis::Pitch,
239/// rate: RateLaw::Radius { radius_m: 25.0 },
240/// end: half_turn,
241/// thrust: Thrust::Maneuver,
242/// path: Path::Circle,
243/// },
244/// Segment::Rotate {
245/// axis: Axis::Roll,
246/// rate: RateLaw::Constant { radps: 90.0_f32.to_radians() },
247/// end: half_turn,
248/// thrust: Thrust::Maneuver,
249/// path: Path::Line,
250/// },
251/// ])
252/// .expect("valid segments");
253/// assert_eq!(immelmann.segments().len(), 2);
254/// assert!(Maneuver::loop_(0.0).is_err());
255/// ```
256#[derive(Clone, Copy, Debug, PartialEq)]
257pub struct Maneuver {
258 segments: [Segment; MAX_SEGMENTS],
259 len: usize,
260}
261
262impl Maneuver {
263 /// A maneuver flying `segments` in order.
264 ///
265 /// # Errors
266 ///
267 /// [`ManeuverError::Empty`] for none, [`ManeuverError::TooManySegments`] for more than
268 /// [`MAX_SEGMENTS`], [`ManeuverError::InvalidSegment`] for the first segment out of range.
269 pub fn new(segments: &[Segment]) -> Result<Self, ManeuverError> {
270 let count = segments.len();
271 if count == 0 {
272 return Err(ManeuverError::Empty);
273 }
274 if count > MAX_SEGMENTS {
275 return Err(ManeuverError::TooManySegments { count });
276 }
277 for (index, segment) in segments.iter().enumerate() {
278 segment
279 .check()
280 .map_err(|reason| ManeuverError::InvalidSegment { index, reason })?;
281 }
282 let mut maneuver = Maneuver {
283 segments: [UNUSED; MAX_SEGMENTS],
284 len: count,
285 };
286 maneuver.segments[..count].copy_from_slice(segments);
287 Ok(maneuver)
288 }
289
290 /// One full roll at `rate_radps` (negative rolls left), holding its line.
291 ///
292 /// # Errors
293 ///
294 /// [`ManeuverError::InvalidSegment`] for a zero or non-finite rate.
295 pub fn roll(rate_radps: f32) -> Result<Self, ManeuverError> {
296 Maneuver::new(&[Segment::Rotate {
297 axis: Axis::Roll,
298 rate: RateLaw::Constant { radps: rate_radps },
299 end: SegmentEnd::Angle { rad: FULL_TURN_RAD },
300 thrust: Thrust::Maneuver,
301 path: Path::Line,
302 }])
303 }
304
305 /// One loop of `radius_m`, holding its circle: inside, or outside for a negative radius.
306 ///
307 /// # Errors
308 ///
309 /// [`ManeuverError::InvalidSegment`] for a zero or non-finite radius.
310 pub fn loop_(radius_m: f32) -> Result<Self, ManeuverError> {
311 Maneuver::new(&[Segment::Rotate {
312 axis: Axis::Pitch,
313 rate: RateLaw::Radius { radius_m },
314 end: SegmentEnd::Angle { rad: FULL_TURN_RAD },
315 thrust: Thrust::Maneuver,
316 path: Path::Circle,
317 }])
318 }
319
320 /// A doublet about `axis`: `rate_radps` for `half_s`, `-rate_radps` for `half_s`, then a
321 /// [`DOUBLET_PAUSE_S`] pause, all at cruise thrust and on rates alone ([`Path::Free`]), so
322 /// it measures the rate loop. The two halves leave the attitude about where it began.
323 ///
324 /// # Errors
325 ///
326 /// [`ManeuverError::InvalidSegment`] for a zero or non-finite rate, or a half width that
327 /// isn't positive and finite.
328 pub fn doublet(axis: Axis, rate_radps: f32, half_s: f32) -> Result<Self, ManeuverError> {
329 let half = |radps| Segment::Rotate {
330 axis,
331 rate: RateLaw::Constant { radps },
332 end: SegmentEnd::Duration { s: half_s },
333 thrust: Thrust::Cruise,
334 path: Path::Free,
335 };
336 Maneuver::new(&[
337 half(rate_radps),
338 half(-rate_radps),
339 Segment::Pause {
340 duration_s: DOUBLET_PAUSE_S,
341 thrust: Thrust::Cruise,
342 },
343 ])
344 }
345
346 /// The segments, in order.
347 pub fn segments(&self) -> &[Segment] {
348 &self.segments[..self.len]
349 }
350}
351
352/// Fills a [`Maneuver`]'s unused slots.
353pub(super) const UNUSED: Segment = Segment::Pause {
354 duration_s: 0.0,
355 thrust: Thrust::Cruise,
356};
357
358/// A full turn, in rad.
359const FULL_TURN_RAD: f32 = core::f32::consts::TAU;