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/sgstream.hxx>
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>
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"
59 #define RM "/autopilot/route-manager/"
61 #include <GUI/new_gui.hxx>
62 #include <GUI/dialog.hxx>
64 using namespace flightgear;
66 class PropertyWatcher : public SGPropertyChangeListener
69 void watch(SGPropertyNode* p)
71 p->addChangeListener(this, false);
74 virtual void valueChanged(SGPropertyNode*)
79 virtual void fire() = 0;
83 * Template adapter, created by convenience helper below
86 class MethodPropertyWatcher : public PropertyWatcher
89 typedef void (T::*fire_method)();
91 MethodPropertyWatcher(T* obj, fire_method m) :
98 { // dispatch to the object method we're helping
99 (_object->*_method)();
108 PropertyWatcher* createWatcher(T* obj, void (T::*m)())
110 return new MethodPropertyWatcher<T>(obj, m);
113 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
115 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
116 SGPath path(arg->getStringValue("path"));
117 return self->loadRoute(path);
120 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
122 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
123 SGPath path(arg->getStringValue("path"));
124 return self->saveRoute(path);
127 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
129 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
130 bool activate = arg->getBoolValue("activate", true);
140 static bool commandClearFlightPlan(const SGPropertyNode*)
142 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
147 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
149 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
150 int index = arg->getIntValue("index");
151 if ((index < 0) || (index >= self->numWaypts())) {
155 self->jumpToIndex(index);
159 static bool commandInsertWaypt(const SGPropertyNode* arg)
161 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
162 int index = arg->getIntValue("index");
163 std::string ident(arg->getStringValue("id"));
164 int alt = arg->getIntValue("altitude-ft", -999);
165 int ias = arg->getIntValue("speed-knots", -999);
168 // lat/lon may be supplied to narrow down navaid search, or to specify
171 if (arg->hasChild("longitude-deg")) {
172 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
173 arg->getDoubleValue("latitude-deg"));
176 if (arg->hasChild("navaid")) {
177 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
179 if (arg->hasChild("navaid", 1)) {
180 // intersection of two radials
181 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
183 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
187 double r1 = arg->getDoubleValue("radial"),
188 r2 = arg->getDoubleValue("radial[1]");
191 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
193 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
194 << "," << p2->ident());
198 std::string name = p->ident() + "-" + p2->ident();
199 wp = new BasicWaypt(intersection, name, NULL);
200 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
201 // offset radial from navaid
202 double radial = arg->getDoubleValue("radial");
203 double distanceNm = arg->getDoubleValue("offset-nm");
204 //radial += magvar->getDoubleValue(); // convert to true bearing
205 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
207 wp = new NavaidWaypoint(p, NULL);
209 } else if (arg->hasChild("airport")) {
210 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
212 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
216 if (arg->hasChild("runway")) {
217 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
218 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
222 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
223 wp = new RunwayWaypt(runway, NULL);
225 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
227 } else if (arg->hasChild("text")) {
228 wp = self->waypointFromString(arg->getStringValue("text"));
229 } else if (!(pos == SGGeod())) {
230 // just a raw lat/lon
231 wp = new BasicWaypt(pos, ident, NULL);
233 return false; // failed to build waypoint
237 wp->setAltitude(alt, flightgear::RESTRICT_AT);
241 wp->setSpeed(ias, flightgear::RESTRICT_AT);
244 self->insertWayptAtIndex(wp, index);
248 static bool commandDeleteWaypt(const SGPropertyNode* arg)
250 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
251 int index = arg->getIntValue("index");
252 self->removeWayptAtIndex(index);
256 /////////////////////////////////////////////////////////////////////////////
258 FGRouteMgr::FGRouteMgr() :
260 input(fgGetNode( RM "input", true )),
261 mirror(fgGetNode( RM "route", true ))
263 listener = new InputListener(this);
264 input->setStringValue("");
265 input->addChangeListener(listener);
267 SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
268 SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
269 SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
270 SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
271 SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
272 SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
273 SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
277 FGRouteMgr::~FGRouteMgr()
279 input->removeChangeListener(listener);
284 void FGRouteMgr::init() {
285 SGPropertyNode_ptr rm(fgGetNode(RM));
287 lon = fgGetNode( "/position/longitude-deg", true );
288 lat = fgGetNode( "/position/latitude-deg", true );
289 alt = fgGetNode( "/position/altitude-ft", true );
290 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
292 departure = fgGetNode(RM "departure", true);
293 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
294 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
295 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
296 &FGRouteMgr::getDepartureName, NULL));
297 departure->setStringValue("runway", "");
299 _departureWatcher = createWatcher(this, &FGRouteMgr::departureChanged);
300 _departureWatcher->watch(departure->getChild("runway"));
302 departure->getChild("etd", 0, true);
303 _departureWatcher->watch(departure->getChild("sid", 0, true));
304 departure->getChild("takeoff-time", 0, true);
306 destination = fgGetNode(RM "destination", true);
307 destination->getChild("airport", 0, true);
309 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
310 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
311 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
312 &FGRouteMgr::getDestinationName, NULL));
314 _arrivalWatcher = createWatcher(this, &FGRouteMgr::arrivalChanged);
315 _arrivalWatcher->watch(destination->getChild("runway", 0, true));
317 destination->getChild("eta", 0, true);
318 _arrivalWatcher->watch(destination->getChild("star", 0, true));
319 _arrivalWatcher->watch(destination->getChild("transition", 0, true));
320 destination->getChild("touchdown-time", 0, true);
322 alternate = fgGetNode(RM "alternate", true);
323 alternate->getChild("airport", 0, true);
324 alternate->getChild("runway", 0, true);
326 cruise = fgGetNode(RM "cruise", true);
327 cruise->getChild("altitude-ft", 0, true);
328 cruise->setDoubleValue("altitude-ft", 10000.0);
329 cruise->getChild("flight-level", 0, true);
330 cruise->getChild("speed-kts", 0, true);
331 cruise->setDoubleValue("speed-kts", 160.0);
333 _routingType = cruise->getChild("routing", 0, true);
334 _routingType->setIntValue(ROUTE_HIGH_AIRWAYS);
336 totalDistance = fgGetNode(RM "total-distance", true);
337 totalDistance->setDoubleValue(0.0);
339 ete = fgGetNode(RM "ete", true);
340 ete->setDoubleValue(0.0);
342 elapsedFlightTime = fgGetNode(RM "flight-time", true);
343 elapsedFlightTime->setDoubleValue(0.0);
345 active = fgGetNode(RM "active", true);
346 active->setBoolValue(false);
348 airborne = fgGetNode(RM "airborne", true);
349 airborne->setBoolValue(false);
351 _edited = fgGetNode(RM "signals/edited", true);
352 _finished = fgGetNode(RM "signals/finished", true);
354 _currentWpt = fgGetNode(RM "current-wp", true);
355 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
356 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
358 // temporary distance / eta calculations, for backward-compatability
359 wp0 = fgGetNode(RM "wp", 0, true);
360 wp0->getChild("id", 0, true);
361 wp0->getChild("dist", 0, true);
362 wp0->getChild("eta", 0, true);
363 wp0->getChild("bearing-deg", 0, true);
365 wp1 = fgGetNode(RM "wp", 1, true);
366 wp1->getChild("id", 0, true);
367 wp1->getChild("dist", 0, true);
368 wp1->getChild("eta", 0, true);
370 wpn = fgGetNode(RM "wp-last", 0, true);
371 wpn->getChild("dist", 0, true);
372 wpn->getChild("eta", 0, true);
375 _pathNode = fgGetNode(RM "file-path", 0, true);
379 void FGRouteMgr::postinit()
381 SGPath path(_pathNode->getStringValue());
382 if (!path.isNull()) {
383 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
387 // this code only matters for the --wp option now - perhaps the option
388 // should be deprecated in favour of an explicit flight-plan file?
389 // then the global initial waypoint list could die.
390 string_list *waypoints = globals->get_initial_waypoints();
392 string_list::iterator it;
393 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
394 WayptRef w = waypointFromString(*it);
400 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << _route.size());
403 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
404 // check airbone flag agrees with presets
407 void FGRouteMgr::bind() { }
408 void FGRouteMgr::unbind() { }
410 bool FGRouteMgr::isRouteActive() const
412 return active->getBoolValue();
415 void FGRouteMgr::update( double dt )
418 return; // paused, nothing to do here
421 double groundSpeed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
422 if (airborne->getBoolValue()) {
423 time_t now = time(NULL);
424 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
425 } else { // not airborne
426 if (weightOnWheels->getBoolValue() || (groundSpeed < 40)) {
430 airborne->setBoolValue(true);
431 _takeoffTime = time(NULL); // start the clock
432 departure->setIntValue("takeoff-time", _takeoffTime);
435 if (!active->getBoolValue()) {
439 // basic course/distance information
440 SGGeod currentPos = SGGeod::fromDegFt(lon->getDoubleValue(),
441 lat->getDoubleValue(),alt->getDoubleValue());
443 Waypt* curWpt = currentWaypt();
450 boost::tie(courseDeg, distanceM) = curWpt->courseAndDistanceFrom(currentPos);
452 // update wp0 / wp1 / wp-last for legacy users
453 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
454 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
455 wp0->setDoubleValue("bearing-deg", courseDeg);
456 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
458 double totalDistanceRemaining = distanceM; // distance to current waypoint
460 Waypt* nextWpt = nextWaypt();
462 boost::tie(courseDeg, distanceM) = nextWpt->courseAndDistanceFrom(currentPos);
464 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
465 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
466 wp1->setDoubleValue("bearing-deg", courseDeg);
467 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
470 Waypt* prev = curWpt;
471 for (unsigned int i=_currentIndex + 1; i<_route.size(); ++i) {
472 Waypt* w = _route[i];
473 if (w->flag(WPT_DYNAMIC)) continue;
474 totalDistanceRemaining += SGGeodesy::distanceM(prev->position(), w->position());
480 wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
481 ete->setDoubleValue(totalDistanceRemaining * SG_METER_TO_NM / groundSpeed * 3600.0);
482 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
485 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
487 double speed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
489 aProp->setStringValue("--:--");
494 double eta = aDistance * SG_METER_TO_NM / speed;
495 if ( eta >= 100.0 ) {
496 eta = 99.999; // clamp
499 if ( eta < (1.0/6.0) ) {
500 eta *= 60.0; // within 10 minutes, bump up to min/secs
503 int major = (int)eta,
504 minor = (int)((eta - (int)eta) * 60.0);
505 snprintf( eta_str, 64, "%d:%02d", major, minor );
506 aProp->setStringValue( eta_str );
509 flightgear::WayptRef FGRouteMgr::removeWayptAtIndex(int aIndex)
512 if (aIndex < 0) { // negative indices count the the end
513 index = _route.size() + index;
516 if ((index < 0) || (index >= numWaypts())) {
517 SG_LOG(SG_AUTOPILOT, SG_WARN, "removeWayptAtIndex with invalid index:" << aIndex);
520 WayptVec::iterator it = _route.begin();
523 WayptRef w = *it; // hold a ref now, in case _route is the only other owner
528 if (_currentIndex == index) {
529 currentWaypointChanged(); // current waypoint was removed
532 if (_currentIndex > index) {
533 --_currentIndex; // shift current index down if necessary
536 _edited->fireValueChanged();
542 void FGRouteMgr::clearRoute()
548 active->setBoolValue(false);
549 _edited->fireValueChanged();
553 * route between index-1 and index, using airways.
555 bool FGRouteMgr::routeToIndex(int index, RouteType aRouteType)
561 index = _route.size(); // can still be zero, of course
566 SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no departure set");
570 wp1 = new NavaidWaypoint(_departure.get(), NULL);
572 wp1 = wayptAtIndex(index - 1);
575 if (index >= numWaypts()) {
577 SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no destination set");
581 wp2 = new NavaidWaypoint(_destination.get(), NULL);
583 wp2 = wayptAtIndex(index);
586 double distNm = SGGeodesy::distanceNm(wp1->position(), wp2->position());
587 if (distNm < 100.0) {
588 SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: existing waypoints are nearby, direct route");
593 switch (aRouteType) {
594 case ROUTE_HIGH_AIRWAYS:
595 Airway::highLevel()->route(wp1, wp2, r);
598 case ROUTE_LOW_AIRWAYS:
599 Airway::lowLevel()->route(wp1, wp2, r);
603 throw sg_exception("VOR routing not supported yet");
607 SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: no route found");
611 WayptVec::iterator it = _route.begin();
613 _route.insert(it, r.begin(), r.end());
616 _edited->fireValueChanged();
620 void FGRouteMgr::autoRoute()
622 if (!_departure || !_destination) {
626 string runwayId(departure->getStringValue("runway"));
627 FGRunway* runway = NULL;
628 if (_departure->hasRunwayWithIdent(runwayId)) {
629 runway = _departure->getRunwayByIdent(runwayId);
632 FGRunway* dstRunway = NULL;
633 runwayId = destination->getStringValue("runway");
634 if (_destination->hasRunwayWithIdent(runwayId)) {
635 dstRunway = _destination->getRunwayByIdent(runwayId);
638 _route.clear(); // clear out the existing, first
640 flightgear::SID* sid;
643 boost::tie(sid, sidTrans) = _departure->selectSID(_destination->geod(), runway);
645 SG_LOG(SG_AUTOPILOT, SG_INFO, "selected SID " << sid->ident());
647 SG_LOG(SG_AUTOPILOT, SG_INFO, "\tvia " << sidTrans->ident() << " transition");
650 sid->route(runway, sidTrans, _route);
651 departure->setStringValue("sid", sid->ident());
653 // use airport location for airway search
654 sidTrans = new NavaidWaypoint(_departure.get(), NULL);
655 departure->setStringValue("sid", "");
659 destination->setStringValue("transition", "");
660 destination->setStringValue("star", "");
664 boost::tie(star, starTrans) = _destination->selectSTAR(_departure->geod(), dstRunway);
666 SG_LOG(SG_AUTOPILOT, SG_INFO, "selected STAR " << star->ident());
668 SG_LOG(SG_AUTOPILOT, SG_INFO, "\tvia " << starTrans->ident() << " transition");
669 destination->setStringValue("transition", starTrans->ident());
671 destination->setStringValue("star", star->ident());
673 // use airport location for search
674 starTrans = new NavaidWaypoint(_destination.get(), NULL);
677 // route between them
678 WayptVec airwayRoute;
679 if (Airway::highLevel()->route(sidTrans, starTrans, airwayRoute)) {
680 _route.insert(_route.end(), airwayRoute.begin(), airwayRoute.end());
683 // add the STAR if we have one
685 _destination->buildApproach(starTrans, star, dstRunway, _route);
689 _edited->fireValueChanged();
692 void FGRouteMgr::departureChanged()
694 // remove existing departure waypoints
695 WayptVec::iterator it = _route.begin();
696 for (; it != _route.end(); ++it) {
697 if (!(*it)->flag(WPT_DEPARTURE)) {
702 // erase() invalidates iterators, so grab now
704 if (it == _route.end()) {
706 enroute = new NavaidWaypoint(_destination.get(), NULL);
712 _route.erase(_route.begin(), it);
719 buildDeparture(enroute, wps);
720 for (it = wps.begin(); it != wps.end(); ++it) {
721 (*it)->setFlag(WPT_DEPARTURE);
722 (*it)->setFlag(WPT_GENERATED);
724 _route.insert(_route.begin(), wps.begin(), wps.end());
730 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
732 string runwayId(departure->getStringValue("runway"));
733 if (!_departure->hasRunwayWithIdent(runwayId)) {
734 // valid airport, but no runway selected, so just the airport noide itself
735 wps.push_back(new NavaidWaypoint(_departure.get(), NULL));
739 FGRunway* r = _departure->getRunwayByIdent(runwayId);
740 string sidId = departure->getStringValue("sid");
741 flightgear::SID* sid = _departure->findSIDWithIdent(sidId);
743 // valid runway, but no SID selected/found, so just the runway node for now
744 if (!sidId.empty() && (sidId != "(none)")) {
745 SG_LOG(SG_AUTOPILOT, SG_INFO, "SID not found:" << sidId);
748 wps.push_back(new RunwayWaypt(r, NULL));
752 // we have a valid SID, awesome
753 string trans(departure->getStringValue("transition"));
754 WayptRef t = sid->findTransitionByName(trans);
756 t = sid->findBestTransition(enroute->position());
759 sid->route(r, t, wps);
760 if (!wps.empty() && wps.front()->flag(WPT_DYNAMIC)) {
761 // ensure first waypoint is static, to simplify other computations
762 wps.insert(wps.begin(), new RunwayWaypt(r, NULL));
766 void FGRouteMgr::arrivalChanged()
768 // remove existing arrival waypoints
769 WayptVec::reverse_iterator rit = _route.rbegin();
770 for (; rit != _route.rend(); ++rit) {
771 if (!(*rit)->flag(WPT_ARRIVAL)) {
776 // erase() invalidates iterators, so grab now
778 WayptVec::iterator it;
780 if (rit != _route.rend()) {
782 it = rit.base(); // convert to fwd iterator
787 _route.erase(it, _route.end());
790 buildArrival(enroute, wps);
791 for (it = wps.begin(); it != wps.end(); ++it) {
792 (*it)->setFlag(WPT_ARRIVAL);
793 (*it)->setFlag(WPT_GENERATED);
795 _route.insert(_route.end(), wps.begin(), wps.end());
801 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
807 string runwayId(destination->getStringValue("runway"));
808 if (!_destination->hasRunwayWithIdent(runwayId)) {
809 // valid airport, but no runway selected, so just the airport node itself
810 wps.push_back(new NavaidWaypoint(_destination.get(), NULL));
814 FGRunway* r = _destination->getRunwayByIdent(runwayId);
815 string starId = destination->getStringValue("star");
816 STAR* star = _destination->findSTARWithIdent(starId);
818 // valid runway, but no STAR selected/found, so just the runway node for now
819 wps.push_back(new RunwayWaypt(r, NULL));
823 // we have a valid STAR
824 string trans(destination->getStringValue("transition"));
825 WayptRef t = star->findTransitionByName(trans);
827 t = star->findBestTransition(enroute->position());
830 _destination->buildApproach(t, star, r, wps);
833 void FGRouteMgr::waypointsChanged()
838 void FGRouteMgr::insertWayptAtIndex(Waypt* aWpt, int aIndex)
845 if ((aIndex == -1) || (aIndex > (int) _route.size())) {
846 index = _route.size();
849 WayptVec::iterator it = _route.begin();
852 if (_currentIndex >= index) {
856 _route.insert(it, aWpt);
859 _edited->fireValueChanged();
862 WayptRef FGRouteMgr::waypointFromString(const string& tgt )
864 string target(boost::to_upper_copy(tgt));
868 double altFt = cruise->getDoubleValue("altitude-ft");
869 RouteRestriction altSetting = RESTRICT_NONE;
871 size_t pos = target.find( '@' );
872 if ( pos != string::npos ) {
873 altFt = atof( target.c_str() + pos + 1 );
874 target = target.substr( 0, pos );
875 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
876 altFt *= SG_METER_TO_FEET;
877 altSetting = RESTRICT_AT;
881 pos = target.find( ',' );
882 if ( pos != string::npos ) {
883 double lon = atof( target.substr(0, pos).c_str());
884 double lat = atof( target.c_str() + pos + 1);
886 char ew = (lon < 0.0) ? 'W' : 'E';
887 char ns = (lat < 0.0) ? 'S' : 'N';
888 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
890 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
891 if (altSetting != RESTRICT_NONE) {
892 wpt->setAltitude(altFt, altSetting);
898 if (_route.empty()) {
899 // route is empty, use current position
900 basePosition = SGGeod::fromDeg(lon->getDoubleValue(), lat->getDoubleValue());
902 basePosition = _route.back()->position();
905 string_list pieces(simgear::strutils::split(target, "/"));
906 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
908 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
912 if (pieces.size() == 1) {
913 wpt = new NavaidWaypoint(p, NULL);
914 } else if (pieces.size() == 3) {
915 // navaid/radial/distance-nm notation
916 double radial = atof(pieces[1].c_str()),
917 distanceNm = atof(pieces[2].c_str());
918 radial += magvar->getDoubleValue(); // convert to true bearing
919 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
920 } else if (pieces.size() == 2) {
921 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
923 SG_LOG(SG_AUTOPILOT, SG_INFO, "Waypoint is not an airport:" << pieces.front());
927 if (!apt->hasRunwayWithIdent(pieces[1])) {
928 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
932 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
933 wpt = new NavaidWaypoint(runway, NULL);
934 } else if (pieces.size() == 4) {
935 // navid/radial/navid/radial notation
936 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
938 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
942 double r1 = atof(pieces[1].c_str()),
943 r2 = atof(pieces[3].c_str());
944 r1 += magvar->getDoubleValue();
945 r2 += magvar->getDoubleValue();
948 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
950 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << target);
954 std::string name = p->ident() + "-" + p2->ident();
955 wpt = new BasicWaypt(intersection, name, NULL);
959 SG_LOG(SG_AUTOPILOT, SG_INFO, "Unable to parse waypoint:" << target);
963 if (altSetting != RESTRICT_NONE) {
964 wpt->setAltitude(altFt, altSetting);
969 // mirror internal route to the property system for inspection by other subsystems
970 void FGRouteMgr::update_mirror()
972 mirror->removeChildren("wp");
974 int num = numWaypts();
975 for (int i = 0; i < num; i++) {
976 Waypt* wp = _route[i];
977 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
979 const SGGeod& pos(wp->position());
980 prop->setStringValue("id", wp->ident().c_str());
981 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
982 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
984 // leg course+distance
986 Waypt* next = _route[i+1];
987 std::pair<double, double> crsDist =
988 next->courseAndDistanceFrom(pos);
989 prop->setDoubleValue("leg-bearing-true-deg", crsDist.first);
990 prop->setDoubleValue("leg-distance-nm", crsDist.second * SG_METER_TO_NM);
993 if (wp->altitudeRestriction() != RESTRICT_NONE) {
994 double ft = wp->altitudeFt();
995 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
996 prop->setDoubleValue("altitude-ft", ft);
997 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
999 prop->setDoubleValue("altitude-m", -9999.9);
1000 prop->setDoubleValue("altitude-ft", -9999.9);
1003 if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
1004 prop->setDoubleValue("speed-mach", wp->speedMach());
1005 } else if (wp->speedRestriction() != RESTRICT_NONE) {
1006 prop->setDoubleValue("speed-kts", wp->speedKts());
1009 if (wp->flag(WPT_ARRIVAL)) {
1010 prop->setBoolValue("arrival", true);
1013 if (wp->flag(WPT_DEPARTURE)) {
1014 prop->setBoolValue("departure", true);
1017 if (wp->flag(WPT_MISS)) {
1018 prop->setBoolValue("missed-approach", true);
1021 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
1022 } // of waypoint iteration
1024 // set number as listener attachment point
1025 mirror->setIntValue("num", _route.size());
1027 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1028 FGDialog* rmDlg = gui->getDialog("route-manager");
1030 rmDlg->updateValues();
1034 // command interface /autopilot/route-manager/input:
1036 // @CLEAR ... clear route
1037 // @POP ... remove first entry
1038 // @DELETE3 ... delete 4th entry
1039 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
1040 // KSFO@900 ... append "KSFO@900"
1042 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
1044 const char *s = prop->getStringValue();
1045 if (strlen(s) == 0) {
1049 if (!strcmp(s, "@CLEAR"))
1051 else if (!strcmp(s, "@ACTIVATE"))
1053 else if (!strcmp(s, "@LOAD")) {
1054 SGPath path(mgr->_pathNode->getStringValue());
1055 mgr->loadRoute(path);
1056 } else if (!strcmp(s, "@SAVE")) {
1057 SGPath path(mgr->_pathNode->getStringValue());
1058 mgr->saveRoute(path);
1059 } else if (!strcmp(s, "@NEXT")) {
1060 mgr->jumpToIndex(mgr->_currentIndex + 1);
1061 } else if (!strcmp(s, "@PREVIOUS")) {
1062 mgr->jumpToIndex(mgr->_currentIndex - 1);
1063 } else if (!strncmp(s, "@JUMP", 5)) {
1064 mgr->jumpToIndex(atoi(s + 5));
1065 } else if (!strncmp(s, "@DELETE", 7))
1066 mgr->removeWayptAtIndex(atoi(s + 7));
1067 else if (!strncmp(s, "@INSERT", 7)) {
1069 int pos = strtol(s + 7, &r, 10);
1075 mgr->insertWayptAtIndex(mgr->waypointFromString(r), pos);
1076 } else if (!strncmp(s, "@ROUTE", 6)) {
1078 int endIndex = strtol(s + 6, &r, 10);
1079 RouteType rt = (RouteType) mgr->_routingType->getIntValue();
1080 mgr->routeToIndex(endIndex, rt);
1081 } else if (!strcmp(s, "@AUTOROUTE")) {
1083 } else if (!strcmp(s, "@POSINIT")) {
1084 mgr->initAtPosition();
1086 mgr->insertWayptAtIndex(mgr->waypointFromString(s), -1);
1089 void FGRouteMgr::initAtPosition()
1091 if (isRouteActive()) {
1092 return; // don't mess with the active route
1095 if (haveUserWaypoints()) {
1096 // user has already defined, loaded or entered a route, again
1097 // don't interfere with it
1101 if (airborne->getBoolValue()) {
1102 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
1104 departure->setStringValue("runway", "");
1109 SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(),
1110 lat->getDoubleValue(), alt->getDoubleValue());
1112 _departure = FGAirport::findClosest(pos, 20.0);
1114 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
1115 departure->setStringValue("runway", "");
1120 std::string rwy = departure->getStringValue("runway");
1122 // runway already set, fine
1126 FGRunway* r = _departure->findBestRunwayForPos(pos);
1131 departure->setStringValue("runway", r->ident().c_str());
1132 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
1133 << _departure->ident() << " on runway " << r->ident());
1136 bool FGRouteMgr::haveUserWaypoints() const
1138 for (int i = 0; i < numWaypts(); i++) {
1139 if (!_route[i]->flag(WPT_GENERATED)) {
1140 // have a non-generated waypoint, we're done
1145 // all waypoints are generated
1149 bool FGRouteMgr::activate()
1151 if (isRouteActive()) {
1152 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
1157 currentWaypointChanged();
1159 /* double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
1160 totalDistance->setDoubleValue(routeDistanceNm);
1161 double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
1162 if (cruiseSpeedKts > 1.0) {
1163 // very very crude approximation, doesn't allow for climb / descent
1164 // performance or anything else at all
1165 ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
1168 active->setBoolValue(true);
1169 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
1174 void FGRouteMgr::sequence()
1176 if (!active->getBoolValue()) {
1177 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
1181 if (checkFinished()) {
1186 currentWaypointChanged();
1189 bool FGRouteMgr::checkFinished()
1191 if (_currentIndex < (int) _route.size()) {
1195 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
1196 _finished->fireValueChanged();
1197 active->setBoolValue(false);
1201 void FGRouteMgr::jumpToIndex(int index)
1203 if ((index < 0) || (index >= (int) _route.size())) {
1204 SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" <<
1205 index << ") to FGRouteMgr::jumpToIndex");
1209 if (_currentIndex == index) {
1213 // all the checks out the way, go ahead and update state
1214 _currentIndex = index;
1215 currentWaypointChanged();
1216 _currentWpt->fireValueChanged();
1219 void FGRouteMgr::currentWaypointChanged()
1221 Waypt* cur = currentWaypt();
1222 Waypt* next = nextWaypt();
1224 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
1225 wp1->getChild("id")->setStringValue(next ? next->ident() : "");
1227 _currentWpt->fireValueChanged();
1228 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _currentIndex);
1231 int FGRouteMgr::findWayptIndex(const SGGeod& aPos) const
1233 for (int i=0; i<numWaypts(); ++i) {
1234 if (_route[i]->matches(aPos)) {
1242 Waypt* FGRouteMgr::currentWaypt() const
1244 if ((_currentIndex < 0) || (_currentIndex >= numWaypts()))
1246 return wayptAtIndex(_currentIndex);
1249 Waypt* FGRouteMgr::previousWaypt() const
1251 if (_currentIndex == 0) {
1255 return wayptAtIndex(_currentIndex - 1);
1258 Waypt* FGRouteMgr::nextWaypt() const
1260 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numWaypts())) {
1264 return wayptAtIndex(_currentIndex + 1);
1267 Waypt* FGRouteMgr::wayptAtIndex(int index) const
1269 if ((index < 0) || (index >= numWaypts())) {
1270 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1273 return _route[index];
1276 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1278 if ((index < 0) || (index >= numWaypts())) {
1279 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1282 return mirror->getChild("wp", index);
1285 bool FGRouteMgr::saveRoute(const SGPath& path)
1287 SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
1289 SGPropertyNode_ptr d(new SGPropertyNode);
1290 SGPath path(_pathNode->getStringValue());
1291 d->setIntValue("version", 2);
1294 d->setStringValue("departure/airport", _departure->ident());
1295 d->setStringValue("departure/sid", departure->getStringValue("sid"));
1296 d->setStringValue("departure/runway", departure->getStringValue("runway"));
1300 d->setStringValue("destination/airport", _destination->ident());
1301 d->setStringValue("destination/star", destination->getStringValue("star"));
1302 d->setStringValue("destination/transition", destination->getStringValue("transition"));
1303 d->setStringValue("destination/runway", destination->getStringValue("runway"));
1307 SGPropertyNode* routeNode = d->getChild("route", 0, true);
1308 for (unsigned int i=0; i<_route.size(); ++i) {
1309 Waypt* wpt = _route[i];
1310 wpt->saveAsNode(routeNode->getChild("wp", i, true));
1311 } // of waypoint iteration
1312 writeProperties(path.str(), d, true /* write-all */);
1314 } catch (sg_exception& e) {
1315 SG_LOG(SG_IO, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
1320 bool FGRouteMgr::loadRoute(const SGPath& path)
1324 SG_LOG(SG_IO, SG_ALERT, "Failed to load flight-plan '" << path.str()
1325 << "'. The file does not exist.");
1329 // deactivate route first
1330 active->setBoolValue(false);
1332 SGPropertyNode_ptr routeData(new SGPropertyNode);
1334 SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
1337 readProperties(path.str(), routeData);
1338 } catch (sg_exception& ) {
1339 // if XML parsing fails, the file might be simple textual list of waypoints
1340 return loadPlainTextRoute(path);
1344 int version = routeData->getIntValue("version", 1);
1346 loadVersion1XMLRoute(routeData);
1347 } else if (version == 2) {
1348 loadVersion2XMLRoute(routeData);
1350 throw sg_io_exception("unsupported XML route version");
1353 } catch (sg_exception& e) {
1354 SG_LOG(SG_IO, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
1355 << "'. " << e.getMessage());
1360 void FGRouteMgr::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
1363 SGPropertyNode* dep = routeData->getChild("departure");
1365 string depIdent = dep->getStringValue("airport");
1366 _departure = (FGAirport*) fgFindAirportID(depIdent);
1367 departure->setStringValue("runway", dep->getStringValue("runway"));
1368 departure->setStringValue("sid", dep->getStringValue("sid"));
1369 departure->setStringValue("transition", dep->getStringValue("transition"));
1373 SGPropertyNode* dst = routeData->getChild("destination");
1375 _destination = (FGAirport*) fgFindAirportID(dst->getStringValue("airport"));
1376 destination->setStringValue("runway", dst->getStringValue("runway"));
1377 destination->setStringValue("star", dst->getStringValue("star"));
1378 destination->setStringValue("transition", dst->getStringValue("transition"));
1382 SGPropertyNode* alt = routeData->getChild("alternate");
1384 alternate->setStringValue(alt->getStringValue("airport"));
1385 } // of cruise data loading
1388 SGPropertyNode* crs = routeData->getChild("cruise");
1390 cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
1391 cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
1392 cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
1393 } // of cruise data loading
1397 void FGRouteMgr::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
1399 loadXMLRouteHeader(routeData);
1403 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
1404 for (int i=0; i<routeNode->nChildren(); ++i) {
1405 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
1406 WayptRef wpt = Waypt::createFromProperties(NULL, wpNode);
1407 wpts.push_back(wpt);
1408 } // of route iteration
1413 void FGRouteMgr::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
1415 loadXMLRouteHeader(routeData);
1419 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
1420 for (int i=0; i<routeNode->nChildren(); ++i) {
1421 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
1422 WayptRef wpt = parseVersion1XMLWaypt(wpNode);
1423 wpts.push_back(wpt);
1424 } // of route iteration
1429 WayptRef FGRouteMgr::parseVersion1XMLWaypt(SGPropertyNode* aWP)
1432 if (!_route.empty()) {
1433 lastPos = _route.back()->position();
1434 } else if (_departure) {
1435 lastPos = _departure->geod();
1439 string ident(aWP->getStringValue("ident"));
1440 if (aWP->hasChild("longitude-deg")) {
1441 // explicit longitude/latitude
1442 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
1443 aWP->getDoubleValue("latitude-deg")), ident, NULL);
1446 string nid = aWP->getStringValue("navid", ident.c_str());
1447 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
1449 throw sg_io_exception("bad route file, unknown navid:" + nid);
1452 SGGeod pos(p->geod());
1453 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
1454 double radialDeg = aWP->getDoubleValue("offset-radial");
1455 // convert magnetic radial to a true radial!
1456 radialDeg += magvar->getDoubleValue();
1457 double offsetNm = aWP->getDoubleValue("offset-nm");
1459 SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
1462 w = new BasicWaypt(pos, ident, NULL);
1465 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
1466 if (altFt > -9990.0) {
1467 w->setAltitude(altFt, RESTRICT_AT);
1473 bool FGRouteMgr::loadPlainTextRoute(const SGPath& path)
1476 sg_gzifstream in(path.str().c_str());
1477 if (!in.is_open()) {
1478 throw sg_io_exception("Cannot open file for reading.");
1484 getline(in, line, '\n');
1485 // trim CR from end of line, if found
1486 if (line[line.size() - 1] == '\r') {
1487 line.erase(line.size() - 1, 1);
1490 line = simgear::strutils::strip(line);
1491 if (line.empty() || (line[0] == '#')) {
1492 continue; // ignore empty/comment lines
1495 WayptRef w = waypointFromString(line);
1497 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
1501 } // of line iteration
1505 } catch (sg_exception& e) {
1506 SG_LOG(SG_IO, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
1511 const char* FGRouteMgr::getDepartureICAO() const
1517 return _departure->ident().c_str();
1520 const char* FGRouteMgr::getDepartureName() const
1526 return _departure->name().c_str();
1529 void FGRouteMgr::setDepartureICAO(const char* aIdent)
1531 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1534 _departure = FGAirport::findByIdent(aIdent);
1540 const char* FGRouteMgr::getDestinationICAO() const
1542 if (!_destination) {
1546 return _destination->ident().c_str();
1549 const char* FGRouteMgr::getDestinationName() const
1551 if (!_destination) {
1555 return _destination->name().c_str();
1558 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1560 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1561 _destination = NULL;
1563 _destination = FGAirport::findByIdent(aIdent);
1569 FGAirportRef FGRouteMgr::departureAirport() const
1574 FGAirportRef FGRouteMgr::destinationAirport() const
1576 return _destination;
1579 FGRunway* FGRouteMgr::departureRunway() const
1585 string runwayId(departure->getStringValue("runway"));
1586 if (!_departure->hasRunwayWithIdent(runwayId)) {
1590 return _departure->getRunwayByIdent(runwayId);
1593 FGRunway* FGRouteMgr::destinationRunway() const
1595 if (!_destination) {
1599 string runwayId(destination->getStringValue("runway"));
1600 if (!_destination->hasRunwayWithIdent(runwayId)) {
1604 return _destination->getRunwayByIdent(runwayId);