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