]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
When clearing the route, skip generated waypoints.
[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 #include <boost/tuple/tuple.hpp>
40
41 #include <simgear/misc/strutils.hxx>
42 #include <simgear/structure/exception.hxx>
43 #include <simgear/structure/commands.hxx>
44 #include <simgear/misc/sgstream.hxx>
45
46 #include <simgear/props/props_io.hxx>
47 #include <simgear/misc/sg_path.hxx>
48 #include <simgear/route/route.hxx>
49 #include <simgear/sg_inlines.h>
50
51 #include "Main/fg_props.hxx"
52 #include "Navaids/positioned.hxx"
53 #include <Navaids/waypoint.hxx>
54 #include <Navaids/airways.hxx>
55 #include <Navaids/procedure.hxx>
56 #include "Airports/simple.hxx"
57 #include "Airports/runways.hxx"
58
59 #define RM "/autopilot/route-manager/"
60
61 #include <GUI/new_gui.hxx>
62 #include <GUI/dialog.hxx>
63
64 using namespace flightgear;
65
66 class PropertyWatcher : public SGPropertyChangeListener
67 {
68 public:
69   void watch(SGPropertyNode* p)
70   {
71     p->addChangeListener(this, false);
72   }
73
74   virtual void valueChanged(SGPropertyNode*)
75   {
76     fire();
77   }
78 protected:
79   virtual void fire() = 0;
80 };
81
82 /**
83  * Template adapter, created by convenience helper below
84  */
85 template <class T>
86 class MethodPropertyWatcher : public PropertyWatcher
87 {
88 public:
89   typedef void (T::*fire_method)();
90
91   MethodPropertyWatcher(T* obj, fire_method m) :
92     _object(obj),
93     _method(m)
94   { ; }
95   
96 protected:
97   virtual void fire()
98   { // dispatch to the object method we're helping
99     (_object->*_method)();
100   }
101   
102 private:
103   T* _object;
104   fire_method _method;
105 };
106
107 template <class T>
108 PropertyWatcher* createWatcher(T* obj, void (T::*m)())
109 {
110   return new MethodPropertyWatcher<T>(obj, m);
111 }
112
113 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
114 {
115   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
116   SGPath path(arg->getStringValue("path"));
117   return self->loadRoute(path);
118 }
119
120 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
121 {
122   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
123   SGPath path(arg->getStringValue("path"));
124   return self->saveRoute(path);
125 }
126
127 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
128 {
129   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
130   bool activate = arg->getBoolValue("activate", true);
131   if (activate) {
132     self->activate();
133   } else {
134     
135   }
136   
137   return true;
138 }
139
140 static bool commandClearFlightPlan(const SGPropertyNode*)
141 {
142   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
143   self->clearRoute();
144   return true;
145 }
146
147 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
148 {
149   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
150   int index = arg->getIntValue("index");
151   if ((index < 0) || (index >= self->numWaypts())) {
152     return false;
153   }
154   
155   self->jumpToIndex(index);
156   return true;
157 }
158
159 static bool commandInsertWaypt(const SGPropertyNode* arg)
160 {
161   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
162   int index = arg->getIntValue("index");
163   std::string ident(arg->getStringValue("id"));
164   int alt = arg->getIntValue("altitude-ft", -999);
165   int ias = arg->getIntValue("speed-knots", -999);
166   
167   WayptRef wp;
168 // lat/lon may be supplied to narrow down navaid search, or to specify
169 // a raw waypoint
170   SGGeod pos;
171   if (arg->hasChild("longitude-deg")) {
172     pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
173                                arg->getDoubleValue("latitude-deg"));
174   }
175   
176   if (arg->hasChild("navaid")) {
177     FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
178     
179     if (arg->hasChild("navaid", 1)) {
180       // intersection of two radials
181       FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
182       if (!p2) {
183         SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
184         return false;
185       }
186       
187       double r1 = arg->getDoubleValue("radial"),
188         r2 = arg->getDoubleValue("radial[1]");
189       
190       SGGeod intersection;
191       bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
192       if (!ok) {
193         SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident() 
194                 << "," << p2->ident());
195         return false;
196       }
197       
198       std::string name = p->ident() + "-" + p2->ident();
199       wp = new BasicWaypt(intersection, name, NULL);
200     } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
201       // offset radial from navaid
202       double radial = arg->getDoubleValue("radial");
203       double distanceNm = arg->getDoubleValue("offset-nm");
204       //radial += magvar->getDoubleValue(); // convert to true bearing
205       wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
206     } else {
207       wp = new NavaidWaypoint(p, NULL);
208     }
209   } else if (arg->hasChild("airport")) {
210     const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
211     if (!apt) {
212       SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
213       return false;
214     }
215     
216     if (arg->hasChild("runway")) {
217       if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
218         SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
219         return false;
220       }
221       
222       FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
223       wp = new RunwayWaypt(runway, NULL);
224     } else {
225       wp = new NavaidWaypoint((FGAirport*) apt, NULL);
226     }
227   } else if (arg->hasChild("text")) {
228     wp = self->waypointFromString(arg->getStringValue("text"));
229   } else if (!(pos == SGGeod())) {
230     // just a raw lat/lon
231     wp = new BasicWaypt(pos, ident, NULL);
232   } else {
233     return false; // failed to build waypoint
234   }
235   
236   if (alt >= 0) {
237     wp->setAltitude(alt, flightgear::RESTRICT_AT);
238   }
239   
240   if (ias > 0) {
241     wp->setSpeed(ias, flightgear::RESTRICT_AT);
242   }
243
244   self->insertWayptAtIndex(wp, index);
245   return true;
246 }
247
248 static bool commandDeleteWaypt(const SGPropertyNode* arg)
249 {
250   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
251   int index = arg->getIntValue("index");
252   self->removeWayptAtIndex(index);
253   return true;
254 }
255
256 /////////////////////////////////////////////////////////////////////////////
257
258 FGRouteMgr::FGRouteMgr() :
259   _currentIndex(0),
260   input(fgGetNode( RM "input", true )),
261   mirror(fgGetNode( RM "route", true ))
262 {
263   listener = new InputListener(this);
264   input->setStringValue("");
265   input->addChangeListener(listener);
266   
267   SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
268   SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
269   SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
270   SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
271   SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
272   SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
273   SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
274 }
275
276
277 FGRouteMgr::~FGRouteMgr()
278 {
279   input->removeChangeListener(listener);
280   delete listener;
281 }
282
283
284 void FGRouteMgr::init() {
285   SGPropertyNode_ptr rm(fgGetNode(RM));
286   
287   lon = fgGetNode( "/position/longitude-deg", true );
288   lat = fgGetNode( "/position/latitude-deg", true );
289   alt = fgGetNode( "/position/altitude-ft", true );
290   magvar = fgGetNode("/environment/magnetic-variation-deg", true);
291      
292   departure = fgGetNode(RM "departure", true);
293   departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
294     &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
295   departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
296     &FGRouteMgr::getDepartureName, NULL));
297   departure->setStringValue("runway", "");
298   
299   _departureWatcher = createWatcher(this, &FGRouteMgr::departureChanged);
300   _departureWatcher->watch(departure->getChild("runway"));
301   
302   departure->getChild("etd", 0, true);
303   _departureWatcher->watch(departure->getChild("sid", 0, true));
304   departure->getChild("takeoff-time", 0, true);
305
306   destination = fgGetNode(RM "destination", true);
307   destination->getChild("airport", 0, true);
308   
309   destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
310     &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
311   destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
312     &FGRouteMgr::getDestinationName, NULL));
313   
314   _arrivalWatcher = createWatcher(this, &FGRouteMgr::arrivalChanged);
315   _arrivalWatcher->watch(destination->getChild("runway", 0, true));
316   
317   destination->getChild("eta", 0, true);
318   _arrivalWatcher->watch(destination->getChild("star", 0, true));
319   _arrivalWatcher->watch(destination->getChild("transition", 0, true));
320   destination->getChild("touchdown-time", 0, true);
321
322   alternate = fgGetNode(RM "alternate", true);
323   alternate->getChild("airport", 0, true);
324   alternate->getChild("runway", 0, true);
325   
326   cruise = fgGetNode(RM "cruise", true);
327   cruise->getChild("altitude-ft", 0, true);
328   cruise->setDoubleValue("altitude-ft", 10000.0);
329   cruise->getChild("flight-level", 0, true);
330   cruise->getChild("speed-kts", 0, true);
331   cruise->setDoubleValue("speed-kts", 160.0);
332   
333   _routingType = cruise->getChild("routing", 0, true);
334   _routingType->setIntValue(ROUTE_HIGH_AIRWAYS);
335   
336   totalDistance = fgGetNode(RM "total-distance", true);
337   totalDistance->setDoubleValue(0.0);
338   
339   ete = fgGetNode(RM "ete", true);
340   ete->setDoubleValue(0.0);
341   
342   elapsedFlightTime = fgGetNode(RM "flight-time", true);
343   elapsedFlightTime->setDoubleValue(0.0);
344   
345   active = fgGetNode(RM "active", true);
346   active->setBoolValue(false);
347   
348   airborne = fgGetNode(RM "airborne", true);
349   airborne->setBoolValue(false);
350     
351   _edited = fgGetNode(RM "signals/edited", true);
352   _finished = fgGetNode(RM "signals/finished", true);
353   
354   _currentWpt = fgGetNode(RM "current-wp", true);
355   _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
356     (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
357       
358   // temporary distance / eta calculations, for backward-compatability
359   wp0 = fgGetNode(RM "wp", 0, true);
360   wp0->getChild("id", 0, true);
361   wp0->getChild("dist", 0, true);
362   wp0->getChild("eta", 0, true);
363   wp0->getChild("bearing-deg", 0, true);
364   
365   wp1 = fgGetNode(RM "wp", 1, true);
366   wp1->getChild("id", 0, true);
367   wp1->getChild("dist", 0, true);
368   wp1->getChild("eta", 0, true);
369   
370   wpn = fgGetNode(RM "wp-last", 0, true);
371   wpn->getChild("dist", 0, true);
372   wpn->getChild("eta", 0, true);
373   
374   update_mirror();
375   _pathNode = fgGetNode(RM "file-path", 0, true);
376 }
377
378
379 void FGRouteMgr::postinit()
380 {
381   SGPath path(_pathNode->getStringValue());
382   if (!path.isNull()) {
383     SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
384     loadRoute(path);
385   }
386   
387 // this code only matters for the --wp option now - perhaps the option
388 // should be deprecated in favour of an explicit flight-plan file?
389 // then the global initial waypoint list could die.
390   string_list *waypoints = globals->get_initial_waypoints();
391   if (waypoints) {
392     string_list::iterator it;
393     for (it = waypoints->begin(); it != waypoints->end(); ++it) {
394       WayptRef w = waypointFromString(*it);
395       if (w) {
396         _route.push_back(w);
397       }
398     }
399     
400     SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << _route.size());
401   }
402
403   weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
404   // check airbone flag agrees with presets
405 }
406
407 void FGRouteMgr::bind() { }
408 void FGRouteMgr::unbind() { }
409
410 bool FGRouteMgr::isRouteActive() const
411 {
412   return active->getBoolValue();
413 }
414
415 void FGRouteMgr::update( double dt )
416 {
417   if (dt <= 0.0) {
418     return; // paused, nothing to do here
419   }
420   
421   double groundSpeed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
422   if (airborne->getBoolValue()) {
423     time_t now = time(NULL);
424     elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
425   } else { // not airborne
426     if (weightOnWheels->getBoolValue() || (groundSpeed < 40)) {
427       return;
428     }
429     
430     airborne->setBoolValue(true);
431     _takeoffTime = time(NULL); // start the clock
432     departure->setIntValue("takeoff-time", _takeoffTime);
433   }
434   
435   if (!active->getBoolValue()) {
436     return;
437   }
438
439 // basic course/distance information
440   SGGeod currentPos = SGGeod::fromDegFt(lon->getDoubleValue(), 
441     lat->getDoubleValue(),alt->getDoubleValue());
442
443   Waypt* curWpt = currentWaypt();
444   if (!curWpt) {
445     return;
446   }
447   
448   double courseDeg;
449   double distanceM;
450   boost::tie(courseDeg, distanceM) = curWpt->courseAndDistanceFrom(currentPos);
451   
452 // update wp0 / wp1 / wp-last for legacy users
453   wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
454   courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
455   wp0->setDoubleValue("bearing-deg", courseDeg);
456   setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
457   
458   double totalDistanceRemaining = distanceM; // distance to current waypoint
459   
460   Waypt* nextWpt = nextWaypt();
461   if (nextWpt) {
462     boost::tie(courseDeg, distanceM) = nextWpt->courseAndDistanceFrom(currentPos);
463      
464     wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
465     courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
466     wp1->setDoubleValue("bearing-deg", courseDeg);
467     setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
468   }
469   
470   Waypt* prev = curWpt;
471   for (unsigned int i=_currentIndex + 1; i<_route.size(); ++i) {
472     Waypt* w = _route[i];
473     if (w->flag(WPT_DYNAMIC)) continue;
474     totalDistanceRemaining += SGGeodesy::distanceM(prev->position(), w->position());
475     prev = w;
476     
477     
478   }
479   
480   wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
481   ete->setDoubleValue(totalDistanceRemaining * SG_METER_TO_NM / groundSpeed * 3600.0);
482   setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
483 }
484
485 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
486 {
487   double speed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
488   if (speed < 1.0) {
489     aProp->setStringValue("--:--");
490     return;
491   }
492
493   char eta_str[64];
494   double eta = aDistance * SG_METER_TO_NM / speed;
495   if ( eta >= 100.0 ) { 
496       eta = 99.999; // clamp
497   }
498   
499   if ( eta < (1.0/6.0) ) {
500     eta *= 60.0; // within 10 minutes, bump up to min/secs
501   }
502   
503   int major = (int)eta, 
504       minor = (int)((eta - (int)eta) * 60.0);
505   snprintf( eta_str, 64, "%d:%02d", major, minor );
506   aProp->setStringValue( eta_str );
507 }
508
509 flightgear::WayptRef FGRouteMgr::removeWayptAtIndex(int aIndex)
510 {
511   int index = aIndex;
512   if (aIndex < 0) { // negative indices count the the end
513     index = _route.size() + index;
514   }
515   
516   if ((index < 0) || (index >= numWaypts())) {
517     SG_LOG(SG_AUTOPILOT, SG_WARN, "removeWayptAtIndex with invalid index:" << aIndex);
518     return NULL;
519   }
520   WayptVec::iterator it = _route.begin();
521   it += index;
522   
523   WayptRef w = *it; // hold a ref now, in case _route is the only other owner
524   _route.erase(it);
525   
526   update_mirror();
527   
528   if (_currentIndex == index) {
529     currentWaypointChanged(); // current waypoint was removed
530   }
531   else
532   if (_currentIndex > index) {
533     --_currentIndex; // shift current index down if necessary
534   }
535
536   _edited->fireValueChanged();
537   checkFinished();
538   
539   return w;
540 }
541   
542 struct NotGeneratedWayptPredicate : public std::unary_function<const Waypt*, bool>
543 {
544   bool operator() (const Waypt* w) const
545   {
546     return (w->flag(WPT_GENERATED) == false);
547   }
548 };
549
550
551 void FGRouteMgr::clearRoute()
552 {
553 // erase all non-generated waypoints
554   WayptVec::iterator r =  
555     std::remove_if(_route.begin(), _route.end(), NotGeneratedWayptPredicate());
556   _route.erase(r, _route.end());
557   
558   _currentIndex = -1;
559   
560   update_mirror();
561   active->setBoolValue(false);
562   _edited->fireValueChanged();
563 }
564
565 /**
566  * route between index-1 and index, using airways.
567  */
568 bool FGRouteMgr::routeToIndex(int index, RouteType aRouteType)
569 {
570   WayptRef wp1;
571   WayptRef wp2;
572   
573   if (index == -1) {
574     index = _route.size(); // can still be zero, of course
575   }
576   
577   if (index == 0) {
578     if (!_departure) {
579       SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no departure set");
580       return false;
581     }
582     
583     wp1 = new NavaidWaypoint(_departure.get(), NULL);
584   } else {
585     wp1 = wayptAtIndex(index - 1);
586   }
587   
588   if (index >= numWaypts()) {
589     if (!_destination) {
590       SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no destination set");
591       return false;
592     }
593     
594     wp2 = new NavaidWaypoint(_destination.get(), NULL);
595   } else {
596     wp2 = wayptAtIndex(index);
597   }
598   
599   double distNm = SGGeodesy::distanceNm(wp1->position(), wp2->position());
600   if (distNm < 100.0) {
601     SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: existing waypoints are nearby, direct route");
602     return true;
603   }
604   
605   WayptVec r;
606   switch (aRouteType) {
607   case ROUTE_HIGH_AIRWAYS:
608     Airway::highLevel()->route(wp1, wp2, r);
609     break;
610     
611   case ROUTE_LOW_AIRWAYS:
612     Airway::lowLevel()->route(wp1, wp2, r);
613     break;
614     
615   case ROUTE_VOR:
616     throw sg_exception("VOR routing not supported yet");
617   }
618   
619   if (r.empty()) {
620     SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: no route found");
621     return false;
622   }
623
624   WayptVec::iterator it = _route.begin();
625   it += index;
626   _route.insert(it, r.begin(), r.end());
627
628   update_mirror();
629   _edited->fireValueChanged();
630   return true;
631 }
632
633 void FGRouteMgr::autoRoute()
634 {
635   if (!_departure || !_destination) {
636     return;
637   }
638   
639   string runwayId(departure->getStringValue("runway"));
640   FGRunway* runway = NULL;
641   if (_departure->hasRunwayWithIdent(runwayId)) {
642     runway = _departure->getRunwayByIdent(runwayId);
643   }
644   
645   FGRunway* dstRunway = NULL;
646   runwayId = destination->getStringValue("runway");
647   if (_destination->hasRunwayWithIdent(runwayId)) {
648     dstRunway = _destination->getRunwayByIdent(runwayId);
649   }
650     
651   _route.clear(); // clear out the existing, first
652 // SID
653   flightgear::SID* sid;
654   WayptRef sidTrans;
655   
656   boost::tie(sid, sidTrans) = _departure->selectSID(_destination->geod(), runway);
657   if (sid) { 
658     SG_LOG(SG_AUTOPILOT, SG_INFO, "selected SID " << sid->ident());
659     if (sidTrans) {
660       SG_LOG(SG_AUTOPILOT, SG_INFO, "\tvia " << sidTrans->ident() << " transition");
661     }
662     
663     sid->route(runway, sidTrans, _route);
664     departure->setStringValue("sid", sid->ident());
665   } else {
666     // use airport location for airway search
667     sidTrans = new NavaidWaypoint(_departure.get(), NULL);
668     departure->setStringValue("sid", "");
669   }
670   
671 // STAR
672   destination->setStringValue("transition", "");
673   destination->setStringValue("star", "");
674   
675   STAR* star;
676   WayptRef starTrans;
677   boost::tie(star, starTrans) = _destination->selectSTAR(_departure->geod(), dstRunway);
678   if (star) {
679     SG_LOG(SG_AUTOPILOT, SG_INFO, "selected STAR " << star->ident());
680     if (starTrans) {
681       SG_LOG(SG_AUTOPILOT, SG_INFO, "\tvia " << starTrans->ident() << " transition");
682       destination->setStringValue("transition", starTrans->ident());
683     }    
684     destination->setStringValue("star", star->ident());
685   } else {
686     // use airport location for search
687     starTrans = new NavaidWaypoint(_destination.get(), NULL);
688   }
689   
690 // route between them
691   WayptVec airwayRoute;
692   if (Airway::highLevel()->route(sidTrans, starTrans, airwayRoute)) {
693     _route.insert(_route.end(), airwayRoute.begin(), airwayRoute.end());
694   }
695   
696 // add the STAR if we have one
697   if (star) {
698     _destination->buildApproach(starTrans, star, dstRunway, _route);
699   }
700
701   update_mirror();
702   _edited->fireValueChanged();
703 }
704
705 void FGRouteMgr::departureChanged()
706 {
707 // remove existing departure waypoints
708   WayptVec::iterator it = _route.begin();
709   for (; it != _route.end(); ++it) {
710     if (!(*it)->flag(WPT_DEPARTURE)) {
711       break;
712     }
713   }
714   
715   // erase() invalidates iterators, so grab now
716   WayptRef enroute;
717   if (it == _route.end()) {
718     if (_destination) {
719       enroute = new NavaidWaypoint(_destination.get(), NULL);
720     }
721   } else {
722     enroute = *it;
723   }
724
725   _route.erase(_route.begin(), it);
726   if (!_departure) {
727     waypointsChanged();
728     return;
729   }
730   
731   WayptVec wps;
732   buildDeparture(enroute, wps);
733   for (it = wps.begin(); it != wps.end(); ++it) {
734     (*it)->setFlag(WPT_DEPARTURE);
735     (*it)->setFlag(WPT_GENERATED);
736   }
737   _route.insert(_route.begin(), wps.begin(), wps.end());
738   
739   update_mirror();
740   waypointsChanged();
741 }
742
743 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
744 {
745   string runwayId(departure->getStringValue("runway"));
746   if (!_departure->hasRunwayWithIdent(runwayId)) {
747 // valid airport, but no runway selected, so just the airport noide itself
748     wps.push_back(new NavaidWaypoint(_departure.get(), NULL));
749     return;
750   }
751   
752   FGRunway* r = _departure->getRunwayByIdent(runwayId);
753   string sidId = departure->getStringValue("sid");
754   flightgear::SID* sid = _departure->findSIDWithIdent(sidId);
755   if (!sid) {
756 // valid runway, but no SID selected/found, so just the runway node for now
757     if (!sidId.empty() && (sidId != "(none)")) {
758       SG_LOG(SG_AUTOPILOT, SG_INFO, "SID not found:" << sidId);
759     }
760     
761     wps.push_back(new RunwayWaypt(r, NULL));
762     return;
763   }
764   
765 // we have a valid SID, awesome
766   string trans(departure->getStringValue("transition"));
767   WayptRef t = sid->findTransitionByName(trans);
768   if (!t && enroute) {
769     t = sid->findBestTransition(enroute->position());
770   }
771
772   sid->route(r, t, wps);
773   if (!wps.empty() && wps.front()->flag(WPT_DYNAMIC)) {
774     // ensure first waypoint is static, to simplify other computations
775     wps.insert(wps.begin(), new RunwayWaypt(r, NULL));
776   }
777 }
778
779 void FGRouteMgr::arrivalChanged()
780 {  
781   // remove existing arrival waypoints
782   WayptVec::reverse_iterator rit = _route.rbegin();
783   for (; rit != _route.rend(); ++rit) {
784     if (!(*rit)->flag(WPT_ARRIVAL)) {
785       break;
786     }
787   }
788   
789   // erase() invalidates iterators, so grab now
790   WayptRef enroute;
791   WayptVec::iterator it;
792   
793   if (rit != _route.rend()) {
794     enroute = *rit;
795     it = rit.base(); // convert to fwd iterator
796   } else {
797     it = _route.begin();
798   }
799
800   _route.erase(it, _route.end());
801   
802   WayptVec wps;
803   buildArrival(enroute, wps);
804   for (it = wps.begin(); it != wps.end(); ++it) {
805     (*it)->setFlag(WPT_ARRIVAL);
806     (*it)->setFlag(WPT_GENERATED);
807   }
808   _route.insert(_route.end(), wps.begin(), wps.end());
809   
810   update_mirror();
811   waypointsChanged();
812 }
813
814 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
815 {
816   if (!_destination) {
817     return;
818   }
819   
820   string runwayId(destination->getStringValue("runway"));
821   if (!_destination->hasRunwayWithIdent(runwayId)) {
822 // valid airport, but no runway selected, so just the airport node itself
823     wps.push_back(new NavaidWaypoint(_destination.get(), NULL));
824     return;
825   }
826   
827   FGRunway* r = _destination->getRunwayByIdent(runwayId);
828   string starId = destination->getStringValue("star");
829   STAR* star = _destination->findSTARWithIdent(starId);
830   if (!star) {
831 // valid runway, but no STAR selected/found, so just the runway node for now
832     wps.push_back(new RunwayWaypt(r, NULL));
833     return;
834   }
835   
836 // we have a valid STAR
837   string trans(destination->getStringValue("transition"));
838   WayptRef t = star->findTransitionByName(trans);
839   if (!t && enroute) {
840     t = star->findBestTransition(enroute->position());
841   }
842   
843   _destination->buildApproach(t, star, r, wps);
844 }
845
846 void FGRouteMgr::waypointsChanged()
847 {
848
849 }
850
851 void FGRouteMgr::insertWayptAtIndex(Waypt* aWpt, int aIndex)
852 {
853   if (!aWpt) {
854     return;
855   }
856   
857   int index = aIndex;
858   if ((aIndex == -1) || (aIndex > (int) _route.size())) {
859     index = _route.size();
860   }
861   
862   WayptVec::iterator it = _route.begin();
863   it += index;
864       
865   if (_currentIndex >= index) {
866     ++_currentIndex;
867   }
868   
869   _route.insert(it, aWpt);
870   
871   update_mirror();
872   _edited->fireValueChanged();
873 }
874
875 WayptRef FGRouteMgr::waypointFromString(const string& tgt )
876 {
877   string target(boost::to_upper_copy(tgt));
878   WayptRef wpt;
879   
880 // extract altitude
881   double altFt = cruise->getDoubleValue("altitude-ft");
882   RouteRestriction altSetting = RESTRICT_NONE;
883     
884   size_t pos = target.find( '@' );
885   if ( pos != string::npos ) {
886     altFt = atof( target.c_str() + pos + 1 );
887     target = target.substr( 0, pos );
888     if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
889       altFt *= SG_METER_TO_FEET;
890     altSetting = RESTRICT_AT;
891   }
892
893 // check for lon,lat
894   pos = target.find( ',' );
895   if ( pos != string::npos ) {
896     double lon = atof( target.substr(0, pos).c_str());
897     double lat = atof( target.c_str() + pos + 1);
898     char buf[32];
899     char ew = (lon < 0.0) ? 'W' : 'E';
900     char ns = (lat < 0.0) ? 'S' : 'N';
901     snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
902     
903     wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
904     if (altSetting != RESTRICT_NONE) {
905       wpt->setAltitude(altFt, altSetting);
906     }
907     return wpt;
908   }
909
910   SGGeod basePosition;
911   if (_route.empty()) {
912     // route is empty, use current position
913     basePosition = SGGeod::fromDeg(lon->getDoubleValue(), lat->getDoubleValue());
914   } else {
915     basePosition = _route.back()->position();
916   }
917     
918   string_list pieces(simgear::strutils::split(target, "/"));
919   FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
920   if (!p) {
921     SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
922     return NULL;
923   }
924
925   if (pieces.size() == 1) {
926     wpt = new NavaidWaypoint(p, NULL);
927   } else if (pieces.size() == 3) {
928     // navaid/radial/distance-nm notation
929     double radial = atof(pieces[1].c_str()),
930       distanceNm = atof(pieces[2].c_str());
931     radial += magvar->getDoubleValue(); // convert to true bearing
932     wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
933   } else if (pieces.size() == 2) {
934     FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
935     if (!apt) {
936       SG_LOG(SG_AUTOPILOT, SG_INFO, "Waypoint is not an airport:" << pieces.front());
937       return NULL;
938     }
939     
940     if (!apt->hasRunwayWithIdent(pieces[1])) {
941       SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
942       return NULL;
943     }
944       
945     FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
946     wpt = new NavaidWaypoint(runway, NULL);
947   } else if (pieces.size() == 4) {
948     // navid/radial/navid/radial notation     
949     FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
950     if (!p2) {
951       SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
952       return NULL;
953     }
954
955     double r1 = atof(pieces[1].c_str()),
956       r2 = atof(pieces[3].c_str());
957     r1 += magvar->getDoubleValue();
958     r2 += magvar->getDoubleValue();
959     
960     SGGeod intersection;
961     bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
962     if (!ok) {
963       SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << target);
964       return NULL;
965     }
966     
967     std::string name = p->ident() + "-" + p2->ident();
968     wpt = new BasicWaypt(intersection, name, NULL);
969   }
970   
971   if (!wpt) {
972     SG_LOG(SG_AUTOPILOT, SG_INFO, "Unable to parse waypoint:" << target);
973     return NULL;
974   }
975   
976   if (altSetting != RESTRICT_NONE) {
977     wpt->setAltitude(altFt, altSetting);
978   }
979   return wpt;
980 }
981
982 // mirror internal route to the property system for inspection by other subsystems
983 void FGRouteMgr::update_mirror()
984 {
985   mirror->removeChildren("wp");
986   
987   int num = numWaypts();
988   for (int i = 0; i < num; i++) {
989     Waypt* wp = _route[i];
990     SGPropertyNode *prop = mirror->getChild("wp", i, 1);
991
992     const SGGeod& pos(wp->position());
993     prop->setStringValue("id", wp->ident().c_str());
994     prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
995     prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
996    
997     // leg course+distance
998     if (i < (num - 1)) {
999       Waypt* next = _route[i+1];
1000       std::pair<double, double> crsDist =
1001         next->courseAndDistanceFrom(pos);
1002       prop->setDoubleValue("leg-bearing-true-deg", crsDist.first);
1003       prop->setDoubleValue("leg-distance-nm", crsDist.second * SG_METER_TO_NM);
1004     }
1005     
1006     if (wp->altitudeRestriction() != RESTRICT_NONE) {
1007       double ft = wp->altitudeFt();
1008       prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
1009       prop->setDoubleValue("altitude-ft", ft);
1010       prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
1011     } else {
1012       prop->setDoubleValue("altitude-m", -9999.9);
1013       prop->setDoubleValue("altitude-ft", -9999.9);
1014     }
1015     
1016     if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
1017       prop->setDoubleValue("speed-mach", wp->speedMach());
1018     } else if (wp->speedRestriction() != RESTRICT_NONE) {
1019       prop->setDoubleValue("speed-kts", wp->speedKts());
1020     }
1021     
1022     if (wp->flag(WPT_ARRIVAL)) {
1023       prop->setBoolValue("arrival", true);
1024     }
1025     
1026     if (wp->flag(WPT_DEPARTURE)) {
1027       prop->setBoolValue("departure", true);
1028     }
1029     
1030     if (wp->flag(WPT_MISS)) {
1031       prop->setBoolValue("missed-approach", true);
1032     }
1033     
1034     prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
1035   } // of waypoint iteration
1036   
1037   // set number as listener attachment point
1038   mirror->setIntValue("num", _route.size());
1039     
1040   NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1041   FGDialog* rmDlg = gui->getDialog("route-manager");
1042   if (rmDlg) {
1043     rmDlg->updateValues();
1044   }
1045 }
1046
1047 // command interface /autopilot/route-manager/input:
1048 //
1049 //   @CLEAR             ... clear route
1050 //   @POP               ... remove first entry
1051 //   @DELETE3           ... delete 4th entry
1052 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
1053 //   KSFO@900           ... append "KSFO@900"
1054 //
1055 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
1056 {
1057     const char *s = prop->getStringValue();
1058     if (strlen(s) == 0) {
1059       return;
1060     }
1061     
1062     if (!strcmp(s, "@CLEAR"))
1063         mgr->clearRoute();
1064     else if (!strcmp(s, "@ACTIVATE"))
1065         mgr->activate();
1066     else if (!strcmp(s, "@LOAD")) {
1067       SGPath path(mgr->_pathNode->getStringValue());
1068       mgr->loadRoute(path);
1069     } else if (!strcmp(s, "@SAVE")) {
1070       SGPath path(mgr->_pathNode->getStringValue());
1071       mgr->saveRoute(path);
1072     } else if (!strcmp(s, "@NEXT")) {
1073       mgr->jumpToIndex(mgr->_currentIndex + 1);
1074     } else if (!strcmp(s, "@PREVIOUS")) {
1075       mgr->jumpToIndex(mgr->_currentIndex - 1);
1076     } else if (!strncmp(s, "@JUMP", 5)) {
1077       mgr->jumpToIndex(atoi(s + 5));
1078     } else if (!strncmp(s, "@DELETE", 7))
1079         mgr->removeWayptAtIndex(atoi(s + 7));
1080     else if (!strncmp(s, "@INSERT", 7)) {
1081         char *r;
1082         int pos = strtol(s + 7, &r, 10);
1083         if (*r++ != ':')
1084             return;
1085         while (isspace(*r))
1086             r++;
1087         if (*r)
1088             mgr->insertWayptAtIndex(mgr->waypointFromString(r), pos);
1089     } else if (!strncmp(s, "@ROUTE", 6)) {
1090       char* r;
1091       int endIndex = strtol(s + 6, &r, 10);
1092       RouteType rt = (RouteType) mgr->_routingType->getIntValue();
1093       mgr->routeToIndex(endIndex, rt);
1094     } else if (!strcmp(s, "@AUTOROUTE")) {
1095       mgr->autoRoute();
1096     } else if (!strcmp(s, "@POSINIT")) {
1097       mgr->initAtPosition();
1098     } else
1099       mgr->insertWayptAtIndex(mgr->waypointFromString(s), -1);
1100 }
1101
1102 void FGRouteMgr::initAtPosition()
1103 {
1104   if (isRouteActive()) {
1105     return; // don't mess with the active route
1106   }
1107   
1108   if (haveUserWaypoints()) {
1109     // user has already defined, loaded or entered a route, again
1110     // don't interfere with it
1111     return; 
1112   }
1113   
1114   if (airborne->getBoolValue()) {
1115     SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
1116     _departure = NULL;
1117     departure->setStringValue("runway", "");
1118     return;
1119   }
1120   
1121 // on the ground
1122   SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(), 
1123     lat->getDoubleValue(), alt->getDoubleValue());
1124   if (!_departure) {
1125     _departure = FGAirport::findClosest(pos, 20.0);
1126     if (!_departure) {
1127       SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
1128       departure->setStringValue("runway", "");
1129       return;
1130     }
1131   }
1132   
1133   std::string rwy = departure->getStringValue("runway");
1134   if (!rwy.empty()) {
1135     // runway already set, fine
1136     return;
1137   }
1138   
1139   FGRunway* r = _departure->findBestRunwayForPos(pos);
1140   if (!r) {
1141     return;
1142   }
1143   
1144   departure->setStringValue("runway", r->ident().c_str());
1145   SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at " 
1146     << _departure->ident() << " on runway " << r->ident());
1147 }
1148
1149 bool FGRouteMgr::haveUserWaypoints() const
1150 {
1151   return std::find_if(_route.begin(), _route.end(), NotGeneratedWayptPredicate()) != _route.end();
1152 }
1153
1154 bool FGRouteMgr::activate()
1155 {
1156   if (isRouteActive()) {
1157     SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
1158     return false;
1159   }
1160  
1161   _currentIndex = 0;
1162   currentWaypointChanged();
1163   
1164  /* double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
1165   totalDistance->setDoubleValue(routeDistanceNm);
1166   double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
1167   if (cruiseSpeedKts > 1.0) {
1168     // very very crude approximation, doesn't allow for climb / descent
1169     // performance or anything else at all
1170     ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
1171   }
1172   */
1173   active->setBoolValue(true);
1174   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
1175   return true;
1176 }
1177
1178
1179 void FGRouteMgr::sequence()
1180 {
1181   if (!active->getBoolValue()) {
1182     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
1183     return;
1184   }
1185   
1186   if (checkFinished()) {
1187     return;
1188   }
1189   
1190   _currentIndex++;
1191   currentWaypointChanged();
1192 }
1193
1194 bool FGRouteMgr::checkFinished()
1195 {
1196   if (_currentIndex < (int) _route.size()) {
1197     return false;
1198   }
1199   
1200   SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
1201   _finished->fireValueChanged();
1202   active->setBoolValue(false);
1203   return true;
1204 }
1205
1206 void FGRouteMgr::jumpToIndex(int index)
1207 {
1208   if ((index < 0) || (index >= (int) _route.size())) {
1209     SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" << 
1210       index << ") to FGRouteMgr::jumpToIndex");
1211     return;
1212   }
1213
1214   if (_currentIndex == index) {
1215     return; // no-op
1216   }
1217   
1218 // all the checks out the way, go ahead and update state
1219   _currentIndex = index;
1220   currentWaypointChanged();
1221   _currentWpt->fireValueChanged();
1222 }
1223
1224 void FGRouteMgr::currentWaypointChanged()
1225 {
1226   Waypt* cur = currentWaypt();
1227   Waypt* next = nextWaypt();
1228
1229   wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
1230   wp1->getChild("id")->setStringValue(next ? next->ident() : "");
1231   
1232   _currentWpt->fireValueChanged();
1233   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _currentIndex);
1234 }
1235
1236 int FGRouteMgr::findWayptIndex(const SGGeod& aPos) const
1237 {  
1238   for (int i=0; i<numWaypts(); ++i) {
1239     if (_route[i]->matches(aPos)) {
1240       return i;
1241     }
1242   }
1243   
1244   return -1;
1245 }
1246
1247 Waypt* FGRouteMgr::currentWaypt() const
1248 {
1249   if ((_currentIndex < 0) || (_currentIndex >= numWaypts()))
1250       return NULL;
1251   return wayptAtIndex(_currentIndex);
1252 }
1253
1254 Waypt* FGRouteMgr::previousWaypt() const
1255 {
1256   if (_currentIndex == 0) {
1257     return NULL;
1258   }
1259   
1260   return wayptAtIndex(_currentIndex - 1);
1261 }
1262
1263 Waypt* FGRouteMgr::nextWaypt() const
1264 {
1265   if ((_currentIndex < 0) || ((_currentIndex + 1) >= numWaypts())) {
1266     return NULL;
1267   }
1268   
1269   return wayptAtIndex(_currentIndex + 1);
1270 }
1271
1272 Waypt* FGRouteMgr::wayptAtIndex(int index) const
1273 {
1274   if ((index < 0) || (index >= numWaypts())) {
1275     throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1276   }
1277   
1278   return _route[index];
1279 }
1280
1281 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1282 {
1283     if ((index < 0) || (index >= numWaypts())) {
1284         throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1285     }
1286     
1287     return mirror->getChild("wp", index);
1288 }
1289
1290 bool FGRouteMgr::saveRoute(const SGPath& path)
1291 {
1292   SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
1293   try {
1294     SGPropertyNode_ptr d(new SGPropertyNode);
1295     SGPath path(_pathNode->getStringValue());
1296     d->setIntValue("version", 2);
1297     
1298     if (_departure) {
1299       d->setStringValue("departure/airport", _departure->ident());
1300       d->setStringValue("departure/sid", departure->getStringValue("sid"));
1301       d->setStringValue("departure/runway", departure->getStringValue("runway"));
1302     }
1303     
1304     if (_destination) {
1305       d->setStringValue("destination/airport", _destination->ident());
1306       d->setStringValue("destination/star", destination->getStringValue("star"));
1307       d->setStringValue("destination/transition", destination->getStringValue("transition"));
1308       d->setStringValue("destination/runway", destination->getStringValue("runway"));
1309     }
1310     
1311   // route nodes
1312     SGPropertyNode* routeNode = d->getChild("route", 0, true);
1313     for (unsigned int i=0; i<_route.size(); ++i) {
1314       Waypt* wpt = _route[i];
1315       wpt->saveAsNode(routeNode->getChild("wp", i, true));
1316     } // of waypoint iteration
1317     writeProperties(path.str(), d, true /* write-all */);
1318     return true;
1319   } catch (sg_exception& e) {
1320     SG_LOG(SG_IO, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
1321     return false;
1322   }
1323 }
1324
1325 bool FGRouteMgr::loadRoute(const SGPath& path)
1326 {
1327   if (!path.exists())
1328   {
1329       SG_LOG(SG_IO, SG_ALERT, "Failed to load flight-plan '" << path.str()
1330               << "'. The file does not exist.");
1331       return false;
1332   }
1333     
1334   // deactivate route first
1335   active->setBoolValue(false);
1336   
1337   SGPropertyNode_ptr routeData(new SGPropertyNode);
1338   
1339   SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
1340     
1341   try {
1342     readProperties(path.str(), routeData);
1343   } catch (sg_exception& ) {
1344     // if XML parsing fails, the file might be simple textual list of waypoints
1345     return loadPlainTextRoute(path);
1346   }
1347   
1348   try {
1349     int version = routeData->getIntValue("version", 1);
1350     if (version == 1) {
1351       loadVersion1XMLRoute(routeData);
1352     } else if (version == 2) {
1353       loadVersion2XMLRoute(routeData);
1354     } else {
1355       throw sg_io_exception("unsupported XML route version");
1356     }
1357     return true;
1358   } catch (sg_exception& e) {
1359     SG_LOG(SG_IO, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
1360       << "'. " << e.getMessage());
1361     return false;
1362   }
1363 }
1364
1365 void FGRouteMgr::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
1366 {
1367   // departure nodes
1368   SGPropertyNode* dep = routeData->getChild("departure");
1369   if (dep) {
1370     string depIdent = dep->getStringValue("airport");
1371     _departure = (FGAirport*) fgFindAirportID(depIdent);
1372     departure->setStringValue("runway", dep->getStringValue("runway"));
1373     departure->setStringValue("sid", dep->getStringValue("sid"));
1374     departure->setStringValue("transition", dep->getStringValue("transition"));
1375   }
1376   
1377 // destination
1378   SGPropertyNode* dst = routeData->getChild("destination");
1379   if (dst) {
1380     _destination = (FGAirport*) fgFindAirportID(dst->getStringValue("airport"));
1381     destination->setStringValue("runway", dst->getStringValue("runway"));
1382     destination->setStringValue("star", dst->getStringValue("star"));
1383     destination->setStringValue("transition", dst->getStringValue("transition"));
1384   }
1385
1386 // alternate
1387   SGPropertyNode* alt = routeData->getChild("alternate");
1388   if (alt) {
1389     alternate->setStringValue(alt->getStringValue("airport"));
1390   } // of cruise data loading
1391   
1392 // cruise
1393   SGPropertyNode* crs = routeData->getChild("cruise");
1394   if (crs) {
1395     cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
1396     cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
1397     cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
1398   } // of cruise data loading
1399
1400 }
1401
1402 void FGRouteMgr::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
1403 {
1404   loadXMLRouteHeader(routeData);
1405   
1406 // route nodes
1407   WayptVec wpts;
1408   SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);    
1409   for (int i=0; i<routeNode->nChildren(); ++i) {
1410     SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
1411     WayptRef wpt = Waypt::createFromProperties(NULL, wpNode);
1412     wpts.push_back(wpt);
1413   } // of route iteration
1414   
1415   _route = wpts;
1416 }
1417
1418 void FGRouteMgr::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
1419 {
1420   loadXMLRouteHeader(routeData);
1421
1422 // route nodes
1423   WayptVec wpts;
1424   SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);    
1425   for (int i=0; i<routeNode->nChildren(); ++i) {
1426     SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
1427     WayptRef wpt = parseVersion1XMLWaypt(wpNode);
1428     wpts.push_back(wpt);
1429   } // of route iteration
1430   
1431   _route = wpts;
1432 }
1433
1434 WayptRef FGRouteMgr::parseVersion1XMLWaypt(SGPropertyNode* aWP)
1435 {
1436   SGGeod lastPos;
1437   if (!_route.empty()) {
1438     lastPos = _route.back()->position();
1439   } else if (_departure) {
1440     lastPos = _departure->geod();
1441   }
1442
1443   WayptRef w;
1444   string ident(aWP->getStringValue("ident"));
1445   if (aWP->hasChild("longitude-deg")) {
1446     // explicit longitude/latitude
1447     w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"), 
1448       aWP->getDoubleValue("latitude-deg")), ident, NULL);
1449     
1450   } else {
1451     string nid = aWP->getStringValue("navid", ident.c_str());
1452     FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
1453     if (!p) {
1454       throw sg_io_exception("bad route file, unknown navid:" + nid);
1455     }
1456       
1457     SGGeod pos(p->geod());
1458     if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
1459       double radialDeg = aWP->getDoubleValue("offset-radial");
1460       // convert magnetic radial to a true radial!
1461       radialDeg += magvar->getDoubleValue();
1462       double offsetNm = aWP->getDoubleValue("offset-nm");
1463       double az2;
1464       SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
1465     }
1466
1467     w = new BasicWaypt(pos, ident, NULL);
1468   }
1469   
1470   double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
1471   if (altFt > -9990.0) {
1472     w->setAltitude(altFt, RESTRICT_AT);
1473   }
1474
1475   return w;
1476 }
1477
1478 bool FGRouteMgr::loadPlainTextRoute(const SGPath& path)
1479 {
1480   try {
1481     sg_gzifstream in(path.str().c_str());
1482     if (!in.is_open()) {
1483         throw sg_io_exception("Cannot open file for reading.");
1484     }
1485   
1486     WayptVec wpts;
1487     while (!in.eof()) {
1488       string line;
1489       getline(in, line, '\n');
1490     // trim CR from end of line, if found
1491       if (line[line.size() - 1] == '\r') {
1492         line.erase(line.size() - 1, 1);
1493       }
1494       
1495       line = simgear::strutils::strip(line);
1496       if (line.empty() || (line[0] == '#')) {
1497         continue; // ignore empty/comment lines
1498       }
1499       
1500       WayptRef w = waypointFromString(line);
1501       if (!w) {
1502         throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
1503       }
1504       
1505       wpts.push_back(w);
1506     } // of line iteration
1507   
1508     _route = wpts;
1509     return true;
1510   } catch (sg_exception& e) {
1511     SG_LOG(SG_IO, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
1512     return false;
1513   }
1514 }
1515
1516 const char* FGRouteMgr::getDepartureICAO() const
1517 {
1518   if (!_departure) {
1519     return "";
1520   }
1521   
1522   return _departure->ident().c_str();
1523 }
1524
1525 const char* FGRouteMgr::getDepartureName() const
1526 {
1527   if (!_departure) {
1528     return "";
1529   }
1530   
1531   return _departure->name().c_str();
1532 }
1533
1534 void FGRouteMgr::setDepartureICAO(const char* aIdent)
1535 {
1536   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1537     _departure = NULL;
1538   } else {
1539     _departure = FGAirport::findByIdent(aIdent);
1540   }
1541   
1542   departureChanged();
1543 }
1544
1545 const char* FGRouteMgr::getDestinationICAO() const
1546 {
1547   if (!_destination) {
1548     return "";
1549   }
1550   
1551   return _destination->ident().c_str();
1552 }
1553
1554 const char* FGRouteMgr::getDestinationName() const
1555 {
1556   if (!_destination) {
1557     return "";
1558   }
1559   
1560   return _destination->name().c_str();
1561 }
1562
1563 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1564 {
1565   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1566     _destination = NULL;
1567   } else {
1568     _destination = FGAirport::findByIdent(aIdent);
1569   }
1570   
1571   arrivalChanged();
1572 }
1573
1574 FGAirportRef FGRouteMgr::departureAirport() const
1575 {
1576     return _departure;
1577 }
1578
1579 FGAirportRef FGRouteMgr::destinationAirport() const
1580 {
1581     return _destination;
1582 }
1583
1584 FGRunway* FGRouteMgr::departureRunway() const
1585 {
1586     if (!_departure) {
1587         return NULL;
1588     }
1589     
1590     string runwayId(departure->getStringValue("runway"));
1591     if (!_departure->hasRunwayWithIdent(runwayId)) {
1592         return NULL;
1593     }
1594     
1595     return _departure->getRunwayByIdent(runwayId);
1596 }
1597
1598 FGRunway* FGRouteMgr::destinationRunway() const
1599 {
1600     if (!_destination) {
1601         return NULL;
1602     }
1603     
1604     string runwayId(destination->getStringValue("runway"));
1605     if (!_destination->hasRunwayWithIdent(runwayId)) {
1606         return NULL;
1607     }
1608     
1609     return _destination->getRunwayByIdent(runwayId);
1610 }
1611