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;
37 ///////////////////////////////////////////////////////////////////
39 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
41 _lon = base->getChild(lonStr, 0, true);
42 _lat = base->getChild(latStr, 0, true);
44 _alt = base->getChild(altStr, 0, true);
48 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
50 _lon = fgGetNode(lonStr, true);
51 _lat = fgGetNode(latStr, true);
53 _alt = fgGetNode(altStr, true);
57 void SGGeodProperty::clear()
59 _lon = _lat = _alt = NULL;
62 void SGGeodProperty::operator=(const SGGeod& geod)
64 _lon->setDoubleValue(geod.getLongitudeDeg());
65 _lat->setDoubleValue(geod.getLatitudeDeg());
67 _alt->setDoubleValue(geod.getElevationFt());
71 SGGeod SGGeodProperty::get() const
73 double lon = _lon->getDoubleValue(),
74 lat = _lat->getDoubleValue();
76 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
78 return SGGeod::fromDeg(lon,lat);
82 static const char* makeTTWString(double TTW)
84 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
88 unsigned int TTW_seconds = (int) (TTW + 0.5);
89 unsigned int TTW_minutes = 0;
90 unsigned int TTW_hours = 0;
91 static char TTW_str[9];
92 TTW_hours = TTW_seconds / 3600;
93 TTW_minutes = (TTW_seconds / 60) % 60;
94 TTW_seconds = TTW_seconds % 60;
95 snprintf(TTW_str, 9, "%02d:%02d:%02d",
96 TTW_hours, TTW_minutes, TTW_seconds);
100 /////////////////////////////////////////////////////////////////////////////
102 class GPSListener : public SGPropertyChangeListener
105 GPSListener(GPS *m) :
109 virtual void valueChanged (SGPropertyNode * prop)
116 if (prop == _gps->_route_current_wp_node) {
117 _gps->routeManagerSequenced();
118 } else if (prop == _gps->_route_active_node) {
119 _gps->routeActivated();
120 } else if (prop == _gps->_ref_navaid_id_node) {
121 _gps->referenceNavaidSet(prop->getStringValue(""));
122 } else if (prop == _gps->_routeEditedSignal) {
124 } else if (prop == _gps->_routeFinishedSignal) {
125 _gps->routeFinished();
131 void setGuard(bool g) {
136 bool _guard; // re-entrancy guard
139 ////////////////////////////////////////////////////////////////////////////
141 * Helper to monitor for Nasal or other code accessing properties we haven't
142 * defined. For the moment we complain about all such activites, since various
143 * users assume all kinds of weird, wonderful and non-existent interfaces.
146 class DeprecatedPropListener : public SGPropertyChangeListener
149 DeprecatedPropListener(SGPropertyNode* gps)
151 _parents.insert(gps);
152 SGPropertyNode* wp = gps->getChild("wp", 0, true);
154 _parents.insert(wp->getChild("wp", 0, true));
155 _parents.insert(wp->getChild("wp", 1, true));
157 std::set<SGPropertyNode*>::iterator it;
158 for (it = _parents.begin(); it != _parents.end(); ++it) {
159 (*it)->addChangeListener(this);
163 virtual void valueChanged (SGPropertyNode * prop)
167 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
169 if (isDeprecated(parent, child)) {
170 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
171 << child->getPath(true));
175 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
177 if (_parents.count(parent) < 1) {
181 // no child exclusions yet
185 std::set<SGPropertyNode*> _parents;
188 ////////////////////////////////////////////////////////////////////////////
189 // configuration helper object
191 GPS::Config::Config() :
192 _enableTurnAnticipation(true),
193 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
194 _overflightArmDistance(1.0),
195 _waypointAlertTime(30.0),
196 _minRunwayLengthFt(0.0),
197 _requireHardSurface(true),
198 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
199 _driveAutopilot(true),
200 _courseSelectable(false)
202 _enableTurnAnticipation = false;
205 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
207 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
208 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
209 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
210 aOwner->tie(aCfg, "min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
211 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
212 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
213 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
214 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
217 ////////////////////////////////////////////////////////////////////////////
219 GPS::GPS ( SGPropertyNode *node) :
220 _selectedCourse(0.0),
223 _lastPosValid(false),
225 _name(node->getStringValue("name", "gps")),
226 _num(node->getIntValue("number", 0)),
227 _computeTurnData(false),
228 _anticipateTurn(false),
231 string branch = "/instrumentation/" + _name;
232 _gpsNode = fgGetNode(branch.c_str(), _num, true );
233 _scratchNode = _gpsNode->getChild("scratch", 0, true);
235 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
236 _currentWayptNode = wp_node->getChild("wp", 1, true);
246 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
249 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
250 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
251 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
252 _serviceable_node->setBoolValue(true);
253 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
256 _raim_node = _gpsNode->getChild("raim", 0, true);
257 _odometer_node = _gpsNode->getChild("odometer", 0, true);
258 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
259 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
260 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
261 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
262 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
265 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
266 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
267 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
269 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
272 SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
273 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
274 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
275 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
276 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
277 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
278 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
279 _ref_navaid_elapsed = 0.0;
280 _ref_navaid_set = false;
283 // should these move to the route manager?
284 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
285 _routeETE = _gpsNode->getChild("ETE", 0, true);
286 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
287 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
289 // add listener to various things
290 _listener = new GPSListener(this);
291 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
292 _route_current_wp_node->addChangeListener(_listener);
293 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
294 _route_active_node->addChangeListener(_listener);
295 _ref_navaid_id_node->addChangeListener(_listener);
296 _routeEditedSignal->addChangeListener(_listener);
297 _routeFinishedSignal->addChangeListener(_listener);
299 // navradio slaving properties
300 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
301 toFlag->alias(_currentWayptNode->getChild("to-flag"));
303 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
304 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
306 // autopilot drive properties
307 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
308 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
309 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
310 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
313 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
314 if (!_realismSimpleGps->hasValue()) {
315 _realismSimpleGps->setBoolValue(true);
318 // last thing, add the deprecated prop watcher
319 new DeprecatedPropListener(_gpsNode);
327 _config.bind(this, _gpsNode->getChild("config", 0, true));
329 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
330 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
332 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
333 (*this, &GPS::getDesiredCourse, NULL));
334 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
336 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
337 "indicated-latitude-deg", "indicated-altitude-ft");
339 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
340 (*this, &GPS::getVerticalSpeed, NULL));
341 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
342 (*this, &GPS::getTrueTrack, NULL));
343 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
344 (*this, &GPS::getMagTrack, NULL));
345 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
346 (*this, &GPS::getGroundspeedKts, NULL));
349 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
350 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
352 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
353 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
354 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
355 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
356 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
357 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
358 _scratchValid = false;
361 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
362 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
364 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
365 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
366 (*this, &GPS::getWP1Ident, NULL));
368 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
369 (*this, &GPS::getWP1Distance, NULL));
370 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
371 (*this, &GPS::getWP1Bearing, NULL));
372 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
373 (*this, &GPS::getWP1MagBearing, NULL));
374 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
375 (*this, &GPS::getWP1TTW, NULL));
376 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
377 (*this, &GPS::getWP1TTWString, NULL));
379 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
380 (*this, &GPS::getWP1CourseDeviation, NULL));
381 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
382 (*this, &GPS::getWP1CourseErrorNm, NULL));
383 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
384 (*this, &GPS::getWP1ToFlag, NULL));
385 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
386 (*this, &GPS::getWP1FromFlag, NULL));
388 // leg properties (only valid in DTO/LEG modes, not OBS)
389 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
390 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
391 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
393 // navradio slaving properties
394 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
395 (*this, &GPS::getCDIDeflection));
401 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
402 _tiedNodes[t]->untie();
411 _last_speed_kts = 0.0;
412 _last_pos = SGGeod();
413 _lastPosValid = false;
414 _indicated_pos = SGGeod();
415 _last_vertical_speed = 0.0;
416 _last_true_track = 0.0;
417 _lastEWVelocity = _lastNSVelocity = 0.0;
418 _currentWaypt = _prevWaypt = NULL;
419 _legDistanceNm = -1.0;
421 _raim_node->setDoubleValue(0.0);
422 _indicated_pos = SGGeod();
423 _odometer_node->setDoubleValue(0);
424 _trip_odometer_node->setDoubleValue(0);
425 _tracking_bug_node->setDoubleValue(0);
426 _true_bug_error_node->setDoubleValue(0);
427 _magnetic_bug_error_node->setDoubleValue(0);
428 _northSouthVelocity->setDoubleValue(0.0);
429 _eastWestVelocity->setDoubleValue(0.0);
433 GPS::update (double delta_time_sec)
435 if (!_realismSimpleGps->getBoolValue()) {
436 // If it's off, don't bother.
437 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
443 if (delta_time_sec <= 0.0) {
444 return; // paused, don't bother
447 _raim_node->setDoubleValue(1.0);
448 _indicated_pos = _position.get();
449 updateBasicData(delta_time_sec);
452 if (_wayptController.get()) {
453 _wayptController->update();
454 SGGeod p(_wayptController->position());
455 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
456 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
457 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
459 _desiredCourse = getLegMagCourse();
467 updateReferenceNavaid(delta_time_sec);
471 if (_dataValid && (_mode == "init")) {
472 // allow a realistic delay in the future, here
473 SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
475 if (_route_active_node->getBoolValue()) {
476 // GPS init with active route
477 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
480 // initialise in OBS mode, with waypt set to the nearest airport.
481 // keep in mind at this point, _dataValid is not set
483 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
484 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
486 setScratchFromPositioned(apt, 0);
490 } // of init mode check
492 _last_pos = _indicated_pos;
493 _lastPosValid = true;
496 ///////////////////////////////////////////////////////////////////////////
497 // implement the RNAV interface
498 SGGeod GPS::position()
504 return _indicated_pos;
507 double GPS::trackDeg()
509 return _last_true_track;
512 double GPS::groundSpeedKts()
514 return _last_speed_kts;
517 double GPS::vspeedFPM()
519 return _last_vertical_speed;
522 double GPS::magvarDeg()
524 return _magvar_node->getDoubleValue();
527 double GPS::overflightArmDistanceM()
529 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
532 double GPS::selectedMagCourse()
534 return _selectedCourse;
537 ///////////////////////////////////////////////////////////////////////////
540 GPS::updateBasicData(double dt)
542 if (!_lastPosValid) {
548 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
550 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
551 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
552 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
554 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
555 _last_speed_kts = speed_kt;
557 SGGeod g = _indicated_pos;
558 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
559 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
560 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
562 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
563 _lastNSVelocity = nsMSec;
564 _northSouthVelocity->setDoubleValue(nsMSec);
568 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
569 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
570 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
572 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
573 _lastEWVelocity = ewMSec;
574 _eastWestVelocity->setDoubleValue(ewMSec);
576 double odometer = _odometer_node->getDoubleValue();
577 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
578 odometer = _trip_odometer_node->getDoubleValue();
579 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
582 SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
588 GPS::updateTrackingBug()
590 double tracking_bug = _tracking_bug_node->getDoubleValue();
591 double true_bug_error = tracking_bug - getTrueTrack();
592 double magnetic_bug_error = tracking_bug - getMagTrack();
594 // Get the errors into the (-180,180) range.
595 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
596 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
598 _true_bug_error_node->setDoubleValue(true_bug_error);
599 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
602 void GPS::updateReferenceNavaid(double dt)
604 if (!_ref_navaid_set) {
605 _ref_navaid_elapsed += dt;
606 if (_ref_navaid_elapsed > 5.0) {
607 _ref_navaid_elapsed = 0.0;
609 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
610 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
612 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
613 _ref_navaid_id_node->setStringValue("");
614 _ref_navaid_name_node->setStringValue("");
615 _ref_navaid_bearing_node->setDoubleValue(0.0);
616 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
617 _ref_navaid_distance_node->setDoubleValue(0.0);
618 _ref_navaid_frequency_node->setStringValue("");
619 } else if (nav != _ref_navaid) {
620 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
621 _listener->setGuard(true);
622 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
623 _ref_navaid_name_node->setStringValue(nav->name().c_str());
624 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
625 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
626 _listener->setGuard(false);
628 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
636 double trueCourse, distanceM, az2;
637 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
638 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
639 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
640 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
644 void GPS::referenceNavaidSet(const std::string& aNavaid)
647 // allow setting an empty string to restore normal nearest-vor selection
648 if (aNavaid.size() > 0) {
649 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
650 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
651 _position.get(), &vorFilter);
654 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
659 _ref_navaid_set = true;
660 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
661 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
662 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
663 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
664 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
666 _ref_navaid_set = false;
667 _ref_navaid_elapsed = 9999.0; // update next tick
671 void GPS::routeActivated()
673 if (_route_active_node->getBoolValue()) {
674 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
677 // if we've already passed the current waypoint, sequence.
678 if (_dataValid && getWP1FromFlag()) {
679 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
680 _routeMgr->sequence();
682 } else if (_mode == "leg") {
683 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
684 // select OBS mode, but keep current waypoint-as is
690 void GPS::routeManagerSequenced()
692 if (_mode != "leg") {
693 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
697 int index = _routeMgr->currentIndex(),
698 count = _routeMgr->numWaypts();
699 if ((index < 0) || (index >= count)) {
700 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
704 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
707 _prevWaypt = _routeMgr->previousWaypt();
708 if (_prevWaypt->flag(WPT_DYNAMIC)) {
709 _wp0_position = _indicated_pos;
711 _wp0_position = _prevWaypt->position();
715 _currentWaypt = _routeMgr->currentWaypt();
717 _desiredCourse = getLegMagCourse();
718 _desiredCourseNode->fireValueChanged();
722 void GPS::routeEdited()
724 if (_mode != "leg") {
728 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
729 routeManagerSequenced();
732 void GPS::routeFinished()
734 if (_mode != "leg") {
738 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
739 // select OBS mode, but keep current waypoint-as is
744 void GPS::updateTurn()
746 bool printProgress = false;
748 if (_computeTurnData) {
749 if (_last_speed_kts < 60) {
750 // need valid leg course and sensible ground speed to compute the turn
755 printProgress = true;
758 if (!_anticipateTurn) {
764 // find bearing to turn centre
765 double bearing, az2, distanceM;
766 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
767 double progress = computeTurnProgress(bearing);
770 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
773 if (!_inTurn && (progress > 0.0)) {
777 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
778 _turnSequenced = true;
779 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
780 _routeMgr->sequence();
783 if (_inTurn && (progress >= 1.0)) {
788 // drive deviation and desired course
789 double desiredCourse = bearing - copysign(90, _turnAngle);
790 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
791 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
792 double deviationDeg = desiredCourse - getMagTrack();
793 deviationNm = copysign(deviationNm, deviationDeg);
795 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
796 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
797 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
801 void GPS::updateOverflight()
803 if (!_wayptController->isDone()) {
807 if (_mode == "dto") {
808 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
810 // check for wp1 being on active route - resume leg mode
811 if (_routeMgr->isRouteActive()) {
812 int index = _routeMgr->findWayptIndex(_currentWaypt->position());
814 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
816 _routeMgr->jumpToIndex(index);
820 if (_mode == "dto") {
821 // if we didn't enter leg mode, drop back to OBS mode
822 // select OBS mode, but keep current waypoint-as is
826 } else if (_mode == "leg") {
827 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
828 _routeMgr->sequence();
829 } else if (_mode == "obs") {
830 // nothing to do here, TO/FROM will update but that's fine
833 _computeTurnData = true;
836 void GPS::beginTurn()
839 _turnSequenced = false;
840 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
846 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
847 _computeTurnData = true;
850 double GPS::computeTurnProgress(double aBearing) const
852 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
853 return (aBearing - startBearing) / _turnAngle;
856 void GPS::computeTurnData()
858 _computeTurnData = false;
859 if (_mode != "leg") { // and approach modes in the future
860 _anticipateTurn = false;
864 WayptRef next = _routeMgr->nextWaypt();
865 if (!next || next->flag(WPT_DYNAMIC)) {
866 _anticipateTurn = false;
870 if (!_config.turnAnticipationEnabled()) {
871 _anticipateTurn = false;
875 _turnStartBearing = _desiredCourse;
876 // compute next leg course
878 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
881 // compute offset bearing
882 _turnAngle = crs - _turnStartBearing;
883 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
884 double median = _turnStartBearing + (_turnAngle * 0.5);
885 double offsetBearing = median + copysign(90, _turnAngle);
886 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
888 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
889 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
890 << ", offset=" << offsetBearing);
892 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
894 _turnPt = _currentWaypt->position();
895 _anticipateTurn = true;
898 void GPS::updateTurnData()
900 // depends on ground speed, so needs to be updated per-frame
901 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
903 // compute the turn centre, based on the turn radius.
904 // key thing is to understand that we're working a right-angle triangle,
905 // where the right-angle is the point we start the turn. From that point,
906 // one side is the inbound course to the turn pt, and the other is the
907 // perpendicular line, of length 'r', to the turn centre.
908 // the triangle's hypotenuse, which we need to find, is the distance from the
909 // turn pt to the turn center (in the direction of the offset bearing)
910 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
912 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
913 double d = _turnRadius / cos(halfTurnAngle);
915 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
916 // << " (cut distance=" << d - _turnRadius << ")");
918 double median = _turnStartBearing + (_turnAngle * 0.5);
919 double offsetBearing = median + copysign(90, _turnAngle);
920 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
923 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
926 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
928 // turn time is seconds to execute a 360 turn.
929 double turnTime = 360.0 / _config.turnRateDegSec();
931 // c is ground distance covered in that time (circumference of the circle)
932 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
934 // divide by 2PI to go from circumference -> radius
935 return c / (2 * M_PI);
938 void GPS::updateRouteData()
940 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
941 // walk all waypoints from wp2 to route end, and sum
942 for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
943 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
946 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
947 if (_last_speed_kts > 1.0) {
948 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
949 _routeETE->setStringValue(makeTTWString(TTW));
953 void GPS::driveAutopilot()
955 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
956 _apDrivingFlag->setBoolValue(false);
960 // compatability feature - allow the route-manager / GPS to drive the
961 // generic autopilot heading hold *in leg mode only*
963 bool drive = _mode == "leg";
964 _apDrivingFlag->setBoolValue(drive);
967 // FIXME: we want to set desired track, not heading, here
968 _apTrueHeading->setDoubleValue(getWP1Bearing());
972 void GPS::wp1Changed()
974 if (_mode == "leg") {
975 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
976 } else if (_mode == "obs") {
977 _wayptController.reset(new OBSController(this, _currentWaypt));
978 } else if (_mode == "dto") {
979 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
982 _wayptController->init();
984 if (_mode == "obs") {
985 _legDistanceNm = -1.0;
987 _wayptController->update();
988 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
991 if (!_config.driveAutopilot()) {
995 RouteRestriction ar = _currentWaypt->altitudeRestriction();
996 double restrictAlt = _currentWaypt->altitudeFt();
997 double alt = _indicated_pos.getElevationFt();
998 if ((ar == RESTRICT_AT) ||
999 ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
1000 ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
1002 SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
1003 _apTargetAltitudeFt->setDoubleValue(restrictAlt);
1007 /////////////////////////////////////////////////////////////////////////////
1008 // property getter/setters
1010 void GPS::setSelectedCourse(double crs)
1012 if (_selectedCourse == crs) {
1016 _selectedCourse = crs;
1017 if ((_mode == "obs") || _config.courseSelectable()) {
1018 _desiredCourse = _selectedCourse;
1019 _desiredCourseNode->fireValueChanged();
1023 double GPS::getLegDistance() const
1025 if (!_dataValid || (_mode == "obs")) {
1029 return _legDistanceNm;
1032 double GPS::getLegCourse() const
1034 if (!_dataValid || !_wayptController.get()) {
1038 return _wayptController->targetTrackDeg();
1041 double GPS::getLegMagCourse() const
1047 double m = getLegCourse() - _magvar_node->getDoubleValue();
1048 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1052 double GPS::getMagTrack() const
1058 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1059 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1063 double GPS::getCDIDeflection() const
1070 if (_config.cdiDeflectionIsAngular()) {
1071 defl = getWP1CourseDeviation();
1072 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1074 double fullScale = _config.cdiDeflectionLinearPeg();
1075 double normError = getWP1CourseErrorNm() / fullScale;
1076 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1077 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1083 const char* GPS::getWP0Ident() const
1085 if (!_dataValid || (_mode != "leg")) {
1089 return _prevWaypt->ident().c_str();
1092 const char* GPS::getWP0Name() const
1097 const char* GPS::getWP1Ident() const
1103 return _currentWaypt->ident().c_str();
1106 const char* GPS::getWP1Name() const
1111 double GPS::getWP1Distance() const
1113 if (!_dataValid || !_wayptController.get()) {
1117 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1120 double GPS::getWP1TTW() const
1122 if (!_dataValid || !_wayptController.get()) {
1126 return _wayptController->timeToWaypt();
1129 const char* GPS::getWP1TTWString() const
1131 double t = getWP1TTW();
1136 return makeTTWString(t);
1139 double GPS::getWP1Bearing() const
1141 if (!_dataValid || !_wayptController.get()) {
1145 return _wayptController->trueBearingDeg();
1148 double GPS::getWP1MagBearing() const
1154 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1155 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1159 double GPS::getWP1CourseDeviation() const
1161 if (!_dataValid || !_wayptController.get()) {
1165 return _wayptController->courseDeviationDeg();
1168 double GPS::getWP1CourseErrorNm() const
1170 if (!_dataValid || !_wayptController.get()) {
1174 return _wayptController->xtrackErrorNm();
1177 bool GPS::getWP1ToFlag() const
1179 if (!_dataValid || !_wayptController.get()) {
1183 return _wayptController->toFlag();
1186 bool GPS::getWP1FromFlag() const
1188 if (!_dataValid || !_wayptController.get()) {
1192 return !getWP1ToFlag();
1195 double GPS::getScratchDistance() const
1197 if (!_scratchValid) {
1201 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1204 double GPS::getScratchTrueBearing() const
1206 if (!_scratchValid) {
1210 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1213 double GPS::getScratchMagBearing() const
1215 if (!_scratchValid) {
1219 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1220 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1224 /////////////////////////////////////////////////////////////////////////////
1225 // command / scratch / search system
1227 void GPS::setCommand(const char* aCmd)
1229 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1231 if (!strcmp(aCmd, "direct")) {
1233 } else if (!strcmp(aCmd, "obs")) {
1235 } else if (!strcmp(aCmd, "leg")) {
1237 } else if (!strcmp(aCmd, "load-route-wpt")) {
1238 loadRouteWaypoint();
1239 } else if (!strcmp(aCmd, "nearest")) {
1241 } else if (!strcmp(aCmd, "search")) {
1242 _searchNames = false;
1244 } else if (!strcmp(aCmd, "search-names")) {
1245 _searchNames = true;
1247 } else if (!strcmp(aCmd, "next")) {
1249 } else if (!strcmp(aCmd, "previous")) {
1251 } else if (!strcmp(aCmd, "define-user-wpt")) {
1253 } else if (!strcmp(aCmd, "route-insert-before")) {
1254 int index = _scratchNode->getIntValue("index");
1255 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1256 index = _routeMgr->numWaypts();
1257 } else if (index >= _routeMgr->numWaypts()) {
1258 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1262 insertWaypointAtIndex(index);
1263 } else if (!strcmp(aCmd, "route-insert-after")) {
1264 int index = _scratchNode->getIntValue("index");
1265 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1266 index = _routeMgr->numWaypts();
1267 } else if (index >= _routeMgr->numWaypts()) {
1268 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1274 insertWaypointAtIndex(index);
1275 } else if (!strcmp(aCmd, "route-delete")) {
1276 int index = _scratchNode->getIntValue("index");
1278 index = _routeMgr->numWaypts();
1279 } else if (index >= _routeMgr->numWaypts()) {
1280 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1284 removeWaypointAtIndex(index);
1286 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1290 void GPS::clearScratch()
1292 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1293 _scratchValid = false;
1294 _scratchNode->setStringValue("type", "");
1295 _scratchNode->setStringValue("query", "");
1298 bool GPS::isScratchPositionValid() const
1300 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1301 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1308 void GPS::directTo()
1310 if (!isScratchPositionValid()) {
1315 _wp0_position = _indicated_pos;
1316 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1323 void GPS::loadRouteWaypoint()
1325 _scratchValid = false;
1326 // if (!_routeMgr->isRouteActive()) {
1327 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1331 int index = _scratchNode->getIntValue("index", -9999);
1334 if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1335 index = _routeMgr->currentIndex();
1338 _searchIsRoute = true;
1339 setScratchFromRouteWaypoint(index);
1342 void GPS::setScratchFromRouteWaypoint(int aIndex)
1344 assert(_searchIsRoute);
1345 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1346 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1350 _searchResultIndex = aIndex;
1351 WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1352 _scratchNode->setStringValue("ident", wp->ident());
1353 _scratchPos = wp->position();
1354 _scratchValid = true;
1355 _scratchNode->setIntValue("index", aIndex);
1358 void GPS::loadNearest()
1360 string sty(_scratchNode->getStringValue("type"));
1361 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1362 if (ty == FGPositioned::INVALID) {
1363 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1367 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1368 int limitCount = _scratchNode->getIntValue("max-results", 1);
1369 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1371 SGGeod searchPos = _indicated_pos;
1372 if (isScratchPositionValid()) {
1373 searchPos = _scratchPos;
1376 clearScratch(); // clear now, regardless of whether we find a match or not
1379 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1380 _searchResultIndex = 0;
1381 _searchIsRoute = false;
1383 if (_searchResults.empty()) {
1384 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1388 setScratchFromCachedSearchResult();
1391 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1393 switch (aPos->type()) {
1394 case FGPositioned::AIRPORT:
1395 // heliport and seaport too?
1396 case FGPositioned::VOR:
1397 case FGPositioned::NDB:
1398 case FGPositioned::FIX:
1399 case FGPositioned::TACAN:
1400 case FGPositioned::WAYPOINT:
1407 FGPositioned::Type GPS::SearchFilter::minType() const
1409 return FGPositioned::AIRPORT;
1412 FGPositioned::Type GPS::SearchFilter::maxType() const
1414 return FGPositioned::WAYPOINT;
1417 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1419 if (aTy == FGPositioned::AIRPORT) {
1420 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1423 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1424 if (aTy == FGPositioned::INVALID) {
1425 return new SearchFilter;
1428 return new FGPositioned::TypeFilter(aTy);
1433 // parse search terms into local members, and exec the first search
1434 string sty(_scratchNode->getStringValue("type"));
1435 _searchType = FGPositioned::typeFromName(sty);
1436 _searchQuery = _scratchNode->getStringValue("query");
1437 if (_searchQuery.empty()) {
1438 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1443 _searchExact = _scratchNode->getBoolValue("exact", true);
1444 _searchResultIndex = 0;
1445 _searchIsRoute = false;
1447 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1449 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1451 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1454 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1456 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1459 if (_searchResults.empty()) {
1464 setScratchFromCachedSearchResult();
1467 bool GPS::getScratchHasNext() const
1470 if (_searchIsRoute) {
1471 lastResult = _routeMgr->numWaypts() - 1;
1473 lastResult = (int) _searchResults.size() - 1;
1476 if (lastResult < 0) { // search array might be empty
1480 return (_searchResultIndex < lastResult);
1483 void GPS::setScratchFromCachedSearchResult()
1485 int index = _searchResultIndex;
1487 if ((index < 0) || (index >= (int) _searchResults.size())) {
1488 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1492 setScratchFromPositioned(_searchResults[index], index);
1495 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1500 _scratchPos = aPos->geod();
1501 _scratchNode->setStringValue("name", aPos->name());
1502 _scratchNode->setStringValue("ident", aPos->ident());
1503 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1506 _scratchNode->setIntValue("index", aIndex);
1509 _scratchValid = true;
1510 _scratchNode->setIntValue("result-count", _searchResults.size());
1512 switch (aPos->type()) {
1513 case FGPositioned::VOR:
1514 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1517 case FGPositioned::NDB:
1518 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1521 case FGPositioned::AIRPORT:
1522 addAirportToScratch((FGAirport*)aPos);
1530 // look for being on the route and set?
1533 void GPS::addAirportToScratch(FGAirport* aAirport)
1535 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1536 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1537 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1538 // TODO - filter out unsuitable runways in the future
1539 // based on config again
1541 rwyNd->setStringValue("id", rwy->ident().c_str());
1542 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1543 rwyNd->setIntValue("width-ft", rwy->widthFt());
1544 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1545 // map surface code to a string
1546 // TODO - lighting information
1549 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1551 } // of runways iteration
1555 void GPS::selectOBSMode()
1557 if (!isScratchPositionValid()) {
1561 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1564 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1565 _wp0_position = _indicated_pos;
1569 void GPS::selectLegMode()
1571 if (_mode == "leg") {
1575 if (!_routeMgr->isRouteActive()) {
1576 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1580 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1583 // depending on the situation, this will either get over-written
1584 // in routeManagerSequenced or not; either way it does no harm to
1586 _wp0_position = _indicated_pos;
1588 // not really sequenced, but does all the work of updating wp0/1
1589 routeManagerSequenced();
1592 void GPS::nextResult()
1594 if (!getScratchHasNext()) {
1599 if (_searchIsRoute) {
1600 setScratchFromRouteWaypoint(++_searchResultIndex);
1602 ++_searchResultIndex;
1603 setScratchFromCachedSearchResult();
1607 void GPS::previousResult()
1609 if (_searchResultIndex <= 0) {
1614 --_searchResultIndex;
1616 if (_searchIsRoute) {
1617 setScratchFromRouteWaypoint(_searchResultIndex);
1619 setScratchFromCachedSearchResult();
1623 void GPS::defineWaypoint()
1625 if (!isScratchPositionValid()) {
1626 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1630 string ident = _scratchNode->getStringValue("ident");
1631 if (ident.size() < 2) {
1632 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1636 // check for duplicate idents
1637 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1638 FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1639 if (!dups.empty()) {
1640 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1643 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1644 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1645 _searchResults.clear();
1646 _searchResults.push_back(wpt);
1647 setScratchFromPositioned(wpt.get(), -1);
1650 void GPS::insertWaypointAtIndex(int aIndex)
1652 // note we do allow index = routeMgr->size(), that's an append
1653 if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1654 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1657 if (!isScratchPositionValid()) {
1658 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1662 string ident = _scratchNode->getStringValue("ident");
1664 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1665 _routeMgr->insertWayptAtIndex(wpt, aIndex);
1668 void GPS::removeWaypointAtIndex(int aIndex)
1670 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1671 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1674 _routeMgr->removeWayptAtIndex(aIndex);
1677 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1678 const char* lonStr, const char* latStr, const char* altStr)
1680 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1681 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1684 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1688 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1689 const char* lonStr, const char* latStr, const char* altStr)
1691 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1692 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1695 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));