]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
Merge branch 'durk/traffic' into next
[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     
344     double alt = -9999.0;
345     // extract altitude
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 (strlen(s) == 0) {
459       return;
460     }
461     
462     if (!strcmp(s, "@CLEAR"))
463         mgr->init();
464     else if (!strcmp(s, "@ACTIVATE"))
465         mgr->activate();
466     else if (!strcmp(s, "@LOAD")) {
467       mgr->loadRoute();
468     } else if (!strcmp(s, "@SAVE")) {
469       mgr->saveRoute();
470     } else if (!strcmp(s, "@POP"))
471         mgr->pop_waypoint(0);
472     else if (!strncmp(s, "@DELETE", 7))
473         mgr->pop_waypoint(atoi(s + 7));
474     else if (!strncmp(s, "@INSERT", 7)) {
475         char *r;
476         int pos = strtol(s + 7, &r, 10);
477         if (*r++ != ':')
478             return;
479         while (isspace(*r))
480             r++;
481         if (*r)
482             mgr->new_waypoint(r, pos);
483     } else
484         mgr->new_waypoint(s);
485 }
486
487 //    SGWayPoint( const double lon = 0.0, const double lat = 0.0,
488 //              const double alt = 0.0, const modetype m = WGS84,
489 //              const string& s = "", const string& n = "" );
490
491 bool FGRouteMgr::activate()
492 {
493   if (isRouteActive()) {
494     SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
495     return false;
496   }
497
498   // only add departure waypoint if we're not airborne, so that
499   // in-air route activation doesn't confuse matters.
500   if (weightOnWheels->getBoolValue() && _departure) {
501     string runwayId(departure->getStringValue("runway"));
502     FGRunway* runway = NULL;
503     if (_departure->hasRunwayWithIdent(runwayId)) {
504       runway = _departure->getRunwayByIdent(runwayId);
505     } else {
506       SG_LOG(SG_AUTOPILOT, SG_INFO, 
507         "route-manager, departure runway not found:" << runwayId);
508       runway = _departure->getActiveRunwayForUsage();
509     }
510     
511     SGWayPoint swp(runway->threshold(), 
512       _departure->ident() + "-" + runway->ident(), runway->name());
513     add_waypoint(swp, 0);
514   }
515   
516   if (_destination) {
517     string runwayId = (destination->getStringValue("runway"));
518     if (_destination->hasRunwayWithIdent(runwayId)) {
519       FGRunway* runway = _destination->getRunwayByIdent(runwayId);
520       SGWayPoint swp(runway->end(), 
521         _destination->ident() + "-" + runway->ident(), runway->name());
522       add_waypoint(swp);
523     } else {
524       // quite likely, since destination runway may not be known until enroute
525       // probably want a listener on the 'destination' node to allow an enroute
526       // update
527       add_waypoint(SGWayPoint(_destination->geod(), _destination->ident(), _destination->name()));
528     }
529   }
530
531   _route->set_current(0);
532   
533   double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
534   totalDistance->setDoubleValue(routeDistanceNm);
535   double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
536   if (cruiseSpeedKts > 1.0) {
537     // very very crude approximation, doesn't allow for climb / descent
538     // performance or anything else at all
539     ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
540   }
541   
542   active->setBoolValue(true);
543   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
544   return true;
545 }
546
547
548 void FGRouteMgr::sequence()
549 {
550   if (!active->getBoolValue()) {
551     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
552     return;
553   }
554   
555   if (checkFinished()) {
556     return;
557   }
558   
559   _route->increment_current();
560   currentWaypointChanged();
561   _currentWpt->fireValueChanged();
562 }
563
564 bool FGRouteMgr::checkFinished()
565 {
566   int lastWayptIndex = _route->size() - 1;
567   if (_route->current_index() < lastWayptIndex) {
568     return false;
569   }
570   
571   SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
572   _finished->fireValueChanged();
573   active->setBoolValue(false);
574   return true;
575 }
576
577 void FGRouteMgr::jumpToIndex(int index)
578 {
579   if (!active->getBoolValue()) {
580     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
581     return;
582   }
583
584   if ((index < 0) || (index >= _route->size())) {
585     SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" << 
586       index << ") to FGRouteMgr::jumpToIndex");
587     return;
588   }
589
590   if (_route->current_index() == index) {
591     return; // no-op
592   }
593   
594   _route->set_current(index);
595   currentWaypointChanged();
596 }
597
598 void FGRouteMgr::currentWaypointChanged()
599 {
600   SGWayPoint previous = _route->get_previous();
601   SGWayPoint cur = _route->get_current();
602   
603   wp0->getChild("id")->setStringValue(cur.get_id());
604   if ((_route->current_index() + 1) < _route->size()) {
605     wp1->getChild("id")->setStringValue(_route->get_next().get_id());
606   } else {
607     wp1->getChild("id")->setStringValue("");
608   }
609   
610   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _route->current_index());
611 }
612
613 int FGRouteMgr::findWaypoint(const SGGeod& aPos) const
614 {  
615   for (int i=0; i<_route->size(); ++i) {
616     double d = SGGeodesy::distanceM(aPos, _route->get_waypoint(i).get_target());
617     if (d < 200.0) { // 200 metres seems close enough
618       return i;
619     }
620   }
621   
622   return -1;
623 }
624
625 SGWayPoint FGRouteMgr::get_waypoint( int i ) const
626 {
627   return _route->get_waypoint(i);
628 }
629
630 int FGRouteMgr::size() const
631 {
632   return _route->size();
633 }
634
635 int FGRouteMgr::currentWaypoint() const
636 {
637   return _route->current_index();
638 }
639
640 void FGRouteMgr::saveRoute()
641 {
642   SGPath path(_pathNode->getStringValue());
643   SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
644   try {
645     writeProperties(path.str(), mirror, false, SGPropertyNode::ARCHIVE);
646   } catch (const sg_exception &e) {
647     SG_LOG(SG_IO, SG_WARN, "Error saving route:" << e.getMessage());
648     //guiErrorMessage("Error writing autosave.xml: ", e);
649   }
650 }
651
652 void FGRouteMgr::loadRoute()
653 {
654   try {
655     // deactivate route first
656     active->setBoolValue(false);
657     
658     SGPropertyNode_ptr routeData(new SGPropertyNode);
659     SGPath path(_pathNode->getStringValue());
660     
661     SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
662     readProperties(path.str(), routeData);
663     
664   // departure nodes
665     SGPropertyNode* dep = routeData->getChild("departure");
666     if (!dep) {
667       throw sg_io_exception("malformed route file, no departure node");
668     }
669     
670     string depIdent = dep->getStringValue("airport");
671     _departure = (FGAirport*) fgFindAirportID(depIdent);
672
673         
674   // destination
675     SGPropertyNode* dst = routeData->getChild("destination");
676     if (!dst) {
677       throw sg_io_exception("malformed route file, no destination node");
678     }
679     
680     _destination = (FGAirport*) fgFindAirportID(dst->getStringValue("airport"));
681     destination->setStringValue("runway", dst->getStringValue("runway"));
682
683   // alternate
684     SGPropertyNode* alt = routeData->getChild("alternate");
685     if (alt) {
686       alternate->setStringValue(alt->getStringValue("airport"));
687     } // of cruise data loading
688     
689   // cruise
690     SGPropertyNode* crs = routeData->getChild("cruise");
691     if (crs) {
692       cruise->setDoubleValue(crs->getDoubleValue("speed"));
693     } // of cruise data loading
694
695   // route nodes
696     _route->clear();
697     SGPropertyNode_ptr _route = routeData->getChild("route", 0);
698     SGGeod lastPos = (_departure ? _departure->geod() : SGGeod());
699     
700     for (int i=0; i<_route->nChildren(); ++i) {
701       SGPropertyNode_ptr wp = _route->getChild("wp", i);
702       parseRouteWaypoint(wp);
703     } // of route iteration
704   } catch (sg_exception& e) {
705     SG_LOG(SG_IO, SG_WARN, "failed to load flight-plan (from '" << e.getOrigin()
706       << "'):" << e.getMessage());
707   }
708 }
709
710 void FGRouteMgr::parseRouteWaypoint(SGPropertyNode* aWP)
711 {
712   SGGeod lastPos;
713   if (_route->size() > 0) {
714     lastPos = get_waypoint(_route->size()-1).get_target();
715   } else {
716     // route is empty, use departure airport position
717     const FGAirport* apt = fgFindAirportID(departure->getStringValue("airport"));
718     assert(apt); // shouldn't have got this far with an invalid airport
719     lastPos = apt->geod();
720   }
721
722   SGPropertyNode_ptr altProp = aWP->getChild("altitude-ft");
723   double altM = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
724   if (altProp) {
725     altM = altProp->getDoubleValue() * SG_FEET_TO_METER;
726   }
727       
728   string ident(aWP->getStringValue("ident"));
729   if (aWP->hasChild("longitude-deg")) {
730     // explicit longitude/latitude
731     SGWayPoint swp(aWP->getDoubleValue("longitude-deg"),
732       aWP->getDoubleValue("latitude-deg"), altM, 
733       SGWayPoint::WGS84, ident, aWP->getStringValue("name"));
734     add_waypoint(swp);
735   } else if (aWP->hasChild("navid")) {
736     // lookup by navid (possibly with offset)
737     string nid(aWP->getStringValue("navid"));
738     FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
739     if (!p) {
740       throw sg_io_exception("bad route file, unknown navid:" + nid);
741     }
742     
743     SGGeod pos(p->geod());
744     if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
745       double radialDeg = aWP->getDoubleValue("offset-radial");
746       // convert magnetic radial to a true radial!
747       radialDeg += magvar->getDoubleValue();
748       double offsetNm = aWP->getDoubleValue("offset-nm");
749       double az2;
750       SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
751     }
752     
753     SGWayPoint swp(pos.getLongitudeDeg(), pos.getLatitudeDeg(), altM, 
754       SGWayPoint::WGS84, ident, "");
755     add_waypoint(swp);
756   } else {
757     // lookup by ident (symbolic waypoint)
758     FGPositionedRef p = FGPositioned::findClosestWithIdent(ident, lastPos);
759     if (!p) {
760       throw sg_io_exception("bad route file, unknown waypoint:" + ident);
761     }
762     
763     SGWayPoint swp(p->longitude(), p->latitude(), altM, 
764       SGWayPoint::WGS84, p->ident(), p->name());
765     add_waypoint(swp);
766   }
767 }
768
769 const char* FGRouteMgr::getDepartureICAO() const
770 {
771   if (!_departure) {
772     return "";
773   }
774   
775   return _departure->ident().c_str();
776 }
777
778 const char* FGRouteMgr::getDepartureName() const
779 {
780   if (!_departure) {
781     return "";
782   }
783   
784   return _departure->name().c_str();
785 }
786
787 void FGRouteMgr::setDepartureICAO(const char* aIdent)
788 {
789   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
790     _departure = NULL;
791   } else {
792     _departure = FGAirport::findByIdent(aIdent);
793   }
794 }
795
796 const char* FGRouteMgr::getDestinationICAO() const
797 {
798   if (!_destination) {
799     return "";
800   }
801   
802   return _destination->ident().c_str();
803 }
804
805 const char* FGRouteMgr::getDestinationName() const
806 {
807   if (!_destination) {
808     return "";
809   }
810   
811   return _destination->name().c_str();
812 }
813
814 void FGRouteMgr::setDestinationICAO(const char* aIdent)
815 {
816   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
817     _destination = NULL;
818   } else {
819     _destination = FGAirport::findByIdent(aIdent);
820   }
821 }
822