efb 0.7.1

Electronic Flight Bag library to plan and conduct a flight.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024, 2026 Joe Pearson
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use log::trace;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use geo::{Bearing, Distance, Geodesic};

use crate::fp::LegPerformance;
use crate::measurements::{Angle, AngleUnit, Duration, Length, LengthUnit, Speed};
use crate::nd::{Fix, NavAid};
use crate::{Fuel, VerticalDistance, Wind};

use super::LegFuel;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ClimbDescentAlongLeg {
    /// Level the aircraft is at when entering this leg (before any transitions).
    from: Option<VerticalDistance>,
    /// Target level of a transition starting at the FROM fix.
    to: Option<VerticalDistance>,
    /// Target level that must be reached by the TO fix.
    reach_at: Option<VerticalDistance>,
}

impl ClimbDescentAlongLeg {
    /// Level the aircraft is at when entering this leg.
    pub fn from(&self) -> Option<&VerticalDistance> {
        self.from.as_ref()
    }

    /// Target level of a transition starting at the FROM fix.
    pub fn to(&self) -> Option<&VerticalDistance> {
        self.to.as_ref()
    }

    /// Target level that must be reached by the TO fix.
    pub fn reach_at(&self) -> Option<&VerticalDistance> {
        self.reach_at.as_ref()
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub(super) struct LegBuilder {
    level: Option<VerticalDistance>,
    climb_descent: ClimbDescentAlongLeg,
    tas: Option<Speed>,
    wind: Option<Wind>,
}

impl LegBuilder {
    /// Builds a new leg `from` → `to`.
    ///
    /// The builder consumes all level changes and updates the level according
    /// to the changes. Subsequent builds retain the latest cruise level in case
    /// no further level changes occur.
    pub fn build(&mut self, from: NavAid, to: NavAid) -> Leg {
        // Seed `from` level from the builder's current level (before any
        // transitions on this leg). If still None and the FROM fix is an
        // airport, use its elevation.
        self.climb_descent.from = self.level.or_else(|| match &from {
            NavAid::Airport(arpt) => Some(arpt.elevation),
            _ => None,
        });

        self.climb_descent
            .to
            .inspect(|level| trace!("climb/descent to {level} from {from}"));
        self.climb_descent
            .reach_at
            .inspect(|level| trace!("reach {to} on {level}"));

        // The leg's cruise level is the level after the `to` transition (if
        // any), otherwise the previous level.
        let level = self.climb_descent.to.or(self.level);

        let leg = Leg::new(from, to, self.climb_descent, level, self.tas, self.wind);

        // Update the level for subsequent legs: the last transition reached
        // is the new cruise level. Clear both transitions for the next leg.
        if let Some(reach_at) = self.climb_descent.reach_at.take() {
            self.level = Some(reach_at);
        } else if let Some(to) = self.climb_descent.to.take() {
            self.level = Some(to);
        }
        self.climb_descent.to.take();

        leg
    }

    pub fn cruise(&mut self, level: VerticalDistance) {
        // Since we can't teleport to the new level, we need to climb/descent to
        // it starting at the "from" fix. Don't update self.level here — build()
        // needs it to set climb_descent.from to the *previous* level first.
        self.climb_descent.to = Some(level);
    }

    pub fn level_at_fix(&mut self, level: VerticalDistance) {
        // Reaching a new level at a fix along the leg is only possible for the
        // "to" fix.
        self.climb_descent.reach_at = Some(level);
    }

    pub fn tas(&mut self, tas: Speed) {
        self.tas = Some(tas);
        trace!("cruise speed set to {tas}");
    }

    pub fn wind(&mut self, wind: Wind) {
        self.wind = Some(wind);
        trace!("wind set to {wind}");
    }

    /// Marks the next TO fix as the route destination.
    ///
    /// If the destination is an airport and no explicit `reach_at` level has
    /// been set, the aircraft must descend to the airport elevation by the
    /// TO fix.
    pub fn destination(&mut self, dest: &NavAid) {
        if self.climb_descent.reach_at.is_none() {
            if let NavAid::Airport(arpt) = dest {
                self.climb_descent.reach_at = Some(arpt.elevation);
            }
        }
    }
}

/// A leg `from` one point `to` another.
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Leg {
    from: NavAid,
    to: NavAid,
    climb_descent: ClimbDescentAlongLeg,
    level: Option<VerticalDistance>,
    tas: Option<Speed>,
    wind: Option<Wind>,
    heading: Option<Angle>,
    mh: Option<Angle>,
    bearing: Angle,
    mc: Angle,
    dist: Length,
    gs: Option<Speed>,
    wca: Option<Angle>,
    ete: Option<Duration>,
}

impl Leg {
    pub(super) fn builder() -> LegBuilder {
        LegBuilder::default()
    }

    pub fn divert(&self, alternate: NavAid) -> Leg {
        Leg::new(
            self.from.clone(),
            alternate,
            self.climb_descent,
            self.level,
            self.tas,
            self.wind,
        )
    }

    fn new(
        from: NavAid,
        to: NavAid,
        climb_descent: ClimbDescentAlongLeg,
        level: Option<VerticalDistance>,
        tas: Option<Speed>,
        wind: Option<Wind>,
    ) -> Leg {
        let from_coord = from.coordinate();
        let to_coord = to.coordinate();

        // Use geo's Geodesic for bearing and distance calculations
        let bearing_deg = Geodesic.bearing(from_coord, to_coord);
        let bearing = Angle::t(bearing_deg as f32);
        let mc = bearing + from.mag_var();

        let distance_m = Geodesic.distance(from_coord, to_coord);
        let dist = Length::m(distance_m as f32).convert_to(LengthUnit::NauticalMiles);

        let (gs, wca) = {
            match (tas, wind) {
                (Some(tas), Some(wind)) => {
                    let wca = wind_correction_angle(&wind, &tas, &bearing);
                    let gs = ground_speed(&tas, &wind, &wca, &bearing);

                    (Some(gs), Some(wca))
                }
                _ => (None, None),
            }
        };

        let heading = wca.map(|wca| bearing + wca);
        let mh = heading.map(|heading| heading + from.mag_var());
        let ete = gs.map(|gs| dist / gs);

        trace!(
            "leg {} -> {}: dist={:.1}, bearing={:.1}, gs={:?}, ete={:?}",
            from.ident(),
            to.ident(),
            dist,
            bearing,
            gs,
            ete
        );

        Self {
            from,
            to,
            climb_descent,
            level,
            tas,
            wind,
            heading,
            mh,
            bearing,
            mc,
            dist,
            gs,
            wca,
            ete,
        }
    }

    /// The point from which the leg starts.
    pub fn from(&self) -> &NavAid {
        &self.from
    }

    /// The point to which the leg is going.
    pub fn to(&self) -> &NavAid {
        &self.to
    }

    /// The level of the leg.
    pub fn level(&self) -> Option<&VerticalDistance> {
        self.level.as_ref()
    }

    /// The climb and descent transitions along this leg.
    pub fn climb_descent(&self) -> &ClimbDescentAlongLeg {
        &self.climb_descent
    }

    /// The desired true airspeed (TAS).
    pub fn tas(&self) -> Option<&Speed> {
        self.tas.as_ref()
    }

    /// The wind to take into account.
    pub fn wind(&self) -> Option<&Wind> {
        self.wind.as_ref()
    }

    /// The headwind component along this leg's bearing.
    pub fn headwind(&self) -> Option<Speed> {
        self.wind.map(|w| w.headwind(&self.bearing))
    }

    /// The true heading considering the wind correction angle (WCA).
    pub fn heading(&self) -> Option<&Angle> {
        self.heading.as_ref()
    }

    /// The magnetic heading considering the variation at the start of the leg.
    pub fn mh(&self) -> Option<&Angle> {
        self.mh.as_ref()
    }

    /// The bearing between the two points.
    pub fn bearing(&self) -> &Angle {
        &self.bearing
    }

    /// The magnetic course taking the magnetic variation from the starting
    /// point into consideration.
    pub fn mc(&self) -> &Angle {
        &self.mc
    }

    /// The distance between the leg's two points.
    pub fn dist(&self) -> &Length {
        &self.dist
    }

    // TODO add test to verify calculation
    /// The ground speed.
    pub fn gs(&self) -> Option<&Speed> {
        self.gs.as_ref()
    }

    /// The wind correction angle based on the wind.
    pub fn wca(&self) -> Option<&Angle> {
        self.wca.as_ref()
    }

    // TODO add test to verify calculation
    /// The estimated time enroute the leg.
    pub fn ete(&self) -> Option<&Duration> {
        self.ete.as_ref()
    }

    /// The [fuel breakdown](LegFuel) for the leg with the given
    /// [performance](LegPerformance).
    ///
    /// When climb or descent performance is available, climb/descent fuel is
    /// computed for any level transitions on the leg and the cruise time is
    /// reduced accordingly. Falls back to pure cruise when no transitions
    /// exist or no climb/descent performance is provided.
    pub fn fuel(&self, perf: &LegPerformance) -> Option<LegFuel> {
        let from_level = self.climb_descent.from;
        let to_level = self.climb_descent.to;
        let reach_at = self.climb_descent.reach_at;

        let mut climb_time = Duration::s(0);
        let mut descent_time = Duration::s(0);
        let mut climb_fuel: Option<Fuel> = None;
        let mut descent_fuel: Option<Fuel> = None;

        let mut add_transition =
            |current: &VerticalDistance, target: &VerticalDistance| -> Option<()> {
                let (lo, hi) = if target > current {
                    (current, target)
                } else {
                    (target, current)
                };
                let is_climb = target > current;
                let cdp = if is_climb {
                    perf.climb()?
                } else {
                    perf.descent()?
                };

                let hw = self.headwind().unwrap_or(Speed::kt(0.0));
                let result = cdp.between(lo, hi)?.with_wind(hw);

                if is_climb {
                    climb_time = climb_time + result.time;
                    climb_fuel = Some(match climb_fuel {
                        Some(f) => f + result.fuel,
                        None => result.fuel,
                    });
                } else {
                    descent_time = descent_time + result.time;
                    descent_fuel = Some(match descent_fuel {
                        Some(f) => f + result.fuel,
                        None => result.fuel,
                    });
                }
                Some(())
            };

        // Transition at FROM fix (to_level)
        let mut current = from_level;
        if let (Some(from), Some(to)) = (current, to_level) {
            if add_transition(&from, &to).is_some() {
                current = Some(to);
            }
        }

        // Transition reaching TO fix (reach_at)
        if let (Some(from), Some(ra)) = (current.or(from_level), reach_at) {
            add_transition(&from, &ra);
        }

        // Cruise for the remaining time (requires both ETE and a cruise level)
        let cruise_fuel = match (self.ete, self.level) {
            (Some(ete), Some(level)) => {
                let climb_descent_time = climb_time + descent_time;
                if climb_descent_time < ete {
                    let cruise_time = ete - climb_descent_time;
                    perf.cruise().map(|c| c.ff(&level) * cruise_time)
                } else {
                    None
                }
            }
            _ => None,
        };

        if climb_fuel.is_none() && cruise_fuel.is_none() && descent_fuel.is_none() {
            return None;
        }

        Some(LegFuel::new(climb_fuel, cruise_fuel, descent_fuel))
    }
}

fn wind_correction_angle(wind: &Wind, tas: &Speed, bearing: &Angle) -> Angle {
    let wind_azimuth = wind.direction + Angle::t(180.0);
    // the angle between the wind direction and bearing
    let wind_angle = *bearing - wind_azimuth;

    // The law of sines gives us
    //
    //   sin(wca) / ws = sin(wind_angle) / tas
    //
    // from which we get the wca as following:
    Angle::from_si(
        (wind.speed / *tas * wind_angle.to_si().sin()).asin(),
        AngleUnit::TrueNorth,
    )
}

fn ground_speed(tas: &Speed, wind: &Wind, wca: &Angle, bearing: &Angle) -> Speed {
    Speed::from_si(
        (*tas * *tas + wind.speed * wind.speed
            - ((*tas * wind.speed * 2.0) * (*bearing - wind.direction + *wca).to_si().cos()))
        .to_si()
        .sqrt(),
        *tas.unit(),
    )
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn wind_correction_angle_left() {
        let wca = wind_correction_angle(
            &Wind::from_str("18050KT").unwrap(),
            &Speed::from_str("N0100").unwrap(),
            &Angle::t(90.0),
        );

        assert_eq!(wca.value().round(), 30.0);
    }

    #[test]
    fn wind_correction_angle_right() {
        let wca = wind_correction_angle(
            &Wind::from_str("00050KT").unwrap(),
            &Speed::from_str("N0100").unwrap(),
            &Angle::t(90.0),
        );

        // negative angles are wrapped: 360 - 30 = 330
        assert_eq!(wca.value().round(), 330.0);
    }
}