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>
47 #include <Main/globals.hxx>
48 #include "Main/fg_props.hxx"
49 #include <Navaids/procedure.hxx>
50 #include <Navaids/waypoint.hxx>
57 namespace flightgear {
59 typedef std::vector<FlightPlan::DelegateFactory*> FPDelegateFactoryVec;
60 static FPDelegateFactoryVec static_delegateFactories;
62 FlightPlan::FlightPlan() :
65 _departureRunway(NULL),
66 _destinationRunway(NULL),
72 _departureChanged = _arrivalChanged = _waypointsChanged = _currentWaypointChanged = false;
74 BOOST_FOREACH(DelegateFactory* factory, static_delegateFactories) {
75 Delegate* d = factory->createFlightPlanDelegate(this);
76 if (d) { // factory might not always create a delegate
77 d->_deleteWithPlan = true;
83 FlightPlan::~FlightPlan()
85 // delete all delegates which we own.
86 Delegate* d = _delegate;
90 if (cur->_deleteWithPlan) {
96 FlightPlan* FlightPlan::clone(const string& newIdent) const
98 FlightPlan* c = new FlightPlan();
99 c->_ident = newIdent.empty() ? _ident : newIdent;
102 // copy destination / departure data.
103 c->setDeparture(_departure);
104 c->setDeparture(_departureRunway);
107 c->setApproach(_approach);
108 } else if (_destinationRunway) {
109 c->setDestination(_destinationRunway);
110 } else if (_destination) {
111 c->setDestination(_destination);
118 c->_waypointsChanged = true;
119 for (int l=0; l < numLegs(); ++l) {
120 c->_legs.push_back(_legs[l]->cloneFor(c));
126 void FlightPlan::setIdent(const string& s)
131 string FlightPlan::ident() const
136 FlightPlan::Leg* FlightPlan::insertWayptAtIndex(Waypt* aWpt, int aIndex)
146 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
147 index = _legs.size();
150 insertWayptsAtIndex(wps, index);
151 return legAtIndex(index);
154 void FlightPlan::insertWayptsAtIndex(const WayptVec& wps, int aIndex)
161 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
162 index = _legs.size();
165 LegVec::iterator it = _legs.begin();
168 int endIndex = index + wps.size() - 1;
169 if (_currentIndex >= endIndex) {
170 _currentIndex += wps.size();
174 BOOST_FOREACH(WayptRef wp, wps) {
175 newLegs.push_back(new Leg(this, wp));
179 _waypointsChanged = true;
180 _legs.insert(it, newLegs.begin(), newLegs.end());
184 void FlightPlan::deleteIndex(int aIndex)
187 if (aIndex < 0) { // negative indices count the the end
188 index = _legs.size() + index;
191 if ((index < 0) || (index >= numLegs())) {
192 SG_LOG(SG_NAVAID, SG_WARN, "removeAtIndex with invalid index:" << aIndex);
197 _waypointsChanged = true;
199 LegVec::iterator it = _legs.begin();
205 if (_currentIndex == index) {
206 // current waypoint was removed
207 _currentWaypointChanged = true;
208 } else if (_currentIndex > index) {
209 --_currentIndex; // shift current index down if necessary
215 void FlightPlan::clear()
218 _waypointsChanged = true;
219 _currentWaypointChanged = true;
220 _arrivalChanged = true;
221 _departureChanged = true;
224 BOOST_FOREACH(Leg* l, _legs) {
230 _delegate->runCleared();
238 RemoveWithFlag(WayptFlag f) : flag(f), delCount(0) { }
240 int numDeleted() const { return delCount; }
242 bool operator()(FlightPlan::Leg* leg) const
244 if (leg->waypoint()->flag(flag)) {
254 mutable int delCount;
257 int FlightPlan::clearWayptsWithFlag(WayptFlag flag)
260 // first pass, fix up currentIndex
261 for (int i=0; i<_currentIndex; ++i) {
263 if (l->waypoint()->flag(flag)) {
268 // test if the current leg will be removed
269 bool currentIsBeingCleared = false;
270 if (_currentIndex >= 0) {
271 currentIsBeingCleared = _legs[_currentIndex]->waypoint()->flag(flag);
274 _currentIndex -= count;
276 // now delete and remove
277 RemoveWithFlag rf(flag);
278 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
279 if (it == _legs.end()) {
280 return 0; // nothing was cleared, don't fire the delegate
284 _waypointsChanged = true;
285 if ((count > 0) || currentIsBeingCleared) {
286 _currentWaypointChanged = true;
289 _legs.erase(it, _legs.end());
291 if (_legs.empty()) { // maybe all legs were deleted
293 _delegate->runCleared();
298 return rf.numDeleted();
301 void FlightPlan::setCurrentIndex(int index)
303 if ((index < -1) || (index >= numLegs())) {
304 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
307 if (index == _currentIndex) {
312 _currentIndex = index;
313 _currentWaypointChanged = true;
317 void FlightPlan::finish()
319 if (_currentIndex == -1) {
325 _currentWaypointChanged = true;
328 _delegate->runFinished();
334 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
336 for (int i=0; i<numLegs(); ++i) {
337 if (_legs[i]->waypoint()->matches(aPos)) {
345 FlightPlan::Leg* FlightPlan::currentLeg() const
347 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
349 return legAtIndex(_currentIndex);
352 FlightPlan::Leg* FlightPlan::previousLeg() const
354 if (_currentIndex <= 0) {
358 return legAtIndex(_currentIndex - 1);
361 FlightPlan::Leg* FlightPlan::nextLeg() const
363 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
367 return legAtIndex(_currentIndex + 1);
370 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
372 if ((index < 0) || (index >= numLegs())) {
373 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
379 int FlightPlan::findLegIndex(const Leg *l) const
381 for (unsigned int i=0; i<_legs.size(); ++i) {
390 void FlightPlan::setDeparture(FGAirport* apt)
392 if (apt == _departure) {
397 _departureChanged = true;
399 _departureRunway = NULL;
404 void FlightPlan::setDeparture(FGRunway* rwy)
406 if (_departureRunway == rwy) {
411 _departureChanged = true;
413 _departureRunway = rwy;
414 if (rwy->airport() != _departure) {
415 _departure = rwy->airport();
421 void FlightPlan::setSID(SID* sid, const std::string& transition)
428 _departureChanged = true;
430 _sidTransition = transition;
434 void FlightPlan::setSID(Transition* trans)
441 if (trans->parent()->type() != PROCEDURE_SID)
442 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
444 setSID((SID*) trans->parent(), trans->ident());
447 Transition* FlightPlan::sidTransition() const
449 if (!_sid || _sidTransition.empty()) {
453 return _sid->findTransitionByName(_sidTransition);
456 void FlightPlan::setDestination(FGAirport* apt)
458 if (apt == _destination) {
463 _arrivalChanged = true;
465 _destinationRunway = NULL;
466 setSTAR((STAR*)NULL);
471 void FlightPlan::setDestination(FGRunway* rwy)
473 if (_destinationRunway == rwy) {
478 _arrivalChanged = true;
479 _destinationRunway = rwy;
480 if (_destination != rwy->airport()) {
481 _destination = rwy->airport();
482 setSTAR((STAR*)NULL);
488 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
495 _arrivalChanged = true;
497 _starTransition = transition;
501 void FlightPlan::setSTAR(Transition* trans)
504 setSTAR((STAR*) NULL);
508 if (trans->parent()->type() != PROCEDURE_STAR)
509 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
511 setSTAR((STAR*) trans->parent(), trans->ident());
514 Transition* FlightPlan::starTransition() const
516 if (!_star || _starTransition.empty()) {
520 return _star->findTransitionByName(_starTransition);
523 void FlightPlan::setApproach(flightgear::Approach *app)
525 if (_approach == app) {
530 _arrivalChanged = true;
533 // keep runway + airport in sync
534 if (_destinationRunway != _approach->runway()) {
535 _destinationRunway = _approach->runway();
538 if (_destination != _destinationRunway->airport()) {
539 _destination = _destinationRunway->airport();
545 bool FlightPlan::save(const SGPath& path)
547 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
549 SGPropertyNode_ptr d(new SGPropertyNode);
550 d->setIntValue("version", 2);
553 d->setStringValue("departure/airport", _departure->ident());
555 d->setStringValue("departure/sid", _sid->ident());
558 if (_departureRunway) {
559 d->setStringValue("departure/runway", _departureRunway->ident());
564 d->setStringValue("destination/airport", _destination->ident());
566 d->setStringValue("destination/star", _star->ident());
570 d->setStringValue("destination/approach", _approach->ident());
573 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
575 if (_destinationRunway) {
576 d->setStringValue("destination/runway", _destinationRunway->ident());
581 SGPropertyNode* routeNode = d->getChild("route", 0, true);
582 for (unsigned int i=0; i<_legs.size(); ++i) {
583 Waypt* wpt = _legs[i]->waypoint();
584 wpt->saveAsNode(routeNode->getChild("wp", i, true));
585 } // of waypoint iteration
586 writeProperties(path.str(), d, true /* write-all */);
588 } catch (sg_exception& e) {
589 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
594 bool FlightPlan::load(const SGPath& path)
598 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
599 << "'. The file does not exist.");
603 SGPropertyNode_ptr routeData(new SGPropertyNode);
604 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
609 readProperties(path.str(), routeData);
610 } catch (sg_exception& ) {
611 // if XML parsing fails, the file might be simple textual list of waypoints
612 Status = loadPlainTextRoute(path);
614 _waypointsChanged = true;
617 if (routeData.valid())
620 int version = routeData->getIntValue("version", 1);
622 loadVersion1XMLRoute(routeData);
623 } else if (version == 2) {
624 loadVersion2XMLRoute(routeData);
626 throw sg_io_exception("unsupported XML route version");
629 } catch (sg_exception& e) {
630 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
631 << "'. " << e.getMessage());
640 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
643 SGPropertyNode* dep = routeData->getChild("departure");
645 string depIdent = dep->getStringValue("airport");
646 setDeparture((FGAirport*) fgFindAirportID(depIdent));
648 string rwy(dep->getStringValue("runway"));
649 if (_departure->hasRunwayWithIdent(rwy)) {
650 setDeparture(_departure->getRunwayByIdent(rwy));
653 if (dep->hasChild("sid")) {
654 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
656 // departure->setStringValue("transition", dep->getStringValue("transition"));
661 SGPropertyNode* dst = routeData->getChild("destination");
663 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
665 string rwy(dst->getStringValue("runway"));
666 if (_destination->hasRunwayWithIdent(rwy)) {
667 setDestination(_destination->getRunwayByIdent(rwy));
670 if (dst->hasChild("star")) {
671 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
674 if (dst->hasChild("approach")) {
675 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
679 // destination->setStringValue("transition", dst->getStringValue("transition"));
683 SGPropertyNode* alt = routeData->getChild("alternate");
685 //alternate->setStringValue(alt->getStringValue("airport"));
689 SGPropertyNode* crs = routeData->getChild("cruise");
691 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
692 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
693 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
694 } // of cruise data loading
698 void FlightPlan::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
700 loadXMLRouteHeader(routeData);
704 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
705 for (int i=0; i<routeNode->nChildren(); ++i) {
706 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
707 Leg* l = new Leg(this, Waypt::createFromProperties(NULL, wpNode));
709 } // of route iteration
710 _waypointsChanged = true;
713 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
715 loadXMLRouteHeader(routeData);
719 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
720 for (int i=0; i<routeNode->nChildren(); ++i) {
721 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
722 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
724 } // of route iteration
725 _waypointsChanged = true;
728 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
731 if (!_legs.empty()) {
732 lastPos = _legs.back()->waypoint()->position();
733 } else if (_departure) {
734 lastPos = _departure->geod();
738 string ident(aWP->getStringValue("ident"));
739 if (aWP->hasChild("longitude-deg")) {
740 // explicit longitude/latitude
741 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
742 aWP->getDoubleValue("latitude-deg")), ident, NULL);
745 string nid = aWP->getStringValue("navid", ident.c_str());
746 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
752 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
753 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
754 aWP->getDoubleValue("latitude-deg"));
757 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
758 double radialDeg = aWP->getDoubleValue("offset-radial");
759 // convert magnetic radial to a true radial!
760 radialDeg += magvarDegAt(pos);
761 double offsetNm = aWP->getDoubleValue("offset-nm");
763 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
766 w = new BasicWaypt(pos, ident, NULL);
769 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
770 if (altFt > -9990.0) {
771 w->setAltitude(altFt, RESTRICT_AT);
777 bool FlightPlan::loadPlainTextRoute(const SGPath& path)
780 sg_gzifstream in(path.str().c_str());
782 throw sg_io_exception("Cannot open file for reading.");
788 getline(in, line, '\n');
789 // trim CR from end of line, if found
790 if (line[line.size() - 1] == '\r') {
791 line.erase(line.size() - 1, 1);
794 line = simgear::strutils::strip(line);
795 if (line.empty() || (line[0] == '#')) {
796 continue; // ignore empty/comment lines
799 WayptRef w = waypointFromString(line);
801 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
804 _legs.push_back(new Leg(this, w));
805 } // of line iteration
806 } catch (sg_exception& e) {
807 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
815 double FlightPlan::magvarDegAt(const SGGeod& pos) const
817 double jd = globals->get_time_params()->getJD();
818 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
821 WayptRef FlightPlan::waypointFromString(const string& tgt )
823 string target(boost::to_upper_copy(tgt));
828 RouteRestriction altSetting = RESTRICT_NONE;
830 size_t pos = target.find( '@' );
831 if ( pos != string::npos ) {
832 altFt = atof( target.c_str() + pos + 1 );
833 target = target.substr( 0, pos );
834 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
835 altFt *= SG_METER_TO_FEET;
836 altSetting = RESTRICT_AT;
840 pos = target.find( ',' );
841 if ( pos != string::npos ) {
842 double lon = atof( target.substr(0, pos).c_str());
843 double lat = atof( target.c_str() + pos + 1);
845 char ew = (lon < 0.0) ? 'W' : 'E';
846 char ns = (lat < 0.0) ? 'S' : 'N';
847 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
849 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
850 if (altSetting != RESTRICT_NONE) {
851 wpt->setAltitude(altFt, altSetting);
858 // route is empty, use current position
859 basePosition = globals->get_aircraft_position();
861 basePosition = _legs.back()->waypoint()->position();
864 string_list pieces(simgear::strutils::split(target, "/"));
865 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
867 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
871 double magvar = magvarDegAt(basePosition);
873 if (pieces.size() == 1) {
874 wpt = new NavaidWaypoint(p, NULL);
875 } else if (pieces.size() == 3) {
876 // navaid/radial/distance-nm notation
877 double radial = atof(pieces[1].c_str()),
878 distanceNm = atof(pieces[2].c_str());
880 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
881 } else if (pieces.size() == 2) {
882 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
884 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
888 if (!apt->hasRunwayWithIdent(pieces[1])) {
889 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
893 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
894 wpt = new NavaidWaypoint(runway, NULL);
895 } else if (pieces.size() == 4) {
896 // navid/radial/navid/radial notation
897 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
899 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
903 double r1 = atof(pieces[1].c_str()),
904 r2 = atof(pieces[3].c_str());
909 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
911 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
915 std::string name = p->ident() + "-" + p2->ident();
916 wpt = new BasicWaypt(intersection, name, NULL);
920 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
924 if (altSetting != RESTRICT_NONE) {
925 wpt->setAltitude(altFt, altSetting);
930 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
932 _speedRestrict(RESTRICT_NONE),
933 _altRestrict(RESTRICT_NONE),
937 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
939 _speed = _altitudeFt = 0;
942 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
944 Leg* c = new Leg(owner, _waypt);
947 c->_speedRestrict = _speedRestrict;
948 c->_altitudeFt = _altitudeFt;
949 c->_altRestrict = _altRestrict;
954 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
956 return _parent->legAtIndex(index() + 1);
959 unsigned int FlightPlan::Leg::index() const
961 return _parent->findLegIndex(this);
964 int FlightPlan::Leg::altitudeFt() const
966 if (_altRestrict != RESTRICT_NONE) {
970 return _waypt->altitudeFt();
973 int FlightPlan::Leg::speed() const
975 if (_speedRestrict != RESTRICT_NONE) {
979 return _waypt->speed();
982 int FlightPlan::Leg::speedKts() const
987 double FlightPlan::Leg::speedMach() const
989 if (!isMachRestrict(_speedRestrict)) {
993 return -(_speed / 100.0);
996 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
998 if (_altRestrict != RESTRICT_NONE) {
1002 return _waypt->altitudeRestriction();
1005 RouteRestriction FlightPlan::Leg::speedRestriction() const
1007 if (_speedRestrict != RESTRICT_NONE) {
1008 return _speedRestrict;
1011 return _waypt->speedRestriction();
1014 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
1016 _speedRestrict = ty;
1017 if (isMachRestrict(ty)) {
1018 _speed = (speed * -100);
1024 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1027 _altitudeFt = altFt;
1030 double FlightPlan::Leg::courseDeg() const
1035 double FlightPlan::Leg::distanceNm() const
1037 return _pathDistance;
1040 double FlightPlan::Leg::distanceAlongRoute() const
1042 return _distanceAlongPath;
1045 void FlightPlan::rebuildLegData()
1047 _totalDistance = 0.0;
1048 int lastLeg = static_cast<int>(_legs.size()) - 1;
1049 for (int l=0; l<lastLeg; ++l) {
1050 Leg* cur = _legs[l];
1051 Leg* next = _legs[l + 1];
1053 std::pair<double, double> crsDist =
1054 next->waypoint()->courseAndDistanceFrom(cur->waypoint()->position());
1055 _legs[l]->_courseDeg = crsDist.first;
1056 _legs[l]->_pathDistance = crsDist.second * SG_METER_TO_NM;
1057 _legs[l]->_distanceAlongPath = _totalDistance;
1058 _totalDistance += crsDist.second * SG_METER_TO_NM;
1059 } // of legs iteration
1061 // set some data on the final leg
1063 // keep the same course as the final leg, when passing the final
1065 _legs[lastLeg]->_courseDeg = _legs[lastLeg - 1]->_courseDeg;
1066 _legs[lastLeg]->_pathDistance = 0.0;
1067 _legs[lastLeg]->_distanceAlongPath = _totalDistance;
1071 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1073 if (aIndex >= (int) _legs.size()) {
1074 throw sg_range_exception();
1077 const int lastLeg = static_cast<int>(_legs.size()) - 1;
1078 // convert the relative offset and leg index into an absolute, positive
1079 // distance in nm from the route origin. This means we can simply walk
1080 // forwards to find the actual leg.
1081 Leg* leg = _legs[(aIndex >= 0) ? aIndex : lastLeg];
1082 double absolutePathDistance = leg->_distanceAlongPath + aOffsetNm;
1083 if (absolutePathDistance < 0.0) {
1084 return _legs[0]->waypoint()->position(); // begining of route
1087 if (absolutePathDistance > _totalDistance) {
1088 return _legs[lastLeg]->waypoint()->position(); // end of route
1091 // find the leg containing the absolute distance
1092 for (int l=0; l<lastLeg; ++l) {
1094 if (absolutePathDistance < leg->_pathDistance) {
1095 break; // found our matching leg
1097 absolutePathDistance -= leg->_pathDistance;
1098 } // of forwards walk along route to find leg
1100 return SGGeodesy::direct(leg->waypoint()->position(),
1101 leg->_courseDeg, absolutePathDistance * SG_NM_TO_METER);
1104 void FlightPlan::lockDelegate()
1106 if (_delegateLock == 0) {
1107 assert(!_departureChanged && !_arrivalChanged &&
1108 !_waypointsChanged && !_currentWaypointChanged);
1114 void FlightPlan::unlockDelegate()
1116 assert(_delegateLock > 0);
1117 if (_delegateLock > 1) {
1122 if (_departureChanged) {
1123 _departureChanged = false;
1125 _delegate->runDepartureChanged();
1129 if (_arrivalChanged) {
1130 _arrivalChanged = false;
1132 _delegate->runArrivalChanged();
1136 if (_waypointsChanged) {
1137 _waypointsChanged = false;
1140 _delegate->runWaypointsChanged();
1144 if (_currentWaypointChanged) {
1145 _currentWaypointChanged = false;
1147 _delegate->runCurrentWaypointChanged();
1154 void FlightPlan::registerDelegateFactory(DelegateFactory* df)
1156 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1157 static_delegateFactories.end(), df);
1158 if (it != static_delegateFactories.end()) {
1159 throw sg_exception("duplicate delegate factory registration");
1162 static_delegateFactories.push_back(df);
1165 void FlightPlan::unregisterDelegateFactory(DelegateFactory* df)
1167 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1168 static_delegateFactories.end(), df);
1169 if (it == static_delegateFactories.end()) {
1173 static_delegateFactories.erase(it);
1176 void FlightPlan::addDelegate(Delegate* d)
1178 // wrap any existing delegate(s) in the new one
1179 d->_inner = _delegate;
1183 void FlightPlan::removeDelegate(Delegate* d)
1185 if (d == _delegate) {
1186 _delegate = _delegate->_inner;
1187 } else if (_delegate) {
1188 _delegate->removeInner(d);
1192 FlightPlan::Delegate::Delegate() :
1193 _deleteWithPlan(false),
1199 FlightPlan::Delegate::~Delegate()
1204 void FlightPlan::Delegate::removeInner(Delegate* d)
1211 // replace with grand-child
1213 } else { // recurse downwards
1214 _inner->removeInner(d);
1218 void FlightPlan::Delegate::runDepartureChanged()
1220 if (_inner) _inner->runDepartureChanged();
1224 void FlightPlan::Delegate::runArrivalChanged()
1226 if (_inner) _inner->runArrivalChanged();
1230 void FlightPlan::Delegate::runWaypointsChanged()
1232 if (_inner) _inner->runWaypointsChanged();
1236 void FlightPlan::Delegate::runCurrentWaypointChanged()
1238 if (_inner) _inner->runCurrentWaypointChanged();
1239 currentWaypointChanged();
1242 void FlightPlan::Delegate::runCleared()
1244 if (_inner) _inner->runCleared();
1248 void FlightPlan::Delegate::runFinished()
1250 if (_inner) _inner->runFinished();
1254 } // of namespace flightgear