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 BOOST_FOREACH(Leg* l, _legs) {
101 FlightPlan* FlightPlan::clone(const string& newIdent) const
103 FlightPlan* c = new FlightPlan();
104 c->_ident = newIdent.empty() ? _ident : newIdent;
107 // copy destination / departure data.
108 c->setDeparture(_departure);
109 c->setDeparture(_departureRunway);
112 c->setApproach(_approach);
113 } else if (_destinationRunway) {
114 c->setDestination(_destinationRunway);
115 } else if (_destination) {
116 c->setDestination(_destination);
123 c->_waypointsChanged = true;
124 for (int l=0; l < numLegs(); ++l) {
125 c->_legs.push_back(_legs[l]->cloneFor(c));
131 void FlightPlan::setIdent(const string& s)
136 string FlightPlan::ident() const
141 FlightPlan::Leg* FlightPlan::insertWayptAtIndex(Waypt* aWpt, int aIndex)
151 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
152 index = _legs.size();
155 insertWayptsAtIndex(wps, index);
156 return legAtIndex(index);
159 void FlightPlan::insertWayptsAtIndex(const WayptVec& wps, int aIndex)
166 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
167 index = _legs.size();
170 LegVec::iterator it = _legs.begin();
173 int endIndex = index + wps.size() - 1;
174 if (_currentIndex >= endIndex) {
175 _currentIndex += wps.size();
179 BOOST_FOREACH(WayptRef wp, wps) {
180 newLegs.push_back(new Leg(this, wp));
184 _waypointsChanged = true;
185 _legs.insert(it, newLegs.begin(), newLegs.end());
189 void FlightPlan::deleteIndex(int aIndex)
192 if (aIndex < 0) { // negative indices count the the end
193 index = _legs.size() + index;
196 if ((index < 0) || (index >= numLegs())) {
197 SG_LOG(SG_NAVAID, SG_WARN, "removeAtIndex with invalid index:" << aIndex);
202 _waypointsChanged = true;
204 LegVec::iterator it = _legs.begin();
210 if (_currentIndex == index) {
211 // current waypoint was removed
212 _currentWaypointChanged = true;
213 } else if (_currentIndex > index) {
214 --_currentIndex; // shift current index down if necessary
220 void FlightPlan::clear()
223 _waypointsChanged = true;
224 _currentWaypointChanged = true;
225 _arrivalChanged = true;
226 _departureChanged = true;
229 BOOST_FOREACH(Leg* l, _legs) {
235 _delegate->runCleared();
243 RemoveWithFlag(WayptFlag f) : flag(f), delCount(0) { }
245 int numDeleted() const { return delCount; }
247 bool operator()(FlightPlan::Leg* leg) const
249 if (leg->waypoint()->flag(flag)) {
259 mutable int delCount;
262 int FlightPlan::clearWayptsWithFlag(WayptFlag flag)
265 // first pass, fix up currentIndex
266 for (int i=0; i<_currentIndex; ++i) {
268 if (l->waypoint()->flag(flag)) {
273 // test if the current leg will be removed
274 bool currentIsBeingCleared = false;
275 if (_currentIndex >= 0) {
276 currentIsBeingCleared = _legs[_currentIndex]->waypoint()->flag(flag);
279 _currentIndex -= count;
281 // now delete and remove
282 RemoveWithFlag rf(flag);
283 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
284 if (it == _legs.end()) {
285 return 0; // nothing was cleared, don't fire the delegate
289 _waypointsChanged = true;
290 if ((count > 0) || currentIsBeingCleared) {
291 _currentWaypointChanged = true;
294 _legs.erase(it, _legs.end());
296 if (_legs.empty()) { // maybe all legs were deleted
298 _delegate->runCleared();
303 return rf.numDeleted();
306 void FlightPlan::setCurrentIndex(int index)
308 if ((index < -1) || (index >= numLegs())) {
309 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
312 if (index == _currentIndex) {
317 _currentIndex = index;
318 _currentWaypointChanged = true;
322 void FlightPlan::finish()
324 if (_currentIndex == -1) {
330 _currentWaypointChanged = true;
333 _delegate->runFinished();
339 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
341 for (int i=0; i<numLegs(); ++i) {
342 if (_legs[i]->waypoint()->matches(aPos)) {
350 FlightPlan::Leg* FlightPlan::currentLeg() const
352 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
354 return legAtIndex(_currentIndex);
357 FlightPlan::Leg* FlightPlan::previousLeg() const
359 if (_currentIndex <= 0) {
363 return legAtIndex(_currentIndex - 1);
366 FlightPlan::Leg* FlightPlan::nextLeg() const
368 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
372 return legAtIndex(_currentIndex + 1);
375 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
377 if ((index < 0) || (index >= numLegs())) {
378 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
384 int FlightPlan::findLegIndex(const Leg *l) const
386 for (unsigned int i=0; i<_legs.size(); ++i) {
395 void FlightPlan::setDeparture(FGAirport* apt)
397 if (apt == _departure) {
402 _departureChanged = true;
404 _departureRunway = NULL;
409 void FlightPlan::setDeparture(FGRunway* rwy)
411 if (_departureRunway == rwy) {
416 _departureChanged = true;
418 _departureRunway = rwy;
419 if (rwy->airport() != _departure) {
420 _departure = rwy->airport();
426 void FlightPlan::setSID(SID* sid, const std::string& transition)
433 _departureChanged = true;
435 _sidTransition = transition;
439 void FlightPlan::setSID(Transition* trans)
446 if (trans->parent()->type() != PROCEDURE_SID)
447 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
449 setSID((SID*) trans->parent(), trans->ident());
452 Transition* FlightPlan::sidTransition() const
454 if (!_sid || _sidTransition.empty()) {
458 return _sid->findTransitionByName(_sidTransition);
461 void FlightPlan::setDestination(FGAirport* apt)
463 if (apt == _destination) {
468 _arrivalChanged = true;
470 _destinationRunway = NULL;
471 setSTAR((STAR*)NULL);
476 void FlightPlan::setDestination(FGRunway* rwy)
478 if (_destinationRunway == rwy) {
483 _arrivalChanged = true;
484 _destinationRunway = rwy;
485 if (_destination != rwy->airport()) {
486 _destination = rwy->airport();
487 setSTAR((STAR*)NULL);
493 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
500 _arrivalChanged = true;
502 _starTransition = transition;
506 void FlightPlan::setSTAR(Transition* trans)
509 setSTAR((STAR*) NULL);
513 if (trans->parent()->type() != PROCEDURE_STAR)
514 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
516 setSTAR((STAR*) trans->parent(), trans->ident());
519 Transition* FlightPlan::starTransition() const
521 if (!_star || _starTransition.empty()) {
525 return _star->findTransitionByName(_starTransition);
528 void FlightPlan::setApproach(flightgear::Approach *app)
530 if (_approach == app) {
535 _arrivalChanged = true;
538 // keep runway + airport in sync
539 if (_destinationRunway != _approach->runway()) {
540 _destinationRunway = _approach->runway();
543 if (_destination != _destinationRunway->airport()) {
544 _destination = _destinationRunway->airport();
550 bool FlightPlan::save(const SGPath& path)
552 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
554 SGPropertyNode_ptr d(new SGPropertyNode);
555 d->setIntValue("version", 2);
558 d->setStringValue("departure/airport", _departure->ident());
560 d->setStringValue("departure/sid", _sid->ident());
563 if (_departureRunway) {
564 d->setStringValue("departure/runway", _departureRunway->ident());
569 d->setStringValue("destination/airport", _destination->ident());
571 d->setStringValue("destination/star", _star->ident());
575 d->setStringValue("destination/approach", _approach->ident());
578 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
580 if (_destinationRunway) {
581 d->setStringValue("destination/runway", _destinationRunway->ident());
586 SGPropertyNode* routeNode = d->getChild("route", 0, true);
587 for (unsigned int i=0; i<_legs.size(); ++i) {
588 Waypt* wpt = _legs[i]->waypoint();
589 wpt->saveAsNode(routeNode->getChild("wp", i, true));
590 } // of waypoint iteration
591 writeProperties(path.str(), d, true /* write-all */);
593 } catch (sg_exception& e) {
594 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
599 bool FlightPlan::load(const SGPath& path)
603 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
604 << "'. The file does not exist.");
608 SGPropertyNode_ptr routeData(new SGPropertyNode);
609 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
614 readProperties(path.str(), routeData);
615 } catch (sg_exception& ) {
616 // if XML parsing fails, the file might be simple textual list of waypoints
617 Status = loadPlainTextRoute(path);
619 _waypointsChanged = true;
622 if (routeData.valid())
625 int version = routeData->getIntValue("version", 1);
627 loadVersion1XMLRoute(routeData);
628 } else if (version == 2) {
629 loadVersion2XMLRoute(routeData);
631 throw sg_io_exception("unsupported XML route version");
634 } catch (sg_exception& e) {
635 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
636 << "'. " << e.getMessage());
645 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
648 SGPropertyNode* dep = routeData->getChild("departure");
650 string depIdent = dep->getStringValue("airport");
651 setDeparture((FGAirport*) fgFindAirportID(depIdent));
653 string rwy(dep->getStringValue("runway"));
654 if (_departure->hasRunwayWithIdent(rwy)) {
655 setDeparture(_departure->getRunwayByIdent(rwy));
658 if (dep->hasChild("sid")) {
659 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
661 // departure->setStringValue("transition", dep->getStringValue("transition"));
666 SGPropertyNode* dst = routeData->getChild("destination");
668 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
670 string rwy(dst->getStringValue("runway"));
671 if (_destination->hasRunwayWithIdent(rwy)) {
672 setDestination(_destination->getRunwayByIdent(rwy));
675 if (dst->hasChild("star")) {
676 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
679 if (dst->hasChild("approach")) {
680 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
684 // destination->setStringValue("transition", dst->getStringValue("transition"));
688 SGPropertyNode* alt = routeData->getChild("alternate");
690 //alternate->setStringValue(alt->getStringValue("airport"));
694 SGPropertyNode* crs = routeData->getChild("cruise");
696 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
697 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
698 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
699 } // of cruise data loading
703 void FlightPlan::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
705 loadXMLRouteHeader(routeData);
709 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
710 for (int i=0; i<routeNode->nChildren(); ++i) {
711 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
712 Leg* l = new Leg(this, Waypt::createFromProperties(NULL, wpNode));
714 } // of route iteration
715 _waypointsChanged = true;
718 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
720 loadXMLRouteHeader(routeData);
724 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
725 for (int i=0; i<routeNode->nChildren(); ++i) {
726 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
727 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
729 } // of route iteration
730 _waypointsChanged = true;
733 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
736 if (!_legs.empty()) {
737 lastPos = _legs.back()->waypoint()->position();
738 } else if (_departure) {
739 lastPos = _departure->geod();
743 string ident(aWP->getStringValue("ident"));
744 if (aWP->hasChild("longitude-deg")) {
745 // explicit longitude/latitude
746 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
747 aWP->getDoubleValue("latitude-deg")), ident, NULL);
750 string nid = aWP->getStringValue("navid", ident.c_str());
751 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
757 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
758 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
759 aWP->getDoubleValue("latitude-deg"));
762 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
763 double radialDeg = aWP->getDoubleValue("offset-radial");
764 // convert magnetic radial to a true radial!
765 radialDeg += magvarDegAt(pos);
766 double offsetNm = aWP->getDoubleValue("offset-nm");
768 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
771 w = new BasicWaypt(pos, ident, NULL);
774 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
775 if (altFt > -9990.0) {
776 w->setAltitude(altFt, RESTRICT_AT);
782 bool FlightPlan::loadPlainTextRoute(const SGPath& path)
785 sg_gzifstream in(path.str().c_str());
787 throw sg_io_exception("Cannot open file for reading.");
793 getline(in, line, '\n');
794 // trim CR from end of line, if found
795 if (line[line.size() - 1] == '\r') {
796 line.erase(line.size() - 1, 1);
799 line = simgear::strutils::strip(line);
800 if (line.empty() || (line[0] == '#')) {
801 continue; // ignore empty/comment lines
804 WayptRef w = waypointFromString(line);
806 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
809 _legs.push_back(new Leg(this, w));
810 } // of line iteration
811 } catch (sg_exception& e) {
812 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
820 double FlightPlan::magvarDegAt(const SGGeod& pos) const
822 double jd = globals->get_time_params()->getJD();
823 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
826 WayptRef FlightPlan::waypointFromString(const string& tgt )
828 string target(boost::to_upper_copy(tgt));
833 RouteRestriction altSetting = RESTRICT_NONE;
835 size_t pos = target.find( '@' );
836 if ( pos != string::npos ) {
837 altFt = atof( target.c_str() + pos + 1 );
838 target = target.substr( 0, pos );
839 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
840 altFt *= SG_METER_TO_FEET;
841 altSetting = RESTRICT_AT;
845 pos = target.find( ',' );
846 if ( pos != string::npos ) {
847 double lon = atof( target.substr(0, pos).c_str());
848 double lat = atof( target.c_str() + pos + 1);
850 char ew = (lon < 0.0) ? 'W' : 'E';
851 char ns = (lat < 0.0) ? 'S' : 'N';
852 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
854 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
855 if (altSetting != RESTRICT_NONE) {
856 wpt->setAltitude(altFt, altSetting);
863 // route is empty, use current position
864 basePosition = globals->get_aircraft_position();
866 basePosition = _legs.back()->waypoint()->position();
869 string_list pieces(simgear::strutils::split(target, "/"));
870 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
872 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
876 double magvar = magvarDegAt(basePosition);
878 if (pieces.size() == 1) {
879 wpt = new NavaidWaypoint(p, NULL);
880 } else if (pieces.size() == 3) {
881 // navaid/radial/distance-nm notation
882 double radial = atof(pieces[1].c_str()),
883 distanceNm = atof(pieces[2].c_str());
885 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
886 } else if (pieces.size() == 2) {
887 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
889 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
893 if (!apt->hasRunwayWithIdent(pieces[1])) {
894 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
898 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
899 wpt = new NavaidWaypoint(runway, NULL);
900 } else if (pieces.size() == 4) {
901 // navid/radial/navid/radial notation
902 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
904 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
908 double r1 = atof(pieces[1].c_str()),
909 r2 = atof(pieces[3].c_str());
914 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
916 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
920 std::string name = p->ident() + "-" + p2->ident();
921 wpt = new BasicWaypt(intersection, name, NULL);
925 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
929 if (altSetting != RESTRICT_NONE) {
930 wpt->setAltitude(altFt, altSetting);
935 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
937 _speedRestrict(RESTRICT_NONE),
938 _altRestrict(RESTRICT_NONE),
942 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
944 _speed = _altitudeFt = 0;
947 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
949 Leg* c = new Leg(owner, _waypt);
952 c->_speedRestrict = _speedRestrict;
953 c->_altitudeFt = _altitudeFt;
954 c->_altRestrict = _altRestrict;
959 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
961 return _parent->legAtIndex(index() + 1);
964 unsigned int FlightPlan::Leg::index() const
966 return _parent->findLegIndex(this);
969 int FlightPlan::Leg::altitudeFt() const
971 if (_altRestrict != RESTRICT_NONE) {
975 return _waypt->altitudeFt();
978 int FlightPlan::Leg::speed() const
980 if (_speedRestrict != RESTRICT_NONE) {
984 return _waypt->speed();
987 int FlightPlan::Leg::speedKts() const
992 double FlightPlan::Leg::speedMach() const
994 if (!isMachRestrict(_speedRestrict)) {
998 return -(_speed / 100.0);
1001 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
1003 if (_altRestrict != RESTRICT_NONE) {
1004 return _altRestrict;
1007 return _waypt->altitudeRestriction();
1010 RouteRestriction FlightPlan::Leg::speedRestriction() const
1012 if (_speedRestrict != RESTRICT_NONE) {
1013 return _speedRestrict;
1016 return _waypt->speedRestriction();
1019 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
1021 _speedRestrict = ty;
1022 if (isMachRestrict(ty)) {
1023 _speed = (speed * -100);
1029 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1032 _altitudeFt = altFt;
1035 double FlightPlan::Leg::courseDeg() const
1040 double FlightPlan::Leg::distanceNm() const
1042 return _pathDistance;
1045 double FlightPlan::Leg::distanceAlongRoute() const
1047 return _distanceAlongPath;
1050 void FlightPlan::rebuildLegData()
1052 _totalDistance = 0.0;
1053 int lastLeg = static_cast<int>(_legs.size()) - 1;
1054 for (int l=0; l<lastLeg; ++l) {
1055 Leg* cur = _legs[l];
1056 Leg* next = _legs[l + 1];
1058 std::pair<double, double> crsDist =
1059 next->waypoint()->courseAndDistanceFrom(cur->waypoint()->position());
1060 _legs[l]->_courseDeg = crsDist.first;
1061 _legs[l]->_pathDistance = crsDist.second * SG_METER_TO_NM;
1062 _legs[l]->_distanceAlongPath = _totalDistance;
1063 _totalDistance += crsDist.second * SG_METER_TO_NM;
1064 } // of legs iteration
1066 // set some data on the final leg
1068 // keep the same course as the final leg, when passing the final
1070 _legs[lastLeg]->_courseDeg = _legs[lastLeg - 1]->_courseDeg;
1071 _legs[lastLeg]->_pathDistance = 0.0;
1072 _legs[lastLeg]->_distanceAlongPath = _totalDistance;
1076 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1078 if (aIndex >= (int) _legs.size()) {
1079 throw sg_range_exception();
1082 const int lastLeg = static_cast<int>(_legs.size()) - 1;
1083 // convert the relative offset and leg index into an absolute, positive
1084 // distance in nm from the route origin. This means we can simply walk
1085 // forwards to find the actual leg.
1086 Leg* leg = _legs[(aIndex >= 0) ? aIndex : lastLeg];
1087 double absolutePathDistance = leg->_distanceAlongPath + aOffsetNm;
1088 if (absolutePathDistance < 0.0) {
1089 return _legs[0]->waypoint()->position(); // begining of route
1092 if (absolutePathDistance > _totalDistance) {
1093 return _legs[lastLeg]->waypoint()->position(); // end of route
1096 // find the leg containing the absolute distance
1097 for (int l=0; l<lastLeg; ++l) {
1099 if (absolutePathDistance < leg->_pathDistance) {
1100 break; // found our matching leg
1102 absolutePathDistance -= leg->_pathDistance;
1103 } // of forwards walk along route to find leg
1105 return SGGeodesy::direct(leg->waypoint()->position(),
1106 leg->_courseDeg, absolutePathDistance * SG_NM_TO_METER);
1109 void FlightPlan::lockDelegate()
1111 if (_delegateLock == 0) {
1112 assert(!_departureChanged && !_arrivalChanged &&
1113 !_waypointsChanged && !_currentWaypointChanged);
1119 void FlightPlan::unlockDelegate()
1121 assert(_delegateLock > 0);
1122 if (_delegateLock > 1) {
1127 if (_departureChanged) {
1128 _departureChanged = false;
1130 _delegate->runDepartureChanged();
1134 if (_arrivalChanged) {
1135 _arrivalChanged = false;
1137 _delegate->runArrivalChanged();
1141 if (_waypointsChanged) {
1142 _waypointsChanged = false;
1145 _delegate->runWaypointsChanged();
1149 if (_currentWaypointChanged) {
1150 _currentWaypointChanged = false;
1152 _delegate->runCurrentWaypointChanged();
1159 void FlightPlan::registerDelegateFactory(DelegateFactory* df)
1161 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1162 static_delegateFactories.end(), df);
1163 if (it != static_delegateFactories.end()) {
1164 throw sg_exception("duplicate delegate factory registration");
1167 static_delegateFactories.push_back(df);
1170 void FlightPlan::unregisterDelegateFactory(DelegateFactory* df)
1172 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1173 static_delegateFactories.end(), df);
1174 if (it == static_delegateFactories.end()) {
1178 static_delegateFactories.erase(it);
1181 void FlightPlan::addDelegate(Delegate* d)
1183 // wrap any existing delegate(s) in the new one
1184 d->_inner = _delegate;
1188 void FlightPlan::removeDelegate(Delegate* d)
1190 if (d == _delegate) {
1191 _delegate = _delegate->_inner;
1192 } else if (_delegate) {
1193 _delegate->removeInner(d);
1197 FlightPlan::Delegate::Delegate() :
1198 _deleteWithPlan(false),
1203 FlightPlan::Delegate::~Delegate()
1207 void FlightPlan::Delegate::removeInner(Delegate* d)
1210 throw sg_exception("FlightPlan delegate not found");
1214 // replace with grand-child
1216 } else { // recurse downwards
1217 _inner->removeInner(d);
1221 void FlightPlan::Delegate::runDepartureChanged()
1223 if (_inner) _inner->runDepartureChanged();
1227 void FlightPlan::Delegate::runArrivalChanged()
1229 if (_inner) _inner->runArrivalChanged();
1233 void FlightPlan::Delegate::runWaypointsChanged()
1235 if (_inner) _inner->runWaypointsChanged();
1239 void FlightPlan::Delegate::runCurrentWaypointChanged()
1241 if (_inner) _inner->runCurrentWaypointChanged();
1242 currentWaypointChanged();
1245 void FlightPlan::Delegate::runCleared()
1247 if (_inner) _inner->runCleared();
1251 void FlightPlan::Delegate::runFinished()
1253 if (_inner) _inner->runFinished();
1257 } // of namespace flightgear