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