1 // route_mgr.cxx - manage a route (i.e. a collection of waypoints)
3 // Written by Curtis Olson, started January 2004.
7 // Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
34 #include <simgear/compiler.h>
36 #include "route_mgr.hxx"
38 #include <boost/algorithm/string/case_conv.hpp>
39 #include <boost/tuple/tuple.hpp>
41 #include <simgear/misc/strutils.hxx>
42 #include <simgear/structure/exception.hxx>
43 #include <simgear/structure/commands.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/sg_inlines.h>
47 #include "Main/fg_props.hxx"
48 #include "Navaids/positioned.hxx"
49 #include <Navaids/waypoint.hxx>
50 #include <Navaids/procedure.hxx>
51 #include "Airports/simple.hxx"
52 #include "Airports/runways.hxx"
53 #include <GUI/new_gui.hxx>
54 #include <GUI/dialog.hxx>
56 #define RM "/autopilot/route-manager/"
58 using namespace flightgear;
60 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
62 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
63 SGPath path(arg->getStringValue("path"));
64 return self->loadRoute(path);
67 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
69 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
70 SGPath path(arg->getStringValue("path"));
71 return self->saveRoute(path);
74 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
76 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
77 bool activate = arg->getBoolValue("activate", true);
87 static bool commandClearFlightPlan(const SGPropertyNode*)
89 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
94 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
96 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
97 int index = arg->getIntValue("index");
98 if ((index < 0) || (index >= self->numLegs())) {
102 self->jumpToIndex(index);
106 static bool commandInsertWaypt(const SGPropertyNode* arg)
108 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
109 int index = arg->getIntValue("index");
110 std::string ident(arg->getStringValue("id"));
111 int alt = arg->getIntValue("altitude-ft", -999);
112 int ias = arg->getIntValue("speed-knots", -999);
115 // lat/lon may be supplied to narrow down navaid search, or to specify
118 if (arg->hasChild("longitude-deg")) {
119 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
120 arg->getDoubleValue("latitude-deg"));
123 if (arg->hasChild("navaid")) {
124 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
126 if (arg->hasChild("navaid", 1)) {
127 // intersection of two radials
128 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
130 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
134 double r1 = arg->getDoubleValue("radial"),
135 r2 = arg->getDoubleValue("radial[1]");
138 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
140 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
141 << "," << p2->ident());
145 std::string name = p->ident() + "-" + p2->ident();
146 wp = new BasicWaypt(intersection, name, NULL);
147 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
148 // offset radial from navaid
149 double radial = arg->getDoubleValue("radial");
150 double distanceNm = arg->getDoubleValue("offset-nm");
151 //radial += magvar->getDoubleValue(); // convert to true bearing
152 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
154 wp = new NavaidWaypoint(p, NULL);
156 } else if (arg->hasChild("airport")) {
157 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
159 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
163 if (arg->hasChild("runway")) {
164 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
165 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
169 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
170 wp = new RunwayWaypt(runway, NULL);
172 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
174 } else if (arg->hasChild("text")) {
175 wp = self->waypointFromString(arg->getStringValue("text"));
176 } else if (!(pos == SGGeod())) {
177 // just a raw lat/lon
178 wp = new BasicWaypt(pos, ident, NULL);
180 return false; // failed to build waypoint
183 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
185 leg->setAltitude(RESTRICT_AT, alt);
189 leg->setSpeed(RESTRICT_AT, ias);
195 static bool commandDeleteWaypt(const SGPropertyNode* arg)
197 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
198 int index = arg->getIntValue("index");
199 self->removeLegAtIndex(index);
203 /////////////////////////////////////////////////////////////////////////////
205 FGRouteMgr::FGRouteMgr() :
207 input(fgGetNode( RM "input", true )),
208 mirror(fgGetNode( RM "route", true ))
210 listener = new InputListener(this);
211 input->setStringValue("");
212 input->addChangeListener(listener);
214 SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
215 SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
216 SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
217 SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
218 SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
219 SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
220 SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
224 FGRouteMgr::~FGRouteMgr()
226 input->removeChangeListener(listener);
231 void FGRouteMgr::init() {
232 SGPropertyNode_ptr rm(fgGetNode(RM));
234 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
236 departure = fgGetNode(RM "departure", true);
237 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
238 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
239 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
240 &FGRouteMgr::getDepartureRunway,
241 &FGRouteMgr::setDepartureRunway));
242 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
244 &FGRouteMgr::setSID));
246 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
247 &FGRouteMgr::getDepartureName, NULL));
248 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
249 &FGRouteMgr::getDestinationFieldElevation, NULL));
250 departure->getChild("etd", 0, true);
251 departure->getChild("takeoff-time", 0, true);
253 destination = fgGetNode(RM "destination", true);
254 destination->getChild("airport", 0, true);
256 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
257 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
258 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
259 &FGRouteMgr::getDestinationRunway,
260 &FGRouteMgr::setDestinationRunway));
261 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
262 &FGRouteMgr::getSTAR,
263 &FGRouteMgr::setSTAR));
264 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
265 &FGRouteMgr::getApproach,
266 &FGRouteMgr::setApproach));
268 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
269 &FGRouteMgr::getDestinationName, NULL));
270 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
271 &FGRouteMgr::getDestinationFieldElevation, NULL));
273 destination->getChild("eta", 0, true);
274 destination->getChild("touchdown-time", 0, true);
276 alternate = fgGetNode(RM "alternate", true);
277 alternate->getChild("airport", 0, true);
278 alternate->getChild("runway", 0, true);
280 cruise = fgGetNode(RM "cruise", true);
281 cruise->getChild("altitude-ft", 0, true);
282 cruise->setDoubleValue("altitude-ft", 10000.0);
283 cruise->getChild("flight-level", 0, true);
284 cruise->getChild("speed-kts", 0, true);
285 cruise->setDoubleValue("speed-kts", 160.0);
287 totalDistance = fgGetNode(RM "total-distance", true);
288 totalDistance->setDoubleValue(0.0);
289 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
290 distanceToGo->setDoubleValue(0.0);
292 ete = fgGetNode(RM "ete", true);
293 ete->setDoubleValue(0.0);
295 elapsedFlightTime = fgGetNode(RM "flight-time", true);
296 elapsedFlightTime->setDoubleValue(0.0);
298 active = fgGetNode(RM "active", true);
299 active->setBoolValue(false);
301 airborne = fgGetNode(RM "airborne", true);
302 airborne->setBoolValue(false);
304 _edited = fgGetNode(RM "signals/edited", true);
305 _finished = fgGetNode(RM "signals/finished", true);
306 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
308 _currentWpt = fgGetNode(RM "current-wp", true);
309 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
310 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
312 // temporary distance / eta calculations, for backward-compatability
313 wp0 = fgGetNode(RM "wp", 0, true);
314 wp0->getChild("id", 0, true);
315 wp0->getChild("dist", 0, true);
316 wp0->getChild("eta", 0, true);
317 wp0->getChild("bearing-deg", 0, true);
319 wp1 = fgGetNode(RM "wp", 1, true);
320 wp1->getChild("id", 0, true);
321 wp1->getChild("dist", 0, true);
322 wp1->getChild("eta", 0, true);
324 wpn = fgGetNode(RM "wp-last", 0, true);
325 wpn->getChild("dist", 0, true);
326 wpn->getChild("eta", 0, true);
328 _pathNode = fgGetNode(RM "file-path", 0, true);
329 setFlightPlan(new FlightPlan());
333 void FGRouteMgr::postinit()
335 SGPath path(_pathNode->getStringValue());
336 if (!path.isNull()) {
337 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
341 // this code only matters for the --wp option now - perhaps the option
342 // should be deprecated in favour of an explicit flight-plan file?
343 // then the global initial waypoint list could die.
344 string_list *waypoints = globals->get_initial_waypoints();
346 string_list::iterator it;
347 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
348 WayptRef w = waypointFromString(*it);
350 _plan->insertWayptAtIndex(w, -1);
354 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
358 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
359 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
361 // check airbone flag agrees with presets
364 void FGRouteMgr::bind() { }
365 void FGRouteMgr::unbind() { }
367 bool FGRouteMgr::isRouteActive() const
369 return active->getBoolValue();
372 bool FGRouteMgr::saveRoute(const SGPath& p)
378 return _plan->save(p);
381 bool FGRouteMgr::loadRoute(const SGPath& p)
383 FlightPlan* fp = new FlightPlan;
393 FlightPlan* FGRouteMgr::flightPlan() const
398 void FGRouteMgr::setFlightPlan(FlightPlan* plan)
406 active->setBoolValue(false);
410 _plan->setDelegate(this);
412 _flightplanChanged->fireValueChanged();
414 // fire all the callbacks!
418 currentWaypointChanged();
421 void FGRouteMgr::update( double dt )
424 return; // paused, nothing to do here
427 double gs = groundSpeed->getDoubleValue();
428 if (airborne->getBoolValue()) {
429 time_t now = time(NULL);
430 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
432 if (weightOnWheels->getBoolValue()) {
434 destination->setIntValue("touchdown-time", time(NULL));
435 airborne->setBoolValue(false);
437 } else { // not airborne
438 if (weightOnWheels->getBoolValue() || (gs < 40)) {
439 // either taking-off or rolling-out after touchdown
441 airborne->setBoolValue(true);
442 _takeoffTime = time(NULL); // start the clock
443 departure->setIntValue("takeoff-time", _takeoffTime);
447 if (!active->getBoolValue()) {
451 if (checkFinished()) {
455 // basic course/distance information
456 SGGeod currentPos = globals->get_aircraft_position();
458 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
465 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
467 // update wp0 / wp1 / wp-last
468 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
469 wp0->setDoubleValue("true-bearing-deg", courseDeg);
470 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
471 wp0->setDoubleValue("bearing-deg", courseDeg);
472 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
474 double totalPathDistanceNm = _plan->totalDistanceNm();
475 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
477 // total distance to go, is direct distance to wp0, plus the remaining
478 // path distance from wp0
479 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
481 wp0->setDoubleValue("distance-along-route-nm",
482 leg->distanceAlongRoute());
483 wp0->setDoubleValue("remaining-distance-nm",
484 totalPathDistanceNm - leg->distanceAlongRoute());
486 FlightPlan::Leg* nextLeg = _plan->nextLeg();
488 boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
490 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
491 wp1->setDoubleValue("true-bearing-deg", courseDeg);
492 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
493 wp1->setDoubleValue("bearing-deg", courseDeg);
494 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
495 wp1->setDoubleValue("distance-along-route-nm",
496 nextLeg->distanceAlongRoute());
497 wp1->setDoubleValue("remaining-distance-nm",
498 totalPathDistanceNm - nextLeg->distanceAlongRoute());
501 distanceToGo->setDoubleValue(totalDistanceRemaining);
502 wpn->setDoubleValue("dist", totalDistanceRemaining);
503 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
504 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
507 void FGRouteMgr::clearRoute()
514 Waypt* FGRouteMgr::currentWaypt() const
516 if (_plan && _plan->currentLeg()) {
517 return _plan->currentLeg()->waypoint();
523 int FGRouteMgr::currentIndex() const
529 return _plan->currentIndex();
532 Waypt* FGRouteMgr::wayptAtIndex(int index) const
535 FlightPlan::Leg* leg = _plan->legAtIndex(index);
537 return leg->waypoint();
544 int FGRouteMgr::numLegs() const
547 return _plan->numLegs();
553 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
555 double speed = groundSpeed->getDoubleValue();
557 aProp->setStringValue("--:--");
562 double eta = aDistance * SG_METER_TO_NM / speed;
563 if ( eta >= 100.0 ) {
564 eta = 99.999; // clamp
567 if ( eta < (1.0/6.0) ) {
568 eta *= 60.0; // within 10 minutes, bump up to min/secs
571 int major = (int)eta,
572 minor = (int)((eta - (int)eta) * 60.0);
573 snprintf( eta_str, 64, "%d:%02d", major, minor );
574 aProp->setStringValue( eta_str );
577 void FGRouteMgr::removeLegAtIndex(int aIndex)
583 _plan->deleteIndex(aIndex);
586 void FGRouteMgr::departureChanged()
588 _plan->clearWayptsWithFlag(WPT_DEPARTURE);
591 buildDeparture(enroute, wps);
592 _plan->insertWayptsAtIndex(wps, 0);
595 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
597 if (!_plan->departureAirport()) {
601 if (!_plan->departureRunway()) {
602 // valid airport, but no runway selected, so just the airport _plan itself
603 WayptRef w = new NavaidWaypoint(_plan->departureAirport(), _plan);
604 w->setFlag(WPT_DEPARTURE);
609 WayptRef rwyWaypt = new RunwayWaypt(_plan->departureRunway(), _plan);
610 rwyWaypt->setFlag(WPT_DEPARTURE);
611 wps.push_back(rwyWaypt);
617 _plan->sid()->route(_plan->departureRunway(), _plan->sidTransition(), wps);
620 void FGRouteMgr::arrivalChanged()
622 _plan->clearWayptsWithFlag(WPT_ARRIVAL);
623 _plan->clearWayptsWithFlag(WPT_APPROACH);
626 buildArrival(enroute, wps);
627 _plan->insertWayptsAtIndex(wps, -1);
630 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
632 FGAirportRef apt = _plan->destinationAirport();
637 if (!_plan->destinationRunway()) {
638 WayptRef w = new NavaidWaypoint(apt.ptr(), _plan);
639 w->setFlag(WPT_ARRIVAL);
645 _plan->star()->route(_plan->destinationRunway(), _plan->starTransition(), wps);
648 if (_plan->approach()) {
649 _plan->approach()->route(wps.back(), wps);
651 WayptRef w = new RunwayWaypt(_plan->destinationRunway(), _plan);
652 w->setFlag(WPT_APPROACH);
657 void FGRouteMgr::waypointsChanged()
660 _edited->fireValueChanged();
664 // mirror internal route to the property system for inspection by other subsystems
665 void FGRouteMgr::update_mirror()
667 mirror->removeChildren("wp");
668 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
669 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
672 mirror->setIntValue("num", 0);
674 rmDlg->updateValues();
679 int num = _plan->numLegs();
681 for (int i = 0; i < num; i++) {
682 FlightPlan::Leg* leg = _plan->legAtIndex(i);
683 WayptRef wp = leg->waypoint();
684 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
686 const SGGeod& pos(wp->position());
687 prop->setStringValue("id", wp->ident().c_str());
688 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
689 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
691 // leg course+distance
693 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
694 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
695 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
697 if (leg->altitudeRestriction() != RESTRICT_NONE) {
698 double ft = leg->altitudeFt();
699 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
700 prop->setDoubleValue("altitude-ft", ft);
701 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
703 prop->setDoubleValue("altitude-m", -9999.9);
704 prop->setDoubleValue("altitude-ft", -9999.9);
707 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
708 prop->setDoubleValue("speed-mach", leg->speedMach());
709 } else if (leg->speedRestriction() != RESTRICT_NONE) {
710 prop->setDoubleValue("speed-kts", leg->speedKts());
713 if (wp->flag(WPT_ARRIVAL)) {
714 prop->setBoolValue("arrival", true);
717 if (wp->flag(WPT_DEPARTURE)) {
718 prop->setBoolValue("departure", true);
721 if (wp->flag(WPT_MISS)) {
722 prop->setBoolValue("missed-approach", true);
725 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
726 } // of waypoint iteration
728 // set number as listener attachment point
729 mirror->setIntValue("num", _plan->numLegs());
732 rmDlg->updateValues();
735 totalDistance->setDoubleValue(_plan->totalDistanceNm());
738 // command interface /autopilot/route-manager/input:
740 // @CLEAR ... clear route
741 // @POP ... remove first entry
742 // @DELETE3 ... delete 4th entry
743 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
744 // KSFO@900 ... append "KSFO@900"
746 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
748 const char *s = prop->getStringValue();
749 if (strlen(s) == 0) {
753 if (!strcmp(s, "@CLEAR"))
755 else if (!strcmp(s, "@ACTIVATE"))
757 else if (!strcmp(s, "@LOAD")) {
758 SGPath path(mgr->_pathNode->getStringValue());
759 mgr->loadRoute(path);
760 } else if (!strcmp(s, "@SAVE")) {
761 SGPath path(mgr->_pathNode->getStringValue());
762 mgr->saveRoute(path);
763 } else if (!strcmp(s, "@NEXT")) {
764 mgr->jumpToIndex(mgr->currentIndex() + 1);
765 } else if (!strcmp(s, "@PREVIOUS")) {
766 mgr->jumpToIndex(mgr->currentIndex() - 1);
767 } else if (!strncmp(s, "@JUMP", 5)) {
768 mgr->jumpToIndex(atoi(s + 5));
769 } else if (!strncmp(s, "@DELETE", 7))
770 mgr->removeLegAtIndex(atoi(s + 7));
771 else if (!strncmp(s, "@INSERT", 7)) {
773 int pos = strtol(s + 7, &r, 10);
779 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
780 } else if (!strcmp(s, "@POSINIT")) {
781 mgr->initAtPosition();
783 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
786 void FGRouteMgr::initAtPosition()
788 if (isRouteActive()) {
789 return; // don't mess with the active route
792 if (haveUserWaypoints()) {
793 // user has already defined, loaded or entered a route, again
794 // don't interfere with it
798 if (airborne->getBoolValue()) {
799 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
800 _plan->setDeparture((FGAirport*) NULL);
805 SGGeod pos = globals->get_aircraft_position();
806 if (!_plan->departureAirport()) {
807 _plan->setDeparture(FGAirport::findClosest(pos, 20.0));
808 if (!_plan->departureAirport()) {
809 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
814 std::string rwy = departure->getStringValue("runway");
817 r = _plan->departureAirport()->getRunwayByIdent(rwy);
819 r = _plan->departureAirport()->findBestRunwayForPos(pos);
826 _plan->setDeparture(r);
827 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
828 << _plan->departureAirport()->ident() << " on runway " << r->ident());
831 bool FGRouteMgr::haveUserWaypoints() const
837 bool FGRouteMgr::activate()
840 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
844 if (isRouteActive()) {
845 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
849 _plan->setCurrentIndex(0);
850 active->setBoolValue(true);
851 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
856 void FGRouteMgr::sequence()
858 if (!_plan || !active->getBoolValue()) {
859 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
863 if (checkFinished()) {
867 _plan->setCurrentIndex(_plan->currentIndex() + 1);
870 bool FGRouteMgr::checkFinished()
877 // done if we're stopped on the destination runway
878 if (_plan->currentLeg() &&
879 (_plan->currentLeg()->waypoint()->source() == _plan->destinationRunway()))
881 double gs = groundSpeed->getDoubleValue();
882 done = weightOnWheels->getBoolValue() && (gs < 25);
885 // also done if we hit the final waypoint
886 if (_plan->currentIndex() >= _plan->numLegs()) {
891 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
892 _finished->fireValueChanged();
893 active->setBoolValue(false);
899 void FGRouteMgr::jumpToIndex(int index)
905 _plan->setCurrentIndex(index);
908 void FGRouteMgr::currentWaypointChanged()
910 Waypt* cur = currentWaypt();
911 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
913 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
914 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
916 _currentWpt->fireValueChanged();
917 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
920 const char* FGRouteMgr::getDepartureICAO() const
922 if (!_plan || !_plan->departureAirport()) {
926 return _plan->departureAirport()->ident().c_str();
929 const char* FGRouteMgr::getDepartureName() const
931 if (!_plan || !_plan->departureAirport()) {
935 return _plan->departureAirport()->name().c_str();
938 const char* FGRouteMgr::getDepartureRunway() const
940 if (_plan && _plan->departureRunway()) {
941 return _plan->departureRunway()->ident().c_str();
947 void FGRouteMgr::setDepartureRunway(const char* aIdent)
949 FGAirport* apt = _plan->departureAirport();
950 if (!apt || (aIdent == NULL)) {
951 _plan->setDeparture(apt);
952 } else if (apt->hasRunwayWithIdent(aIdent)) {
953 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
957 void FGRouteMgr::setDepartureICAO(const char* aIdent)
959 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
960 _plan->setDeparture((FGAirport*) NULL);
962 _plan->setDeparture(FGAirport::findByIdent(aIdent));
966 const char* FGRouteMgr::getSID() const
968 if (_plan && _plan->sid()) {
969 return _plan->sid()->ident().c_str();
975 void FGRouteMgr::setSID(const char* aIdent)
977 FGAirport* apt = _plan->departureAirport();
978 if (!apt || (aIdent == NULL)) {
979 _plan->setSID((flightgear::SID*) NULL);
983 string ident(aIdent);
984 size_t hyphenPos = ident.find('-');
985 if (hyphenPos != string::npos) {
986 string sidIdent = ident.substr(0, hyphenPos);
987 string transIdent = ident.substr(hyphenPos + 1);
989 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
990 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
991 _plan->setSID(trans);
993 _plan->setSID(apt->findSIDWithIdent(aIdent));
997 const char* FGRouteMgr::getDestinationICAO() const
999 if (!_plan || !_plan->destinationAirport()) {
1003 return _plan->destinationAirport()->ident().c_str();
1006 const char* FGRouteMgr::getDestinationName() const
1008 if (!_plan || !_plan->destinationAirport()) {
1012 return _plan->destinationAirport()->name().c_str();
1015 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1017 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1018 _plan->setDestination((FGAirport*) NULL);
1020 _plan->setDestination(FGAirport::findByIdent(aIdent));
1024 const char* FGRouteMgr::getDestinationRunway() const
1026 if (_plan && _plan->destinationRunway()) {
1027 return _plan->destinationRunway()->ident().c_str();
1033 void FGRouteMgr::setDestinationRunway(const char* aIdent)
1035 FGAirport* apt = _plan->destinationAirport();
1036 if (!apt || (aIdent == NULL)) {
1037 _plan->setDestination(apt);
1038 } else if (apt->hasRunwayWithIdent(aIdent)) {
1039 _plan->setDestination(apt->getRunwayByIdent(aIdent));
1043 const char* FGRouteMgr::getApproach() const
1045 if (_plan && _plan->approach()) {
1046 return _plan->approach()->ident().c_str();
1052 void FGRouteMgr::setApproach(const char* aIdent)
1054 FGAirport* apt = _plan->destinationAirport();
1055 if (!apt || (aIdent == NULL)) {
1056 _plan->setApproach(NULL);
1058 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1062 const char* FGRouteMgr::getSTAR() const
1064 if (_plan && _plan->star()) {
1065 return _plan->star()->ident().c_str();
1071 void FGRouteMgr::setSTAR(const char* aIdent)
1073 FGAirport* apt = _plan->destinationAirport();
1074 if (!apt || (aIdent == NULL)) {
1075 _plan->setSTAR((STAR*) NULL);
1079 string ident(aIdent);
1080 size_t hyphenPos = ident.find('-');
1081 if (hyphenPos != string::npos) {
1082 string starIdent = ident.substr(0, hyphenPos);
1083 string transIdent = ident.substr(hyphenPos + 1);
1085 STAR* star = apt->findSTARWithIdent(starIdent);
1086 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1087 _plan->setSTAR(trans);
1089 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1093 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1095 return _plan->waypointFromString(target);
1098 double FGRouteMgr::getDepartureFieldElevation() const
1100 if (!_plan || !_plan->departureAirport()) {
1104 return _plan->departureAirport()->elevation();
1107 double FGRouteMgr::getDestinationFieldElevation() const
1109 if (!_plan || !_plan->destinationAirport()) {
1113 return _plan->destinationAirport()->elevation();
1116 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1118 if ((index < 0) || (index >= numWaypts())) {
1119 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1122 return mirror->getChild("wp", index);