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>
19 #include "Main/fg_props.hxx"
20 #include "Main/globals.hxx" // for get_subsystem
21 #include "Main/util.hxx" // for fgLowPass
22 #include "Navaids/positioned.hxx"
23 #include <Navaids/waypoint.hxx>
24 #include "Navaids/navrecord.hxx"
25 #include "Navaids/FlightPlan.hxx"
26 #include "Airports/airport.hxx"
27 #include "Airports/runways.hxx"
28 #include "Autopilot/route_mgr.hxx"
30 #include <simgear/math/sg_random.h>
31 #include <simgear/sg_inlines.h>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/structure/exception.hxx>
37 using namespace flightgear;
40 static const char* makeTTWString(double TTW)
42 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
46 unsigned int TTW_seconds = (int) (TTW + 0.5);
47 unsigned int TTW_minutes = 0;
48 unsigned int TTW_hours = 0;
49 static char TTW_str[9];
50 TTW_hours = TTW_seconds / 3600;
51 TTW_minutes = (TTW_seconds / 60) % 60;
52 TTW_seconds = TTW_seconds % 60;
53 snprintf(TTW_str, 9, "%02d:%02d:%02d",
54 TTW_hours, TTW_minutes, TTW_seconds);
58 ////////////////////////////////////////////////////////////////////////////
59 // configuration helper object
61 GPS::Config::Config() :
62 _enableTurnAnticipation(true),
63 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
64 _overflightArmDistance(1.0),
65 _waypointAlertTime(30.0),
66 _requireHardSurface(true),
67 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
68 _driveAutopilot(true),
69 _courseSelectable(false)
71 _enableTurnAnticipation = false;
74 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
76 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
77 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
78 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
79 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
80 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
81 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
82 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
85 ////////////////////////////////////////////////////////////////////////////
87 GPS::GPS ( SGPropertyNode *node, bool defaultGPSMode) :
92 _defaultGPSMode(defaultGPSMode),
94 _name(node->getStringValue("name", "gps")),
95 _num(node->getIntValue("number", 0)),
96 _computeTurnData(false),
97 _anticipateTurn(false),
99 _callbackFlightPlanChanged(SGPropertyChangeCallback<GPS>(this,&GPS::routeManagerFlightPlanChanged,
100 fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true))),
101 _callbackRouteActivated(SGPropertyChangeCallback<GPS>(this,&GPS::routeActivated,
102 fgGetNode("/autopilot/route-manager/active", true)))
104 string branch = "/instrumentation/" + _name;
105 _gpsNode = fgGetNode(branch.c_str(), _num, true );
106 _scratchNode = _gpsNode->getChild("scratch", 0, true);
108 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
109 _currentWayptNode = wp_node->getChild("wp", 1, true);
119 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
120 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
121 _serviceable_node->setBoolValue(true);
122 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
125 _raim_node = _gpsNode->getChild("raim", 0, true);
126 _odometer_node = _gpsNode->getChild("odometer", 0, true);
127 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
128 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
129 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
130 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
131 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
134 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
135 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
136 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
138 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
141 // should these move to the route manager?
142 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
143 _routeETE = _gpsNode->getChild("ETE", 0, true);
146 // navradio slaving properties
147 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
148 toFlag->alias(_currentWayptNode->getChild("to-flag"));
150 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
151 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
153 // autopilot drive properties
154 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
155 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
169 _config.bind(this, _gpsNode->getChild("config", 0, true));
172 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
173 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
175 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
176 (*this, &GPS::getDesiredCourse, NULL));
177 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
179 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
180 "indicated-latitude-deg", "indicated-altitude-ft");
182 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
183 (*this, &GPS::getVerticalSpeed, NULL));
184 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
185 (*this, &GPS::getTrueTrack, NULL));
186 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
187 (*this, &GPS::getMagTrack, NULL));
188 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
189 (*this, &GPS::getGroundspeedKts, NULL));
192 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
193 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
194 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
197 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
198 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
199 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
200 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
201 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
202 _scratchValid = false;
204 _scratchNode->setStringValue("type", "");
205 _scratchNode->setStringValue("query", "");
208 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
209 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
210 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
211 tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
212 (*this, &GPS::getWP0Ident, NULL));
215 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
216 (*this, &GPS::getWP1Ident, NULL));
218 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
219 (*this, &GPS::getWP1Distance, NULL));
220 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
221 (*this, &GPS::getWP1Bearing, NULL));
222 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
223 (*this, &GPS::getWP1MagBearing, NULL));
224 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
225 (*this, &GPS::getWP1TTW, NULL));
226 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
227 (*this, &GPS::getWP1TTWString, NULL));
229 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
230 (*this, &GPS::getWP1CourseDeviation, NULL));
231 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
232 (*this, &GPS::getWP1CourseErrorNm, NULL));
233 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
234 (*this, &GPS::getWP1ToFlag, NULL));
235 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
236 (*this, &GPS::getWP1FromFlag, NULL));
238 // leg properties (only valid in DTO/LEG modes, not OBS)
239 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
240 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
241 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
243 // navradio slaving properties
244 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
245 (*this, &GPS::getCDIDeflection));
251 _tiedProperties.Untie();
258 _last_speed_kts = 0.0;
259 _last_pos = SGGeod();
260 _lastPosValid = false;
261 _indicated_pos = SGGeod();
262 _last_vertical_speed = 0.0;
263 _last_true_track = 0.0;
264 _lastEWVelocity = _lastNSVelocity = 0.0;
265 _currentWaypt = _prevWaypt = NULL;
266 _legDistanceNm = -1.0;
268 _raim_node->setDoubleValue(0.0);
269 _indicated_pos = SGGeod();
270 _odometer_node->setDoubleValue(0);
271 _trip_odometer_node->setDoubleValue(0);
272 _tracking_bug_node->setDoubleValue(0);
273 _true_bug_error_node->setDoubleValue(0);
274 _magnetic_bug_error_node->setDoubleValue(0);
275 _northSouthVelocity->setDoubleValue(0.0);
276 _eastWestVelocity->setDoubleValue(0.0);
280 GPS::update (double delta_time_sec)
282 if (!_defaultGPSMode) {
283 // If it's off, don't bother.
284 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
290 if (delta_time_sec <= 0.0) {
291 return; // paused, don't bother
294 _raim_node->setDoubleValue(1.0);
295 _indicated_pos = globals->get_aircraft_position();
296 updateBasicData(delta_time_sec);
299 if (_wayptController.get()) {
300 _wayptController->update();
301 SGGeod p(_wayptController->position());
302 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
303 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
304 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
306 _desiredCourse = getLegMagCourse();
317 if (_dataValid && (_mode == "init")) {
318 // will select LEG mode if the route is active
319 routeManagerFlightPlanChanged(NULL);
321 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
322 if (!routeMgr->isRouteActive()) {
323 // initialise in OBS mode, with waypt set to the nearest airport.
324 // keep in mind at this point, _dataValid is not set
325 auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
326 FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
328 selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
334 // allow a realistic delay in the future, here
336 } // of init mode check
338 _last_pos = _indicated_pos;
339 _lastPosValid = !(_last_pos == SGGeod());
342 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
345 _route->removeDelegate(this);
348 SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
349 FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
350 _route = routeMgr->flightPlan();
352 _route->addDelegate(this);
355 if (routeMgr->isRouteActive()) {
358 selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
362 void GPS::routeActivated(SGPropertyNode* aNode)
364 bool isActive = aNode->getBoolValue();
366 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
369 // if we've already passed the current waypoint, sequence.
370 if (_dataValid && getWP1FromFlag()) {
371 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
374 } else if (_mode == "leg") {
375 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
376 selectOBSMode(_currentWaypt);
380 ///////////////////////////////////////////////////////////////////////////
381 // implement the RNAV interface
382 SGGeod GPS::position()
388 return _indicated_pos;
391 double GPS::trackDeg()
393 return _last_true_track;
396 double GPS::groundSpeedKts()
398 return _last_speed_kts;
401 double GPS::vspeedFPM()
403 return _last_vertical_speed;
406 double GPS::magvarDeg()
408 return _magvar_node->getDoubleValue();
411 double GPS::overflightArmDistanceM()
413 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
416 double GPS::selectedMagCourse()
418 return _selectedCourse;
421 ///////////////////////////////////////////////////////////////////////////
424 GPS::updateBasicData(double dt)
426 if (!_lastPosValid) {
432 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
434 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
435 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
436 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
438 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
439 _last_speed_kts = speed_kt;
441 SGGeod g = _indicated_pos;
442 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
443 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
444 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
446 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
447 _lastNSVelocity = nsMSec;
448 _northSouthVelocity->setDoubleValue(nsMSec);
452 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
453 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
454 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
456 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
457 _lastEWVelocity = ewMSec;
458 _eastWestVelocity->setDoubleValue(ewMSec);
460 double odometer = _odometer_node->getDoubleValue();
461 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
462 odometer = _trip_odometer_node->getDoubleValue();
463 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
471 GPS::updateTrackingBug()
473 double tracking_bug = _tracking_bug_node->getDoubleValue();
474 double true_bug_error = tracking_bug - getTrueTrack();
475 double magnetic_bug_error = tracking_bug - getMagTrack();
477 // Get the errors into the (-180,180) range.
478 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
479 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
481 _true_bug_error_node->setDoubleValue(true_bug_error);
482 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
485 void GPS::endOfFlightPlan()
487 selectOBSMode(_currentWaypt);
490 void GPS::currentWaypointChanged()
496 int index = _route->currentIndex(),
497 count = _route->numLegs();
498 if ((index < 0) || (index >= count)) {
501 // no active leg on the route
506 _prevWaypt = _route->previousLeg()->waypoint();
507 if (_prevWaypt->flag(WPT_DYNAMIC)) {
508 _wp0_position = _indicated_pos;
510 _wp0_position = _prevWaypt->position();
514 _currentWaypt = _route->currentLeg()->waypoint();
515 _desiredCourse = getLegMagCourse();
516 _desiredCourseNode->fireValueChanged();
521 void GPS::waypointsChanged()
523 if (_mode != "leg") {
527 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
528 currentWaypointChanged();
533 if (_mode != "leg") {
537 selectOBSMode(_currentWaypt);
546 int nextIndex = _route->currentIndex() + 1;
547 if (nextIndex >= _route->numLegs()) {
548 SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
550 selectOBSMode(_currentWaypt);
554 // will callback into currentWaypointChanged
555 _route->setCurrentIndex(nextIndex);
558 void GPS::updateTurn()
560 bool printProgress = false;
562 if (_computeTurnData) {
563 if (_last_speed_kts < 10) {
564 // need valid leg course and sensible ground speed to compute the turn
569 printProgress = true;
572 if (!_anticipateTurn) {
578 // find bearing to turn centre
579 double bearing, az2, distanceM;
580 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
581 double progress = computeTurnProgress(bearing);
584 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
587 if (!_inTurn && (progress > 0.0)) {
591 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
592 _turnSequenced = true;
593 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
597 if (_inTurn && (progress >= 1.0)) {
602 // drive deviation and desired course
603 double desiredCourse = bearing - copysign(90, _turnAngle);
604 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
605 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
606 double deviationDeg = desiredCourse - getMagTrack();
607 deviationNm = copysign(deviationNm, deviationDeg);
609 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
610 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
611 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
615 void GPS::updateOverflight()
617 if (!_wayptController->isDone()) {
621 if (_mode == "dto") {
622 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
624 // check for wp1 being on active route - resume leg mode
626 int index = _route->findWayptIndex(_currentWaypt->position());
628 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
630 _route->setCurrentIndex(index);
631 sequence(); // and sequence to the next point
635 if (_mode == "dto") {
636 // if we didn't enter leg mode, drop back to OBS mode
637 // select OBS mode, but keep current waypoint-as is
641 } else if (_mode == "leg") {
642 SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
644 } else if (_mode == "obs") {
645 // nothing to do here, TO/FROM will update but that's fine
648 _computeTurnData = true;
651 void GPS::beginTurn()
654 _turnSequenced = false;
655 SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
661 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
662 _computeTurnData = true;
665 double GPS::computeTurnProgress(double aBearing) const
667 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
668 return (aBearing - startBearing) / _turnAngle;
671 void GPS::computeTurnData()
673 _computeTurnData = false;
674 if ((_mode != "leg") || !_route->nextLeg()) {
675 _anticipateTurn = false;
679 WayptRef next = _route->nextLeg()->waypoint();
680 if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
681 _anticipateTurn = false;
685 _turnStartBearing = _desiredCourse;
686 // compute next leg course
688 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
691 // compute offset bearing
692 _turnAngle = crs - _turnStartBearing;
693 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
694 double median = _turnStartBearing + (_turnAngle * 0.5);
695 double offsetBearing = median + copysign(90, _turnAngle);
696 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
698 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
699 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
700 << ", offset=" << offsetBearing);
702 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
704 _turnPt = _currentWaypt->position();
705 _anticipateTurn = true;
708 void GPS::updateTurnData()
710 // depends on ground speed, so needs to be updated per-frame
711 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
713 // compute the turn centre, based on the turn radius.
714 // key thing is to understand that we're working a right-angle triangle,
715 // where the right-angle is the point we start the turn. From that point,
716 // one side is the inbound course to the turn pt, and the other is the
717 // perpendicular line, of length 'r', to the turn centre.
718 // the triangle's hypotenuse, which we need to find, is the distance from the
719 // turn pt to the turn center (in the direction of the offset bearing)
720 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
722 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
723 double d = _turnRadius / cos(halfTurnAngle);
725 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
726 // << " (cut distance=" << d - _turnRadius << ")");
728 double median = _turnStartBearing + (_turnAngle * 0.5);
729 double offsetBearing = median + copysign(90, _turnAngle);
730 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
733 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
736 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
738 // turn time is seconds to execute a 360 turn.
739 double turnTime = 360.0 / _config.turnRateDegSec();
741 // c is ground distance covered in that time (circumference of the circle)
742 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
744 // divide by 2PI to go from circumference -> radius
745 return c / (2 * M_PI);
748 void GPS::updateRouteData()
750 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
751 // walk all waypoints from wp2 to route end, and sum
752 // for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
753 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
756 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
757 if (_last_speed_kts > 1.0) {
758 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
759 _routeETE->setStringValue(makeTTWString(TTW));
763 void GPS::driveAutopilot()
765 if (!_config.driveAutopilot() || !_defaultGPSMode) {
766 _apDrivingFlag->setBoolValue(false);
770 // compatability feature - allow the route-manager / GPS to drive the
771 // generic autopilot heading hold *in leg mode only*
773 bool drive = _mode == "leg";
774 _apDrivingFlag->setBoolValue(drive);
777 // FIXME: we want to set desired track, not heading, here
778 _apTrueHeading->setDoubleValue(getWP1Bearing());
782 void GPS::wp1Changed()
786 if (_mode == "leg") {
787 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
788 } else if (_mode == "obs") {
789 _wayptController.reset(new OBSController(this, _currentWaypt));
790 } else if (_mode == "dto") {
791 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
794 _wayptController->init();
796 if (_mode == "obs") {
797 _legDistanceNm = -1.0;
799 _wayptController->update();
800 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
804 /////////////////////////////////////////////////////////////////////////////
805 // property getter/setters
807 void GPS::setSelectedCourse(double crs)
809 if (_selectedCourse == crs) {
813 _selectedCourse = crs;
814 if ((_mode == "obs") || _config.courseSelectable()) {
815 _desiredCourse = _selectedCourse;
816 _desiredCourseNode->fireValueChanged();
820 double GPS::getLegDistance() const
822 if (!_dataValid || (_mode == "obs")) {
826 return _legDistanceNm;
829 double GPS::getLegCourse() const
831 if (!_dataValid || !_wayptController.get()) {
835 return _wayptController->targetTrackDeg();
838 double GPS::getLegMagCourse() const
844 double m = getLegCourse() - _magvar_node->getDoubleValue();
845 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
849 double GPS::getMagTrack() const
855 double m = getTrueTrack() - _magvar_node->getDoubleValue();
856 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
860 double GPS::getCDIDeflection() const
867 if (_config.cdiDeflectionIsAngular()) {
868 defl = getWP1CourseDeviation();
869 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
871 double fullScale = _config.cdiDeflectionLinearPeg();
872 double normError = getWP1CourseErrorNm() / fullScale;
873 SG_CLAMP_RANGE(normError, -1.0, 1.0);
874 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
880 const char* GPS::getWP0Ident() const
882 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
886 return _prevWaypt->ident().c_str();
889 const char* GPS::getWP0Name() const
894 const char* GPS::getWP1Ident() const
896 if ((!_dataValid)||(!_currentWaypt)) {
900 return _currentWaypt->ident().c_str();
903 const char* GPS::getWP1Name() const
908 double GPS::getWP1Distance() const
910 if (!_dataValid || !_wayptController.get()) {
914 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
917 double GPS::getWP1TTW() const
919 if (!_dataValid || !_wayptController.get()) {
923 return _wayptController->timeToWaypt();
926 const char* GPS::getWP1TTWString() const
928 double t = getWP1TTW();
933 return makeTTWString(t);
936 double GPS::getWP1Bearing() const
938 if (!_dataValid || !_wayptController.get()) {
942 return _wayptController->trueBearingDeg();
945 double GPS::getWP1MagBearing() const
947 if (!_dataValid || !_wayptController.get()) {
951 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
952 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
956 double GPS::getWP1CourseDeviation() const
958 if (!_dataValid || !_wayptController.get()) {
962 return _wayptController->courseDeviationDeg();
965 double GPS::getWP1CourseErrorNm() const
967 if (!_dataValid || !_wayptController.get()) {
971 return _wayptController->xtrackErrorNm();
974 bool GPS::getWP1ToFlag() const
976 if (!_dataValid || !_wayptController.get()) {
980 return _wayptController->toFlag();
983 bool GPS::getWP1FromFlag() const
985 if (!_dataValid || !_wayptController.get()) {
989 return !getWP1ToFlag();
993 double GPS::getScratchDistance() const
995 if (!_scratchValid) {
999 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1002 double GPS::getScratchTrueBearing() const
1004 if (!_scratchValid) {
1008 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1011 double GPS::getScratchMagBearing() const
1013 if (!_scratchValid) {
1017 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1018 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1024 /////////////////////////////////////////////////////////////////////////////
1027 void GPS::setCommand(const char* aCmd)
1029 SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1031 if (!strcmp(aCmd, "direct")) {
1033 } else if (!strcmp(aCmd, "obs")) {
1034 selectOBSMode(NULL);
1035 } else if (!strcmp(aCmd, "leg")) {
1038 } else if (!strcmp(aCmd, "load-route-wpt")) {
1039 loadRouteWaypoint();
1040 } else if (!strcmp(aCmd, "nearest")) {
1042 } else if (!strcmp(aCmd, "search")) {
1043 _searchNames = false;
1045 } else if (!strcmp(aCmd, "search-names")) {
1046 _searchNames = true;
1048 } else if (!strcmp(aCmd, "next")) {
1050 } else if (!strcmp(aCmd, "previous")) {
1052 } else if (!strcmp(aCmd, "define-user-wpt")) {
1054 } else if (!strcmp(aCmd, "route-insert-before")) {
1055 int index = _scratchNode->getIntValue("index");
1056 if (index < 0 || (_route->numLegs() == 0)) {
1057 index = _route->numLegs();
1058 } else if (index >= _route->numLegs()) {
1059 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1063 insertWaypointAtIndex(index);
1064 } else if (!strcmp(aCmd, "route-insert-after")) {
1065 int index = _scratchNode->getIntValue("index");
1066 if (index < 0 || (_route->numLegs() == 0)) {
1067 index = _route->numLegs();
1068 } else if (index >= _route->numLegs()) {
1069 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1075 insertWaypointAtIndex(index);
1076 } else if (!strcmp(aCmd, "route-delete")) {
1077 int index = _scratchNode->getIntValue("index");
1079 index = _route->numLegs();
1080 } else if (index >= _route->numLegs()) {
1081 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1085 removeWaypointAtIndex(index);
1088 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1092 void GPS::clearScratch()
1094 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1095 _scratchNode->setBoolValue("valid", false);
1097 _scratchNode->setStringValue("type", "");
1098 _scratchNode->setStringValue("query", "");
1102 bool GPS::isScratchPositionValid() const
1104 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1105 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1112 void GPS::directTo()
1114 if (!isScratchPositionValid()) {
1119 _wp0_position = _indicated_pos;
1120 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1127 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1130 // initialise from scratch
1131 if (!isScratchPositionValid()) {
1135 waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1139 _currentWaypt = waypt;
1140 _wp0_position = _indicated_pos;
1144 void GPS::selectLegMode()
1146 if (_mode == "leg") {
1151 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1156 // depending on the situation, this will either get over-written
1157 // in routeManagerSequenced or not; either way it does no harm to
1159 _wp0_position = _indicated_pos;
1161 // not really sequenced, but does all the work of updating wp0/1
1162 currentWaypointChanged();
1167 void GPS::loadRouteWaypoint()
1169 _scratchValid = false;
1170 int index = _scratchNode->getIntValue("index", -9999);
1173 if ((index < 0) || (index >= _route->numLegs())) { // no index supplied, use current wp
1174 index = _route->currentIndex();
1177 _searchIsRoute = true;
1178 setScratchFromRouteWaypoint(index);
1181 void GPS::setScratchFromRouteWaypoint(int aIndex)
1183 assert(_searchIsRoute);
1184 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1185 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1189 _searchResultIndex = aIndex;
1190 WayptRef wp = _route->legAtIndex(aIndex)->waypoint();
1191 _scratchNode->setStringValue("ident", wp->ident());
1192 _scratchPos = wp->position();
1193 _scratchValid = true;
1194 _scratchNode->setIntValue("index", aIndex);
1197 void GPS::loadNearest()
1199 string sty(_scratchNode->getStringValue("type"));
1200 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1201 if (ty == FGPositioned::INVALID) {
1202 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1206 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1207 int limitCount = _scratchNode->getIntValue("max-results", 1);
1208 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1210 SGGeod searchPos = _indicated_pos;
1211 if (isScratchPositionValid()) {
1212 searchPos = _scratchPos;
1215 clearScratch(); // clear now, regardless of whether we find a match or not
1218 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1219 _searchResultIndex = 0;
1220 _searchIsRoute = false;
1222 if (_searchResults.empty()) {
1226 setScratchFromCachedSearchResult();
1229 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1231 switch (aPos->type()) {
1232 case FGPositioned::AIRPORT:
1233 // heliport and seaport too?
1234 case FGPositioned::VOR:
1235 case FGPositioned::NDB:
1236 case FGPositioned::FIX:
1237 case FGPositioned::TACAN:
1238 case FGPositioned::WAYPOINT:
1245 FGPositioned::Type GPS::SearchFilter::minType() const
1247 return FGPositioned::AIRPORT;
1250 FGPositioned::Type GPS::SearchFilter::maxType() const
1252 return FGPositioned::VOR;
1255 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1257 if (aTy == FGPositioned::AIRPORT) {
1258 return new FGAirport::HardSurfaceFilter();
1261 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1262 if (aTy == FGPositioned::INVALID) {
1263 return new SearchFilter;
1266 return new FGPositioned::TypeFilter(aTy);
1271 // parse search terms into local members, and exec the first search
1272 string sty(_scratchNode->getStringValue("type"));
1273 _searchType = FGPositioned::typeFromName(sty);
1274 _searchQuery = _scratchNode->getStringValue("query");
1275 if (_searchQuery.empty()) {
1276 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1281 _searchExact = _scratchNode->getBoolValue("exact", true);
1282 _searchResultIndex = 0;
1283 _searchIsRoute = false;
1285 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1287 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1289 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1292 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1294 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1297 if (_searchResults.empty()) {
1302 setScratchFromCachedSearchResult();
1305 bool GPS::getScratchHasNext() const
1308 if (_searchIsRoute) {
1309 lastResult = _route->numLegs() - 1;
1311 lastResult = (int) _searchResults.size() - 1;
1314 if (lastResult < 0) { // search array might be empty
1318 return (_searchResultIndex < lastResult);
1321 void GPS::setScratchFromCachedSearchResult()
1323 int index = _searchResultIndex;
1325 if ((index < 0) || (index >= (int) _searchResults.size())) {
1326 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1330 setScratchFromPositioned(_searchResults[index], index);
1333 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1338 _scratchPos = aPos->geod();
1339 _scratchNode->setStringValue("name", aPos->name());
1340 _scratchNode->setStringValue("ident", aPos->ident());
1341 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1344 _scratchNode->setIntValue("index", aIndex);
1347 _scratchValid = true;
1348 _scratchNode->setIntValue("result-count", _searchResults.size());
1350 switch (aPos->type()) {
1351 case FGPositioned::VOR:
1352 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1355 case FGPositioned::NDB:
1356 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1359 case FGPositioned::AIRPORT:
1360 addAirportToScratch((FGAirport*)aPos);
1368 // look for being on the route and set?
1371 void GPS::addAirportToScratch(FGAirport* aAirport)
1373 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1374 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1375 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1376 // TODO - filter out unsuitable runways in the future
1377 // based on config again
1379 rwyNd->setStringValue("id", rwy->ident().c_str());
1380 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1381 rwyNd->setIntValue("width-ft", rwy->widthFt());
1382 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1383 // map surface code to a string
1384 // TODO - lighting information
1387 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1389 } // of runways iteration
1392 void GPS::nextResult()
1394 if (!getScratchHasNext()) {
1399 if (_searchIsRoute) {
1400 setScratchFromRouteWaypoint(++_searchResultIndex);
1402 ++_searchResultIndex;
1403 setScratchFromCachedSearchResult();
1407 void GPS::previousResult()
1409 if (_searchResultIndex <= 0) {
1414 --_searchResultIndex;
1416 if (_searchIsRoute) {
1417 setScratchFromRouteWaypoint(_searchResultIndex);
1419 setScratchFromCachedSearchResult();
1423 void GPS::defineWaypoint()
1425 if (!isScratchPositionValid()) {
1426 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1430 string ident = _scratchNode->getStringValue("ident");
1431 if (ident.size() < 2) {
1432 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1436 // check for duplicate idents
1437 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1438 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1439 if (!dups.empty()) {
1440 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1443 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1444 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1445 _searchResults.clear();
1446 _searchResults.push_back(wpt);
1447 setScratchFromPositioned(wpt.get(), -1);
1450 void GPS::insertWaypointAtIndex(int aIndex)
1452 // note we do allow index = routeMgr->size(), that's an append
1453 if ((aIndex < 0) || (aIndex > _route->numLegs())) {
1454 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1457 if (!isScratchPositionValid()) {
1458 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1462 string ident = _scratchNode->getStringValue("ident");
1464 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1465 _route->insertWayptAtIndex(wpt, aIndex);
1468 void GPS::removeWaypointAtIndex(int aIndex)
1470 if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1471 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1474 _route->deleteIndex(aIndex);
1478 #endif // of FG_210_COMPAT
1480 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1481 const char* lonStr, const char* latStr, const char* altStr)
1483 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1484 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1487 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1491 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1492 const char* lonStr, const char* latStr, const char* altStr)
1494 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1495 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1498 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));