]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
bd6b47e07bea7d64f1686c911a00becd97d6fbbb
[flightgear.git] / src / Autopilot / route_mgr.cxx
1 // route_mgr.cxx - manage a route (i.e. a collection of waypoints)
2 //
3 // Written by Curtis Olson, started January 2004.
4 //            Norman Vine
5 //            Melchior FRANZ
6 //
7 // Copyright (C) 2004  Curtis L. Olson  - http://www.flightgear.org/~curt
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #ifdef HAVE_WINDOWS_H
31 #include <time.h>
32 #endif
33
34 #include <simgear/compiler.h>
35
36 #include "route_mgr.hxx"
37
38 #include <boost/algorithm/string/case_conv.hpp>
39
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/structure/exception.hxx>
42
43 #include <simgear/props/props_io.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/route/route.hxx>
46 #include <simgear/sg_inlines.h>
47
48 #include "Main/fg_props.hxx"
49 #include "Navaids/positioned.hxx"
50 #include "Airports/simple.hxx"
51 #include "Airports/runways.hxx"
52
53 #include "FDM/flight.hxx" // for getting ground speed
54
55 #define RM "/autopilot/route-manager/"
56
57 static double get_ground_speed() {
58   // starts in ft/s so we convert to kts
59   static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
60
61   double ft_s = cur_fdm_state->get_V_ground_speed()
62       * speedup_node->getIntValue();
63   double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
64   return kts;
65 }
66
67 FGRouteMgr::FGRouteMgr() :
68     _route( new SGRoute ),
69     input(fgGetNode( RM "input", true )),
70     mirror(fgGetNode( RM "route", true ))
71 {
72     listener = new InputListener(this);
73     input->setStringValue("");
74     input->addChangeListener(listener);
75 }
76
77
78 FGRouteMgr::~FGRouteMgr() {
79     input->removeChangeListener(listener);
80     
81     delete listener;
82     delete _route;
83 }
84
85
86 void FGRouteMgr::init() {
87   SGPropertyNode_ptr rm(fgGetNode(RM));
88   
89   lon = fgGetNode( "/position/longitude-deg", true );
90   lat = fgGetNode( "/position/latitude-deg", true );
91   alt = fgGetNode( "/position/altitude-ft", true );
92   magvar = fgGetNode("/environment/magnetic-variation-deg", true);
93      
94   departure = fgGetNode(RM "departure", true);
95 // init departure information from current location
96   SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(), lat->getDoubleValue(), alt->getDoubleValue());
97   FGAirport* apt = FGAirport::findClosest(pos, 20.0);
98   if (apt) {
99     departure->setStringValue("airport", apt->ident().c_str());
100     FGRunway* active = apt->getActiveRunwayForUsage();
101     departure->setStringValue("runway", active->ident().c_str());
102   } else {
103     departure->setStringValue("airport", "");
104     departure->setStringValue("runway", "");
105   }
106   
107   departure->getChild("etd", 0, true);
108   departure->getChild("takeoff-time", 0, true);
109
110   destination = fgGetNode(RM "destination", true);
111   destination->getChild("airport", 0, true);
112   destination->getChild("runway", 0, true);
113   destination->getChild("eta", 0, true);
114   destination->getChild("touchdown-time", 0, true);
115   
116   alternate = fgGetNode(RM "alternate", true);
117   alternate->getChild("airport", 0, true);
118   alternate->getChild("runway", 0, true);
119   
120   cruise = fgGetNode(RM "cruise", true);
121   cruise->getChild("altitude-ft", 0, true);
122   cruise->setDoubleValue("altitude-ft", 10000.0);
123   cruise->getChild("flight-level", 0, true);
124   cruise->getChild("speed-kts", 0, true);
125   cruise->setDoubleValue("speed-kts", 160.0);
126   
127   totalDistance = fgGetNode(RM "total-distance", true);
128   totalDistance->setDoubleValue(0.0);
129   
130   ete = fgGetNode(RM "ete", true);
131   ete->setDoubleValue(0.0);
132   
133   elapsedFlightTime = fgGetNode(RM "flight-time", true);
134   elapsedFlightTime->setDoubleValue(0.0);
135   
136   active = fgGetNode(RM "active", true);
137   active->setBoolValue(false);
138   
139   airborne = fgGetNode(RM "airborne", true);
140   airborne->setBoolValue(false);
141     
142   _edited = fgGetNode(RM "signals/edited", true);
143   _finished = fgGetNode(RM "signals/finished", true);
144   
145   rm->tie("current-wp", SGRawValueMethods<FGRouteMgr, int>
146     (*this, &FGRouteMgr::currentWaypoint, &FGRouteMgr::jumpToIndex));
147       
148   // temporary distance / eta calculations, for backward-compatability
149   wp0 = fgGetNode(RM "wp", 0, true);
150   wp0->getChild("id", 0, true);
151   wp0->getChild("dist", 0, true);
152   wp0->getChild("eta", 0, true);
153   wp0->getChild("bearing-deg", 0, true);
154   
155   wp1 = fgGetNode(RM "wp", 1, true);
156   wp1->getChild("id", 0, true);
157   wp1->getChild("dist", 0, true);
158   wp1->getChild("eta", 0, true);
159   
160   wpn = fgGetNode(RM "wp-last", 0, true);
161   wpn->getChild("dist", 0, true);
162   wpn->getChild("eta", 0, true);
163   
164   _route->clear();
165   update_mirror();
166   
167   _pathNode = fgGetNode(RM "file-path", 0, true);
168 }
169
170
171 void FGRouteMgr::postinit() {
172     string_list *waypoints = globals->get_initial_waypoints();
173     if (waypoints) {
174       vector<string>::iterator it;
175       for (it = waypoints->begin(); it != waypoints->end(); ++it)
176         new_waypoint(*it);
177     }
178
179     weightOnWheels = fgGetNode("/gear/gear[0]/wow", false);
180     // check airbone flag agrees with presets
181     
182 }
183
184
185 void FGRouteMgr::bind() { }
186 void FGRouteMgr::unbind() { }
187
188 bool FGRouteMgr::isRouteActive() const
189 {
190   return active->getBoolValue();
191 }
192
193 void FGRouteMgr::update( double dt ) {
194     if (dt <= 0.0) {
195       // paused, nothing to do here
196       return;
197     }
198   
199     if (!active->getBoolValue()) {
200       return;
201     }
202     
203     double groundSpeed = get_ground_speed();
204     if (airborne->getBoolValue()) {
205       time_t now = time(NULL);
206       elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
207     } else { // not airborne
208       if (weightOnWheels->getBoolValue() || (groundSpeed < 40)) {
209         return;
210       }
211       
212       airborne->setBoolValue(true);
213       _takeoffTime = time(NULL); // start the clock
214       departure->setIntValue("takeoff-time", _takeoffTime);
215     }
216     
217   // basic course/distance information
218     double inboundCourse, dummy, wp_course, wp_distance;
219     SGWayPoint wp = _route->get_current();
220   
221     wp.CourseAndDistance(_route->get_waypoint(_route->current_index() - 1), 
222       &inboundCourse, &dummy);
223     
224     wp.CourseAndDistance( lon->getDoubleValue(), lat->getDoubleValue(),
225                           alt->getDoubleValue(), &wp_course, &wp_distance );
226
227   // update wp0 / wp1 / wp-last for legacy users
228     wp0->setDoubleValue("dist", wp_distance * SG_METER_TO_NM);
229     wp_course -= magvar->getDoubleValue(); // expose magnetic bearing
230     wp0->setDoubleValue("bearing-deg", wp_course);
231     setETAPropertyFromDistance(wp0->getChild("eta"), wp_distance);
232     
233     if ((_route->current_index() + 1) < _route->size()) {
234       wp = _route->get_waypoint(_route->current_index() + 1);
235       double wp1_course, wp1_distance;
236       wp.CourseAndDistance(lon->getDoubleValue(), lat->getDoubleValue(),
237                           alt->getDoubleValue(), &wp1_course, &wp1_distance);
238     
239       wp1->setDoubleValue("dist", wp1_distance * SG_METER_TO_NM);
240       setETAPropertyFromDistance(wp1->getChild("eta"), wp1_distance);
241     }
242     
243     double totalDistanceRemaining = wp_distance; // distance to current waypoint
244     for (int i=_route->current_index() + 1; i<_route->size(); ++i) {
245       totalDistanceRemaining += _route->get_waypoint(i).get_distance();
246     }
247     
248     wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
249     ete->setDoubleValue(totalDistanceRemaining * SG_METER_TO_NM / groundSpeed * 3600.0);
250     setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
251     
252     // get time now at destination tz as tm struct
253     // add ete seconds
254     // convert to string ... and stash in property
255     //destination->setDoubleValue("eta", eta);
256 }
257
258
259 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance) {
260     double speed = get_ground_speed();
261     if (speed < 1.0) {
262       aProp->setStringValue("--:--");
263       return;
264     }
265   
266     char eta_str[64];
267     double eta = aDistance * SG_METER_TO_NM / get_ground_speed();
268     if ( eta >= 100.0 ) { 
269         eta = 99.999; // clamp
270     }
271     
272     if ( eta < (1.0/6.0) ) {
273       eta *= 60.0; // within 10 minutes, bump up to min/secs
274     }
275     
276     int major = (int)eta, 
277         minor = (int)((eta - (int)eta) * 60.0);
278     snprintf( eta_str, 64, "%d:%02d", major, minor );
279     aProp->setStringValue( eta_str );
280 }
281
282 void FGRouteMgr::add_waypoint( const SGWayPoint& wp, int n ) {
283   _route->add_waypoint( wp, n );
284     
285   if (_route->current_index() > n) {
286     _route->set_current(_route->current_index() + 1);
287   }
288   
289   update_mirror();
290   _edited->fireValueChanged();
291 }
292
293
294 SGWayPoint FGRouteMgr::pop_waypoint( int n ) {
295   if ( _route->size() <= 0 ) {
296     return SGWayPoint();
297   }
298   
299   if ( n < 0 ) {
300     n = _route->size() - 1;
301   }
302   
303   if (_route->current_index() > n) {
304     _route->set_current(_route->current_index() - 1);
305   }
306
307   SGWayPoint wp = _route->get_waypoint(n);
308   _route->delete_waypoint(n);
309     
310   update_mirror();
311   _edited->fireValueChanged();
312   checkFinished();
313   
314   return wp;
315 }
316
317
318 bool FGRouteMgr::build() {
319     return true;
320 }
321
322
323 void FGRouteMgr::new_waypoint( const string& target, int n ) {
324     SGWayPoint* wp = make_waypoint( target );
325     if (!wp) {
326         return;
327     }
328     
329     add_waypoint( *wp, n );
330     delete wp;
331 }
332
333
334 SGWayPoint* FGRouteMgr::make_waypoint(const string& tgt ) {
335     string target(boost::to_upper_copy(tgt));
336     
337     // extract altitude
338     double alt = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
339     
340     size_t pos = target.find( '@' );
341     if ( pos != string::npos ) {
342         alt = atof( target.c_str() + pos + 1 );
343         target = target.substr( 0, pos );
344         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
345             alt *= SG_FEET_TO_METER;
346     }
347
348     // check for lon,lat
349     pos = target.find( ',' );
350     if ( pos != string::npos ) {
351         double lon = atof( target.substr(0, pos).c_str());
352         double lat = atof( target.c_str() + pos + 1);
353         return new SGWayPoint( lon, lat, alt, SGWayPoint::WGS84, target );
354     }    
355
356     SGGeod basePosition;
357     if (_route->size() > 0) {
358         SGWayPoint wp = get_waypoint(_route->size()-1);
359         basePosition = wp.get_target();
360     } else {
361         // route is empty, use current position
362         basePosition = SGGeod::fromDeg(
363             fgGetNode("/position/longitude-deg")->getDoubleValue(), 
364             fgGetNode("/position/latitude-deg")->getDoubleValue());
365     }
366     
367     vector<string> pieces(simgear::strutils::split(target, "/"));
368
369
370     FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
371     if (!p) {
372       SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
373       return NULL;
374     }
375     
376     SGGeod geod = SGGeod::fromGeodM(p->geod(), alt);
377     if (pieces.size() == 1) {
378       // simple case
379       return new SGWayPoint(geod, target, p->name());
380     }
381         
382     if (pieces.size() == 3) {
383       // navaid/radial/distance-nm notation
384       double radial = atof(pieces[1].c_str()),
385         distanceNm = atof(pieces[2].c_str()),
386         az2;
387       radial += magvar->getDoubleValue(); // convert to true bearing
388       SGGeod offsetPos;
389       SGGeodesy::direct(geod, radial, distanceNm * SG_NM_TO_METER, offsetPos, az2);
390       offsetPos.setElevationM(alt);
391       
392       SG_LOG(SG_AUTOPILOT, SG_INFO, "final offset radial is " << radial);
393       return new SGWayPoint(offsetPos, p->ident() + pieces[2], target);
394     }
395     
396     if (pieces.size() == 2) {
397       FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
398       if (!apt) {
399         SG_LOG(SG_AUTOPILOT, SG_INFO, "Waypoint is not an airport:" << pieces.front());
400         return NULL;
401       }
402       
403       if (!apt->hasRunwayWithIdent(pieces[1])) {
404         SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
405         return NULL;
406       }
407       
408       FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
409       SGGeod t = runway->threshold();
410       return new SGWayPoint(t.getLongitudeDeg(), t.getLatitudeDeg(), alt, SGWayPoint::WGS84, pieces[1]);
411     }
412     
413     SG_LOG(SG_AUTOPILOT, SG_INFO, "Unable to parse waypoint:" << target);
414     return NULL;
415 }
416
417
418 // mirror internal route to the property system for inspection by other subsystems
419 void FGRouteMgr::update_mirror() {
420     mirror->removeChildren("wp");
421     for (int i = 0; i < _route->size(); i++) {
422         SGWayPoint wp = _route->get_waypoint(i);
423         SGPropertyNode *prop = mirror->getChild("wp", i, 1);
424
425         const SGGeod& pos(wp.get_target());
426         prop->setStringValue("id", wp.get_id().c_str());
427         prop->setStringValue("name", wp.get_name().c_str());
428         prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
429         prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
430         prop->setDoubleValue("altitude-m", pos.getElevationM());
431         prop->setDoubleValue("altitude-ft", pos.getElevationFt());
432     }
433     // set number as listener attachment point
434     mirror->setIntValue("num", _route->size());
435 }
436
437 // command interface /autopilot/route-manager/input:
438 //
439 //   @CLEAR             ... clear route
440 //   @POP               ... remove first entry
441 //   @DELETE3           ... delete 4th entry
442 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
443 //   KSFO@900           ... append "KSFO@900"
444 //
445 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
446 {
447     const char *s = prop->getStringValue();
448     if (!strcmp(s, "@CLEAR"))
449         mgr->init();
450     else if (!strcmp(s, "@ACTIVATE"))
451         mgr->activate();
452     else if (!strcmp(s, "@LOAD")) {
453       mgr->loadRoute();
454     } else if (!strcmp(s, "@SAVE")) {
455       mgr->saveRoute();
456     } else if (!strcmp(s, "@POP"))
457         mgr->pop_waypoint(0);
458     else if (!strncmp(s, "@DELETE", 7))
459         mgr->pop_waypoint(atoi(s + 7));
460     else if (!strncmp(s, "@INSERT", 7)) {
461         char *r;
462         int pos = strtol(s + 7, &r, 10);
463         if (*r++ != ':')
464             return;
465         while (isspace(*r))
466             r++;
467         if (*r)
468             mgr->new_waypoint(r, pos);
469     } else
470         mgr->new_waypoint(s);
471 }
472
473 //    SGWayPoint( const double lon = 0.0, const double lat = 0.0,
474 //              const double alt = 0.0, const modetype m = WGS84,
475 //              const string& s = "", const string& n = "" );
476
477 bool FGRouteMgr::activate()
478 {
479   const FGAirport* depApt = fgFindAirportID(departure->getStringValue("airport"));
480   if (!depApt) {
481     SG_LOG(SG_AUTOPILOT, SG_ALERT, 
482       "unable to activate route: departure airport is invalid:" 
483         << departure->getStringValue("airport") );
484     return false;
485   }
486   
487   string runwayId(departure->getStringValue("runway"));
488   FGRunway* runway = NULL;
489   if (depApt->hasRunwayWithIdent(runwayId)) {
490     runway = depApt->getRunwayByIdent(runwayId);
491   } else {
492     SG_LOG(SG_AUTOPILOT, SG_INFO, 
493       "route-manager, departure runway not found:" << runwayId);
494     runway = depApt->getActiveRunwayForUsage();
495   }
496   
497   SGWayPoint swp(runway->threshold(), 
498     depApt->ident() + "-" + runway->ident(), runway->name());
499   add_waypoint(swp, 0);
500   
501   const FGAirport* destApt = fgFindAirportID(destination->getStringValue("airport"));
502   if (!destApt) {
503     SG_LOG(SG_AUTOPILOT, SG_ALERT, 
504       "unable to activate route: destination airport is invalid:" 
505         << destination->getStringValue("airport") );
506     return false;
507   }
508
509   runwayId = (destination->getStringValue("runway"));
510   if (destApt->hasRunwayWithIdent(runwayId)) {
511     FGRunway* runway = destApt->getRunwayByIdent(runwayId);
512     SGWayPoint swp(runway->end(), 
513       destApt->ident() + "-" + runway->ident(), runway->name());
514     add_waypoint(swp);
515   } else {
516     // quite likely, since destination runway may not be known until enroute
517     // probably want a listener on the 'destination' node to allow an enroute
518     // update
519     add_waypoint(SGWayPoint(destApt->geod(), destApt->ident(), destApt->name()));
520   }
521   
522   _route->set_current(0);
523   
524   double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
525   totalDistance->setDoubleValue(routeDistanceNm);
526   double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
527   if (cruiseSpeedKts > 1.0) {
528     // very very crude approximation, doesn't allow for climb / descent
529     // performance or anything else at all
530     ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
531   }
532   
533   active->setBoolValue(true);
534   sequence(); // sequence will sync up wp0, wp1 and current-wp
535   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
536   return true;
537 }
538
539
540 void FGRouteMgr::sequence()
541 {
542   if (!active->getBoolValue()) {
543     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
544     return;
545   }
546   
547   if (checkFinished()) {
548     return;
549   }
550   
551   _route->increment_current();
552   currentWaypointChanged();
553 }
554
555 bool FGRouteMgr::checkFinished()
556 {
557   int lastWayptIndex = _route->size() - 1;
558   if (_route->current_index() < lastWayptIndex) {
559     return false;
560   }
561   
562   SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
563   _finished->fireValueChanged();
564   active->setBoolValue(false);
565   return true;
566 }
567
568 void FGRouteMgr::jumpToIndex(int index)
569 {
570   if (!active->getBoolValue()) {
571     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
572     return;
573   }
574
575   if ((index < 0) || (index >= _route->size())) {
576     SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" << 
577       index << ") to FGRouteMgr::jumpToIndex");
578     return;
579   }
580
581   if (_route->current_index() == index) {
582     return; // no-op
583   }
584   
585   _route->set_current(index);
586   currentWaypointChanged();
587 }
588
589 void FGRouteMgr::currentWaypointChanged()
590 {
591   SGWayPoint previous = _route->get_previous();
592   SGWayPoint cur = _route->get_current();
593   
594   wp0->getChild("id")->setStringValue(cur.get_id());
595   if ((_route->current_index() + 1) < _route->size()) {
596     wp1->getChild("id")->setStringValue(_route->get_next().get_id());
597   } else {
598     wp1->getChild("id")->setStringValue("");
599   }
600   
601   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _route->current_index());
602 }
603
604 int FGRouteMgr::findWaypoint(const SGGeod& aPos) const
605 {  
606   for (int i=0; i<_route->size(); ++i) {
607     double d = SGGeodesy::distanceM(aPos, _route->get_waypoint(i).get_target());
608     if (d < 200.0) { // 200 metres seems close enough
609       return i;
610     }
611   }
612   
613   return -1;
614 }
615
616 SGWayPoint FGRouteMgr::get_waypoint( int i ) const
617 {
618   return _route->get_waypoint(i);
619 }
620
621 int FGRouteMgr::size() const
622 {
623   return _route->size();
624 }
625
626 int FGRouteMgr::currentWaypoint() const
627 {
628   return _route->current_index();
629 }
630
631 void FGRouteMgr::saveRoute()
632 {
633   SGPath path(_pathNode->getStringValue());
634   SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
635   try {
636     writeProperties(path.str(), mirror, false, SGPropertyNode::ARCHIVE);
637   } catch (const sg_exception &e) {
638     SG_LOG(SG_IO, SG_WARN, "Error saving route:" << e.getMessage());
639     //guiErrorMessage("Error writing autosave.xml: ", e);
640   }
641 }
642
643 void FGRouteMgr::loadRoute()
644 {
645   try {
646     // deactivate route first
647     active->setBoolValue(false);
648     
649     SGPropertyNode_ptr routeData(new SGPropertyNode);
650     SGPath path(_pathNode->getStringValue());
651     
652     SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
653     readProperties(path.str(), routeData);
654     
655   // departure nodes
656     SGPropertyNode* dep = routeData->getChild("departure");
657     if (!dep) {
658       throw sg_io_exception("malformed route file, no departure node");
659     }
660     
661     string depIdent = dep->getStringValue("airport");
662     const FGAirport* depApt = fgFindAirportID(depIdent);
663     if (!depApt) {
664       throw sg_io_exception("bad route file, unknown airport:" + depIdent);
665     }
666     
667     departure->setStringValue("runway", dep->getStringValue("runway"));
668     
669   // destination
670     SGPropertyNode* dst = routeData->getChild("destination");
671     if (!dst) {
672       throw sg_io_exception("malformed route file, no destination node");
673     }
674     
675     destination->setStringValue("airport", dst->getStringValue("airport"));
676     destination->setStringValue("runay", dst->getStringValue("runway"));
677
678   // alternate
679     SGPropertyNode* alt = routeData->getChild("alternate");
680     if (alt) {
681       alternate->setStringValue(alt->getStringValue("airport"));
682     } // of cruise data loading
683     
684   // cruise
685     SGPropertyNode* crs = routeData->getChild("cruise");
686     if (crs) {
687       cruise->setDoubleValue(crs->getDoubleValue("speed"));
688     } // of cruise data loading
689
690   // route nodes
691     _route->clear();
692     SGPropertyNode_ptr _route = routeData->getChild("route", 0);
693     SGGeod lastPos(depApt->geod());
694     
695     for (int i=0; i<_route->nChildren(); ++i) {
696       SGPropertyNode_ptr wp = _route->getChild("wp", i);
697       parseRouteWaypoint(wp);
698     } // of route iteration
699   } catch (sg_exception& e) {
700     SG_LOG(SG_IO, SG_WARN, "failed to load flight-plan (from '" << e.getOrigin()
701       << "'):" << e.getMessage());
702   }
703 }
704
705 void FGRouteMgr::parseRouteWaypoint(SGPropertyNode* aWP)
706 {
707   SGGeod lastPos;
708   if (_route->size() > 0) {
709     lastPos = get_waypoint(_route->size()-1).get_target();
710   } else {
711     // route is empty, use departure airport position
712     const FGAirport* apt = fgFindAirportID(departure->getStringValue("airport"));
713     assert(apt); // shouldn't have got this far with an invalid airport
714     lastPos = apt->geod();
715   }
716
717   SGPropertyNode_ptr altProp = aWP->getChild("altitude-ft");
718   double alt = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
719   if (altProp) {
720     alt = altProp->getDoubleValue();
721   }
722       
723   string ident(aWP->getStringValue("ident"));
724   if (aWP->hasChild("longitude-deg")) {
725     // explicit longitude/latitude
726     SGWayPoint swp(aWP->getDoubleValue("longitude-deg"),
727       aWP->getDoubleValue("latitude-deg"), alt, 
728       SGWayPoint::WGS84, ident, aWP->getStringValue("name"));
729     add_waypoint(swp);
730   } else if (aWP->hasChild("navid")) {
731     // lookup by navid (possibly with offset)
732     string nid(aWP->getStringValue("navid"));
733     FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
734     if (!p) {
735       throw sg_io_exception("bad route file, unknown navid:" + nid);
736     }
737     
738     SGGeod pos(p->geod());
739     if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
740       double radialDeg = aWP->getDoubleValue("offset-radial");
741       // convert magnetic radial to a true radial!
742       radialDeg += magvar->getDoubleValue();
743       double offsetNm = aWP->getDoubleValue("offset-nm");
744       double az2;
745       SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
746     }
747     
748     SGWayPoint swp(pos.getLongitudeDeg(), pos.getLatitudeDeg(), alt, 
749       SGWayPoint::WGS84, ident, "");
750     add_waypoint(swp);
751   } else {
752     // lookup by ident (symbolic waypoint)
753     FGPositionedRef p = FGPositioned::findClosestWithIdent(ident, lastPos);
754     if (!p) {
755       throw sg_io_exception("bad route file, unknown waypoint:" + ident);
756     }
757     
758     SGWayPoint swp(p->longitude(), p->latitude(), alt, 
759       SGWayPoint::WGS84, p->ident(), p->name());
760     add_waypoint(swp);
761   }
762 }