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.
36 #include <simgear/compiler.h>
38 #include "route_mgr.hxx"
40 #include <boost/algorithm/string/case_conv.hpp>
41 #include <boost/tuple/tuple.hpp>
42 #include <boost/foreach.hpp>
44 #include <simgear/misc/strutils.hxx>
45 #include <simgear/structure/exception.hxx>
46 #include <simgear/structure/commands.hxx>
47 #include <simgear/misc/sg_path.hxx>
48 #include <simgear/sg_inlines.h>
50 #include "Main/fg_props.hxx"
51 #include "Navaids/positioned.hxx"
52 #include <Navaids/waypoint.hxx>
53 #include <Navaids/procedure.hxx>
54 #include "Airports/airport.hxx"
55 #include "Airports/runways.hxx"
56 #include <GUI/new_gui.hxx>
57 #include <GUI/dialog.hxx>
59 #define RM "/autopilot/route-manager/"
61 using namespace flightgear;
64 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
66 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
67 SGPath path(arg->getStringValue("path"));
68 return self->loadRoute(path);
71 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
73 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
74 SGPath path(arg->getStringValue("path"));
75 return self->saveRoute(path);
78 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
80 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
81 bool activate = arg->getBoolValue("activate", true);
91 static bool commandClearFlightPlan(const SGPropertyNode*)
93 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
98 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
100 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
101 int index = arg->getIntValue("index");
102 if ((index < 0) || (index >= self->numLegs())) {
106 self->jumpToIndex(index);
110 static bool commandInsertWaypt(const SGPropertyNode* arg)
112 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
113 int index = arg->getIntValue("index");
114 std::string ident(arg->getStringValue("id"));
115 int alt = arg->getIntValue("altitude-ft", -999);
116 int ias = arg->getIntValue("speed-knots", -999);
119 // lat/lon may be supplied to narrow down navaid search, or to specify
122 if (arg->hasChild("longitude-deg")) {
123 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
124 arg->getDoubleValue("latitude-deg"));
127 if (arg->hasChild("navaid")) {
128 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
130 if (arg->hasChild("navaid", 1)) {
131 // intersection of two radials
132 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
134 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
138 double r1 = arg->getDoubleValue("radial"),
139 r2 = arg->getDoubleValue("radial[1]");
142 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
144 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
145 << "," << p2->ident());
149 std::string name = p->ident() + "-" + p2->ident();
150 wp = new BasicWaypt(intersection, name, NULL);
151 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
152 // offset radial from navaid
153 double radial = arg->getDoubleValue("radial");
154 double distanceNm = arg->getDoubleValue("offset-nm");
155 //radial += magvar->getDoubleValue(); // convert to true bearing
156 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
158 wp = new NavaidWaypoint(p, NULL);
160 } else if (arg->hasChild("airport")) {
161 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
163 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
167 if (arg->hasChild("runway")) {
168 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
169 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
173 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
174 wp = new RunwayWaypt(runway, NULL);
176 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
178 } else if (arg->hasChild("text")) {
179 wp = self->waypointFromString(arg->getStringValue("text"));
180 } else if (!(pos == SGGeod())) {
181 // just a raw lat/lon
182 wp = new BasicWaypt(pos, ident, NULL);
184 return false; // failed to build waypoint
187 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
189 leg->setAltitude(RESTRICT_AT, alt);
193 leg->setSpeed(RESTRICT_AT, ias);
199 static bool commandDeleteWaypt(const SGPropertyNode* arg)
201 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
202 int index = arg->getIntValue("index");
203 self->removeLegAtIndex(index);
207 /////////////////////////////////////////////////////////////////////////////
209 FGRouteMgr::FGRouteMgr() :
211 input(fgGetNode( RM "input", true )),
212 mirror(fgGetNode( RM "route", true ))
214 listener = new InputListener(this);
215 input->setStringValue("");
216 input->addChangeListener(listener);
218 SGCommandMgr* cmdMgr = SGCommandMgr::instance();
219 cmdMgr->addCommand("define-user-waypoint", this, &FGRouteMgr::commandDefineUserWaypoint);
220 cmdMgr->addCommand("delete-user-waypoint", this, &FGRouteMgr::commandDeleteUserWaypoint);
222 cmdMgr->addCommand("load-flightplan", commandLoadFlightPlan);
223 cmdMgr->addCommand("save-flightplan", commandSaveFlightPlan);
224 cmdMgr->addCommand("activate-flightplan", commandActivateFlightPlan);
225 cmdMgr->addCommand("clear-flightplan", commandClearFlightPlan);
226 cmdMgr->addCommand("set-active-waypt", commandSetActiveWaypt);
227 cmdMgr->addCommand("insert-waypt", commandInsertWaypt);
228 cmdMgr->addCommand("delete-waypt", commandDeleteWaypt);
232 FGRouteMgr::~FGRouteMgr()
234 input->removeChangeListener(listener);
237 SGCommandMgr* cmdMgr = SGCommandMgr::instance();
238 //cmdMgr->removeCommand("define-user-waypoint");
243 void FGRouteMgr::init() {
244 SGPropertyNode_ptr rm(fgGetNode(RM));
246 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
248 departure = fgGetNode(RM "departure", true);
249 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
250 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
251 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
252 &FGRouteMgr::getDepartureRunway,
253 &FGRouteMgr::setDepartureRunway));
254 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
256 &FGRouteMgr::setSID));
258 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
259 &FGRouteMgr::getDepartureName, NULL));
260 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
261 &FGRouteMgr::getDestinationFieldElevation, NULL));
262 departure->getChild("etd", 0, true);
263 departure->getChild("takeoff-time", 0, true);
265 destination = fgGetNode(RM "destination", true);
266 destination->getChild("airport", 0, true);
268 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
269 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
270 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
271 &FGRouteMgr::getDestinationRunway,
272 &FGRouteMgr::setDestinationRunway));
273 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
274 &FGRouteMgr::getSTAR,
275 &FGRouteMgr::setSTAR));
276 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
277 &FGRouteMgr::getApproach,
278 &FGRouteMgr::setApproach));
280 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
281 &FGRouteMgr::getDestinationName, NULL));
282 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
283 &FGRouteMgr::getDestinationFieldElevation, NULL));
285 destination->getChild("eta", 0, true);
286 destination->getChild("touchdown-time", 0, true);
288 alternate = fgGetNode(RM "alternate", true);
289 alternate->getChild("airport", 0, true);
290 alternate->getChild("runway", 0, true);
292 cruise = fgGetNode(RM "cruise", true);
293 cruise->getChild("altitude-ft", 0, true);
294 cruise->setDoubleValue("altitude-ft", 10000.0);
295 cruise->getChild("flight-level", 0, true);
296 cruise->getChild("speed-kts", 0, true);
297 cruise->setDoubleValue("speed-kts", 160.0);
299 totalDistance = fgGetNode(RM "total-distance", true);
300 totalDistance->setDoubleValue(0.0);
301 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
302 distanceToGo->setDoubleValue(0.0);
304 ete = fgGetNode(RM "ete", true);
305 ete->setDoubleValue(0.0);
307 elapsedFlightTime = fgGetNode(RM "flight-time", true);
308 elapsedFlightTime->setDoubleValue(0.0);
310 active = fgGetNode(RM "active", true);
311 active->setBoolValue(false);
313 airborne = fgGetNode(RM "airborne", true);
314 airborne->setBoolValue(false);
316 _edited = fgGetNode(RM "signals/edited", true);
317 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
319 _currentWpt = fgGetNode(RM "current-wp", true);
320 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
321 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
323 wp0 = fgGetNode(RM "wp", 0, true);
324 wp0->getChild("id", 0, true);
325 wp0->getChild("dist", 0, true);
326 wp0->getChild("eta", 0, true);
327 wp0->getChild("bearing-deg", 0, true);
329 wp1 = fgGetNode(RM "wp", 1, true);
330 wp1->getChild("id", 0, true);
331 wp1->getChild("dist", 0, true);
332 wp1->getChild("eta", 0, true);
334 wpn = fgGetNode(RM "wp-last", 0, true);
335 wpn->getChild("dist", 0, true);
336 wpn->getChild("eta", 0, true);
338 _pathNode = fgGetNode(RM "file-path", 0, true);
342 void FGRouteMgr::postinit()
344 setFlightPlan(new FlightPlan());
346 SGPath path(_pathNode->getStringValue());
347 if (!path.isNull()) {
348 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
352 // this code only matters for the --wp option now - perhaps the option
353 // should be deprecated in favour of an explicit flight-plan file?
354 // then the global initial waypoint list could die.
355 string_list *waypoints = globals->get_initial_waypoints();
357 string_list::iterator it;
358 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
359 WayptRef w = waypointFromString(*it);
361 _plan->insertWayptAtIndex(w, -1);
365 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
369 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
370 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
372 // check airbone flag agrees with presets
375 void FGRouteMgr::bind() { }
376 void FGRouteMgr::unbind() { }
378 bool FGRouteMgr::isRouteActive() const
380 return active->getBoolValue();
383 bool FGRouteMgr::saveRoute(const SGPath& p)
389 return _plan->save(p);
392 bool FGRouteMgr::loadRoute(const SGPath& p)
394 FlightPlan* fp = new FlightPlan;
404 FlightPlanRef FGRouteMgr::flightPlan() const
409 void FGRouteMgr::setFlightPlan(const FlightPlanRef& plan)
416 _plan->removeDelegate(this);
417 active->setBoolValue(false);
421 _plan->addDelegate(this);
423 _flightplanChanged->fireValueChanged();
425 // fire all the callbacks!
429 currentWaypointChanged();
432 void FGRouteMgr::update( double dt )
435 return; // paused, nothing to do here
438 double gs = groundSpeed->getDoubleValue();
439 if (airborne->getBoolValue()) {
440 time_t now = time(NULL);
441 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
443 if (weightOnWheels->getBoolValue()) {
445 destination->setIntValue("touchdown-time", time(NULL));
446 airborne->setBoolValue(false);
448 } else { // not airborne
449 if (weightOnWheels->getBoolValue() || (gs < 40)) {
450 // either taking-off or rolling-out after touchdown
452 airborne->setBoolValue(true);
453 _takeoffTime = time(NULL); // start the clock
454 departure->setIntValue("takeoff-time", _takeoffTime);
458 if (!active->getBoolValue()) {
462 // basic course/distance information
463 SGGeod currentPos = globals->get_aircraft_position();
465 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
472 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
474 // update wp0 / wp1 / wp-last
475 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
476 wp0->setDoubleValue("true-bearing-deg", courseDeg);
477 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
478 wp0->setDoubleValue("bearing-deg", courseDeg);
479 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
481 double totalPathDistanceNm = _plan->totalDistanceNm();
482 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
484 // total distance to go, is direct distance to wp0, plus the remaining
485 // path distance from wp0
486 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
488 wp0->setDoubleValue("distance-along-route-nm",
489 leg->distanceAlongRoute());
490 wp0->setDoubleValue("remaining-distance-nm",
491 totalPathDistanceNm - leg->distanceAlongRoute());
493 FlightPlan::Leg* nextLeg = _plan->nextLeg();
495 boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
497 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
498 wp1->setDoubleValue("true-bearing-deg", courseDeg);
499 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
500 wp1->setDoubleValue("bearing-deg", courseDeg);
501 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
502 wp1->setDoubleValue("distance-along-route-nm",
503 nextLeg->distanceAlongRoute());
504 wp1->setDoubleValue("remaining-distance-nm",
505 totalPathDistanceNm - nextLeg->distanceAlongRoute());
508 distanceToGo->setDoubleValue(totalDistanceRemaining);
509 wpn->setDoubleValue("dist", totalDistanceRemaining);
510 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
511 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
514 void FGRouteMgr::clearRoute()
521 Waypt* FGRouteMgr::currentWaypt() const
523 if (_plan && _plan->currentLeg()) {
524 return _plan->currentLeg()->waypoint();
530 int FGRouteMgr::currentIndex() const
536 return _plan->currentIndex();
539 Waypt* FGRouteMgr::wayptAtIndex(int index) const
542 throw sg_range_exception("wayptAtindex: no flightplan");
545 return _plan->legAtIndex(index)->waypoint();
548 int FGRouteMgr::numLegs() const
551 return _plan->numLegs();
557 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
559 double speed = groundSpeed->getDoubleValue();
561 aProp->setStringValue("--:--");
566 double eta = aDistance * SG_METER_TO_NM / speed;
567 if ( eta >= 100.0 ) {
568 eta = 99.999; // clamp
571 if ( eta < (1.0/6.0) ) {
572 eta *= 60.0; // within 10 minutes, bump up to min/secs
575 int major = (int)eta,
576 minor = (int)((eta - (int)eta) * 60.0);
577 snprintf( eta_str, 64, "%d:%02d", major, minor );
578 aProp->setStringValue( eta_str );
581 void FGRouteMgr::removeLegAtIndex(int aIndex)
587 _plan->deleteIndex(aIndex);
590 void FGRouteMgr::waypointsChanged()
593 _edited->fireValueChanged();
596 // mirror internal route to the property system for inspection by other subsystems
597 void FGRouteMgr::update_mirror()
599 mirror->removeChildren("wp");
600 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
601 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
604 mirror->setIntValue("num", 0);
606 rmDlg->updateValues();
611 int num = _plan->numLegs();
613 for (int i = 0; i < num; i++) {
614 FlightPlan::Leg* leg = _plan->legAtIndex(i);
615 WayptRef wp = leg->waypoint();
616 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
618 const SGGeod& pos(wp->position());
619 prop->setStringValue("id", wp->ident().c_str());
620 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
621 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
623 // leg course+distance
625 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
626 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
627 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
629 if (leg->altitudeRestriction() != RESTRICT_NONE) {
630 double ft = leg->altitudeFt();
631 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
632 prop->setDoubleValue("altitude-ft", ft);
633 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
635 prop->setDoubleValue("altitude-m", -9999.9);
636 prop->setDoubleValue("altitude-ft", -9999.9);
639 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
640 prop->setDoubleValue("speed-mach", leg->speedMach());
641 } else if (leg->speedRestriction() != RESTRICT_NONE) {
642 prop->setDoubleValue("speed-kts", leg->speedKts());
645 if (wp->flag(WPT_ARRIVAL)) {
646 prop->setBoolValue("arrival", true);
649 if (wp->flag(WPT_DEPARTURE)) {
650 prop->setBoolValue("departure", true);
653 if (wp->flag(WPT_MISS)) {
654 prop->setBoolValue("missed-approach", true);
657 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
658 } // of waypoint iteration
660 // set number as listener attachment point
661 mirror->setIntValue("num", _plan->numLegs());
664 rmDlg->updateValues();
667 totalDistance->setDoubleValue(_plan->totalDistanceNm());
670 // command interface /autopilot/route-manager/input:
672 // @CLEAR ... clear route
673 // @POP ... remove first entry
674 // @DELETE3 ... delete 4th entry
675 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
676 // KSFO@900 ... append "KSFO@900"
678 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
680 const char *s = prop->getStringValue();
681 if (strlen(s) == 0) {
685 if (!strcmp(s, "@CLEAR"))
687 else if (!strcmp(s, "@ACTIVATE"))
689 else if (!strcmp(s, "@LOAD")) {
690 SGPath path(mgr->_pathNode->getStringValue());
691 mgr->loadRoute(path);
692 } else if (!strcmp(s, "@SAVE")) {
693 SGPath path(mgr->_pathNode->getStringValue());
694 mgr->saveRoute(path);
695 } else if (!strcmp(s, "@NEXT")) {
696 mgr->jumpToIndex(mgr->currentIndex() + 1);
697 } else if (!strcmp(s, "@PREVIOUS")) {
698 mgr->jumpToIndex(mgr->currentIndex() - 1);
699 } else if (!strncmp(s, "@JUMP", 5)) {
700 mgr->jumpToIndex(atoi(s + 5));
701 } else if (!strncmp(s, "@DELETE", 7))
702 mgr->removeLegAtIndex(atoi(s + 7));
703 else if (!strncmp(s, "@INSERT", 7)) {
705 int pos = strtol(s + 7, &r, 10);
711 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
713 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
716 bool FGRouteMgr::activate()
719 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
723 if (isRouteActive()) {
724 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
728 _plan->setCurrentIndex(0);
729 active->setBoolValue(true);
730 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
734 void FGRouteMgr::deactivate()
736 if (!isRouteActive()) {
740 SG_LOG(SG_AUTOPILOT, SG_INFO, "deactivating flight plan");
741 active->setBoolValue(false);
744 void FGRouteMgr::jumpToIndex(int index)
750 _plan->setCurrentIndex(index);
753 void FGRouteMgr::currentWaypointChanged()
755 Waypt* cur = currentWaypt();
756 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
758 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
759 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
761 _currentWpt->fireValueChanged();
762 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
765 const char* FGRouteMgr::getDepartureICAO() const
767 if (!_plan || !_plan->departureAirport()) {
771 return _plan->departureAirport()->ident().c_str();
774 const char* FGRouteMgr::getDepartureName() const
776 if (!_plan || !_plan->departureAirport()) {
780 return _plan->departureAirport()->name().c_str();
783 const char* FGRouteMgr::getDepartureRunway() const
785 if (_plan && _plan->departureRunway()) {
786 return _plan->departureRunway()->ident().c_str();
792 void FGRouteMgr::setDepartureRunway(const char* aIdent)
794 FGAirport* apt = _plan->departureAirport();
795 if (!apt || (aIdent == NULL)) {
796 _plan->setDeparture(apt);
797 } else if (apt->hasRunwayWithIdent(aIdent)) {
798 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
802 void FGRouteMgr::setDepartureICAO(const char* aIdent)
804 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
805 _plan->setDeparture((FGAirport*) NULL);
807 _plan->setDeparture(FGAirport::findByIdent(aIdent));
811 const char* FGRouteMgr::getSID() const
813 if (_plan && _plan->sid()) {
814 return _plan->sid()->ident().c_str();
820 static double headingDiffDeg(double a, double b)
822 double rawDiff = b - a;
823 SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
827 flightgear::SID* createDefaultSID(FGRunway* aRunway, double enrouteCourse)
833 double runwayElevFt = aRunway->end().getElevationFt();
835 std::ostringstream ss;
836 ss << aRunway->ident() << "-3";
838 SGGeod p = aRunway->pointOnCenterline(aRunway->lengthM() + (3.0 * SG_NM_TO_METER));
839 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
840 w->setAltitude(runwayElevFt + 3000.0, RESTRICT_AT);
844 ss << aRunway->ident() << "-6";
845 p = aRunway->pointOnCenterline(aRunway->lengthM() + (6.0 * SG_NM_TO_METER));
846 w = new BasicWaypt(p, ss.str(), NULL);
847 w->setAltitude(runwayElevFt + 6000.0, RESTRICT_AT);
850 if (enrouteCourse >= 0.0) {
851 // valid enroute course
853 double course = aRunway->headingDeg();
855 while (fabs(diff = headingDiffDeg(course, enrouteCourse)) > 45.0) {
856 // turn in the sign of the heading change 45 degrees
857 course += copysign(45.0, diff);
859 ss << "DEP-" << index++;
860 SGGeod pos = wpts.back()->position();
861 pos = SGGeodesy::direct(pos, course, 3.0 * SG_NM_TO_METER);
862 w = new BasicWaypt(pos, ss.str(), NULL);
866 // no enroute course, just keep runway heading
868 ss << aRunway->ident() << "-9";
869 p = aRunway->pointOnCenterline(aRunway->lengthM() + (9.0 * SG_NM_TO_METER));
870 w = new BasicWaypt(p, ss.str(), NULL);
871 w->setAltitude(runwayElevFt + 9000.0, RESTRICT_AT);
875 BOOST_FOREACH(Waypt* w, wpts) {
876 w->setFlag(WPT_DEPARTURE);
877 w->setFlag(WPT_GENERATED);
880 return flightgear::SID::createTempSID("DEFAULT", aRunway, wpts);
883 void FGRouteMgr::setSID(const char* aIdent)
885 FGAirport* apt = _plan->departureAirport();
886 if (!apt || (aIdent == NULL)) {
887 _plan->setSID((flightgear::SID*) NULL);
891 if (!strcmp(aIdent, "DEFAULT")) {
892 double enrouteCourse = -1.0;
893 if (_plan->destinationAirport()) {
894 enrouteCourse = SGGeodesy::courseDeg(apt->geod(), _plan->destinationAirport()->geod());
897 _plan->setSID(createDefaultSID(_plan->departureRunway(), enrouteCourse));
901 string ident(aIdent);
902 size_t hyphenPos = ident.find('-');
903 if (hyphenPos != string::npos) {
904 string sidIdent = ident.substr(0, hyphenPos);
905 string transIdent = ident.substr(hyphenPos + 1);
907 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
908 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
909 _plan->setSID(trans);
911 _plan->setSID(apt->findSIDWithIdent(aIdent));
915 const char* FGRouteMgr::getDestinationICAO() const
917 if (!_plan || !_plan->destinationAirport()) {
921 return _plan->destinationAirport()->ident().c_str();
924 const char* FGRouteMgr::getDestinationName() const
926 if (!_plan || !_plan->destinationAirport()) {
930 return _plan->destinationAirport()->name().c_str();
933 void FGRouteMgr::setDestinationICAO(const char* aIdent)
935 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
936 _plan->setDestination((FGAirport*) NULL);
938 _plan->setDestination(FGAirport::findByIdent(aIdent));
942 const char* FGRouteMgr::getDestinationRunway() const
944 if (_plan && _plan->destinationRunway()) {
945 return _plan->destinationRunway()->ident().c_str();
951 void FGRouteMgr::setDestinationRunway(const char* aIdent)
953 FGAirport* apt = _plan->destinationAirport();
954 if (!apt || (aIdent == NULL)) {
955 _plan->setDestination(apt);
956 } else if (apt->hasRunwayWithIdent(aIdent)) {
957 _plan->setDestination(apt->getRunwayByIdent(aIdent));
961 const char* FGRouteMgr::getApproach() const
963 if (_plan && _plan->approach()) {
964 return _plan->approach()->ident().c_str();
970 flightgear::Approach* createDefaultApproach(FGRunway* aRunway, double aEnrouteCourse)
976 double thresholdElevFt = aRunway->threshold().getElevationFt();
977 const double approachHeightFt = 2000.0;
978 double glideslopeDistanceM = (approachHeightFt * SG_FEET_TO_METER) /
979 tan(3.0 * SG_DEGREES_TO_RADIANS);
981 std::ostringstream ss;
982 ss << aRunway->ident() << "-12";
984 SGGeod p = aRunway->pointOnCenterline(-12.0 * SG_NM_TO_METER);
985 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
986 w->setAltitude(thresholdElevFt + 4000, RESTRICT_AT);
989 // work back form the first point on the centerline
991 if (aEnrouteCourse >= 0.0) {
992 // valid enroute course
994 double course = aRunway->headingDeg();
996 while (fabs(diff = headingDiffDeg(aEnrouteCourse, course)) > 45.0) {
997 // turn in the sign of the heading change 45 degrees
998 course -= copysign(45.0, diff);
1000 ss << "APP-" << index++;
1001 SGGeod pos = wpts.front()->position();
1002 pos = SGGeodesy::direct(pos, course + 180.0, 3.0 * SG_NM_TO_METER);
1003 w = new BasicWaypt(pos, ss.str(), NULL);
1004 wpts.insert(wpts.begin(), w);
1008 p = aRunway->pointOnCenterline(-8.0 * SG_NM_TO_METER);
1010 ss << aRunway->ident() << "-8";
1011 w = new BasicWaypt(p, ss.str(), NULL);
1012 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1015 p = aRunway->pointOnCenterline(-glideslopeDistanceM);
1017 ss << aRunway->ident() << "-GS";
1018 w = new BasicWaypt(p, ss.str(), NULL);
1019 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1022 BOOST_FOREACH(Waypt* w, wpts) {
1023 w->setFlag(WPT_APPROACH);
1024 w->setFlag(WPT_GENERATED);
1027 return Approach::createTempApproach("DEFAULT", aRunway, wpts);
1030 void FGRouteMgr::setApproach(const char* aIdent)
1032 FGAirport* apt = _plan->destinationAirport();
1033 if (!strcmp(aIdent, "DEFAULT")) {
1034 double enrouteCourse = -1.0;
1035 if (_plan->departureAirport()) {
1036 enrouteCourse = SGGeodesy::courseDeg(_plan->departureAirport()->geod(), apt->geod());
1039 _plan->setApproach(createDefaultApproach(_plan->destinationRunway(), enrouteCourse));
1043 if (!apt || (aIdent == NULL)) {
1044 _plan->setApproach(NULL);
1046 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1050 const char* FGRouteMgr::getSTAR() const
1052 if (_plan && _plan->star()) {
1053 return _plan->star()->ident().c_str();
1059 void FGRouteMgr::setSTAR(const char* aIdent)
1061 FGAirport* apt = _plan->destinationAirport();
1062 if (!apt || (aIdent == NULL)) {
1063 _plan->setSTAR((STAR*) NULL);
1067 string ident(aIdent);
1068 size_t hyphenPos = ident.find('-');
1069 if (hyphenPos != string::npos) {
1070 string starIdent = ident.substr(0, hyphenPos);
1071 string transIdent = ident.substr(hyphenPos + 1);
1073 STAR* star = apt->findSTARWithIdent(starIdent);
1074 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1075 _plan->setSTAR(trans);
1077 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1081 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1083 return _plan->waypointFromString(target);
1086 double FGRouteMgr::getDepartureFieldElevation() const
1088 if (!_plan || !_plan->departureAirport()) {
1092 return _plan->departureAirport()->elevation();
1095 double FGRouteMgr::getDestinationFieldElevation() const
1097 if (!_plan || !_plan->destinationAirport()) {
1101 return _plan->destinationAirport()->elevation();
1104 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1106 if ((index < 0) || (index >= numWaypts())) {
1107 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1110 return mirror->getChild("wp", index);
1113 bool FGRouteMgr::commandDefineUserWaypoint(const SGPropertyNode* arg)
1115 std::string ident = arg->getStringValue("ident");
1116 if (ident.empty()) {
1117 SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident defining user waypoint");
1121 // check for duplicate idents
1122 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1123 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1124 if (!dups.empty()) {
1125 SG_LOG(SG_AUTOPILOT, SG_WARN, "defineUserWaypoint: non-unique waypoint identifier:" << ident);
1129 SGGeod pos(SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1130 arg->getDoubleValue("latitude-deg")));
1131 FGPositioned::createUserWaypoint(ident, pos);
1135 bool FGRouteMgr::commandDeleteUserWaypoint(const SGPropertyNode* arg)
1137 std::string ident = arg->getStringValue("ident");
1138 if (ident.empty()) {
1139 SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident deleting user waypoint");
1143 return FGPositioned::deleteUserWaypoint(ident);