]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
Merge branch 'vivian/trainz'
[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   departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
96     &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
97   departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
98     &FGRouteMgr::getDepartureName, NULL));
99     
100 // init departure information from current location
101   SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(), lat->getDoubleValue(), alt->getDoubleValue());
102   _departure = FGAirport::findClosest(pos, 20.0);
103   if (_departure) {
104     FGRunway* active = _departure->getActiveRunwayForUsage();
105     departure->setStringValue("runway", active->ident().c_str());
106   } else {
107     departure->setStringValue("runway", "");
108   }
109   
110   departure->getChild("etd", 0, true);
111   departure->getChild("takeoff-time", 0, true);
112
113   destination = fgGetNode(RM "destination", true);
114   destination->getChild("airport", 0, true);
115   
116   destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
117     &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
118   destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
119     &FGRouteMgr::getDestinationName, NULL));
120     
121   destination->getChild("runway", 0, true);
122   destination->getChild("eta", 0, true);
123   destination->getChild("touchdown-time", 0, true);
124   
125   alternate = fgGetNode(RM "alternate", true);
126   alternate->getChild("airport", 0, true);
127   alternate->getChild("runway", 0, true);
128   
129   cruise = fgGetNode(RM "cruise", true);
130   cruise->getChild("altitude-ft", 0, true);
131   cruise->setDoubleValue("altitude-ft", 10000.0);
132   cruise->getChild("flight-level", 0, true);
133   cruise->getChild("speed-kts", 0, true);
134   cruise->setDoubleValue("speed-kts", 160.0);
135   
136   totalDistance = fgGetNode(RM "total-distance", true);
137   totalDistance->setDoubleValue(0.0);
138   
139   ete = fgGetNode(RM "ete", true);
140   ete->setDoubleValue(0.0);
141   
142   elapsedFlightTime = fgGetNode(RM "flight-time", true);
143   elapsedFlightTime->setDoubleValue(0.0);
144   
145   active = fgGetNode(RM "active", true);
146   active->setBoolValue(false);
147   
148   airborne = fgGetNode(RM "airborne", true);
149   airborne->setBoolValue(false);
150     
151   _edited = fgGetNode(RM "signals/edited", true);
152   _finished = fgGetNode(RM "signals/finished", true);
153   
154   _currentWpt = fgGetNode(RM "current-wp", true);
155   _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
156     (*this, &FGRouteMgr::currentWaypoint, &FGRouteMgr::jumpToIndex));
157       
158   // temporary distance / eta calculations, for backward-compatability
159   wp0 = fgGetNode(RM "wp", 0, true);
160   wp0->getChild("id", 0, true);
161   wp0->getChild("dist", 0, true);
162   wp0->getChild("eta", 0, true);
163   wp0->getChild("bearing-deg", 0, true);
164   
165   wp1 = fgGetNode(RM "wp", 1, true);
166   wp1->getChild("id", 0, true);
167   wp1->getChild("dist", 0, true);
168   wp1->getChild("eta", 0, true);
169   
170   wpn = fgGetNode(RM "wp-last", 0, true);
171   wpn->getChild("dist", 0, true);
172   wpn->getChild("eta", 0, true);
173   
174   _route->clear();
175   update_mirror();
176   
177   _pathNode = fgGetNode(RM "file-path", 0, true);
178 }
179
180
181 void FGRouteMgr::postinit() {
182     string_list *waypoints = globals->get_initial_waypoints();
183     if (waypoints) {
184       vector<string>::iterator it;
185       for (it = waypoints->begin(); it != waypoints->end(); ++it)
186         new_waypoint(*it);
187     }
188
189     weightOnWheels = fgGetNode("/gear/gear[0]/wow", false);
190     // check airbone flag agrees with presets
191     
192 }
193
194
195 void FGRouteMgr::bind() { }
196 void FGRouteMgr::unbind() { }
197
198 bool FGRouteMgr::isRouteActive() const
199 {
200   return active->getBoolValue();
201 }
202
203 void FGRouteMgr::update( double dt ) {
204     if (dt <= 0.0) {
205       // paused, nothing to do here
206       return;
207     }
208   
209     if (!active->getBoolValue()) {
210       return;
211     }
212     
213     double groundSpeed = get_ground_speed();
214     if (airborne->getBoolValue()) {
215       time_t now = time(NULL);
216       elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
217     } else { // not airborne
218       if (weightOnWheels->getBoolValue() || (groundSpeed < 40)) {
219         return;
220       }
221       
222       airborne->setBoolValue(true);
223       _takeoffTime = time(NULL); // start the clock
224       departure->setIntValue("takeoff-time", _takeoffTime);
225     }
226     
227   // basic course/distance information
228     double wp_course, wp_distance;
229     SGWayPoint wp = _route->get_current();
230     wp.CourseAndDistance( lon->getDoubleValue(), lat->getDoubleValue(),
231                           alt->getDoubleValue(), &wp_course, &wp_distance );
232
233   // update wp0 / wp1 / wp-last for legacy users
234     wp0->setDoubleValue("dist", wp_distance * SG_METER_TO_NM);
235     wp_course -= magvar->getDoubleValue(); // expose magnetic bearing
236     wp0->setDoubleValue("bearing-deg", wp_course);
237     setETAPropertyFromDistance(wp0->getChild("eta"), wp_distance);
238     
239     if ((_route->current_index() + 1) < _route->size()) {
240       wp = _route->get_waypoint(_route->current_index() + 1);
241       double wp1_course, wp1_distance;
242       wp.CourseAndDistance(lon->getDoubleValue(), lat->getDoubleValue(),
243                           alt->getDoubleValue(), &wp1_course, &wp1_distance);
244     
245       wp1->setDoubleValue("dist", wp1_distance * SG_METER_TO_NM);
246       setETAPropertyFromDistance(wp1->getChild("eta"), wp1_distance);
247     }
248     
249     double totalDistanceRemaining = wp_distance; // distance to current waypoint
250     for (int i=_route->current_index() + 1; i<_route->size(); ++i) {
251       totalDistanceRemaining += _route->get_waypoint(i).get_distance();
252     }
253     
254     wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
255     ete->setDoubleValue(totalDistanceRemaining * SG_METER_TO_NM / groundSpeed * 3600.0);
256     setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
257     
258     // get time now at destination tz as tm struct
259     // add ete seconds
260     // convert to string ... and stash in property
261     //destination->setDoubleValue("eta", eta);
262 }
263
264
265 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance) {
266     double speed = get_ground_speed();
267     if (speed < 1.0) {
268       aProp->setStringValue("--:--");
269       return;
270     }
271   
272     char eta_str[64];
273     double eta = aDistance * SG_METER_TO_NM / get_ground_speed();
274     if ( eta >= 100.0 ) { 
275         eta = 99.999; // clamp
276     }
277     
278     if ( eta < (1.0/6.0) ) {
279       eta *= 60.0; // within 10 minutes, bump up to min/secs
280     }
281     
282     int major = (int)eta, 
283         minor = (int)((eta - (int)eta) * 60.0);
284     snprintf( eta_str, 64, "%d:%02d", major, minor );
285     aProp->setStringValue( eta_str );
286 }
287
288 void FGRouteMgr::add_waypoint( const SGWayPoint& wp, int n ) {
289   _route->add_waypoint( wp, n );
290     
291   if (_route->current_index() > n) {
292     _route->set_current(_route->current_index() + 1);
293   }
294   
295   update_mirror();
296   _edited->fireValueChanged();
297 }
298
299
300 SGWayPoint FGRouteMgr::pop_waypoint( int n ) {
301   if ( _route->size() <= 0 ) {
302     return SGWayPoint();
303   }
304   
305   if ( n < 0 ) {
306     n = _route->size() - 1;
307   }
308   
309   if (_route->current_index() > n) {
310     _route->set_current(_route->current_index() - 1);
311   }
312
313   SGWayPoint wp = _route->get_waypoint(n);
314   _route->delete_waypoint(n);
315     
316   update_mirror();
317   _edited->fireValueChanged();
318   checkFinished();
319   
320   return wp;
321 }
322
323
324 bool FGRouteMgr::build() {
325     return true;
326 }
327
328
329 void FGRouteMgr::new_waypoint( const string& target, int n ) {
330     SGWayPoint* wp = make_waypoint( target );
331     if (!wp) {
332         return;
333     }
334     
335     add_waypoint( *wp, n );
336     delete wp;
337 }
338
339
340 SGWayPoint* FGRouteMgr::make_waypoint(const string& tgt ) {
341     string target(boost::to_upper_copy(tgt));
342     
343     // extract altitude
344     double alt = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
345     
346     size_t pos = target.find( '@' );
347     if ( pos != string::npos ) {
348         alt = atof( target.c_str() + pos + 1 );
349         target = target.substr( 0, pos );
350         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
351             alt *= SG_FEET_TO_METER;
352     }
353
354     // check for lon,lat
355     pos = target.find( ',' );
356     if ( pos != string::npos ) {
357         double lon = atof( target.substr(0, pos).c_str());
358         double lat = atof( target.c_str() + pos + 1);
359         char buf[32];
360         char ew = (lon < 0.0) ? 'W' : 'E';
361         char ns = (lat < 0.0) ? 'S' : 'N';
362         snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
363         return new SGWayPoint( lon, lat, alt, SGWayPoint::WGS84, buf);
364     }    
365
366     SGGeod basePosition;
367     if (_route->size() > 0) {
368         SGWayPoint wp = get_waypoint(_route->size()-1);
369         basePosition = wp.get_target();
370     } else {
371         // route is empty, use current position
372         basePosition = SGGeod::fromDeg(
373             fgGetNode("/position/longitude-deg")->getDoubleValue(), 
374             fgGetNode("/position/latitude-deg")->getDoubleValue());
375     }
376     
377     vector<string> pieces(simgear::strutils::split(target, "/"));
378
379
380     FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
381     if (!p) {
382       SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
383       return NULL;
384     }
385     
386     SGGeod geod = SGGeod::fromGeodM(p->geod(), alt);
387     if (pieces.size() == 1) {
388       // simple case
389       return new SGWayPoint(geod, target, p->name());
390     }
391         
392     if (pieces.size() == 3) {
393       // navaid/radial/distance-nm notation
394       double radial = atof(pieces[1].c_str()),
395         distanceNm = atof(pieces[2].c_str()),
396         az2;
397       radial += magvar->getDoubleValue(); // convert to true bearing
398       SGGeod offsetPos;
399       SGGeodesy::direct(geod, radial, distanceNm * SG_NM_TO_METER, offsetPos, az2);
400       offsetPos.setElevationM(alt);
401       
402       SG_LOG(SG_AUTOPILOT, SG_INFO, "final offset radial is " << radial);
403       return new SGWayPoint(offsetPos, p->ident() + pieces[2], target);
404     }
405     
406     if (pieces.size() == 2) {
407       FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
408       if (!apt) {
409         SG_LOG(SG_AUTOPILOT, SG_INFO, "Waypoint is not an airport:" << pieces.front());
410         return NULL;
411       }
412       
413       if (!apt->hasRunwayWithIdent(pieces[1])) {
414         SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
415         return NULL;
416       }
417       
418       FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
419       SGGeod t = runway->threshold();
420       return new SGWayPoint(t.getLongitudeDeg(), t.getLatitudeDeg(), alt, SGWayPoint::WGS84, pieces[1]);
421     }
422     
423     SG_LOG(SG_AUTOPILOT, SG_INFO, "Unable to parse waypoint:" << target);
424     return NULL;
425 }
426
427
428 // mirror internal route to the property system for inspection by other subsystems
429 void FGRouteMgr::update_mirror() {
430     mirror->removeChildren("wp");
431     for (int i = 0; i < _route->size(); i++) {
432         SGWayPoint wp = _route->get_waypoint(i);
433         SGPropertyNode *prop = mirror->getChild("wp", i, 1);
434
435         const SGGeod& pos(wp.get_target());
436         prop->setStringValue("id", wp.get_id().c_str());
437         prop->setStringValue("name", wp.get_name().c_str());
438         prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
439         prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
440         prop->setDoubleValue("altitude-m", pos.getElevationM());
441         prop->setDoubleValue("altitude-ft", pos.getElevationFt());
442     }
443     // set number as listener attachment point
444     mirror->setIntValue("num", _route->size());
445 }
446
447 // command interface /autopilot/route-manager/input:
448 //
449 //   @CLEAR             ... clear route
450 //   @POP               ... remove first entry
451 //   @DELETE3           ... delete 4th entry
452 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
453 //   KSFO@900           ... append "KSFO@900"
454 //
455 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
456 {
457     const char *s = prop->getStringValue();
458     if (!strcmp(s, "@CLEAR"))
459         mgr->init();
460     else if (!strcmp(s, "@ACTIVATE"))
461         mgr->activate();
462     else if (!strcmp(s, "@LOAD")) {
463       mgr->loadRoute();
464     } else if (!strcmp(s, "@SAVE")) {
465       mgr->saveRoute();
466     } else if (!strcmp(s, "@POP"))
467         mgr->pop_waypoint(0);
468     else if (!strncmp(s, "@DELETE", 7))
469         mgr->pop_waypoint(atoi(s + 7));
470     else if (!strncmp(s, "@INSERT", 7)) {
471         char *r;
472         int pos = strtol(s + 7, &r, 10);
473         if (*r++ != ':')
474             return;
475         while (isspace(*r))
476             r++;
477         if (*r)
478             mgr->new_waypoint(r, pos);
479     } else
480         mgr->new_waypoint(s);
481 }
482
483 //    SGWayPoint( const double lon = 0.0, const double lat = 0.0,
484 //              const double alt = 0.0, const modetype m = WGS84,
485 //              const string& s = "", const string& n = "" );
486
487 bool FGRouteMgr::activate()
488 {
489   if (_departure) {
490     string runwayId(departure->getStringValue("runway"));
491     FGRunway* runway = NULL;
492     if (_departure->hasRunwayWithIdent(runwayId)) {
493       runway = _departure->getRunwayByIdent(runwayId);
494     } else {
495       SG_LOG(SG_AUTOPILOT, SG_INFO, 
496         "route-manager, departure runway not found:" << runwayId);
497       runway = _departure->getActiveRunwayForUsage();
498     }
499     
500     SGWayPoint swp(runway->threshold(), 
501       _departure->ident() + "-" + runway->ident(), runway->name());
502     add_waypoint(swp, 0);
503   }
504   
505   if (_destination) {
506     string runwayId = (destination->getStringValue("runway"));
507     if (_destination->hasRunwayWithIdent(runwayId)) {
508       FGRunway* runway = _destination->getRunwayByIdent(runwayId);
509       SGWayPoint swp(runway->end(), 
510         _destination->ident() + "-" + runway->ident(), runway->name());
511       add_waypoint(swp);
512     } else {
513       // quite likely, since destination runway may not be known until enroute
514       // probably want a listener on the 'destination' node to allow an enroute
515       // update
516       add_waypoint(SGWayPoint(_destination->geod(), _destination->ident(), _destination->name()));
517     }
518   }
519
520   _route->set_current(0);
521   
522   double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
523   totalDistance->setDoubleValue(routeDistanceNm);
524   double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
525   if (cruiseSpeedKts > 1.0) {
526     // very very crude approximation, doesn't allow for climb / descent
527     // performance or anything else at all
528     ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
529   }
530   
531   active->setBoolValue(true);
532   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
533   return true;
534 }
535
536
537 void FGRouteMgr::sequence()
538 {
539   if (!active->getBoolValue()) {
540     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
541     return;
542   }
543   
544   if (checkFinished()) {
545     return;
546   }
547   
548   _route->increment_current();
549   currentWaypointChanged();
550   _currentWpt->fireValueChanged();
551 }
552
553 bool FGRouteMgr::checkFinished()
554 {
555   int lastWayptIndex = _route->size() - 1;
556   if (_route->current_index() < lastWayptIndex) {
557     return false;
558   }
559   
560   SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
561   _finished->fireValueChanged();
562   active->setBoolValue(false);
563   return true;
564 }
565
566 void FGRouteMgr::jumpToIndex(int index)
567 {
568   if (!active->getBoolValue()) {
569     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
570     return;
571   }
572
573   if ((index < 0) || (index >= _route->size())) {
574     SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" << 
575       index << ") to FGRouteMgr::jumpToIndex");
576     return;
577   }
578
579   if (_route->current_index() == index) {
580     return; // no-op
581   }
582   
583   _route->set_current(index);
584   currentWaypointChanged();
585 }
586
587 void FGRouteMgr::currentWaypointChanged()
588 {
589   SGWayPoint previous = _route->get_previous();
590   SGWayPoint cur = _route->get_current();
591   
592   wp0->getChild("id")->setStringValue(cur.get_id());
593   if ((_route->current_index() + 1) < _route->size()) {
594     wp1->getChild("id")->setStringValue(_route->get_next().get_id());
595   } else {
596     wp1->getChild("id")->setStringValue("");
597   }
598   
599   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _route->current_index());
600 }
601
602 int FGRouteMgr::findWaypoint(const SGGeod& aPos) const
603 {  
604   for (int i=0; i<_route->size(); ++i) {
605     double d = SGGeodesy::distanceM(aPos, _route->get_waypoint(i).get_target());
606     if (d < 200.0) { // 200 metres seems close enough
607       return i;
608     }
609   }
610   
611   return -1;
612 }
613
614 SGWayPoint FGRouteMgr::get_waypoint( int i ) const
615 {
616   return _route->get_waypoint(i);
617 }
618
619 int FGRouteMgr::size() const
620 {
621   return _route->size();
622 }
623
624 int FGRouteMgr::currentWaypoint() const
625 {
626   return _route->current_index();
627 }
628
629 void FGRouteMgr::saveRoute()
630 {
631   SGPath path(_pathNode->getStringValue());
632   SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
633   try {
634     writeProperties(path.str(), mirror, false, SGPropertyNode::ARCHIVE);
635   } catch (const sg_exception &e) {
636     SG_LOG(SG_IO, SG_WARN, "Error saving route:" << e.getMessage());
637     //guiErrorMessage("Error writing autosave.xml: ", e);
638   }
639 }
640
641 void FGRouteMgr::loadRoute()
642 {
643   try {
644     // deactivate route first
645     active->setBoolValue(false);
646     
647     SGPropertyNode_ptr routeData(new SGPropertyNode);
648     SGPath path(_pathNode->getStringValue());
649     
650     SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
651     readProperties(path.str(), routeData);
652     
653   // departure nodes
654     SGPropertyNode* dep = routeData->getChild("departure");
655     if (!dep) {
656       throw sg_io_exception("malformed route file, no departure node");
657     }
658     
659     string depIdent = dep->getStringValue("airport");
660     _departure = (FGAirport*) fgFindAirportID(depIdent);
661
662         
663   // destination
664     SGPropertyNode* dst = routeData->getChild("destination");
665     if (!dst) {
666       throw sg_io_exception("malformed route file, no destination node");
667     }
668     
669     _destination = (FGAirport*) fgFindAirportID(dst->getStringValue("airport"));
670     destination->setStringValue("runway", dst->getStringValue("runway"));
671
672   // alternate
673     SGPropertyNode* alt = routeData->getChild("alternate");
674     if (alt) {
675       alternate->setStringValue(alt->getStringValue("airport"));
676     } // of cruise data loading
677     
678   // cruise
679     SGPropertyNode* crs = routeData->getChild("cruise");
680     if (crs) {
681       cruise->setDoubleValue(crs->getDoubleValue("speed"));
682     } // of cruise data loading
683
684   // route nodes
685     _route->clear();
686     SGPropertyNode_ptr _route = routeData->getChild("route", 0);
687     SGGeod lastPos = (_departure ? _departure->geod() : SGGeod());
688     
689     for (int i=0; i<_route->nChildren(); ++i) {
690       SGPropertyNode_ptr wp = _route->getChild("wp", i);
691       parseRouteWaypoint(wp);
692     } // of route iteration
693   } catch (sg_exception& e) {
694     SG_LOG(SG_IO, SG_WARN, "failed to load flight-plan (from '" << e.getOrigin()
695       << "'):" << e.getMessage());
696   }
697 }
698
699 void FGRouteMgr::parseRouteWaypoint(SGPropertyNode* aWP)
700 {
701   SGGeod lastPos;
702   if (_route->size() > 0) {
703     lastPos = get_waypoint(_route->size()-1).get_target();
704   } else {
705     // route is empty, use departure airport position
706     const FGAirport* apt = fgFindAirportID(departure->getStringValue("airport"));
707     assert(apt); // shouldn't have got this far with an invalid airport
708     lastPos = apt->geod();
709   }
710
711   SGPropertyNode_ptr altProp = aWP->getChild("altitude-ft");
712   double alt = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
713   if (altProp) {
714     alt = altProp->getDoubleValue();
715   }
716       
717   string ident(aWP->getStringValue("ident"));
718   if (aWP->hasChild("longitude-deg")) {
719     // explicit longitude/latitude
720     SGWayPoint swp(aWP->getDoubleValue("longitude-deg"),
721       aWP->getDoubleValue("latitude-deg"), alt, 
722       SGWayPoint::WGS84, ident, aWP->getStringValue("name"));
723     add_waypoint(swp);
724   } else if (aWP->hasChild("navid")) {
725     // lookup by navid (possibly with offset)
726     string nid(aWP->getStringValue("navid"));
727     FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
728     if (!p) {
729       throw sg_io_exception("bad route file, unknown navid:" + nid);
730     }
731     
732     SGGeod pos(p->geod());
733     if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
734       double radialDeg = aWP->getDoubleValue("offset-radial");
735       // convert magnetic radial to a true radial!
736       radialDeg += magvar->getDoubleValue();
737       double offsetNm = aWP->getDoubleValue("offset-nm");
738       double az2;
739       SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
740     }
741     
742     SGWayPoint swp(pos.getLongitudeDeg(), pos.getLatitudeDeg(), alt, 
743       SGWayPoint::WGS84, ident, "");
744     add_waypoint(swp);
745   } else {
746     // lookup by ident (symbolic waypoint)
747     FGPositionedRef p = FGPositioned::findClosestWithIdent(ident, lastPos);
748     if (!p) {
749       throw sg_io_exception("bad route file, unknown waypoint:" + ident);
750     }
751     
752     SGWayPoint swp(p->longitude(), p->latitude(), alt, 
753       SGWayPoint::WGS84, p->ident(), p->name());
754     add_waypoint(swp);
755   }
756 }
757
758 const char* FGRouteMgr::getDepartureICAO() const
759 {
760   if (!_departure) {
761     return "";
762   }
763   
764   return _departure->ident().c_str();
765 }
766
767 const char* FGRouteMgr::getDepartureName() const
768 {
769   if (!_departure) {
770     return "";
771   }
772   
773   return _departure->name().c_str();
774 }
775
776 void FGRouteMgr::setDepartureICAO(const char* aIdent)
777 {
778   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
779     _departure = NULL;
780   } else {
781     _departure = FGAirport::findByIdent(aIdent);
782   }
783 }
784
785 const char* FGRouteMgr::getDestinationICAO() const
786 {
787   if (!_destination) {
788     return "";
789   }
790   
791   return _destination->ident().c_str();
792 }
793
794 const char* FGRouteMgr::getDestinationName() const
795 {
796   if (!_destination) {
797     return "";
798   }
799   
800   return _destination->name().c_str();
801 }
802
803 void FGRouteMgr::setDestinationICAO(const char* aIdent)
804 {
805   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
806     _destination = NULL;
807   } else {
808     _destination = FGAirport::findByIdent(aIdent);
809   }
810 }
811