1 // gps.cxx - distance-measuring equipment.
2 // Written by David Megginson, started 2003.
4 // This file is in the Public Domain and comes with no warranty.
12 #include <boost/tuple/tuple.hpp>
18 #include "Main/fg_props.hxx"
19 #include "Main/globals.hxx" // for get_subsystem
20 #include "Main/util.hxx" // for fgLowPass
21 #include "Navaids/positioned.hxx"
22 #include <Navaids/waypoint.hxx>
23 #include "Navaids/navrecord.hxx"
24 #include "Airports/simple.hxx"
25 #include "Airports/runways.hxx"
26 #include "Autopilot/route_mgr.hxx"
28 #include <simgear/math/sg_random.h>
29 #include <simgear/sg_inlines.h>
30 #include <simgear/math/sg_geodesy.hxx>
31 #include <simgear/structure/exception.hxx>
35 using namespace flightgear;
38 static const char* makeTTWString(double TTW)
40 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
44 unsigned int TTW_seconds = (int) (TTW + 0.5);
45 unsigned int TTW_minutes = 0;
46 unsigned int TTW_hours = 0;
47 static char TTW_str[9];
48 TTW_hours = TTW_seconds / 3600;
49 TTW_minutes = (TTW_seconds / 60) % 60;
50 TTW_seconds = TTW_seconds % 60;
51 snprintf(TTW_str, 9, "%02d:%02d:%02d",
52 TTW_hours, TTW_minutes, TTW_seconds);
56 /////////////////////////////////////////////////////////////////////////////
58 class GPSListener : public SGPropertyChangeListener
65 virtual void valueChanged (SGPropertyNode * prop)
72 if (prop == _gps->_route_current_wp_node) {
73 _gps->routeManagerSequenced();
74 } else if (prop == _gps->_route_active_node) {
75 _gps->routeActivated();
76 } else if (prop == _gps->_ref_navaid_id_node) {
77 _gps->referenceNavaidSet(prop->getStringValue(""));
78 } else if (prop == _gps->_routeEditedSignal) {
80 } else if (prop == _gps->_routeFinishedSignal) {
81 _gps->routeFinished();
87 void setGuard(bool g) {
92 bool _guard; // re-entrancy guard
95 ////////////////////////////////////////////////////////////////////////////
97 * Helper to monitor for Nasal or other code accessing properties we haven't
98 * defined. For the moment we complain about all such activites, since various
99 * users assume all kinds of weird, wonderful and non-existent interfaces.
102 class DeprecatedPropListener : public SGPropertyChangeListener
105 DeprecatedPropListener(SGPropertyNode* gps)
107 _parents.insert(gps);
108 SGPropertyNode* wp = gps->getChild("wp", 0, true);
110 _parents.insert(wp->getChild("wp", 0, true));
111 _parents.insert(wp->getChild("wp", 1, true));
113 std::set<SGPropertyNode*>::iterator it;
114 for (it = _parents.begin(); it != _parents.end(); ++it) {
115 (*it)->addChangeListener(this);
119 virtual void valueChanged (SGPropertyNode * prop)
123 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
125 if (isDeprecated(parent, child)) {
126 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
127 << child->getPath(true));
131 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
133 if (_parents.count(parent) < 1) {
137 // no child exclusions yet
141 std::set<SGPropertyNode*> _parents;
144 ////////////////////////////////////////////////////////////////////////////
145 // configuration helper object
147 GPS::Config::Config() :
148 _enableTurnAnticipation(true),
149 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
150 _overflightArmDistance(1.0),
151 _waypointAlertTime(30.0),
152 _requireHardSurface(true),
153 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
154 _driveAutopilot(true),
155 _courseSelectable(false)
157 _enableTurnAnticipation = false;
160 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
162 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
163 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
164 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
165 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
166 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
167 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
168 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
171 ////////////////////////////////////////////////////////////////////////////
173 GPS::GPS ( SGPropertyNode *node) :
174 _selectedCourse(0.0),
177 _lastPosValid(false),
179 _name(node->getStringValue("name", "gps")),
180 _num(node->getIntValue("number", 0)),
181 _searchResultIndex(0),
183 _searchIsRoute(false),
184 _searchHasNext(false),
186 _computeTurnData(false),
187 _anticipateTurn(false),
190 string branch = "/instrumentation/" + _name;
191 _gpsNode = fgGetNode(branch.c_str(), _num, true );
192 _scratchNode = _gpsNode->getChild("scratch", 0, true);
194 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
195 _currentWayptNode = wp_node->getChild("wp", 1, true);
205 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
208 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
209 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
210 _serviceable_node->setBoolValue(true);
211 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
214 _raim_node = _gpsNode->getChild("raim", 0, true);
215 _odometer_node = _gpsNode->getChild("odometer", 0, true);
216 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
217 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
218 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
219 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
220 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
223 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
224 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
225 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
227 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
230 SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
231 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
232 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
233 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
234 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
235 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
236 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
237 _ref_navaid_elapsed = 0.0;
238 _ref_navaid_set = false;
241 // should these move to the route manager?
242 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
243 _routeETE = _gpsNode->getChild("ETE", 0, true);
244 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
245 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
247 // add listener to various things
248 _listener = new GPSListener(this);
249 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
250 _route_current_wp_node->addChangeListener(_listener);
251 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
252 _route_active_node->addChangeListener(_listener);
253 _ref_navaid_id_node->addChangeListener(_listener);
254 _routeEditedSignal->addChangeListener(_listener);
255 _routeFinishedSignal->addChangeListener(_listener);
257 // navradio slaving properties
258 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
259 toFlag->alias(_currentWayptNode->getChild("to-flag"));
261 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
262 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
264 // autopilot drive properties
265 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
266 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
267 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
268 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
271 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
272 if (!_realismSimpleGps->hasValue()) {
273 _realismSimpleGps->setBoolValue(true);
276 // last thing, add the deprecated prop watcher
277 new DeprecatedPropListener(_gpsNode);
289 _config.bind(this, _gpsNode->getChild("config", 0, true));
292 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
293 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
295 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
296 (*this, &GPS::getDesiredCourse, NULL));
297 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
299 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
300 "indicated-latitude-deg", "indicated-altitude-ft");
302 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
303 (*this, &GPS::getVerticalSpeed, NULL));
304 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
305 (*this, &GPS::getTrueTrack, NULL));
306 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
307 (*this, &GPS::getMagTrack, NULL));
308 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
309 (*this, &GPS::getGroundspeedKts, NULL));
312 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
313 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
315 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
316 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
317 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
318 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
319 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
320 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
321 _scratchValid = false;
324 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
325 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
327 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
328 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
329 (*this, &GPS::getWP1Ident, NULL));
331 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
332 (*this, &GPS::getWP1Distance, NULL));
333 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
334 (*this, &GPS::getWP1Bearing, NULL));
335 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
336 (*this, &GPS::getWP1MagBearing, NULL));
337 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
338 (*this, &GPS::getWP1TTW, NULL));
339 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
340 (*this, &GPS::getWP1TTWString, NULL));
342 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
343 (*this, &GPS::getWP1CourseDeviation, NULL));
344 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
345 (*this, &GPS::getWP1CourseErrorNm, NULL));
346 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
347 (*this, &GPS::getWP1ToFlag, NULL));
348 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
349 (*this, &GPS::getWP1FromFlag, NULL));
351 // leg properties (only valid in DTO/LEG modes, not OBS)
352 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
353 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
354 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
356 // navradio slaving properties
357 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
358 (*this, &GPS::getCDIDeflection));
364 _tiedProperties.Untie();
371 _last_speed_kts = 0.0;
372 _last_pos = SGGeod();
373 _lastPosValid = false;
374 _indicated_pos = SGGeod();
375 _last_vertical_speed = 0.0;
376 _last_true_track = 0.0;
377 _lastEWVelocity = _lastNSVelocity = 0.0;
378 _currentWaypt = _prevWaypt = NULL;
379 _legDistanceNm = -1.0;
381 _raim_node->setDoubleValue(0.0);
382 _indicated_pos = SGGeod();
383 _odometer_node->setDoubleValue(0);
384 _trip_odometer_node->setDoubleValue(0);
385 _tracking_bug_node->setDoubleValue(0);
386 _true_bug_error_node->setDoubleValue(0);
387 _magnetic_bug_error_node->setDoubleValue(0);
388 _northSouthVelocity->setDoubleValue(0.0);
389 _eastWestVelocity->setDoubleValue(0.0);
393 GPS::update (double delta_time_sec)
395 if (!_realismSimpleGps->getBoolValue()) {
396 // If it's off, don't bother.
397 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
403 if (delta_time_sec <= 0.0) {
404 return; // paused, don't bother
407 _raim_node->setDoubleValue(1.0);
408 _indicated_pos = globals->get_aircraft_position();
409 updateBasicData(delta_time_sec);
412 if (_wayptController.get()) {
413 _wayptController->update();
414 SGGeod p(_wayptController->position());
415 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
416 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
417 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
419 _desiredCourse = getLegMagCourse();
427 updateReferenceNavaid(delta_time_sec);
431 if (_dataValid && (_mode == "init")) {
433 if (_route_active_node->getBoolValue()) {
434 // GPS init with active route
435 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
438 // initialise in OBS mode, with waypt set to the nearest airport.
439 // keep in mind at this point, _dataValid is not set
441 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
442 FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
444 setScratchFromPositioned(apt, 0);
451 // allow a realistic delay in the future, here
453 } // of init mode check
455 _last_pos = _indicated_pos;
456 _lastPosValid = !(_last_pos == SGGeod());
459 ///////////////////////////////////////////////////////////////////////////
460 // implement the RNAV interface
461 SGGeod GPS::position()
467 return _indicated_pos;
470 double GPS::trackDeg()
472 return _last_true_track;
475 double GPS::groundSpeedKts()
477 return _last_speed_kts;
480 double GPS::vspeedFPM()
482 return _last_vertical_speed;
485 double GPS::magvarDeg()
487 return _magvar_node->getDoubleValue();
490 double GPS::overflightArmDistanceM()
492 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
495 double GPS::selectedMagCourse()
497 return _selectedCourse;
500 ///////////////////////////////////////////////////////////////////////////
503 GPS::updateBasicData(double dt)
505 if (!_lastPosValid) {
511 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
513 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
514 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
515 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
517 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
518 _last_speed_kts = speed_kt;
520 SGGeod g = _indicated_pos;
521 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
522 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
523 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
525 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
526 _lastNSVelocity = nsMSec;
527 _northSouthVelocity->setDoubleValue(nsMSec);
531 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
532 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
533 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
535 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
536 _lastEWVelocity = ewMSec;
537 _eastWestVelocity->setDoubleValue(ewMSec);
539 double odometer = _odometer_node->getDoubleValue();
540 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
541 odometer = _trip_odometer_node->getDoubleValue();
542 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
550 GPS::updateTrackingBug()
552 double tracking_bug = _tracking_bug_node->getDoubleValue();
553 double true_bug_error = tracking_bug - getTrueTrack();
554 double magnetic_bug_error = tracking_bug - getMagTrack();
556 // Get the errors into the (-180,180) range.
557 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
558 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
560 _true_bug_error_node->setDoubleValue(true_bug_error);
561 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
564 void GPS::updateReferenceNavaid(double dt)
566 if (!_ref_navaid_set) {
567 _ref_navaid_elapsed += dt;
568 if (_ref_navaid_elapsed > 5.0) {
570 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
571 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
573 SG_LOG(SG_INSTR, SG_DEBUG, "GPS couldn't find a reference navaid");
574 _ref_navaid_id_node->setStringValue("");
575 _ref_navaid_name_node->setStringValue("");
576 _ref_navaid_bearing_node->setDoubleValue(0.0);
577 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
578 _ref_navaid_distance_node->setDoubleValue(0.0);
579 _ref_navaid_frequency_node->setStringValue("");
580 } else if (nav != _ref_navaid) {
581 SG_LOG(SG_INSTR, SG_DEBUG, "GPS code selected new ref-navaid:" << nav->ident());
582 _listener->setGuard(true);
583 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
584 _ref_navaid_name_node->setStringValue(nav->name().c_str());
585 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
586 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
587 _listener->setGuard(false);
589 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
593 // reset elapsed time (do not do that before updating the properties above, since their
594 // listeners may request another update (_ref_navaid_elapsed = 9999), which results in
595 // excessive load (FGPositioned::findClosest called in every update loop...)
596 _ref_navaid_elapsed = 0.0;
601 double trueCourse, distanceM, az2;
602 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
603 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
604 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
605 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
609 void GPS::referenceNavaidSet(const std::string& aNavaid)
612 // allow setting an empty string to restore normal nearest-vor selection
613 if (aNavaid.size() > 0) {
614 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
615 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
616 _indicated_pos, &vorFilter);
619 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
624 _ref_navaid_set = true;
625 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explicit ref-navaid:" << _ref_navaid->ident());
626 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
627 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
628 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
629 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
631 _ref_navaid_set = false;
632 _ref_navaid_elapsed = 9999.0; // update next tick
636 void GPS::routeActivated()
638 if (_route_active_node->getBoolValue()) {
639 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
642 // if we've already passed the current waypoint, sequence.
643 if (_dataValid && getWP1FromFlag()) {
644 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
645 _routeMgr->sequence();
647 } else if (_mode == "leg") {
648 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
649 // select OBS mode, but keep current waypoint-as is
655 void GPS::routeManagerSequenced()
657 if (_mode != "leg") {
658 SG_LOG(SG_INSTR, SG_DEBUG, "GPS ignoring route sequencing, not in LEG mode");
662 int index = _routeMgr->currentIndex(),
663 count = _routeMgr->numWaypts();
664 if ((index < 0) || (index >= count)) {
667 // no active leg on the route
671 SG_LOG(SG_INSTR, SG_DEBUG, "GPS waypoint index is now " << index);
674 _prevWaypt = _routeMgr->wayptAtIndex(index - 1);
675 if (_prevWaypt->flag(WPT_DYNAMIC)) {
676 _wp0_position = _indicated_pos;
678 _wp0_position = _prevWaypt->position();
682 _currentWaypt = _routeMgr->currentWaypt();
684 _desiredCourse = getLegMagCourse();
685 _desiredCourseNode->fireValueChanged();
689 void GPS::routeEdited()
691 if (_mode != "leg") {
695 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
696 routeManagerSequenced();
699 void GPS::routeFinished()
701 if (_mode != "leg") {
705 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
706 // select OBS mode, but keep current waypoint-as is
711 void GPS::updateTurn()
713 bool printProgress = false;
715 if (_computeTurnData) {
716 if (_last_speed_kts < 10) {
717 // need valid leg course and sensible ground speed to compute the turn
722 printProgress = true;
725 if (!_anticipateTurn) {
731 // find bearing to turn centre
732 double bearing, az2, distanceM;
733 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
734 double progress = computeTurnProgress(bearing);
737 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
740 if (!_inTurn && (progress > 0.0)) {
744 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
745 _turnSequenced = true;
746 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
747 _routeMgr->sequence();
750 if (_inTurn && (progress >= 1.0)) {
755 // drive deviation and desired course
756 double desiredCourse = bearing - copysign(90, _turnAngle);
757 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
758 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
759 double deviationDeg = desiredCourse - getMagTrack();
760 deviationNm = copysign(deviationNm, deviationDeg);
762 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
763 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
764 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
768 void GPS::updateOverflight()
770 if (!_wayptController->isDone()) {
774 if (_mode == "dto") {
775 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
777 // check for wp1 being on active route - resume leg mode
778 if (_routeMgr->isRouteActive()) {
779 int index = _routeMgr->flightPlan()->findWayptIndex(_currentWaypt->position());
781 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
783 _routeMgr->jumpToIndex(index);
787 if (_mode == "dto") {
788 // if we didn't enter leg mode, drop back to OBS mode
789 // select OBS mode, but keep current waypoint-as is
793 } else if (_mode == "leg") {
794 SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
795 _routeMgr->sequence();
796 } else if (_mode == "obs") {
797 // nothing to do here, TO/FROM will update but that's fine
800 _computeTurnData = true;
803 void GPS::beginTurn()
806 _turnSequenced = false;
807 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
813 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
814 _computeTurnData = true;
817 double GPS::computeTurnProgress(double aBearing) const
819 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
820 return (aBearing - startBearing) / _turnAngle;
823 void GPS::computeTurnData()
825 _computeTurnData = false;
826 int nextIndex = _routeMgr->currentIndex() + 1;
827 if ((_mode != "leg") || (nextIndex >= _routeMgr->numWaypts())) {
828 _anticipateTurn = false;
832 WayptRef next = _routeMgr->wayptAtIndex(nextIndex);
833 if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
834 _anticipateTurn = false;
838 _turnStartBearing = _desiredCourse;
839 // compute next leg course
841 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
844 // compute offset bearing
845 _turnAngle = crs - _turnStartBearing;
846 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
847 double median = _turnStartBearing + (_turnAngle * 0.5);
848 double offsetBearing = median + copysign(90, _turnAngle);
849 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
851 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
852 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
853 << ", offset=" << offsetBearing);
855 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
857 _turnPt = _currentWaypt->position();
858 _anticipateTurn = true;
861 void GPS::updateTurnData()
863 // depends on ground speed, so needs to be updated per-frame
864 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
866 // compute the turn centre, based on the turn radius.
867 // key thing is to understand that we're working a right-angle triangle,
868 // where the right-angle is the point we start the turn. From that point,
869 // one side is the inbound course to the turn pt, and the other is the
870 // perpendicular line, of length 'r', to the turn centre.
871 // the triangle's hypotenuse, which we need to find, is the distance from the
872 // turn pt to the turn center (in the direction of the offset bearing)
873 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
875 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
876 double d = _turnRadius / cos(halfTurnAngle);
878 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
879 // << " (cut distance=" << d - _turnRadius << ")");
881 double median = _turnStartBearing + (_turnAngle * 0.5);
882 double offsetBearing = median + copysign(90, _turnAngle);
883 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
886 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
889 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
891 // turn time is seconds to execute a 360 turn.
892 double turnTime = 360.0 / _config.turnRateDegSec();
894 // c is ground distance covered in that time (circumference of the circle)
895 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
897 // divide by 2PI to go from circumference -> radius
898 return c / (2 * M_PI);
901 void GPS::updateRouteData()
903 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
904 // walk all waypoints from wp2 to route end, and sum
905 for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
906 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
909 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
910 if (_last_speed_kts > 1.0) {
911 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
912 _routeETE->setStringValue(makeTTWString(TTW));
916 void GPS::driveAutopilot()
918 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
919 _apDrivingFlag->setBoolValue(false);
923 // compatability feature - allow the route-manager / GPS to drive the
924 // generic autopilot heading hold *in leg mode only*
926 bool drive = _mode == "leg";
927 _apDrivingFlag->setBoolValue(drive);
930 // FIXME: we want to set desired track, not heading, here
931 _apTrueHeading->setDoubleValue(getWP1Bearing());
935 void GPS::wp1Changed()
939 if (_mode == "leg") {
940 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
941 } else if (_mode == "obs") {
942 _wayptController.reset(new OBSController(this, _currentWaypt));
943 } else if (_mode == "dto") {
944 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
947 _wayptController->init();
949 if (_mode == "obs") {
950 _legDistanceNm = -1.0;
952 _wayptController->update();
953 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
956 if (!_config.driveAutopilot()) {
960 RouteRestriction ar = _currentWaypt->altitudeRestriction();
961 double restrictAlt = _currentWaypt->altitudeFt();
962 double alt = _indicated_pos.getElevationFt();
963 if ((ar == RESTRICT_AT) ||
964 ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
965 ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
967 SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
968 _apTargetAltitudeFt->setDoubleValue(restrictAlt);
972 /////////////////////////////////////////////////////////////////////////////
973 // property getter/setters
975 void GPS::setSelectedCourse(double crs)
977 if (_selectedCourse == crs) {
981 _selectedCourse = crs;
982 if ((_mode == "obs") || _config.courseSelectable()) {
983 _desiredCourse = _selectedCourse;
984 _desiredCourseNode->fireValueChanged();
988 double GPS::getLegDistance() const
990 if (!_dataValid || (_mode == "obs")) {
994 return _legDistanceNm;
997 double GPS::getLegCourse() const
999 if (!_dataValid || !_wayptController.get()) {
1003 return _wayptController->targetTrackDeg();
1006 double GPS::getLegMagCourse() const
1012 double m = getLegCourse() - _magvar_node->getDoubleValue();
1013 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1017 double GPS::getMagTrack() const
1023 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1024 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1028 double GPS::getCDIDeflection() const
1035 if (_config.cdiDeflectionIsAngular()) {
1036 defl = getWP1CourseDeviation();
1037 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1039 double fullScale = _config.cdiDeflectionLinearPeg();
1040 double normError = getWP1CourseErrorNm() / fullScale;
1041 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1042 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1048 const char* GPS::getWP0Ident() const
1050 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
1054 return _prevWaypt->ident().c_str();
1057 const char* GPS::getWP0Name() const
1062 const char* GPS::getWP1Ident() const
1064 if ((!_dataValid)||(!_currentWaypt)) {
1068 return _currentWaypt->ident().c_str();
1071 const char* GPS::getWP1Name() const
1076 double GPS::getWP1Distance() const
1078 if (!_dataValid || !_wayptController.get()) {
1082 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1085 double GPS::getWP1TTW() const
1087 if (!_dataValid || !_wayptController.get()) {
1091 return _wayptController->timeToWaypt();
1094 const char* GPS::getWP1TTWString() const
1096 double t = getWP1TTW();
1101 return makeTTWString(t);
1104 double GPS::getWP1Bearing() const
1106 if (!_dataValid || !_wayptController.get()) {
1110 return _wayptController->trueBearingDeg();
1113 double GPS::getWP1MagBearing() const
1115 if (!_dataValid || !_wayptController.get()) {
1119 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1120 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1124 double GPS::getWP1CourseDeviation() const
1126 if (!_dataValid || !_wayptController.get()) {
1130 return _wayptController->courseDeviationDeg();
1133 double GPS::getWP1CourseErrorNm() const
1135 if (!_dataValid || !_wayptController.get()) {
1139 return _wayptController->xtrackErrorNm();
1142 bool GPS::getWP1ToFlag() const
1144 if (!_dataValid || !_wayptController.get()) {
1148 return _wayptController->toFlag();
1151 bool GPS::getWP1FromFlag() const
1153 if (!_dataValid || !_wayptController.get()) {
1157 return !getWP1ToFlag();
1160 double GPS::getScratchDistance() const
1162 if (!_scratchValid) {
1166 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1169 double GPS::getScratchTrueBearing() const
1171 if (!_scratchValid) {
1175 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1178 double GPS::getScratchMagBearing() const
1180 if (!_scratchValid) {
1184 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1185 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1189 /////////////////////////////////////////////////////////////////////////////
1190 // command / scratch / search system
1192 void GPS::setCommand(const char* aCmd)
1194 SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1196 if (!strcmp(aCmd, "direct")) {
1198 } else if (!strcmp(aCmd, "obs")) {
1200 } else if (!strcmp(aCmd, "leg")) {
1202 } else if (!strcmp(aCmd, "load-route-wpt")) {
1203 loadRouteWaypoint();
1204 } else if (!strcmp(aCmd, "nearest")) {
1206 } else if (!strcmp(aCmd, "search")) {
1207 _searchNames = false;
1209 } else if (!strcmp(aCmd, "search-names")) {
1210 _searchNames = true;
1212 } else if (!strcmp(aCmd, "next")) {
1214 } else if (!strcmp(aCmd, "previous")) {
1216 } else if (!strcmp(aCmd, "define-user-wpt")) {
1218 } else if (!strcmp(aCmd, "route-insert-before")) {
1219 int index = _scratchNode->getIntValue("index");
1220 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1221 index = _routeMgr->numWaypts();
1222 } else if (index >= _routeMgr->numWaypts()) {
1223 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1227 insertWaypointAtIndex(index);
1228 } else if (!strcmp(aCmd, "route-insert-after")) {
1229 int index = _scratchNode->getIntValue("index");
1230 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1231 index = _routeMgr->numWaypts();
1232 } else if (index >= _routeMgr->numWaypts()) {
1233 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1239 insertWaypointAtIndex(index);
1240 } else if (!strcmp(aCmd, "route-delete")) {
1241 int index = _scratchNode->getIntValue("index");
1243 index = _routeMgr->numWaypts();
1244 } else if (index >= _routeMgr->numWaypts()) {
1245 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1249 removeWaypointAtIndex(index);
1251 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1255 void GPS::clearScratch()
1257 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1258 _scratchValid = false;
1259 _scratchNode->setStringValue("type", "");
1260 _scratchNode->setStringValue("query", "");
1263 bool GPS::isScratchPositionValid() const
1265 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1266 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1273 void GPS::directTo()
1275 if (!isScratchPositionValid()) {
1280 _wp0_position = _indicated_pos;
1281 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1288 void GPS::loadRouteWaypoint()
1290 _scratchValid = false;
1291 // if (!_routeMgr->isRouteActive()) {
1292 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1296 int index = _scratchNode->getIntValue("index", -9999);
1299 if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1300 index = _routeMgr->currentIndex();
1303 _searchIsRoute = true;
1304 setScratchFromRouteWaypoint(index);
1307 void GPS::setScratchFromRouteWaypoint(int aIndex)
1309 assert(_searchIsRoute);
1310 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1311 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1315 _searchResultIndex = aIndex;
1316 WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1317 _scratchNode->setStringValue("ident", wp->ident());
1318 _scratchPos = wp->position();
1319 _scratchValid = true;
1320 _scratchNode->setIntValue("index", aIndex);
1323 void GPS::loadNearest()
1325 string sty(_scratchNode->getStringValue("type"));
1326 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1327 if (ty == FGPositioned::INVALID) {
1328 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1332 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1333 int limitCount = _scratchNode->getIntValue("max-results", 1);
1334 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1336 SGGeod searchPos = _indicated_pos;
1337 if (isScratchPositionValid()) {
1338 searchPos = _scratchPos;
1341 clearScratch(); // clear now, regardless of whether we find a match or not
1344 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1345 _searchResultIndex = 0;
1346 _searchIsRoute = false;
1348 if (_searchResults.empty()) {
1352 setScratchFromCachedSearchResult();
1355 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1357 switch (aPos->type()) {
1358 case FGPositioned::AIRPORT:
1359 // heliport and seaport too?
1360 case FGPositioned::VOR:
1361 case FGPositioned::NDB:
1362 case FGPositioned::FIX:
1363 case FGPositioned::TACAN:
1364 case FGPositioned::WAYPOINT:
1371 FGPositioned::Type GPS::SearchFilter::minType() const
1373 return FGPositioned::AIRPORT;
1376 FGPositioned::Type GPS::SearchFilter::maxType() const
1378 return FGPositioned::VOR;
1381 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1383 if (aTy == FGPositioned::AIRPORT) {
1384 return new FGAirport::HardSurfaceFilter();
1387 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1388 if (aTy == FGPositioned::INVALID) {
1389 return new SearchFilter;
1392 return new FGPositioned::TypeFilter(aTy);
1397 // parse search terms into local members, and exec the first search
1398 string sty(_scratchNode->getStringValue("type"));
1399 _searchType = FGPositioned::typeFromName(sty);
1400 _searchQuery = _scratchNode->getStringValue("query");
1401 if (_searchQuery.empty()) {
1402 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1407 _searchExact = _scratchNode->getBoolValue("exact", true);
1408 _searchResultIndex = 0;
1409 _searchIsRoute = false;
1411 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1413 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1415 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1418 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1420 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1423 if (_searchResults.empty()) {
1428 setScratchFromCachedSearchResult();
1431 bool GPS::getScratchHasNext() const
1434 if (_searchIsRoute) {
1435 lastResult = _routeMgr->numWaypts() - 1;
1437 lastResult = (int) _searchResults.size() - 1;
1440 if (lastResult < 0) { // search array might be empty
1444 return (_searchResultIndex < lastResult);
1447 void GPS::setScratchFromCachedSearchResult()
1449 int index = _searchResultIndex;
1451 if ((index < 0) || (index >= (int) _searchResults.size())) {
1452 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1456 setScratchFromPositioned(_searchResults[index], index);
1459 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1464 _scratchPos = aPos->geod();
1465 _scratchNode->setStringValue("name", aPos->name());
1466 _scratchNode->setStringValue("ident", aPos->ident());
1467 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1470 _scratchNode->setIntValue("index", aIndex);
1473 _scratchValid = true;
1474 _scratchNode->setIntValue("result-count", _searchResults.size());
1476 switch (aPos->type()) {
1477 case FGPositioned::VOR:
1478 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1481 case FGPositioned::NDB:
1482 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1485 case FGPositioned::AIRPORT:
1486 addAirportToScratch((FGAirport*)aPos);
1494 // look for being on the route and set?
1497 void GPS::addAirportToScratch(FGAirport* aAirport)
1499 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1500 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1501 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1502 // TODO - filter out unsuitable runways in the future
1503 // based on config again
1505 rwyNd->setStringValue("id", rwy->ident().c_str());
1506 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1507 rwyNd->setIntValue("width-ft", rwy->widthFt());
1508 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1509 // map surface code to a string
1510 // TODO - lighting information
1513 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1515 } // of runways iteration
1519 void GPS::selectOBSMode()
1521 if (!isScratchPositionValid()) {
1526 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1527 _wp0_position = _indicated_pos;
1531 void GPS::selectLegMode()
1533 if (_mode == "leg") {
1537 if (!_routeMgr->isRouteActive()) {
1538 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1543 // depending on the situation, this will either get over-written
1544 // in routeManagerSequenced or not; either way it does no harm to
1546 _wp0_position = _indicated_pos;
1548 // not really sequenced, but does all the work of updating wp0/1
1549 routeManagerSequenced();
1552 void GPS::nextResult()
1554 if (!getScratchHasNext()) {
1559 if (_searchIsRoute) {
1560 setScratchFromRouteWaypoint(++_searchResultIndex);
1562 ++_searchResultIndex;
1563 setScratchFromCachedSearchResult();
1567 void GPS::previousResult()
1569 if (_searchResultIndex <= 0) {
1574 --_searchResultIndex;
1576 if (_searchIsRoute) {
1577 setScratchFromRouteWaypoint(_searchResultIndex);
1579 setScratchFromCachedSearchResult();
1583 void GPS::defineWaypoint()
1585 if (!isScratchPositionValid()) {
1586 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1590 string ident = _scratchNode->getStringValue("ident");
1591 if (ident.size() < 2) {
1592 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1596 // check for duplicate idents
1597 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1598 FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1599 if (!dups.empty()) {
1600 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1603 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1604 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1605 _searchResults.clear();
1606 _searchResults.push_back(wpt);
1607 setScratchFromPositioned(wpt.get(), -1);
1610 void GPS::insertWaypointAtIndex(int aIndex)
1612 // note we do allow index = routeMgr->size(), that's an append
1613 if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1614 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1617 if (!isScratchPositionValid()) {
1618 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1622 string ident = _scratchNode->getStringValue("ident");
1624 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1625 _routeMgr->flightPlan()->insertWayptAtIndex(wpt, aIndex);
1628 void GPS::removeWaypointAtIndex(int aIndex)
1630 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1631 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1634 _routeMgr->removeLegAtIndex(aIndex);
1637 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1638 const char* lonStr, const char* latStr, const char* altStr)
1640 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1641 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1644 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1648 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1649 const char* lonStr, const char* latStr, const char* altStr)
1651 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1652 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1655 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));