]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
Airways routing is driven via Nasal now.
[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/procedure.hxx>
55 #include "Airports/simple.hxx"
56 #include "Airports/runways.hxx"
57
58 #define RM "/autopilot/route-manager/"
59
60 #include <GUI/new_gui.hxx>
61 #include <GUI/dialog.hxx>
62
63 using namespace flightgear;
64
65 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
66 {
67   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
68   SGPath path(arg->getStringValue("path"));
69   return self->loadRoute(path);
70 }
71
72 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
73 {
74   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
75   SGPath path(arg->getStringValue("path"));
76   return self->saveRoute(path);
77 }
78
79 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
80 {
81   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
82   bool activate = arg->getBoolValue("activate", true);
83   if (activate) {
84     self->activate();
85   } else {
86     
87   }
88   
89   return true;
90 }
91
92 static bool commandClearFlightPlan(const SGPropertyNode*)
93 {
94   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
95   self->clearRoute();
96   return true;
97 }
98
99 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
100 {
101   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
102   int index = arg->getIntValue("index");
103   if ((index < 0) || (index >= self->numLegs())) {
104     return false;
105   }
106   
107   self->jumpToIndex(index);
108   return true;
109 }
110
111 static bool commandInsertWaypt(const SGPropertyNode* arg)
112 {
113   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
114   int index = arg->getIntValue("index");
115   std::string ident(arg->getStringValue("id"));
116   int alt = arg->getIntValue("altitude-ft", -999);
117   int ias = arg->getIntValue("speed-knots", -999);
118   
119   WayptRef wp;
120 // lat/lon may be supplied to narrow down navaid search, or to specify
121 // a raw waypoint
122   SGGeod pos;
123   if (arg->hasChild("longitude-deg")) {
124     pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
125                                arg->getDoubleValue("latitude-deg"));
126   }
127   
128   if (arg->hasChild("navaid")) {
129     FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
130     
131     if (arg->hasChild("navaid", 1)) {
132       // intersection of two radials
133       FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
134       if (!p2) {
135         SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
136         return false;
137       }
138       
139       double r1 = arg->getDoubleValue("radial"),
140         r2 = arg->getDoubleValue("radial[1]");
141       
142       SGGeod intersection;
143       bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
144       if (!ok) {
145         SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident() 
146                 << "," << p2->ident());
147         return false;
148       }
149       
150       std::string name = p->ident() + "-" + p2->ident();
151       wp = new BasicWaypt(intersection, name, NULL);
152     } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
153       // offset radial from navaid
154       double radial = arg->getDoubleValue("radial");
155       double distanceNm = arg->getDoubleValue("offset-nm");
156       //radial += magvar->getDoubleValue(); // convert to true bearing
157       wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
158     } else {
159       wp = new NavaidWaypoint(p, NULL);
160     }
161   } else if (arg->hasChild("airport")) {
162     const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
163     if (!apt) {
164       SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
165       return false;
166     }
167     
168     if (arg->hasChild("runway")) {
169       if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
170         SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
171         return false;
172       }
173       
174       FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
175       wp = new RunwayWaypt(runway, NULL);
176     } else {
177       wp = new NavaidWaypoint((FGAirport*) apt, NULL);
178     }
179   } else if (arg->hasChild("text")) {
180     wp = self->waypointFromString(arg->getStringValue("text"));
181   } else if (!(pos == SGGeod())) {
182     // just a raw lat/lon
183     wp = new BasicWaypt(pos, ident, NULL);
184   } else {
185     return false; // failed to build waypoint
186   }
187
188   FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
189   if (alt >= 0) {
190     leg->setAltitude(RESTRICT_AT, alt);
191   }
192   
193   if (ias > 0) {
194     leg->setSpeed(RESTRICT_AT, ias);
195   }
196   
197   return true;
198 }
199
200 static bool commandDeleteWaypt(const SGPropertyNode* arg)
201 {
202   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
203   int index = arg->getIntValue("index");
204   self->removeLegAtIndex(index);
205   return true;
206 }
207
208 /////////////////////////////////////////////////////////////////////////////
209
210 FGRouteMgr::FGRouteMgr() :
211   _plan(NULL),
212   input(fgGetNode( RM "input", true )),
213   mirror(fgGetNode( RM "route", true ))
214 {
215   listener = new InputListener(this);
216   input->setStringValue("");
217   input->addChangeListener(listener);
218   
219   SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
220   SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
221   SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
222   SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
223   SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
224   SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
225   SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
226 }
227
228
229 FGRouteMgr::~FGRouteMgr()
230 {
231   input->removeChangeListener(listener);
232   delete listener;
233 }
234
235
236 void FGRouteMgr::init() {
237   SGPropertyNode_ptr rm(fgGetNode(RM));
238   
239   magvar = fgGetNode("/environment/magnetic-variation-deg", true);
240      
241   departure = fgGetNode(RM "departure", true);
242   departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
243     &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
244   departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
245                                                                        &FGRouteMgr::getDepartureRunway, 
246                                                                       &FGRouteMgr::setDepartureRunway));
247   departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
248                                                                       &FGRouteMgr::getSID, 
249                                                                       &FGRouteMgr::setSID));
250   
251   departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
252     &FGRouteMgr::getDepartureName, NULL));
253   departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this, 
254                                                                                &FGRouteMgr::getDestinationFieldElevation, NULL));
255   departure->getChild("etd", 0, true);
256   departure->getChild("takeoff-time", 0, true);
257
258   destination = fgGetNode(RM "destination", true);
259   destination->getChild("airport", 0, true);
260   
261   destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
262     &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
263   destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
264                              &FGRouteMgr::getDestinationRunway, 
265                             &FGRouteMgr::setDestinationRunway));
266   destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
267                                                                         &FGRouteMgr::getSTAR, 
268                                                                         &FGRouteMgr::setSTAR));
269   destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
270                                                                         &FGRouteMgr::getApproach, 
271                                                                         &FGRouteMgr::setApproach));
272   
273   destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
274     &FGRouteMgr::getDestinationName, NULL));
275   destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this, 
276                                                                       &FGRouteMgr::getDestinationFieldElevation, NULL));
277   
278   destination->getChild("eta", 0, true);
279   destination->getChild("touchdown-time", 0, true);
280
281   alternate = fgGetNode(RM "alternate", true);
282   alternate->getChild("airport", 0, true);
283   alternate->getChild("runway", 0, true);
284   
285   cruise = fgGetNode(RM "cruise", true);
286   cruise->getChild("altitude-ft", 0, true);
287   cruise->setDoubleValue("altitude-ft", 10000.0);
288   cruise->getChild("flight-level", 0, true);
289   cruise->getChild("speed-kts", 0, true);
290   cruise->setDoubleValue("speed-kts", 160.0);
291   
292   totalDistance = fgGetNode(RM "total-distance", true);
293   totalDistance->setDoubleValue(0.0);
294   distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
295   distanceToGo->setDoubleValue(0.0);
296   
297   ete = fgGetNode(RM "ete", true);
298   ete->setDoubleValue(0.0);
299   
300   elapsedFlightTime = fgGetNode(RM "flight-time", true);
301   elapsedFlightTime->setDoubleValue(0.0);
302   
303   active = fgGetNode(RM "active", true);
304   active->setBoolValue(false);
305   
306   airborne = fgGetNode(RM "airborne", true);
307   airborne->setBoolValue(false);
308     
309   _edited = fgGetNode(RM "signals/edited", true);
310   _finished = fgGetNode(RM "signals/finished", true);
311   _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
312   
313   _currentWpt = fgGetNode(RM "current-wp", true);
314   _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
315     (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
316       
317   // temporary distance / eta calculations, for backward-compatability
318   wp0 = fgGetNode(RM "wp", 0, true);
319   wp0->getChild("id", 0, true);
320   wp0->getChild("dist", 0, true);
321   wp0->getChild("eta", 0, true);
322   wp0->getChild("bearing-deg", 0, true);
323   
324   wp1 = fgGetNode(RM "wp", 1, true);
325   wp1->getChild("id", 0, true);
326   wp1->getChild("dist", 0, true);
327   wp1->getChild("eta", 0, true);
328   
329   wpn = fgGetNode(RM "wp-last", 0, true);
330   wpn->getChild("dist", 0, true);
331   wpn->getChild("eta", 0, true);
332   
333   _pathNode = fgGetNode(RM "file-path", 0, true);
334   setFlightPlan(new FlightPlan());
335 }
336
337
338 void FGRouteMgr::postinit()
339 {
340   SGPath path(_pathNode->getStringValue());
341   if (!path.isNull()) {
342     SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
343     loadRoute(path);
344   }
345   
346 // this code only matters for the --wp option now - perhaps the option
347 // should be deprecated in favour of an explicit flight-plan file?
348 // then the global initial waypoint list could die.
349   string_list *waypoints = globals->get_initial_waypoints();
350   if (waypoints) {
351     string_list::iterator it;
352     for (it = waypoints->begin(); it != waypoints->end(); ++it) {
353       WayptRef w = waypointFromString(*it);
354       if (w) {
355         _plan->insertWayptAtIndex(w, -1);
356       }
357     }
358     
359     SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
360     update_mirror();
361   }
362
363   weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
364   groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
365   
366   // check airbone flag agrees with presets
367 }
368
369 void FGRouteMgr::bind() { }
370 void FGRouteMgr::unbind() { }
371
372 bool FGRouteMgr::isRouteActive() const
373 {
374   return active->getBoolValue();
375 }
376
377 bool FGRouteMgr::saveRoute(const SGPath& p)
378 {
379   if (!_plan) {
380     return false;
381   }
382   
383   return _plan->save(p);
384 }
385
386 bool FGRouteMgr::loadRoute(const SGPath& p)
387 {
388   FlightPlan* fp = new FlightPlan;
389   if (!fp->load(p)) {
390     delete fp;
391     return false;
392   }
393   
394   setFlightPlan(fp);
395   return true;
396 }
397
398 FlightPlan* FGRouteMgr::flightPlan() const
399 {
400   return _plan;
401 }
402
403 void FGRouteMgr::setFlightPlan(FlightPlan* plan)
404 {
405   if (plan == _plan) {
406     return;
407   }
408   
409   if (_plan) {
410     delete _plan;
411     active->setBoolValue(false);
412   }
413   
414   _plan = plan;
415   _plan->setDelegate(this);
416   
417   _flightplanChanged->fireValueChanged();
418   
419 // fire all the callbacks!
420   departureChanged();
421   arrivalChanged();
422   waypointsChanged();
423   currentWaypointChanged();
424 }
425
426 void FGRouteMgr::update( double dt )
427 {
428   if (dt <= 0.0) {
429     return; // paused, nothing to do here
430   }
431   
432   double gs = groundSpeed->getDoubleValue();
433   if (airborne->getBoolValue()) {
434     time_t now = time(NULL);
435     elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
436     
437     if (weightOnWheels->getBoolValue()) {
438       // touch down
439       destination->setIntValue("touchdown-time", time(NULL));
440       airborne->setBoolValue(false);
441     }
442   } else { // not airborne
443     if (weightOnWheels->getBoolValue() || (gs < 40)) {
444       // either taking-off or rolling-out after touchdown
445     } else {
446       airborne->setBoolValue(true);
447       _takeoffTime = time(NULL); // start the clock
448       departure->setIntValue("takeoff-time", _takeoffTime);
449     }
450   }
451   
452   if (!active->getBoolValue()) {
453     return;
454   }
455
456   if (checkFinished()) {
457     // maybe we're done
458   }
459   
460 // basic course/distance information
461   SGGeod currentPos = globals->get_aircraft_position();
462
463   FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
464   if (!leg) {
465     return;
466   }
467   
468   double courseDeg;
469   double distanceM;
470   boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
471   
472 // update wp0 / wp1 / wp-last
473   wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
474   wp0->setDoubleValue("true-bearing-deg", courseDeg);
475   courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
476   wp0->setDoubleValue("bearing-deg", courseDeg);
477   setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
478   
479   double totalPathDistanceNm = _plan->totalDistanceNm();
480   double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
481   
482 // total distance to go, is direct distance to wp0, plus the remaining
483 // path distance from wp0
484   totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
485   
486   wp0->setDoubleValue("distance-along-route-nm", 
487                       leg->distanceAlongRoute());
488   wp0->setDoubleValue("remaining-distance-nm", 
489                       totalPathDistanceNm - leg->distanceAlongRoute());
490   
491   FlightPlan::Leg* nextLeg = _plan->nextLeg();
492   if (nextLeg) {
493     boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
494      
495     wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
496     wp1->setDoubleValue("true-bearing-deg", courseDeg);
497     courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
498     wp1->setDoubleValue("bearing-deg", courseDeg);
499     setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);    
500     wp1->setDoubleValue("distance-along-route-nm", 
501                         nextLeg->distanceAlongRoute());
502     wp1->setDoubleValue("remaining-distance-nm", 
503                         totalPathDistanceNm - nextLeg->distanceAlongRoute());
504   }
505   
506   distanceToGo->setDoubleValue(totalDistanceRemaining);
507   wpn->setDoubleValue("dist", totalDistanceRemaining);
508   ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
509   setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
510 }
511
512 void FGRouteMgr::clearRoute()
513 {
514   if (_plan) {
515     _plan->clear();
516   }
517 }
518
519 Waypt* FGRouteMgr::currentWaypt() const
520 {
521   if (_plan && _plan->currentLeg()) {
522     return _plan->currentLeg()->waypoint();
523   }
524   
525   return NULL;
526 }
527
528 int FGRouteMgr::currentIndex() const
529 {
530   if (!_plan) {
531     return 0;
532   }
533   
534   return _plan->currentIndex();
535 }
536
537 Waypt* FGRouteMgr::wayptAtIndex(int index) const
538 {
539   if (_plan) {
540     FlightPlan::Leg* leg = _plan->legAtIndex(index);
541     if (leg) {
542       return leg->waypoint();
543     }
544   }
545   
546   return NULL;
547 }
548
549 int FGRouteMgr::numLegs() const
550 {
551   if (_plan) {
552     return _plan->numLegs();
553   }
554   
555   return 0;
556 }
557
558 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
559 {
560   double speed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
561   if (speed < 1.0) {
562     aProp->setStringValue("--:--");
563     return;
564   }
565
566   char eta_str[64];
567   double eta = aDistance * SG_METER_TO_NM / speed;
568   if ( eta >= 100.0 ) { 
569       eta = 99.999; // clamp
570   }
571   
572   if ( eta < (1.0/6.0) ) {
573     eta *= 60.0; // within 10 minutes, bump up to min/secs
574   }
575   
576   int major = (int)eta, 
577       minor = (int)((eta - (int)eta) * 60.0);
578   snprintf( eta_str, 64, "%d:%02d", major, minor );
579   aProp->setStringValue( eta_str );
580 }
581
582 void FGRouteMgr::removeLegAtIndex(int aIndex)
583 {
584   if (!_plan) {
585     return;
586   }
587   
588   _plan->deleteIndex(aIndex);
589 }
590   
591 void FGRouteMgr::departureChanged()
592 {
593   _plan->clearWayptsWithFlag(WPT_DEPARTURE);
594   WayptRef enroute;
595   WayptVec wps;
596   buildDeparture(enroute, wps);
597   _plan->insertWayptsAtIndex(wps, 0);
598 }
599
600 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
601 {
602   if (!_plan->departureAirport()) {
603     return;
604   }
605   
606   if (!_plan->departureRunway()) {
607 // valid airport, but no runway selected, so just the airport _plan itself
608     WayptRef w = new NavaidWaypoint(_plan->departureAirport(), _plan);
609     w->setFlag(WPT_DEPARTURE);
610     wps.push_back(w);
611     return;
612   }
613   
614   WayptRef rwyWaypt = new RunwayWaypt(_plan->departureRunway(), _plan);
615   rwyWaypt->setFlag(WPT_DEPARTURE);
616   wps.push_back(rwyWaypt);
617   
618   if (!_plan->sid()) {
619     return;
620   }
621   
622   _plan->sid()->route(_plan->departureRunway(), _plan->sidTransition(), wps);
623 }
624
625 void FGRouteMgr::arrivalChanged()
626 {  
627   _plan->clearWayptsWithFlag(WPT_ARRIVAL);
628   _plan->clearWayptsWithFlag(WPT_APPROACH);
629   WayptVec wps;
630   WayptRef enroute;
631   buildArrival(enroute, wps);
632   _plan->insertWayptsAtIndex(wps, -1);
633 }
634
635 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
636 {
637   FGAirportRef apt = _plan->destinationAirport();
638   if (!apt.valid()) {
639     return;
640   }
641   
642   if (!_plan->destinationRunway()) {
643     WayptRef w = new NavaidWaypoint(apt.ptr(), _plan);
644     w->setFlag(WPT_ARRIVAL);
645     wps.push_back(w);
646     return;
647   }
648   
649   if (_plan->star()) {
650     _plan->star()->route(_plan->destinationRunway(), _plan->starTransition(), wps);
651   }
652   
653   if (_plan->approach()) {
654     _plan->approach()->route(wps.back(), wps);
655   } else {
656     WayptRef w = new RunwayWaypt(_plan->destinationRunway(), _plan);
657     w->setFlag(WPT_APPROACH);
658     wps.push_back(w);
659   }
660 }
661
662 void FGRouteMgr::waypointsChanged()
663 {
664   update_mirror();
665    _edited->fireValueChanged();
666   checkFinished();
667 }
668
669 // mirror internal route to the property system for inspection by other subsystems
670 void FGRouteMgr::update_mirror()
671 {
672   mirror->removeChildren("wp");
673   NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
674   FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
675
676   if (!_plan) {
677     mirror->setIntValue("num", 0);
678     if (rmDlg) {
679       rmDlg->updateValues();
680     }
681     return;
682   }
683   
684   int num = _plan->numLegs();
685     
686   for (int i = 0; i < num; i++) {
687     FlightPlan::Leg* leg = _plan->legAtIndex(i);
688     WayptRef wp = leg->waypoint();
689     SGPropertyNode *prop = mirror->getChild("wp", i, 1);
690
691     const SGGeod& pos(wp->position());
692     prop->setStringValue("id", wp->ident().c_str());
693     prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
694     prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
695    
696     // leg course+distance
697
698     prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
699     prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
700     prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
701     
702     if (leg->altitudeRestriction() != RESTRICT_NONE) {
703       double ft = leg->altitudeFt();
704       prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
705       prop->setDoubleValue("altitude-ft", ft);
706       prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
707     } else {
708       prop->setDoubleValue("altitude-m", -9999.9);
709       prop->setDoubleValue("altitude-ft", -9999.9);
710     }
711     
712     if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
713       prop->setDoubleValue("speed-mach", leg->speedMach());
714     } else if (leg->speedRestriction() != RESTRICT_NONE) {
715       prop->setDoubleValue("speed-kts", leg->speedKts());
716     }
717     
718     if (wp->flag(WPT_ARRIVAL)) {
719       prop->setBoolValue("arrival", true);
720     }
721     
722     if (wp->flag(WPT_DEPARTURE)) {
723       prop->setBoolValue("departure", true);
724     }
725     
726     if (wp->flag(WPT_MISS)) {
727       prop->setBoolValue("missed-approach", true);
728     }
729     
730     prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
731   } // of waypoint iteration
732   
733   // set number as listener attachment point
734   mirror->setIntValue("num", _plan->numLegs());
735     
736   if (rmDlg) {
737     rmDlg->updateValues();
738   }
739   
740   totalDistance->setDoubleValue(_plan->totalDistanceNm());
741 }
742
743 // command interface /autopilot/route-manager/input:
744 //
745 //   @CLEAR             ... clear route
746 //   @POP               ... remove first entry
747 //   @DELETE3           ... delete 4th entry
748 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
749 //   KSFO@900           ... append "KSFO@900"
750 //
751 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
752 {
753     const char *s = prop->getStringValue();
754     if (strlen(s) == 0) {
755       return;
756     }
757     
758     if (!strcmp(s, "@CLEAR"))
759         mgr->clearRoute();
760     else if (!strcmp(s, "@ACTIVATE"))
761         mgr->activate();
762     else if (!strcmp(s, "@LOAD")) {
763       SGPath path(mgr->_pathNode->getStringValue());
764       mgr->loadRoute(path);
765     } else if (!strcmp(s, "@SAVE")) {
766       SGPath path(mgr->_pathNode->getStringValue());
767       mgr->saveRoute(path);
768     } else if (!strcmp(s, "@NEXT")) {
769       mgr->jumpToIndex(mgr->currentIndex() + 1);
770     } else if (!strcmp(s, "@PREVIOUS")) {
771       mgr->jumpToIndex(mgr->currentIndex() - 1);
772     } else if (!strncmp(s, "@JUMP", 5)) {
773       mgr->jumpToIndex(atoi(s + 5));
774     } else if (!strncmp(s, "@DELETE", 7))
775         mgr->removeLegAtIndex(atoi(s + 7));
776     else if (!strncmp(s, "@INSERT", 7)) {
777         char *r;
778         int pos = strtol(s + 7, &r, 10);
779         if (*r++ != ':')
780             return;
781         while (isspace(*r))
782             r++;
783         if (*r)
784             mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
785     } else if (!strcmp(s, "@POSINIT")) {
786       mgr->initAtPosition();
787     } else
788       mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
789 }
790
791 void FGRouteMgr::initAtPosition()
792 {
793   if (isRouteActive()) {
794     return; // don't mess with the active route
795   }
796   
797   if (haveUserWaypoints()) {
798     // user has already defined, loaded or entered a route, again
799     // don't interfere with it
800     return; 
801   }
802   
803   if (airborne->getBoolValue()) {
804     SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
805     _plan->setDeparture((FGAirport*) NULL);
806     return;
807   }
808   
809 // on the ground
810   SGGeod pos = globals->get_aircraft_position();
811   if (!_plan->departureAirport()) {
812     _plan->setDeparture(FGAirport::findClosest(pos, 20.0));
813     if (!_plan->departureAirport()) {
814       SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
815       return;
816     }
817   }
818   
819   std::string rwy = departure->getStringValue("runway");
820   FGRunway* r = NULL;
821   if (!rwy.empty()) {
822     r = _plan->departureAirport()->getRunwayByIdent(rwy);
823   } else {
824     r = _plan->departureAirport()->findBestRunwayForPos(pos);
825   }
826   
827   if (!r) {
828     return;
829   }
830   
831   _plan->setDeparture(r);
832   SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at " 
833     << _plan->departureAirport()->ident() << " on runway " << r->ident());
834 }
835
836 bool FGRouteMgr::haveUserWaypoints() const
837 {
838   // FIXME
839   return false;
840 }
841
842 bool FGRouteMgr::activate()
843 {
844   if (!_plan) {
845     SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
846     return false;
847   }
848   
849   if (isRouteActive()) {
850     SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
851     return false;
852   }
853  
854   _plan->setCurrentIndex(0);
855   active->setBoolValue(true);
856   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
857   return true;
858 }
859
860
861 void FGRouteMgr::sequence()
862 {
863   if (!_plan || !active->getBoolValue()) {
864     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
865     return;
866   }
867   
868   if (checkFinished()) {
869     return;
870   }
871   
872   _plan->setCurrentIndex(_plan->currentIndex() + 1);
873 }
874
875 bool FGRouteMgr::checkFinished()
876 {
877   if (!_plan) {
878     return true;
879   }
880   
881   bool done = false;
882 // done if we're stopped on the destination runway 
883   if (_plan->currentLeg() && 
884       (_plan->currentLeg()->waypoint()->source() == _plan->destinationRunway())) 
885   {
886     double gs = groundSpeed->getDoubleValue();
887     done = weightOnWheels->getBoolValue() && (gs < 25);
888   }
889   
890 // also done if we hit the final waypoint
891   if (_plan->currentIndex() >= _plan->numLegs()) {
892     done = true;
893   }
894   
895   if (done) {
896     SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
897     _finished->fireValueChanged();
898     active->setBoolValue(false);
899   }
900   
901   return done;
902 }
903
904 void FGRouteMgr::jumpToIndex(int index)
905 {
906   if (!_plan) {
907     return;
908   }
909   
910   _plan->setCurrentIndex(index);
911 }
912
913 void FGRouteMgr::currentWaypointChanged()
914 {
915   Waypt* cur = currentWaypt();
916   FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
917
918   wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
919   wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
920   
921   _currentWpt->fireValueChanged();
922   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
923 }
924
925 const char* FGRouteMgr::getDepartureICAO() const
926 {
927   if (!_plan || !_plan->departureAirport()) {
928     return "";
929   }
930   
931   return _plan->departureAirport()->ident().c_str();
932 }
933
934 const char* FGRouteMgr::getDepartureName() const
935 {
936   if (!_plan || !_plan->departureAirport()) {
937     return "";
938   }
939   
940   return _plan->departureAirport()->name().c_str();
941 }
942
943 const char* FGRouteMgr::getDepartureRunway() const
944 {
945   if (_plan && _plan->departureRunway()) {
946     return _plan->departureRunway()->ident().c_str();
947   }
948   
949   return "";
950 }
951
952 void FGRouteMgr::setDepartureRunway(const char* aIdent)
953 {
954   FGAirport* apt = _plan->departureAirport();
955   if (!apt || (aIdent == NULL)) {
956     _plan->setDeparture(apt);
957   } else if (apt->hasRunwayWithIdent(aIdent)) {
958     _plan->setDeparture(apt->getRunwayByIdent(aIdent));
959   }
960 }
961
962 void FGRouteMgr::setDepartureICAO(const char* aIdent)
963 {
964   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
965     _plan->setDeparture((FGAirport*) NULL);
966   } else {
967     _plan->setDeparture(FGAirport::findByIdent(aIdent));
968   }
969 }
970
971 const char* FGRouteMgr::getSID() const
972 {
973   if (_plan && _plan->sid()) {
974     return _plan->sid()->ident().c_str();
975   }
976   
977   return "";
978 }
979
980 void FGRouteMgr::setSID(const char* aIdent)
981 {
982   FGAirport* apt = _plan->departureAirport();
983   if (!apt || (aIdent == NULL)) {
984     _plan->setSID((flightgear::SID*) NULL);
985     return;
986   } 
987   
988   string ident(aIdent);
989   size_t hyphenPos = ident.find('-');
990   if (hyphenPos != string::npos) {
991     string sidIdent = ident.substr(0, hyphenPos);
992     string transIdent = ident.substr(hyphenPos + 1);
993     
994     flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
995     Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
996     _plan->setSID(trans);
997   } else {
998     _plan->setSID(apt->findSIDWithIdent(aIdent));
999   }
1000 }
1001
1002 const char* FGRouteMgr::getDestinationICAO() const
1003 {
1004   if (!_plan || !_plan->destinationAirport()) {
1005     return "";
1006   }
1007   
1008   return _plan->destinationAirport()->ident().c_str();
1009 }
1010
1011 const char* FGRouteMgr::getDestinationName() const
1012 {
1013   if (!_plan || !_plan->destinationAirport()) {
1014     return "";
1015   }
1016   
1017   return _plan->destinationAirport()->name().c_str();
1018 }
1019
1020 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1021 {
1022   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1023     _plan->setDestination((FGAirport*) NULL);
1024   } else {
1025     _plan->setDestination(FGAirport::findByIdent(aIdent));
1026   }
1027 }
1028
1029 const char* FGRouteMgr::getDestinationRunway() const
1030 {
1031   if (_plan && _plan->destinationRunway()) {
1032     return _plan->destinationRunway()->ident().c_str();
1033   }
1034   
1035   return "";
1036 }
1037
1038 void FGRouteMgr::setDestinationRunway(const char* aIdent)
1039 {
1040   FGAirport* apt = _plan->destinationAirport();
1041   if (!apt || (aIdent == NULL)) {
1042     _plan->setDestination(apt);
1043   } else if (apt->hasRunwayWithIdent(aIdent)) {
1044     _plan->setDestination(apt->getRunwayByIdent(aIdent));
1045   }
1046 }
1047
1048 const char* FGRouteMgr::getApproach() const
1049 {
1050   if (_plan && _plan->approach()) {
1051     return _plan->approach()->ident().c_str();
1052   }
1053   
1054   return "";
1055 }
1056
1057 void FGRouteMgr::setApproach(const char* aIdent)
1058 {
1059   FGAirport* apt = _plan->destinationAirport();
1060   if (!apt || (aIdent == NULL)) {
1061     _plan->setApproach(NULL);
1062   } else {
1063     _plan->setApproach(apt->findApproachWithIdent(aIdent));
1064   }
1065 }
1066
1067 const char* FGRouteMgr::getSTAR() const
1068 {
1069   if (_plan && _plan->star()) {
1070     return _plan->star()->ident().c_str();
1071   }
1072   
1073   return "";
1074 }
1075
1076 void FGRouteMgr::setSTAR(const char* aIdent)
1077 {
1078   FGAirport* apt = _plan->destinationAirport();
1079   if (!apt || (aIdent == NULL)) {
1080     _plan->setSTAR((STAR*) NULL);
1081     return;
1082   } 
1083   
1084   string ident(aIdent);
1085   size_t hyphenPos = ident.find('-');
1086   if (hyphenPos != string::npos) {
1087     string starIdent = ident.substr(0, hyphenPos);
1088     string transIdent = ident.substr(hyphenPos + 1);
1089     
1090     STAR* star = apt->findSTARWithIdent(starIdent);
1091     Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1092     _plan->setSTAR(trans);
1093   } else {
1094     _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1095   }
1096 }
1097
1098 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1099 {
1100   return _plan->waypointFromString(target);
1101 }
1102
1103 double FGRouteMgr::getDepartureFieldElevation() const
1104 {
1105   if (!_plan || !_plan->departureAirport()) {
1106     return 0.0;
1107   }
1108   
1109   return _plan->departureAirport()->elevation();
1110 }
1111
1112 double FGRouteMgr::getDestinationFieldElevation() const
1113 {
1114   if (!_plan || !_plan->destinationAirport()) {
1115     return 0.0;
1116   }
1117   
1118   return _plan->destinationAirport()->elevation();
1119 }
1120
1121 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1122 {
1123   if ((index < 0) || (index >= numWaypts())) {
1124     throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1125   }
1126   
1127   return mirror->getChild("wp", index);
1128 }