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.
32 #include <simgear/compiler.h>
34 #include "route_mgr.hxx"
36 #include <boost/algorithm/string/case_conv.hpp>
37 #include <boost/tuple/tuple.hpp>
38 #include <boost/foreach.hpp>
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/structure/commands.hxx>
43 #include <simgear/misc/sg_path.hxx>
44 #include <simgear/timing/sg_time.hxx>
45 #include <simgear/sg_inlines.h>
47 #include "Main/fg_props.hxx"
48 #include "Navaids/positioned.hxx"
49 #include <Navaids/waypoint.hxx>
50 #include <Navaids/procedure.hxx>
51 #include <Navaids/routePath.hxx>
53 #include "Airports/airport.hxx"
54 #include "Airports/runways.hxx"
55 #include <GUI/new_gui.hxx>
56 #include <GUI/dialog.hxx>
58 #define RM "/autopilot/route-manager/"
60 using namespace flightgear;
63 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
65 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
66 SGPath path(arg->getStringValue("path"));
67 return self->loadRoute(path);
70 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
72 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
73 SGPath path(arg->getStringValue("path"));
74 return self->saveRoute(path);
77 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
79 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
80 bool activate = arg->getBoolValue("activate", true);
90 static bool commandClearFlightPlan(const SGPropertyNode*)
92 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
97 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
99 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
100 int index = arg->getIntValue("index");
101 if ((index < 0) || (index >= self->numLegs())) {
105 self->jumpToIndex(index);
109 static bool commandInsertWaypt(const SGPropertyNode* arg)
111 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
112 int index = arg->getIntValue("index");
113 std::string ident(arg->getStringValue("id"));
114 int alt = arg->getIntValue("altitude-ft", -999);
115 int ias = arg->getIntValue("speed-knots", -999);
118 // lat/lon may be supplied to narrow down navaid search, or to specify
121 if (arg->hasChild("longitude-deg")) {
122 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
123 arg->getDoubleValue("latitude-deg"));
126 if (arg->hasChild("navaid")) {
127 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
129 if (arg->hasChild("navaid", 1)) {
130 // intersection of two radials
131 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
133 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
137 double r1 = arg->getDoubleValue("radial"),
138 r2 = arg->getDoubleValue("radial[1]");
141 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
143 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
144 << "," << p2->ident());
148 std::string name = p->ident() + "-" + p2->ident();
149 wp = new BasicWaypt(intersection, name, NULL);
150 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
151 // offset radial from navaid
152 double radial = arg->getDoubleValue("radial");
153 double distanceNm = arg->getDoubleValue("offset-nm");
154 //radial += magvar->getDoubleValue(); // convert to true bearing
155 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
157 wp = new NavaidWaypoint(p, NULL);
159 } else if (arg->hasChild("airport")) {
160 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
162 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
166 if (arg->hasChild("runway")) {
167 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
168 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
172 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
173 wp = new RunwayWaypt(runway, NULL);
175 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
177 } else if (arg->hasChild("text")) {
178 wp = self->waypointFromString(arg->getStringValue("text"));
179 } else if (!(pos == SGGeod())) {
180 // just a raw lat/lon
181 wp = new BasicWaypt(pos, ident, NULL);
183 return false; // failed to build waypoint
186 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
188 leg->setAltitude(RESTRICT_AT, alt);
192 leg->setSpeed(RESTRICT_AT, ias);
198 static bool commandDeleteWaypt(const SGPropertyNode* arg)
200 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
201 int index = arg->getIntValue("index");
202 self->removeLegAtIndex(index);
206 /////////////////////////////////////////////////////////////////////////////
208 FGRouteMgr::FGRouteMgr() :
210 input(fgGetNode( RM "input", true )),
211 mirror(fgGetNode( RM "route", true ))
213 listener = new InputListener(this);
214 input->setStringValue("");
215 input->addChangeListener(listener);
217 SGCommandMgr* cmdMgr = globals->get_commands();
218 cmdMgr->addCommand("define-user-waypoint", this, &FGRouteMgr::commandDefineUserWaypoint);
219 cmdMgr->addCommand("delete-user-waypoint", this, &FGRouteMgr::commandDeleteUserWaypoint);
221 cmdMgr->addCommand("load-flightplan", commandLoadFlightPlan);
222 cmdMgr->addCommand("save-flightplan", commandSaveFlightPlan);
223 cmdMgr->addCommand("activate-flightplan", commandActivateFlightPlan);
224 cmdMgr->addCommand("clear-flightplan", commandClearFlightPlan);
225 cmdMgr->addCommand("set-active-waypt", commandSetActiveWaypt);
226 cmdMgr->addCommand("insert-waypt", commandInsertWaypt);
227 cmdMgr->addCommand("delete-waypt", commandDeleteWaypt);
231 FGRouteMgr::~FGRouteMgr()
233 input->removeChangeListener(listener);
237 _plan->removeDelegate(this);
240 SGCommandMgr* cmdMgr = globals->get_commands();
241 cmdMgr->removeCommand("define-user-waypoint");
242 cmdMgr->removeCommand("delete-user-waypoint");
243 cmdMgr->removeCommand("load-flightplan");
244 cmdMgr->removeCommand("save-flightplan");
245 cmdMgr->removeCommand("activate-flightplan");
246 cmdMgr->removeCommand("clear-flightplan");
247 cmdMgr->removeCommand("set-active-waypt");
248 cmdMgr->removeCommand("insert-waypt");
249 cmdMgr->removeCommand("delete-waypt");
253 void FGRouteMgr::init() {
254 SGPropertyNode_ptr rm(fgGetNode(RM));
256 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
258 departure = fgGetNode(RM "departure", true);
259 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
260 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
261 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
262 &FGRouteMgr::getDepartureRunway,
263 &FGRouteMgr::setDepartureRunway));
264 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
266 &FGRouteMgr::setSID));
268 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
269 &FGRouteMgr::getDepartureName, NULL));
270 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
271 &FGRouteMgr::getDepartureFieldElevation, NULL));
272 departure->getChild("etd", 0, true);
273 departure->getChild("takeoff-time", 0, true);
275 destination = fgGetNode(RM "destination", true);
276 destination->getChild("airport", 0, true);
278 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
279 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
280 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
281 &FGRouteMgr::getDestinationRunway,
282 &FGRouteMgr::setDestinationRunway));
283 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
284 &FGRouteMgr::getSTAR,
285 &FGRouteMgr::setSTAR));
286 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
287 &FGRouteMgr::getApproach,
288 &FGRouteMgr::setApproach));
290 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
291 &FGRouteMgr::getDestinationName, NULL));
292 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
293 &FGRouteMgr::getDestinationFieldElevation, NULL));
295 destination->getChild("eta", 0, true);
296 destination->getChild("eta-seconds", 0, true);
297 destination->getChild("touchdown-time", 0, true);
299 alternate = fgGetNode(RM "alternate", true);
300 alternate->getChild("airport", 0, true);
301 alternate->getChild("runway", 0, true);
303 cruise = fgGetNode(RM "cruise", true);
304 cruise->getChild("altitude-ft", 0, true);
305 cruise->setDoubleValue("altitude-ft", 10000.0);
306 cruise->getChild("flight-level", 0, true);
307 cruise->getChild("speed-kts", 0, true);
308 cruise->setDoubleValue("speed-kts", 160.0);
310 totalDistance = fgGetNode(RM "total-distance", true);
311 totalDistance->setDoubleValue(0.0);
312 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
313 distanceToGo->setDoubleValue(0.0);
315 ete = fgGetNode(RM "ete", true);
316 ete->setDoubleValue(0.0);
318 elapsedFlightTime = fgGetNode(RM "flight-time", true);
319 elapsedFlightTime->setDoubleValue(0.0);
321 active = fgGetNode(RM "active", true);
322 active->setBoolValue(false);
324 airborne = fgGetNode(RM "airborne", true);
325 airborne->setBoolValue(false);
327 _edited = fgGetNode(RM "signals/edited", true);
328 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
330 _currentWpt = fgGetNode(RM "current-wp", true);
331 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
332 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
334 wp0 = fgGetNode(RM "wp", 0, true);
335 wp0->getChild("id", 0, true);
336 wp0->getChild("dist", 0, true);
337 wp0->getChild("eta", 0, true);
338 wp0->getChild("eta-seconds", 0, true);
339 wp0->getChild("bearing-deg", 0, true);
341 wp1 = fgGetNode(RM "wp", 1, true);
342 wp1->getChild("id", 0, true);
343 wp1->getChild("dist", 0, true);
344 wp1->getChild("eta", 0, true);
345 wp1->getChild("eta-seconds", 0, true);
347 wpn = fgGetNode(RM "wp-last", 0, true);
348 wpn->getChild("dist", 0, true);
349 wpn->getChild("eta", 0, true);
350 wpn->getChild("eta-seconds", 0, true);
352 _pathNode = fgGetNode(RM "file-path", 0, true);
356 void FGRouteMgr::postinit()
358 setFlightPlan(new FlightPlan());
360 SGPath path(_pathNode->getStringValue());
361 if (!path.isNull()) {
362 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
366 // this code only matters for the --wp option now - perhaps the option
367 // should be deprecated in favour of an explicit flight-plan file?
368 // then the global initial waypoint list could die.
369 string_list *waypoints = globals->get_initial_waypoints();
371 string_list::iterator it;
372 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
373 WayptRef w = waypointFromString(*it);
375 _plan->insertWayptAtIndex(w, -1);
379 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
383 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
384 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
386 // check airbone flag agrees with presets
389 void FGRouteMgr::bind() { }
390 void FGRouteMgr::unbind() { }
392 bool FGRouteMgr::isRouteActive() const
394 return active->getBoolValue();
397 bool FGRouteMgr::saveRoute(const SGPath& p)
403 return _plan->save(p);
406 bool FGRouteMgr::loadRoute(const SGPath& p)
408 FlightPlan* fp = new FlightPlan;
418 FlightPlanRef FGRouteMgr::flightPlan() const
423 void FGRouteMgr::setFlightPlan(const FlightPlanRef& plan)
430 _plan->removeDelegate(this);
431 active->setBoolValue(false);
435 _plan->addDelegate(this);
437 _flightplanChanged->fireValueChanged();
439 // fire all the callbacks!
443 currentWaypointChanged();
446 void FGRouteMgr::update( double dt )
449 return; // paused, nothing to do here
452 double gs = groundSpeed->getDoubleValue();
453 if (airborne->getBoolValue()) {
454 time_t now = globals->get_time_params()->get_cur_time();
455 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
457 if (weightOnWheels->getBoolValue()) {
459 destination->setIntValue("touchdown-time", now);
460 airborne->setBoolValue(false);
462 } else { // not airborne
463 if (weightOnWheels->getBoolValue() || (gs < 40)) {
464 // either taking-off or rolling-out after touchdown
466 airborne->setBoolValue(true);
467 _takeoffTime = globals->get_time_params()->get_cur_time(); // start the clock
468 departure->setIntValue("takeoff-time", _takeoffTime);
472 if (!active->getBoolValue()) {
476 // basic course/distance information
477 SGGeod currentPos = globals->get_aircraft_position();
479 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
484 // use RoutePath to compute location of active WP
485 RoutePath path(_plan);
486 SGGeod wpPos = path.positionForIndex(_plan->currentIndex());
487 double courseDeg, az2, distanceM;
488 SGGeodesy::inverse(currentPos, wpPos, courseDeg, az2, distanceM);
490 // update wp0 / wp1 / wp-last
491 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
492 wp0->setDoubleValue("true-bearing-deg", courseDeg);
493 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
494 wp0->setDoubleValue("bearing-deg", courseDeg);
495 setETAPropertyFromDistance(wp0, distanceM);
497 double totalPathDistanceNm = _plan->totalDistanceNm();
498 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
500 // total distance to go, is direct distance to wp0, plus the remaining
501 // path distance from wp0
502 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
504 wp0->setDoubleValue("distance-along-route-nm",
505 leg->distanceAlongRoute());
506 wp0->setDoubleValue("remaining-distance-nm",
507 totalPathDistanceNm - leg->distanceAlongRoute());
509 FlightPlan::Leg* nextLeg = _plan->nextLeg();
511 wpPos = path.positionForIndex(_plan->currentIndex() + 1);
512 SGGeodesy::inverse(currentPos, wpPos, courseDeg, az2, distanceM);
514 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
515 wp1->setDoubleValue("true-bearing-deg", courseDeg);
516 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
517 wp1->setDoubleValue("bearing-deg", courseDeg);
518 setETAPropertyFromDistance(wp1, distanceM);
519 wp1->setDoubleValue("distance-along-route-nm",
520 nextLeg->distanceAlongRoute());
521 wp1->setDoubleValue("remaining-distance-nm",
522 totalPathDistanceNm - nextLeg->distanceAlongRoute());
525 distanceToGo->setDoubleValue(totalDistanceRemaining);
526 wpn->setDoubleValue("dist", totalDistanceRemaining);
527 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
528 setETAPropertyFromDistance(wpn, totalDistanceRemaining);
531 void FGRouteMgr::clearRoute()
538 Waypt* FGRouteMgr::currentWaypt() const
540 if (_plan && _plan->currentLeg()) {
541 return _plan->currentLeg()->waypoint();
547 int FGRouteMgr::currentIndex() const
553 return _plan->currentIndex();
556 Waypt* FGRouteMgr::wayptAtIndex(int index) const
559 throw sg_range_exception("wayptAtindex: no flightplan");
562 return _plan->legAtIndex(index)->waypoint();
565 int FGRouteMgr::numLegs() const
568 return _plan->numLegs();
574 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
576 double speed = groundSpeed->getDoubleValue();
578 aProp->setStringValue("--:--");
583 double eta = aDistance * SG_METER_TO_NM / speed;
584 aProp->getChild("eta-seconds")->setIntValue( eta * 3600 );
585 if ( eta >= 100.0 ) {
586 eta = 99.999; // clamp
589 if ( eta < (1.0/6.0) ) {
590 eta *= 60.0; // within 10 minutes, bump up to min/secs
593 int major = (int)eta,
594 minor = (int)((eta - (int)eta) * 60.0);
595 snprintf( eta_str, 64, "%d:%02d", major, minor );
596 aProp->getChild("eta")->setStringValue( eta_str );
599 void FGRouteMgr::removeLegAtIndex(int aIndex)
605 _plan->deleteIndex(aIndex);
608 void FGRouteMgr::waypointsChanged()
611 _edited->fireValueChanged();
614 // mirror internal route to the property system for inspection by other subsystems
615 void FGRouteMgr::update_mirror()
617 mirror->removeChildren("wp");
618 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
619 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
622 mirror->setIntValue("num", 0);
624 rmDlg->updateValues();
629 int num = _plan->numLegs();
631 for (int i = 0; i < num; i++) {
632 FlightPlan::Leg* leg = _plan->legAtIndex(i);
633 WayptRef wp = leg->waypoint();
634 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
636 const SGGeod& pos(wp->position());
637 prop->setStringValue("id", wp->ident().c_str());
638 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
639 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
641 // leg course+distance
643 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
644 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
645 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
647 if (leg->altitudeRestriction() != RESTRICT_NONE) {
648 double ft = leg->altitudeFt();
649 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
650 prop->setDoubleValue("altitude-ft", ft);
651 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
653 prop->setDoubleValue("altitude-m", -9999.9);
654 prop->setDoubleValue("altitude-ft", -9999.9);
657 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
658 prop->setDoubleValue("speed-mach", leg->speedMach());
659 } else if (leg->speedRestriction() != RESTRICT_NONE) {
660 prop->setDoubleValue("speed-kts", leg->speedKts());
663 if (wp->flag(WPT_ARRIVAL)) {
664 prop->setBoolValue("arrival", true);
667 if (wp->flag(WPT_DEPARTURE)) {
668 prop->setBoolValue("departure", true);
671 if (wp->flag(WPT_MISS)) {
672 prop->setBoolValue("missed-approach", true);
675 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
676 } // of waypoint iteration
678 // set number as listener attachment point
679 mirror->setIntValue("num", _plan->numLegs());
682 rmDlg->updateValues();
685 totalDistance->setDoubleValue(_plan->totalDistanceNm());
688 // command interface /autopilot/route-manager/input:
690 // @CLEAR ... clear route
691 // @POP ... remove first entry
692 // @DELETE3 ... delete 4th entry
693 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
694 // KSFO@900 ... append "KSFO@900"
696 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
698 const char *s = prop->getStringValue();
699 if (strlen(s) == 0) {
703 if (!strcmp(s, "@CLEAR"))
705 else if (!strcmp(s, "@ACTIVATE"))
707 else if (!strcmp(s, "@LOAD")) {
708 SGPath path(mgr->_pathNode->getStringValue());
709 mgr->loadRoute(path);
710 } else if (!strcmp(s, "@SAVE")) {
711 SGPath path(mgr->_pathNode->getStringValue());
712 mgr->saveRoute(path);
713 } else if (!strcmp(s, "@NEXT")) {
714 mgr->jumpToIndex(mgr->currentIndex() + 1);
715 } else if (!strcmp(s, "@PREVIOUS")) {
716 mgr->jumpToIndex(mgr->currentIndex() - 1);
717 } else if (!strncmp(s, "@JUMP", 5)) {
718 mgr->jumpToIndex(atoi(s + 5));
719 } else if (!strncmp(s, "@DELETE", 7))
720 mgr->removeLegAtIndex(atoi(s + 7));
721 else if (!strncmp(s, "@INSERT", 7)) {
723 int pos = strtol(s + 7, &r, 10);
729 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
731 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
734 bool FGRouteMgr::activate()
737 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
741 if (isRouteActive()) {
742 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
747 active->setBoolValue(true);
748 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
752 void FGRouteMgr::deactivate()
754 if (!isRouteActive()) {
758 SG_LOG(SG_AUTOPILOT, SG_INFO, "deactivating flight plan");
759 active->setBoolValue(false);
762 void FGRouteMgr::jumpToIndex(int index)
768 _plan->setCurrentIndex(index);
771 void FGRouteMgr::currentWaypointChanged()
773 Waypt* cur = currentWaypt();
774 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
776 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
777 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
779 _currentWpt->fireValueChanged();
780 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
783 const char* FGRouteMgr::getDepartureICAO() const
785 if (!_plan || !_plan->departureAirport()) {
789 return _plan->departureAirport()->ident().c_str();
792 const char* FGRouteMgr::getDepartureName() const
794 if (!_plan || !_plan->departureAirport()) {
798 return _plan->departureAirport()->name().c_str();
801 const char* FGRouteMgr::getDepartureRunway() const
803 if (_plan && _plan->departureRunway()) {
804 return _plan->departureRunway()->ident().c_str();
810 void FGRouteMgr::setDepartureRunway(const char* aIdent)
816 FGAirport* apt = _plan->departureAirport();
817 if (!apt || (aIdent == NULL)) {
818 _plan->setDeparture(apt);
819 } else if (apt->hasRunwayWithIdent(aIdent)) {
820 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
824 void FGRouteMgr::setDepartureICAO(const char* aIdent)
830 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
831 _plan->setDeparture((FGAirport*) NULL);
833 _plan->setDeparture(FGAirport::findByIdent(aIdent));
837 const char* FGRouteMgr::getSID() const
839 if (_plan && _plan->sid()) {
840 return _plan->sid()->ident().c_str();
846 static double headingDiffDeg(double a, double b)
848 double rawDiff = b - a;
849 SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
853 flightgear::SID* createDefaultSID(FGRunway* aRunway, double enrouteCourse)
859 double runwayElevFt = aRunway->end().getElevationFt();
861 std::ostringstream ss;
862 ss << aRunway->ident() << "-3";
864 SGGeod p = aRunway->pointOnCenterline(aRunway->lengthM() + (3.0 * SG_NM_TO_METER));
865 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
866 w->setAltitude(runwayElevFt + 3000.0, RESTRICT_AT);
870 ss << aRunway->ident() << "-6";
871 p = aRunway->pointOnCenterline(aRunway->lengthM() + (6.0 * SG_NM_TO_METER));
872 w = new BasicWaypt(p, ss.str(), NULL);
873 w->setAltitude(runwayElevFt + 6000.0, RESTRICT_AT);
876 if (enrouteCourse >= 0.0) {
877 // valid enroute course
879 double course = aRunway->headingDeg();
881 while (fabs(diff = headingDiffDeg(course, enrouteCourse)) > 45.0) {
882 // turn in the sign of the heading change 45 degrees
883 course += copysign(45.0, diff);
885 ss << "DEP-" << index++;
886 SGGeod pos = wpts.back()->position();
887 pos = SGGeodesy::direct(pos, course, 3.0 * SG_NM_TO_METER);
888 w = new BasicWaypt(pos, ss.str(), NULL);
892 // no enroute course, just keep runway heading
894 ss << aRunway->ident() << "-9";
895 p = aRunway->pointOnCenterline(aRunway->lengthM() + (9.0 * SG_NM_TO_METER));
896 w = new BasicWaypt(p, ss.str(), NULL);
897 w->setAltitude(runwayElevFt + 9000.0, RESTRICT_AT);
901 BOOST_FOREACH(Waypt* w, wpts) {
902 w->setFlag(WPT_DEPARTURE);
903 w->setFlag(WPT_GENERATED);
906 return flightgear::SID::createTempSID("DEFAULT", aRunway, wpts);
909 void FGRouteMgr::setSID(const char* aIdent)
915 FGAirport* apt = _plan->departureAirport();
916 if (!apt || (aIdent == NULL)) {
917 _plan->setSID((flightgear::SID*) NULL);
921 if (!strcmp(aIdent, "DEFAULT")) {
922 double enrouteCourse = -1.0;
923 if (_plan->destinationAirport()) {
924 enrouteCourse = SGGeodesy::courseDeg(apt->geod(), _plan->destinationAirport()->geod());
927 _plan->setSID(createDefaultSID(_plan->departureRunway(), enrouteCourse));
931 string ident(aIdent);
932 size_t hyphenPos = ident.find('-');
933 if (hyphenPos != string::npos) {
934 string sidIdent = ident.substr(0, hyphenPos);
935 string transIdent = ident.substr(hyphenPos + 1);
937 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
938 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
939 _plan->setSID(trans);
941 _plan->setSID(apt->findSIDWithIdent(aIdent));
945 const char* FGRouteMgr::getDestinationICAO() const
947 if (!_plan || !_plan->destinationAirport()) {
951 return _plan->destinationAirport()->ident().c_str();
954 const char* FGRouteMgr::getDestinationName() const
956 if (!_plan || !_plan->destinationAirport()) {
960 return _plan->destinationAirport()->name().c_str();
963 void FGRouteMgr::setDestinationICAO(const char* aIdent)
969 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
970 _plan->setDestination((FGAirport*) NULL);
972 _plan->setDestination(FGAirport::findByIdent(aIdent));
976 const char* FGRouteMgr::getDestinationRunway() const
978 if (_plan && _plan->destinationRunway()) {
979 return _plan->destinationRunway()->ident().c_str();
985 void FGRouteMgr::setDestinationRunway(const char* aIdent)
991 FGAirport* apt = _plan->destinationAirport();
992 if (!apt || (aIdent == NULL)) {
993 _plan->setDestination(apt);
994 } else if (apt->hasRunwayWithIdent(aIdent)) {
995 _plan->setDestination(apt->getRunwayByIdent(aIdent));
999 const char* FGRouteMgr::getApproach() const
1001 if (_plan && _plan->approach()) {
1002 return _plan->approach()->ident().c_str();
1008 flightgear::Approach* createDefaultApproach(FGRunway* aRunway, double aEnrouteCourse)
1014 double thresholdElevFt = aRunway->threshold().getElevationFt();
1015 const double approachHeightFt = 2000.0;
1016 double glideslopeDistanceM = (approachHeightFt * SG_FEET_TO_METER) /
1017 tan(3.0 * SG_DEGREES_TO_RADIANS);
1019 std::ostringstream ss;
1020 ss << aRunway->ident() << "-12";
1022 SGGeod p = aRunway->pointOnCenterline(-12.0 * SG_NM_TO_METER);
1023 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
1024 w->setAltitude(thresholdElevFt + 4000, RESTRICT_AT);
1027 // work back form the first point on the centerline
1029 if (aEnrouteCourse >= 0.0) {
1030 // valid enroute course
1032 double course = aRunway->headingDeg();
1034 while (fabs(diff = headingDiffDeg(aEnrouteCourse, course)) > 45.0) {
1035 // turn in the sign of the heading change 45 degrees
1036 course -= copysign(45.0, diff);
1038 ss << "APP-" << index++;
1039 SGGeod pos = wpts.front()->position();
1040 pos = SGGeodesy::direct(pos, course + 180.0, 3.0 * SG_NM_TO_METER);
1041 w = new BasicWaypt(pos, ss.str(), NULL);
1042 wpts.insert(wpts.begin(), w);
1046 p = aRunway->pointOnCenterline(-8.0 * SG_NM_TO_METER);
1048 ss << aRunway->ident() << "-8";
1049 w = new BasicWaypt(p, ss.str(), NULL);
1050 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1053 p = aRunway->pointOnCenterline(-glideslopeDistanceM);
1055 ss << aRunway->ident() << "-GS";
1056 w = new BasicWaypt(p, ss.str(), NULL);
1057 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1060 BOOST_FOREACH(Waypt* w, wpts) {
1061 w->setFlag(WPT_APPROACH);
1062 w->setFlag(WPT_GENERATED);
1065 return Approach::createTempApproach("DEFAULT", aRunway, wpts);
1068 void FGRouteMgr::setApproach(const char* aIdent)
1074 FGAirport* apt = _plan->destinationAirport();
1075 if (!strcmp(aIdent, "DEFAULT")) {
1076 double enrouteCourse = -1.0;
1077 if (_plan->departureAirport()) {
1078 enrouteCourse = SGGeodesy::courseDeg(_plan->departureAirport()->geod(), apt->geod());
1081 _plan->setApproach(createDefaultApproach(_plan->destinationRunway(), enrouteCourse));
1085 if (!apt || (aIdent == NULL)) {
1086 _plan->setApproach(NULL);
1088 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1092 const char* FGRouteMgr::getSTAR() const
1094 if (_plan && _plan->star()) {
1095 return _plan->star()->ident().c_str();
1101 void FGRouteMgr::setSTAR(const char* aIdent)
1107 FGAirport* apt = _plan->destinationAirport();
1108 if (!apt || (aIdent == NULL)) {
1109 _plan->setSTAR((STAR*) NULL);
1113 string ident(aIdent);
1114 size_t hyphenPos = ident.find('-');
1115 if (hyphenPos != string::npos) {
1116 string starIdent = ident.substr(0, hyphenPos);
1117 string transIdent = ident.substr(hyphenPos + 1);
1119 STAR* star = apt->findSTARWithIdent(starIdent);
1120 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1121 _plan->setSTAR(trans);
1123 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1127 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1129 return _plan->waypointFromString(target);
1132 double FGRouteMgr::getDepartureFieldElevation() const
1134 if (!_plan || !_plan->departureAirport()) {
1138 return _plan->departureAirport()->elevation();
1141 double FGRouteMgr::getDestinationFieldElevation() const
1143 if (!_plan || !_plan->destinationAirport()) {
1147 return _plan->destinationAirport()->elevation();
1150 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1152 if ((index < 0) || (index >= numWaypts())) {
1153 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1156 return mirror->getChild("wp", index);
1159 bool FGRouteMgr::commandDefineUserWaypoint(const SGPropertyNode* arg)
1161 std::string ident = arg->getStringValue("ident");
1162 if (ident.empty()) {
1163 SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident defining user waypoint");
1167 // check for duplicate idents
1168 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1169 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1170 if (!dups.empty()) {
1171 SG_LOG(SG_AUTOPILOT, SG_WARN, "defineUserWaypoint: non-unique waypoint identifier:" << ident);
1175 SGGeod pos(SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1176 arg->getDoubleValue("latitude-deg")));
1177 FGPositioned::createUserWaypoint(ident, pos);
1181 bool FGRouteMgr::commandDeleteUserWaypoint(const SGPropertyNode* arg)
1183 std::string ident = arg->getStringValue("ident");
1184 if (ident.empty()) {
1185 SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident deleting user waypoint");
1189 return FGPositioned::deleteUserWaypoint(ident);