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 Leg* curLeg = currentLeg();
277 currentIsBeingCleared = curLeg->waypoint()->flag(flag);
280 _currentIndex -= count;
282 // if we're clearing the current waypoint, what shall we do with the
283 // index? there's various options, but safest is to select no waypoint
284 // and let the use re-activate.
285 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1134
286 if (currentIsBeingCleared) {
287 SG_LOG(SG_GENERAL, SG_INFO, "currentIsBeingCleared:" << currentIsBeingCleared);
291 // now delete and remove
292 RemoveWithFlag rf(flag);
293 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
294 if (it == _legs.end()) {
295 return 0; // nothing was cleared, don't fire the delegate
299 _waypointsChanged = true;
300 if ((count > 0) || currentIsBeingCleared) {
301 _currentWaypointChanged = true;
304 _legs.erase(it, _legs.end());
306 if (_legs.empty()) { // maybe all legs were deleted
308 _delegate->runCleared();
313 return rf.numDeleted();
316 void FlightPlan::setCurrentIndex(int index)
318 if ((index < -1) || (index >= numLegs())) {
319 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
322 if (index == _currentIndex) {
327 _currentIndex = index;
328 _currentWaypointChanged = true;
332 void FlightPlan::finish()
334 if (_currentIndex == -1) {
340 _currentWaypointChanged = true;
343 _delegate->runFinished();
349 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
351 for (int i=0; i<numLegs(); ++i) {
352 if (_legs[i]->waypoint()->matches(aPos)) {
360 FlightPlan::Leg* FlightPlan::currentLeg() const
362 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
364 return legAtIndex(_currentIndex);
367 FlightPlan::Leg* FlightPlan::previousLeg() const
369 if (_currentIndex <= 0) {
373 return legAtIndex(_currentIndex - 1);
376 FlightPlan::Leg* FlightPlan::nextLeg() const
378 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
382 return legAtIndex(_currentIndex + 1);
385 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
387 if ((index < 0) || (index >= numLegs())) {
388 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
394 int FlightPlan::findLegIndex(const Leg *l) const
396 for (unsigned int i=0; i<_legs.size(); ++i) {
405 void FlightPlan::setDeparture(FGAirport* apt)
407 if (apt == _departure) {
412 _departureChanged = true;
414 _departureRunway = NULL;
419 void FlightPlan::setDeparture(FGRunway* rwy)
421 if (_departureRunway == rwy) {
426 _departureChanged = true;
428 _departureRunway = rwy;
429 if (rwy->airport() != _departure) {
430 _departure = rwy->airport();
436 void FlightPlan::setSID(SID* sid, const std::string& transition)
443 _departureChanged = true;
445 _sidTransition = transition;
449 void FlightPlan::setSID(Transition* trans)
456 if (trans->parent()->type() != PROCEDURE_SID)
457 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
459 setSID((SID*) trans->parent(), trans->ident());
462 Transition* FlightPlan::sidTransition() const
464 if (!_sid || _sidTransition.empty()) {
468 return _sid->findTransitionByName(_sidTransition);
471 void FlightPlan::setDestination(FGAirport* apt)
473 if (apt == _destination) {
478 _arrivalChanged = true;
480 _destinationRunway = NULL;
481 setSTAR((STAR*)NULL);
486 void FlightPlan::setDestination(FGRunway* rwy)
488 if (_destinationRunway == rwy) {
493 _arrivalChanged = true;
494 _destinationRunway = rwy;
495 if (_destination != rwy->airport()) {
496 _destination = rwy->airport();
497 setSTAR((STAR*)NULL);
503 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
510 _arrivalChanged = true;
512 _starTransition = transition;
516 void FlightPlan::setSTAR(Transition* trans)
519 setSTAR((STAR*) NULL);
523 if (trans->parent()->type() != PROCEDURE_STAR)
524 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
526 setSTAR((STAR*) trans->parent(), trans->ident());
529 Transition* FlightPlan::starTransition() const
531 if (!_star || _starTransition.empty()) {
535 return _star->findTransitionByName(_starTransition);
538 void FlightPlan::setApproach(flightgear::Approach *app)
540 if (_approach == app) {
545 _arrivalChanged = true;
548 // keep runway + airport in sync
549 if (_destinationRunway != _approach->runway()) {
550 _destinationRunway = _approach->runway();
553 if (_destination != _destinationRunway->airport()) {
554 _destination = _destinationRunway->airport();
560 bool FlightPlan::save(const SGPath& path)
562 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
564 SGPropertyNode_ptr d(new SGPropertyNode);
565 d->setIntValue("version", 2);
568 d->setStringValue("departure/airport", _departure->ident());
570 d->setStringValue("departure/sid", _sid->ident());
573 if (_departureRunway) {
574 d->setStringValue("departure/runway", _departureRunway->ident());
579 d->setStringValue("destination/airport", _destination->ident());
581 d->setStringValue("destination/star", _star->ident());
585 d->setStringValue("destination/approach", _approach->ident());
588 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
590 if (_destinationRunway) {
591 d->setStringValue("destination/runway", _destinationRunway->ident());
596 SGPropertyNode* routeNode = d->getChild("route", 0, true);
597 for (unsigned int i=0; i<_legs.size(); ++i) {
598 Waypt* wpt = _legs[i]->waypoint();
599 wpt->saveAsNode(routeNode->getChild("wp", i, true));
600 } // of waypoint iteration
601 writeProperties(path.str(), d, true /* write-all */);
603 } catch (sg_exception& e) {
604 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
609 bool FlightPlan::load(const SGPath& path)
613 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
614 << "'. The file does not exist.");
618 SGPropertyNode_ptr routeData(new SGPropertyNode);
619 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
624 readProperties(path.str(), routeData);
625 } catch (sg_exception& ) {
626 // if XML parsing fails, the file might be simple textual list of waypoints
627 Status = loadPlainTextRoute(path);
629 _waypointsChanged = true;
632 if (routeData.valid())
635 int version = routeData->getIntValue("version", 1);
637 loadVersion1XMLRoute(routeData);
638 } else if (version == 2) {
639 loadVersion2XMLRoute(routeData);
641 throw sg_io_exception("unsupported XML route version");
644 } catch (sg_exception& e) {
645 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
646 << "'. " << e.getMessage());
655 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
658 SGPropertyNode* dep = routeData->getChild("departure");
660 string depIdent = dep->getStringValue("airport");
661 setDeparture((FGAirport*) fgFindAirportID(depIdent));
663 string rwy(dep->getStringValue("runway"));
664 if (_departure->hasRunwayWithIdent(rwy)) {
665 setDeparture(_departure->getRunwayByIdent(rwy));
668 if (dep->hasChild("sid")) {
669 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
671 // departure->setStringValue("transition", dep->getStringValue("transition"));
676 SGPropertyNode* dst = routeData->getChild("destination");
678 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
680 string rwy(dst->getStringValue("runway"));
681 if (_destination->hasRunwayWithIdent(rwy)) {
682 setDestination(_destination->getRunwayByIdent(rwy));
685 if (dst->hasChild("star")) {
686 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
689 if (dst->hasChild("approach")) {
690 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
694 // destination->setStringValue("transition", dst->getStringValue("transition"));
698 SGPropertyNode* alt = routeData->getChild("alternate");
700 //alternate->setStringValue(alt->getStringValue("airport"));
704 SGPropertyNode* crs = routeData->getChild("cruise");
706 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
707 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
708 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
709 } // of cruise data loading
713 void FlightPlan::loadVersion2XMLRoute(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, Waypt::createFromProperties(NULL, wpNode));
724 } // of route iteration
725 _waypointsChanged = true;
728 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
730 loadXMLRouteHeader(routeData);
734 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
735 for (int i=0; i<routeNode->nChildren(); ++i) {
736 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
737 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
739 } // of route iteration
740 _waypointsChanged = true;
743 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
746 if (!_legs.empty()) {
747 lastPos = _legs.back()->waypoint()->position();
748 } else if (_departure) {
749 lastPos = _departure->geod();
753 string ident(aWP->getStringValue("ident"));
754 if (aWP->hasChild("longitude-deg")) {
755 // explicit longitude/latitude
756 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
757 aWP->getDoubleValue("latitude-deg")), ident, NULL);
760 string nid = aWP->getStringValue("navid", ident.c_str());
761 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
767 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
768 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
769 aWP->getDoubleValue("latitude-deg"));
772 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
773 double radialDeg = aWP->getDoubleValue("offset-radial");
774 // convert magnetic radial to a true radial!
775 radialDeg += magvarDegAt(pos);
776 double offsetNm = aWP->getDoubleValue("offset-nm");
778 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
781 w = new BasicWaypt(pos, ident, NULL);
784 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
785 if (altFt > -9990.0) {
786 w->setAltitude(altFt, RESTRICT_AT);
792 bool FlightPlan::loadPlainTextRoute(const SGPath& path)
795 sg_gzifstream in(path.str().c_str());
797 throw sg_io_exception("Cannot open file for reading.");
803 getline(in, line, '\n');
804 // trim CR from end of line, if found
805 if (line[line.size() - 1] == '\r') {
806 line.erase(line.size() - 1, 1);
809 line = simgear::strutils::strip(line);
810 if (line.empty() || (line[0] == '#')) {
811 continue; // ignore empty/comment lines
814 WayptRef w = waypointFromString(line);
816 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
819 _legs.push_back(new Leg(this, w));
820 } // of line iteration
821 } catch (sg_exception& e) {
822 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
830 double FlightPlan::magvarDegAt(const SGGeod& pos) const
832 double jd = globals->get_time_params()->getJD();
833 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
836 WayptRef FlightPlan::waypointFromString(const string& tgt )
838 string target(boost::to_upper_copy(tgt));
843 RouteRestriction altSetting = RESTRICT_NONE;
845 size_t pos = target.find( '@' );
846 if ( pos != string::npos ) {
847 altFt = atof( target.c_str() + pos + 1 );
848 target = target.substr( 0, pos );
849 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
850 altFt *= SG_METER_TO_FEET;
851 altSetting = RESTRICT_AT;
855 pos = target.find( ',' );
856 if ( pos != string::npos ) {
857 double lon = atof( target.substr(0, pos).c_str());
858 double lat = atof( target.c_str() + pos + 1);
860 char ew = (lon < 0.0) ? 'W' : 'E';
861 char ns = (lat < 0.0) ? 'S' : 'N';
862 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
864 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
865 if (altSetting != RESTRICT_NONE) {
866 wpt->setAltitude(altFt, altSetting);
873 // route is empty, use current position
874 basePosition = globals->get_aircraft_position();
876 basePosition = _legs.back()->waypoint()->position();
879 string_list pieces(simgear::strutils::split(target, "/"));
880 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
882 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
886 double magvar = magvarDegAt(basePosition);
888 if (pieces.size() == 1) {
889 wpt = new NavaidWaypoint(p, NULL);
890 } else if (pieces.size() == 3) {
891 // navaid/radial/distance-nm notation
892 double radial = atof(pieces[1].c_str()),
893 distanceNm = atof(pieces[2].c_str());
895 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
896 } else if (pieces.size() == 2) {
897 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
899 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
903 if (!apt->hasRunwayWithIdent(pieces[1])) {
904 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
908 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
909 wpt = new NavaidWaypoint(runway, NULL);
910 } else if (pieces.size() == 4) {
911 // navid/radial/navid/radial notation
912 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
914 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
918 double r1 = atof(pieces[1].c_str()),
919 r2 = atof(pieces[3].c_str());
924 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
926 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
930 std::string name = p->ident() + "-" + p2->ident();
931 wpt = new BasicWaypt(intersection, name, NULL);
935 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
939 if (altSetting != RESTRICT_NONE) {
940 wpt->setAltitude(altFt, altSetting);
945 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
947 _speedRestrict(RESTRICT_NONE),
948 _altRestrict(RESTRICT_NONE),
952 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
954 _speed = _altitudeFt = 0;
957 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
959 Leg* c = new Leg(owner, _waypt);
962 c->_speedRestrict = _speedRestrict;
963 c->_altitudeFt = _altitudeFt;
964 c->_altRestrict = _altRestrict;
969 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
971 return _parent->legAtIndex(index() + 1);
974 unsigned int FlightPlan::Leg::index() const
976 return _parent->findLegIndex(this);
979 int FlightPlan::Leg::altitudeFt() const
981 if (_altRestrict != RESTRICT_NONE) {
985 return _waypt->altitudeFt();
988 int FlightPlan::Leg::speed() const
990 if (_speedRestrict != RESTRICT_NONE) {
994 return _waypt->speed();
997 int FlightPlan::Leg::speedKts() const
1002 double FlightPlan::Leg::speedMach() const
1004 if (!isMachRestrict(_speedRestrict)) {
1008 return -(_speed / 100.0);
1011 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
1013 if (_altRestrict != RESTRICT_NONE) {
1014 return _altRestrict;
1017 return _waypt->altitudeRestriction();
1020 RouteRestriction FlightPlan::Leg::speedRestriction() const
1022 if (_speedRestrict != RESTRICT_NONE) {
1023 return _speedRestrict;
1026 return _waypt->speedRestriction();
1029 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
1031 _speedRestrict = ty;
1032 if (isMachRestrict(ty)) {
1033 _speed = (speed * -100);
1039 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1042 _altitudeFt = altFt;
1045 double FlightPlan::Leg::courseDeg() const
1050 double FlightPlan::Leg::distanceNm() const
1052 return _pathDistance;
1055 double FlightPlan::Leg::distanceAlongRoute() const
1057 return _distanceAlongPath;
1060 void FlightPlan::rebuildLegData()
1062 _totalDistance = 0.0;
1063 int lastLeg = static_cast<int>(_legs.size()) - 1;
1064 for (int l=0; l<lastLeg; ++l) {
1065 Leg* cur = _legs[l];
1066 Leg* next = _legs[l + 1];
1068 std::pair<double, double> crsDist =
1069 next->waypoint()->courseAndDistanceFrom(cur->waypoint()->position());
1070 _legs[l]->_courseDeg = crsDist.first;
1071 _legs[l]->_pathDistance = crsDist.second * SG_METER_TO_NM;
1072 _legs[l]->_distanceAlongPath = _totalDistance;
1073 _totalDistance += crsDist.second * SG_METER_TO_NM;
1074 } // of legs iteration
1076 // set some data on the final leg
1078 // keep the same course as the final leg, when passing the final
1080 _legs[lastLeg]->_courseDeg = _legs[lastLeg - 1]->_courseDeg;
1081 _legs[lastLeg]->_pathDistance = 0.0;
1082 _legs[lastLeg]->_distanceAlongPath = _totalDistance;
1086 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1088 if (aIndex >= (int) _legs.size()) {
1089 throw sg_range_exception();
1092 const int lastLeg = static_cast<int>(_legs.size()) - 1;
1093 // convert the relative offset and leg index into an absolute, positive
1094 // distance in nm from the route origin. This means we can simply walk
1095 // forwards to find the actual leg.
1096 Leg* leg = _legs[(aIndex >= 0) ? aIndex : lastLeg];
1097 double absolutePathDistance = leg->_distanceAlongPath + aOffsetNm;
1098 if (absolutePathDistance < 0.0) {
1099 return _legs[0]->waypoint()->position(); // begining of route
1102 if (absolutePathDistance > _totalDistance) {
1103 return _legs[lastLeg]->waypoint()->position(); // end of route
1106 // find the leg containing the absolute distance
1107 for (int l=0; l<lastLeg; ++l) {
1109 if (absolutePathDistance < leg->_pathDistance) {
1110 break; // found our matching leg
1112 absolutePathDistance -= leg->_pathDistance;
1113 } // of forwards walk along route to find leg
1115 return SGGeodesy::direct(leg->waypoint()->position(),
1116 leg->_courseDeg, absolutePathDistance * SG_NM_TO_METER);
1119 void FlightPlan::lockDelegate()
1121 if (_delegateLock == 0) {
1122 assert(!_departureChanged && !_arrivalChanged &&
1123 !_waypointsChanged && !_currentWaypointChanged);
1129 void FlightPlan::unlockDelegate()
1131 assert(_delegateLock > 0);
1132 if (_delegateLock > 1) {
1137 if (_departureChanged) {
1138 _departureChanged = false;
1140 _delegate->runDepartureChanged();
1144 if (_arrivalChanged) {
1145 _arrivalChanged = false;
1147 _delegate->runArrivalChanged();
1151 if (_waypointsChanged) {
1152 _waypointsChanged = false;
1155 _delegate->runWaypointsChanged();
1159 if (_currentWaypointChanged) {
1160 _currentWaypointChanged = false;
1162 _delegate->runCurrentWaypointChanged();
1169 void FlightPlan::registerDelegateFactory(DelegateFactory* df)
1171 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1172 static_delegateFactories.end(), df);
1173 if (it != static_delegateFactories.end()) {
1174 throw sg_exception("duplicate delegate factory registration");
1177 static_delegateFactories.push_back(df);
1180 void FlightPlan::unregisterDelegateFactory(DelegateFactory* df)
1182 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1183 static_delegateFactories.end(), df);
1184 if (it == static_delegateFactories.end()) {
1188 static_delegateFactories.erase(it);
1191 void FlightPlan::addDelegate(Delegate* d)
1193 // wrap any existing delegate(s) in the new one
1194 d->_inner = _delegate;
1198 void FlightPlan::removeDelegate(Delegate* d)
1200 if (d == _delegate) {
1201 _delegate = _delegate->_inner;
1202 } else if (_delegate) {
1203 _delegate->removeInner(d);
1207 FlightPlan::Delegate::Delegate() :
1208 _deleteWithPlan(false),
1213 FlightPlan::Delegate::~Delegate()
1217 void FlightPlan::Delegate::removeInner(Delegate* d)
1220 throw sg_exception("FlightPlan delegate not found");
1224 // replace with grand-child
1226 } else { // recurse downwards
1227 _inner->removeInner(d);
1231 void FlightPlan::Delegate::runDepartureChanged()
1233 if (_inner) _inner->runDepartureChanged();
1237 void FlightPlan::Delegate::runArrivalChanged()
1239 if (_inner) _inner->runArrivalChanged();
1243 void FlightPlan::Delegate::runWaypointsChanged()
1245 if (_inner) _inner->runWaypointsChanged();
1249 void FlightPlan::Delegate::runCurrentWaypointChanged()
1251 if (_inner) _inner->runCurrentWaypointChanged();
1252 currentWaypointChanged();
1255 void FlightPlan::Delegate::runCleared()
1257 if (_inner) _inner->runCleared();
1261 void FlightPlan::Delegate::runFinished()
1263 if (_inner) _inner->runFinished();
1267 } // of namespace flightgear