1 // FlightPlan.cxx - flight plan object
3 // Written by James Turner, started 2012.
5 // Copyright (C) 2012 Curtis L. Olson
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include "FlightPlan.hxx"
33 #include <boost/algorithm/string/case_conv.hpp>
34 #include <boost/algorithm/string.hpp>
35 #include <boost/foreach.hpp>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/misc/sg_path.hxx>
40 #include <simgear/magvar/magvar.hxx>
41 #include <simgear/timing/sg_time.hxx>
42 #include <simgear/misc/sgstream.hxx>
43 #include <simgear/misc/strutils.hxx>
44 #include <simgear/props/props_io.hxx>
45 #include <simgear/xml/easyxml.hxx>
48 #include <Main/globals.hxx>
49 #include "Main/fg_props.hxx"
50 #include <Navaids/procedure.hxx>
51 #include <Navaids/waypoint.hxx>
52 #include <Navaids/routePath.hxx>
59 namespace flightgear {
61 typedef std::vector<FlightPlan::DelegateFactory*> FPDelegateFactoryVec;
62 static FPDelegateFactoryVec static_delegateFactories;
64 FlightPlan::FlightPlan() :
67 _departureRunway(NULL),
68 _destinationRunway(NULL),
75 _departureChanged = _arrivalChanged = _waypointsChanged = _currentWaypointChanged = false;
77 BOOST_FOREACH(DelegateFactory* factory, static_delegateFactories) {
78 Delegate* d = factory->createFlightPlanDelegate(this);
79 if (d) { // factory might not always create a delegate
80 d->_deleteWithPlan = true;
86 FlightPlan::~FlightPlan()
88 // delete all delegates which we own.
89 Delegate* d = _delegate;
93 if (cur->_deleteWithPlan) {
99 BOOST_FOREACH(Leg* l, _legs) {
104 FlightPlan* FlightPlan::clone(const string& newIdent) const
106 FlightPlan* c = new FlightPlan();
107 c->_ident = newIdent.empty() ? _ident : newIdent;
110 // copy destination / departure data.
111 c->setDeparture(_departure);
112 c->setDeparture(_departureRunway);
115 c->setApproach(_approach);
116 } else if (_destinationRunway) {
117 c->setDestination(_destinationRunway);
118 } else if (_destination) {
119 c->setDestination(_destination);
126 c->_waypointsChanged = true;
127 for (int l=0; l < numLegs(); ++l) {
128 c->_legs.push_back(_legs[l]->cloneFor(c));
134 void FlightPlan::setIdent(const string& s)
139 string FlightPlan::ident() const
144 FlightPlan::Leg* FlightPlan::insertWayptAtIndex(Waypt* aWpt, int aIndex)
154 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
155 index = _legs.size();
158 insertWayptsAtIndex(wps, index);
159 return legAtIndex(index);
162 void FlightPlan::insertWayptsAtIndex(const WayptVec& wps, int aIndex)
169 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
170 index = _legs.size();
173 LegVec::iterator it = _legs.begin();
176 int endIndex = index + wps.size() - 1;
177 if (_currentIndex >= endIndex) {
178 _currentIndex += wps.size();
182 BOOST_FOREACH(WayptRef wp, wps) {
183 newLegs.push_back(new Leg(this, wp));
187 _waypointsChanged = true;
188 _legs.insert(it, newLegs.begin(), newLegs.end());
192 void FlightPlan::deleteIndex(int aIndex)
195 if (aIndex < 0) { // negative indices count the the end
196 index = _legs.size() + index;
199 if ((index < 0) || (index >= numLegs())) {
200 SG_LOG(SG_NAVAID, SG_WARN, "removeAtIndex with invalid index:" << aIndex);
205 _waypointsChanged = true;
207 LegVec::iterator it = _legs.begin();
213 if (_currentIndex == index) {
214 // current waypoint was removed
215 _currentWaypointChanged = true;
216 } else if (_currentIndex > index) {
217 --_currentIndex; // shift current index down if necessary
223 void FlightPlan::clear()
226 _waypointsChanged = true;
227 _currentWaypointChanged = true;
228 _arrivalChanged = true;
229 _departureChanged = true;
232 BOOST_FOREACH(Leg* l, _legs) {
238 _delegate->runCleared();
246 RemoveWithFlag(WayptFlag f) : flag(f), delCount(0) { }
248 int numDeleted() const { return delCount; }
250 bool operator()(FlightPlan::Leg* leg) const
252 if (leg->waypoint()->flag(flag)) {
262 mutable int delCount;
265 int FlightPlan::clearWayptsWithFlag(WayptFlag flag)
268 // first pass, fix up currentIndex
269 for (int i=0; i<_currentIndex; ++i) {
271 if (l->waypoint()->flag(flag)) {
276 // test if the current leg will be removed
277 bool currentIsBeingCleared = false;
278 Leg* curLeg = currentLeg();
280 currentIsBeingCleared = curLeg->waypoint()->flag(flag);
283 _currentIndex -= count;
285 // if we're clearing the current waypoint, what shall we do with the
286 // index? there's various options, but safest is to select no waypoint
287 // and let the use re-activate.
288 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1134
289 if (currentIsBeingCleared) {
290 SG_LOG(SG_GENERAL, SG_INFO, "currentIsBeingCleared:" << currentIsBeingCleared);
294 // now delete and remove
295 RemoveWithFlag rf(flag);
296 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
297 if (it == _legs.end()) {
298 return 0; // nothing was cleared, don't fire the delegate
302 _waypointsChanged = true;
303 if ((count > 0) || currentIsBeingCleared) {
304 _currentWaypointChanged = true;
307 _legs.erase(it, _legs.end());
309 if (_legs.empty()) { // maybe all legs were deleted
311 _delegate->runCleared();
316 return rf.numDeleted();
319 void FlightPlan::setCurrentIndex(int index)
321 if ((index < -1) || (index >= numLegs())) {
322 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
325 if (index == _currentIndex) {
330 _currentIndex = index;
331 _currentWaypointChanged = true;
335 void FlightPlan::finish()
337 if (_currentIndex == -1) {
343 _currentWaypointChanged = true;
346 _delegate->runFinished();
352 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
354 for (int i=0; i<numLegs(); ++i) {
355 if (_legs[i]->waypoint()->matches(aPos)) {
363 int FlightPlan::findWayptIndex(const FGPositionedRef aPos) const
365 for (int i=0; i<numLegs(); ++i) {
366 if (_legs[i]->waypoint()->source() == aPos) {
374 FlightPlan::Leg* FlightPlan::currentLeg() const
376 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
378 return legAtIndex(_currentIndex);
381 FlightPlan::Leg* FlightPlan::previousLeg() const
383 if (_currentIndex <= 0) {
387 return legAtIndex(_currentIndex - 1);
390 FlightPlan::Leg* FlightPlan::nextLeg() const
392 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
396 return legAtIndex(_currentIndex + 1);
399 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
401 if ((index < 0) || (index >= numLegs())) {
402 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
408 int FlightPlan::findLegIndex(const Leg *l) const
410 for (unsigned int i=0; i<_legs.size(); ++i) {
419 void FlightPlan::setDeparture(FGAirport* apt)
421 if (apt == _departure) {
426 _departureChanged = true;
428 _departureRunway = NULL;
433 void FlightPlan::setDeparture(FGRunway* rwy)
435 if (_departureRunway == rwy) {
440 _departureChanged = true;
442 _departureRunway = rwy;
443 if (rwy->airport() != _departure) {
444 _departure = rwy->airport();
450 void FlightPlan::setSID(SID* sid, const std::string& transition)
457 _departureChanged = true;
459 _sidTransition = transition;
463 void FlightPlan::setSID(Transition* trans)
470 if (trans->parent()->type() != PROCEDURE_SID)
471 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
473 setSID((SID*) trans->parent(), trans->ident());
476 Transition* FlightPlan::sidTransition() const
478 if (!_sid || _sidTransition.empty()) {
482 return _sid->findTransitionByName(_sidTransition);
485 void FlightPlan::setDestination(FGAirport* apt)
487 if (apt == _destination) {
492 _arrivalChanged = true;
494 _destinationRunway = NULL;
495 setSTAR((STAR*)NULL);
500 void FlightPlan::setDestination(FGRunway* rwy)
502 if (_destinationRunway == rwy) {
507 _arrivalChanged = true;
508 _destinationRunway = rwy;
509 if (_destination != rwy->airport()) {
510 _destination = rwy->airport();
511 setSTAR((STAR*)NULL);
517 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
524 _arrivalChanged = true;
526 _starTransition = transition;
530 void FlightPlan::setSTAR(Transition* trans)
533 setSTAR((STAR*) NULL);
537 if (trans->parent()->type() != PROCEDURE_STAR)
538 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
540 setSTAR((STAR*) trans->parent(), trans->ident());
543 Transition* FlightPlan::starTransition() const
545 if (!_star || _starTransition.empty()) {
549 return _star->findTransitionByName(_starTransition);
552 void FlightPlan::setApproach(flightgear::Approach *app)
554 if (_approach == app) {
559 _arrivalChanged = true;
562 // keep runway + airport in sync
563 if (_destinationRunway != _approach->runway()) {
564 _destinationRunway = _approach->runway();
567 if (_destination != _destinationRunway->airport()) {
568 _destination = _destinationRunway->airport();
574 bool FlightPlan::save(const SGPath& path)
576 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
578 SGPropertyNode_ptr d(new SGPropertyNode);
579 d->setIntValue("version", 2);
582 d->setStringValue("departure/airport", _departure->ident());
584 d->setStringValue("departure/sid", _sid->ident());
587 if (_departureRunway) {
588 d->setStringValue("departure/runway", _departureRunway->ident());
593 d->setStringValue("destination/airport", _destination->ident());
595 d->setStringValue("destination/star", _star->ident());
599 d->setStringValue("destination/approach", _approach->ident());
602 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
604 if (_destinationRunway) {
605 d->setStringValue("destination/runway", _destinationRunway->ident());
610 SGPropertyNode* routeNode = d->getChild("route", 0, true);
611 for (unsigned int i=0; i<_legs.size(); ++i) {
612 Waypt* wpt = _legs[i]->waypoint();
613 wpt->saveAsNode(routeNode->getChild("wp", i, true));
614 } // of waypoint iteration
615 writeProperties(path.str(), d, true /* write-all */);
617 } catch (sg_exception& e) {
618 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
623 bool FlightPlan::load(const SGPath& path)
627 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
628 << "'. The file does not exist.");
632 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
637 // try different file formats
638 if (loadGpxFormat(path)) // GPX format
641 if (loadXmlFormat(path)) // XML property data
644 if (loadPlainTextFormat(path)) // simple textual list of waypoints
647 _waypointsChanged = true;
653 /** XML loader for GPX file format */
654 class GpxXmlVisitor : public XMLVisitor
657 GpxXmlVisitor(FlightPlan* fp) : _fp(fp), _lat(-9999), _lon(-9999) {}
659 virtual void startElement (const char * name, const XMLAttributes &atts);
660 virtual void endElement (const char * name);
661 virtual void data (const char * s, int length);
670 void GpxXmlVisitor::startElement(const char * name, const XMLAttributes &atts)
673 if (strcmp(name, "rtept")==0)
678 const char* slat = atts.getValue("lat");
679 const char* slon = atts.getValue("lon");
688 void GpxXmlVisitor::data(const char * s, int length)
690 // use "name" when given, otherwise use "cmt" (comment) as ID
691 if ((_element == "name")||
692 ((_waypoint == "")&&(_element == "cmt")))
694 char* buf = (char*) malloc(length+1);
695 memcpy(buf, s, length);
702 void GpxXmlVisitor::endElement(const char * name)
705 if (strcmp(name, "rtept") == 0)
709 _fp->insertWayptAtIndex(new BasicWaypt(SGGeod::fromDeg(_lon, _lat), _waypoint.c_str(), NULL), -1);
714 /** Load a flightplan in GPX format */
715 bool FlightPlan::loadGpxFormat(const SGPath& path)
717 if (path.lower_extension() != "gpx")
719 // not a valid GPX file
724 GpxXmlVisitor gpxVistor(this);
727 readXML(path.str(), gpxVistor);
728 } catch (sg_exception& e)
730 // XML parsing fails => not a GPX XML file
731 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan in GPX format: '" << e.getOrigin()
732 << "'. " << e.getMessage());
738 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan in GPX format. No route found.");
745 /** Load a flightplan in FlightGear XML property format */
746 bool FlightPlan::loadXmlFormat(const SGPath& path)
748 SGPropertyNode_ptr routeData(new SGPropertyNode);
750 readProperties(path.str(), routeData);
751 } catch (sg_exception& e) {
752 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
753 << "'. " << e.getMessage());
754 // XML parsing fails => not a property XML file
758 if (routeData.valid())
761 int version = routeData->getIntValue("version", 1);
763 loadVersion1XMLRoute(routeData);
764 } else if (version == 2) {
765 loadVersion2XMLRoute(routeData);
767 throw sg_io_exception("unsupported XML route version");
770 } catch (sg_exception& e) {
771 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
772 << "'. " << e.getMessage());
779 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
782 SGPropertyNode* dep = routeData->getChild("departure");
784 string depIdent = dep->getStringValue("airport");
785 setDeparture((FGAirport*) fgFindAirportID(depIdent));
787 string rwy(dep->getStringValue("runway"));
788 if (_departure->hasRunwayWithIdent(rwy)) {
789 setDeparture(_departure->getRunwayByIdent(rwy));
792 if (dep->hasChild("sid")) {
793 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
795 // departure->setStringValue("transition", dep->getStringValue("transition"));
800 SGPropertyNode* dst = routeData->getChild("destination");
802 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
804 string rwy(dst->getStringValue("runway"));
805 if (_destination->hasRunwayWithIdent(rwy)) {
806 setDestination(_destination->getRunwayByIdent(rwy));
809 if (dst->hasChild("star")) {
810 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
813 if (dst->hasChild("approach")) {
814 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
818 // destination->setStringValue("transition", dst->getStringValue("transition"));
822 SGPropertyNode* alt = routeData->getChild("alternate");
824 //alternate->setStringValue(alt->getStringValue("airport"));
828 SGPropertyNode* crs = routeData->getChild("cruise");
830 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
831 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
832 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
833 } // of cruise data loading
837 void FlightPlan::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
839 loadXMLRouteHeader(routeData);
843 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
844 if (routeNode.valid()) {
845 for (int i=0; i<routeNode->nChildren(); ++i) {
846 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
847 Leg* l = new Leg(this, Waypt::createFromProperties(NULL, wpNode));
849 } // of route iteration
851 _waypointsChanged = true;
854 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
856 loadXMLRouteHeader(routeData);
860 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
861 for (int i=0; i<routeNode->nChildren(); ++i) {
862 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
863 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
865 } // of route iteration
866 _waypointsChanged = true;
869 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
872 if (!_legs.empty()) {
873 lastPos = _legs.back()->waypoint()->position();
874 } else if (_departure) {
875 lastPos = _departure->geod();
879 string ident(aWP->getStringValue("ident"));
880 if (aWP->hasChild("longitude-deg")) {
881 // explicit longitude/latitude
882 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
883 aWP->getDoubleValue("latitude-deg")), ident, NULL);
886 string nid = aWP->getStringValue("navid", ident.c_str());
887 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
893 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
894 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
895 aWP->getDoubleValue("latitude-deg"));
898 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
899 double radialDeg = aWP->getDoubleValue("offset-radial");
900 // convert magnetic radial to a true radial!
901 radialDeg += magvarDegAt(pos);
902 double offsetNm = aWP->getDoubleValue("offset-nm");
904 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
907 w = new BasicWaypt(pos, ident, NULL);
910 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
911 if (altFt > -9990.0) {
912 w->setAltitude(altFt, RESTRICT_AT);
918 /** Load a flightplan in FlightGear plain-text format */
919 bool FlightPlan::loadPlainTextFormat(const SGPath& path)
922 sg_gzifstream in(path.str().c_str());
924 throw sg_io_exception("Cannot open file for reading.");
930 getline(in, line, '\n');
931 // trim CR from end of line, if found
932 if (line[line.size() - 1] == '\r') {
933 line.erase(line.size() - 1, 1);
936 line = simgear::strutils::strip(line);
937 if (line.empty() || (line[0] == '#')) {
938 continue; // ignore empty/comment lines
941 WayptRef w = waypointFromString(line);
943 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
946 _legs.push_back(new Leg(this, w));
947 } // of line iteration
948 } catch (sg_exception& e) {
949 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
957 double FlightPlan::magvarDegAt(const SGGeod& pos) const
959 double jd = globals->get_time_params()->getJD();
960 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
963 WayptRef FlightPlan::waypointFromString(const string& tgt )
965 string target(boost::to_upper_copy(tgt));
970 RouteRestriction altSetting = RESTRICT_NONE;
972 size_t pos = target.find( '@' );
973 if ( pos != string::npos ) {
974 altFt = atof( target.c_str() + pos + 1 );
975 target = target.substr( 0, pos );
976 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
977 altFt *= SG_METER_TO_FEET;
978 altSetting = RESTRICT_AT;
982 pos = target.find( ',' );
983 if ( pos != string::npos ) {
984 double lon = atof( target.substr(0, pos).c_str());
985 double lat = atof( target.c_str() + pos + 1);
987 char ew = (lon < 0.0) ? 'W' : 'E';
988 char ns = (lat < 0.0) ? 'S' : 'N';
989 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
991 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
992 if (altSetting != RESTRICT_NONE) {
993 wpt->setAltitude(altFt, altSetting);
1000 // route is empty, use current position
1001 basePosition = globals->get_aircraft_position();
1003 basePosition = _legs.back()->waypoint()->position();
1006 string_list pieces(simgear::strutils::split(target, "/"));
1007 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
1009 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
1013 double magvar = magvarDegAt(basePosition);
1015 if (pieces.size() == 1) {
1016 wpt = new NavaidWaypoint(p, NULL);
1017 } else if (pieces.size() == 3) {
1018 // navaid/radial/distance-nm notation
1019 double radial = atof(pieces[1].c_str()),
1020 distanceNm = atof(pieces[2].c_str());
1022 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
1023 } else if (pieces.size() == 2) {
1024 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
1026 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
1030 if (!apt->hasRunwayWithIdent(pieces[1])) {
1031 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
1035 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
1036 wpt = new NavaidWaypoint(runway, NULL);
1037 } else if (pieces.size() == 4) {
1038 // navid/radial/navid/radial notation
1039 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
1041 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
1045 double r1 = atof(pieces[1].c_str()),
1046 r2 = atof(pieces[3].c_str());
1050 SGGeod intersection;
1051 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
1053 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
1057 std::string name = p->ident() + "-" + p2->ident();
1058 wpt = new BasicWaypt(intersection, name, NULL);
1062 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
1066 if (altSetting != RESTRICT_NONE) {
1067 wpt->setAltitude(altFt, altSetting);
1072 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
1074 _speedRestrict(RESTRICT_NONE),
1075 _altRestrict(RESTRICT_NONE),
1079 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
1081 _speed = _altitudeFt = 0;
1084 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
1086 Leg* c = new Leg(owner, _waypt);
1089 c->_speedRestrict = _speedRestrict;
1090 c->_altitudeFt = _altitudeFt;
1091 c->_altRestrict = _altRestrict;
1096 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
1098 return _parent->legAtIndex(index() + 1);
1101 unsigned int FlightPlan::Leg::index() const
1103 return _parent->findLegIndex(this);
1106 int FlightPlan::Leg::altitudeFt() const
1108 if (_altRestrict != RESTRICT_NONE) {
1112 return _waypt->altitudeFt();
1115 int FlightPlan::Leg::speed() const
1117 if (_speedRestrict != RESTRICT_NONE) {
1121 return _waypt->speed();
1124 int FlightPlan::Leg::speedKts() const
1129 double FlightPlan::Leg::speedMach() const
1131 if (!isMachRestrict(_speedRestrict)) {
1135 return -(_speed / 100.0);
1138 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
1140 if (_altRestrict != RESTRICT_NONE) {
1141 return _altRestrict;
1144 return _waypt->altitudeRestriction();
1147 RouteRestriction FlightPlan::Leg::speedRestriction() const
1149 if (_speedRestrict != RESTRICT_NONE) {
1150 return _speedRestrict;
1153 return _waypt->speedRestriction();
1156 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
1158 _speedRestrict = ty;
1159 if (isMachRestrict(ty)) {
1160 _speed = (speed * -100);
1166 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1169 _altitudeFt = altFt;
1172 double FlightPlan::Leg::courseDeg() const
1177 double FlightPlan::Leg::distanceNm() const
1179 return _pathDistance;
1182 double FlightPlan::Leg::distanceAlongRoute() const
1184 return _distanceAlongPath;
1187 void FlightPlan::rebuildLegData()
1189 _totalDistance = 0.0;
1190 double totalDistanceIncludingMissed = 0.0;
1191 RoutePath path(this);
1193 for (unsigned int l=0; l<_legs.size(); ++l) {
1194 _legs[l]->_courseDeg = path.trackForIndex(l);
1195 _legs[l]->_pathDistance = path.distanceForIndex(l) * SG_METER_TO_NM;
1197 totalDistanceIncludingMissed += _legs[l]->_pathDistance;
1198 // distance along path includes our own leg distance
1199 _legs[l]->_distanceAlongPath = totalDistanceIncludingMissed;
1201 // omit missed-approach waypoints from total distance calculation
1202 if (!_legs[l]->waypoint()->flag(WPT_MISS)) {
1203 _totalDistance += _legs[l]->_pathDistance;
1205 } // of legs iteration
1209 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1212 return rp.positionForDistanceFrom(aIndex, aOffsetNm * SG_NM_TO_METER);
1215 void FlightPlan::lockDelegate()
1217 if (_delegateLock == 0) {
1218 assert(!_departureChanged && !_arrivalChanged &&
1219 !_waypointsChanged && !_currentWaypointChanged);
1225 void FlightPlan::unlockDelegate()
1227 assert(_delegateLock > 0);
1228 if (_delegateLock > 1) {
1233 if (_departureChanged) {
1234 _departureChanged = false;
1236 _delegate->runDepartureChanged();
1240 if (_arrivalChanged) {
1241 _arrivalChanged = false;
1243 _delegate->runArrivalChanged();
1247 if (_waypointsChanged) {
1248 _waypointsChanged = false;
1251 _delegate->runWaypointsChanged();
1255 if (_currentWaypointChanged) {
1256 _currentWaypointChanged = false;
1258 _delegate->runCurrentWaypointChanged();
1265 void FlightPlan::registerDelegateFactory(DelegateFactory* df)
1267 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1268 static_delegateFactories.end(), df);
1269 if (it != static_delegateFactories.end()) {
1270 throw sg_exception("duplicate delegate factory registration");
1273 static_delegateFactories.push_back(df);
1276 void FlightPlan::unregisterDelegateFactory(DelegateFactory* df)
1278 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1279 static_delegateFactories.end(), df);
1280 if (it == static_delegateFactories.end()) {
1284 static_delegateFactories.erase(it);
1287 void FlightPlan::addDelegate(Delegate* d)
1289 // wrap any existing delegate(s) in the new one
1290 d->_inner = _delegate;
1294 void FlightPlan::removeDelegate(Delegate* d)
1296 if (d == _delegate) {
1297 _delegate = _delegate->_inner;
1298 } else if (_delegate) {
1299 _delegate->removeInner(d);
1303 FlightPlan::Delegate::Delegate() :
1304 _deleteWithPlan(false),
1309 FlightPlan::Delegate::~Delegate()
1313 void FlightPlan::Delegate::removeInner(Delegate* d)
1316 throw sg_exception("FlightPlan delegate not found");
1320 // replace with grand-child
1322 } else { // recurse downwards
1323 _inner->removeInner(d);
1327 void FlightPlan::Delegate::runDepartureChanged()
1329 if (_inner) _inner->runDepartureChanged();
1333 void FlightPlan::Delegate::runArrivalChanged()
1335 if (_inner) _inner->runArrivalChanged();
1339 void FlightPlan::Delegate::runWaypointsChanged()
1341 if (_inner) _inner->runWaypointsChanged();
1345 void FlightPlan::Delegate::runCurrentWaypointChanged()
1347 if (_inner) _inner->runCurrentWaypointChanged();
1348 currentWaypointChanged();
1351 void FlightPlan::Delegate::runCleared()
1353 if (_inner) _inner->runCleared();
1357 void FlightPlan::Delegate::runFinished()
1359 if (_inner) _inner->runFinished();
1363 } // of namespace flightgear