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