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