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