]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/gps.cxx
Jean Pellotier: don't show markers for invalid targets in HUD
[flightgear.git] / src / Instrumentation / gps.cxx
1 // gps.cxx - distance-measuring equipment.
2 // Written by David Megginson, started 2003.
3 //
4 // This file is in the Public Domain and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #  include <config.h>
8 #endif
9
10 #include "gps.hxx"
11
12 #include <boost/tuple/tuple.hpp>
13
14 #include <memory>
15 #include <set>
16 #include <cstring>
17
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"
27
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>
32 #include <simgear/scene/util/OsgMath.hxx>
33
34 using std::auto_ptr;
35 using std::string;
36 using namespace flightgear;
37
38 ///////////////////////////////////////////////////////////////////
39
40 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
41 {
42     _lon = base->getChild(lonStr, 0, true);
43     _lat = base->getChild(latStr, 0, true);
44     if (altStr) {
45         _alt = base->getChild(altStr, 0, true);
46     }
47 }
48
49 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
50 {
51     _lon = fgGetNode(lonStr, true);
52     _lat = fgGetNode(latStr, true);
53     if (altStr) {
54         _alt = fgGetNode(altStr, true);
55     }
56 }
57
58 void SGGeodProperty::clear()
59 {
60     _lon = _lat = _alt = NULL;
61 }
62
63 void SGGeodProperty::operator=(const SGGeod& geod)
64 {
65     _lon->setDoubleValue(geod.getLongitudeDeg());
66     _lat->setDoubleValue(geod.getLatitudeDeg());
67     if (_alt) {
68         _alt->setDoubleValue(geod.getElevationFt());
69     }
70 }
71
72 SGGeod SGGeodProperty::get() const
73 {
74     double lon = _lon->getDoubleValue(),
75         lat = _lat->getDoubleValue();
76         
77     if (osg::isNaN(lon) || osg::isNaN(lat)) {
78       SG_LOG(SG_INSTR, SG_WARN, "read NaN for lon/lat:" << _lon->getPath() 
79         << ", " << _lat->getPath());
80       return SGGeod();
81     }
82         
83     if (_alt) {
84         return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
85     } else {
86         return SGGeod::fromDeg(lon,lat);
87     }
88 }
89
90 static const char* makeTTWString(double TTW)
91 {
92   if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
93     return "--:--:--";
94   }
95       
96   unsigned int TTW_seconds = (int) (TTW + 0.5);
97   unsigned int TTW_minutes = 0;
98   unsigned int TTW_hours   = 0;
99   static char TTW_str[9];
100   TTW_hours   = TTW_seconds / 3600;
101   TTW_minutes = (TTW_seconds / 60) % 60;
102   TTW_seconds = TTW_seconds % 60;
103   snprintf(TTW_str, 9, "%02d:%02d:%02d",
104     TTW_hours, TTW_minutes, TTW_seconds);
105   return TTW_str;
106 }
107
108 /////////////////////////////////////////////////////////////////////////////
109
110 class GPSListener : public SGPropertyChangeListener
111 {
112 public:
113   GPSListener(GPS *m) : 
114     _gps(m),
115     _guard(false) {}
116     
117   virtual void valueChanged (SGPropertyNode * prop)
118   {
119     if (_guard) {
120       return;
121     }
122     
123     _guard = true;
124     if (prop == _gps->_route_current_wp_node) {
125       _gps->routeManagerSequenced();
126     } else if (prop == _gps->_route_active_node) {
127       _gps->routeActivated();
128     } else if (prop == _gps->_ref_navaid_id_node) {
129       _gps->referenceNavaidSet(prop->getStringValue(""));
130     } else if (prop == _gps->_routeEditedSignal) {
131       _gps->routeEdited();
132     } else if (prop == _gps->_routeFinishedSignal) {
133       _gps->routeFinished();
134     }
135         
136     _guard = false;
137   }
138   
139   void setGuard(bool g) {
140     _guard = g;
141   }
142 private:
143   GPS* _gps;
144   bool _guard; // re-entrancy guard
145 };
146
147 ////////////////////////////////////////////////////////////////////////////
148 /**
149  * Helper to monitor for Nasal or other code accessing properties we haven't
150  * defined. For the moment we complain about all such activites, since various
151  * users assume all kinds of weird, wonderful and non-existent interfaces.
152  */
153  
154 class DeprecatedPropListener : public SGPropertyChangeListener
155 {
156 public:
157   DeprecatedPropListener(SGPropertyNode* gps)
158   {
159     _parents.insert(gps);
160     SGPropertyNode* wp = gps->getChild("wp", 0, true); 
161     _parents.insert(wp);
162     _parents.insert(wp->getChild("wp", 0, true));
163     _parents.insert(wp->getChild("wp", 1, true));
164     
165     std::set<SGPropertyNode*>::iterator it;
166     for (it = _parents.begin(); it != _parents.end(); ++it) {
167       (*it)->addChangeListener(this);
168     }
169   }
170   
171   virtual void valueChanged (SGPropertyNode * prop)
172   {
173   }
174   
175   virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
176   {
177     if (isDeprecated(parent, child)) {
178       SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
179         << child->getPath(true));
180     }
181   }
182 private:
183   bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const 
184   {
185     if (_parents.count(parent) < 1) {
186       return false;
187     }
188     
189     // no child exclusions yet
190     return true;
191   }
192   
193   std::set<SGPropertyNode*> _parents;
194 };
195
196 ////////////////////////////////////////////////////////////////////////////
197 // configuration helper object
198
199 GPS::Config::Config() :
200   _enableTurnAnticipation(true),
201   _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
202   _overflightArmDistance(1.0),
203   _waypointAlertTime(30.0),
204   _requireHardSurface(true),
205   _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
206   _driveAutopilot(true),
207   _courseSelectable(false)
208 {
209   _enableTurnAnticipation = false;
210 }
211
212 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
213 {
214   aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
215   aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
216   aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
217   aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
218   aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
219   aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
220   aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
221 }
222
223 ////////////////////////////////////////////////////////////////////////////
224
225 GPS::GPS ( SGPropertyNode *node) : 
226   _selectedCourse(0.0),
227   _desiredCourse(0.0),
228   _dataValid(false),
229   _lastPosValid(false),
230   _mode("init"),
231   _name(node->getStringValue("name", "gps")),
232   _num(node->getIntValue("number", 0)),
233   _searchResultIndex(0),
234   _searchExact(true),
235   _searchIsRoute(false),
236   _searchHasNext(false),
237   _searchNames(false),
238   _computeTurnData(false),
239   _anticipateTurn(false),
240   _inTurn(false)
241 {
242   string branch = "/instrumentation/" + _name;
243   _gpsNode = fgGetNode(branch.c_str(), _num, true );
244   _scratchNode = _gpsNode->getChild("scratch", 0, true);
245   
246   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
247   _currentWayptNode = wp_node->getChild("wp", 1, true);
248 }
249
250 GPS::~GPS ()
251 {
252 }
253
254 void
255 GPS::init ()
256 {
257   _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
258   assert(_routeMgr);
259   
260   _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
261   _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
262   _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
263   _serviceable_node->setBoolValue(true);
264   _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
265
266 // basic GPS outputs
267   _raim_node = _gpsNode->getChild("raim", 0, true);
268   _odometer_node = _gpsNode->getChild("odometer", 0, true);
269   _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
270   _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
271   _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
272   _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
273   _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
274   
275 // waypoints
276   // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
277   SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
278   wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
279
280   _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
281          
282 // reference navid
283   SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
284   _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
285   _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
286   _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
287   _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
288   _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
289   _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
290   _ref_navaid_elapsed = 0.0;
291   _ref_navaid_set = false;
292     
293 // route properties    
294   // should these move to the route manager?
295   _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
296   _routeETE = _gpsNode->getChild("ETE", 0, true);
297   _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
298   _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
299   
300 // add listener to various things
301   _listener = new GPSListener(this);
302   _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
303   _route_current_wp_node->addChangeListener(_listener);
304   _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
305   _route_active_node->addChangeListener(_listener);
306   _ref_navaid_id_node->addChangeListener(_listener);
307   _routeEditedSignal->addChangeListener(_listener);
308   _routeFinishedSignal->addChangeListener(_listener);
309   
310 // navradio slaving properties  
311   SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
312   toFlag->alias(_currentWayptNode->getChild("to-flag"));
313   
314   SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
315   fromFlag->alias(_currentWayptNode->getChild("from-flag"));
316     
317 // autopilot drive properties
318   _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
319   _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
320   _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
321   _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
322   
323 // realism prop[s]
324   _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
325   if (!_realismSimpleGps->hasValue()) {
326     _realismSimpleGps->setBoolValue(true);
327   }
328   
329   // last thing, add the deprecated prop watcher
330   new DeprecatedPropListener(_gpsNode);
331 }
332
333 void
334 GPS::reinit ()
335 {
336   clearOutput();
337 }
338
339 void
340 GPS::bind()
341 {
342   _config.bind(this, _gpsNode->getChild("config", 0, true));
343
344 // basic GPS outputs
345   tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
346     (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
347
348   tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
349     (*this, &GPS::getDesiredCourse, NULL));
350   _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
351     
352   tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", 
353         "indicated-latitude-deg", "indicated-altitude-ft");
354
355   tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
356     (*this, &GPS::getVerticalSpeed, NULL));
357   tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
358     (*this, &GPS::getTrueTrack, NULL));
359   tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
360     (*this, &GPS::getMagTrack, NULL));
361   tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
362     (*this, &GPS::getGroundspeedKts, NULL));
363   
364 // command system
365   tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
366   tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
367     
368   tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
369   tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
370   tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
371   tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
372   tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
373   tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
374   _scratchValid = false;
375
376   
377   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
378   SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
379   
380   tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
381   tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
382     (*this, &GPS::getWP1Ident, NULL));
383   
384   tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
385     (*this, &GPS::getWP1Distance, NULL));
386   tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
387     (*this, &GPS::getWP1Bearing, NULL));
388   tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
389     (*this, &GPS::getWP1MagBearing, NULL));
390   tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
391     (*this, &GPS::getWP1TTW, NULL));
392   tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
393     (*this, &GPS::getWP1TTWString, NULL));
394   
395   tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
396     (*this, &GPS::getWP1CourseDeviation, NULL));
397   tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
398     (*this, &GPS::getWP1CourseErrorNm, NULL));
399   tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
400     (*this, &GPS::getWP1ToFlag, NULL));
401   tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
402     (*this, &GPS::getWP1FromFlag, NULL));
403
404 // leg properties (only valid in DTO/LEG modes, not OBS)
405   tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
406   tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
407   tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
408
409 // navradio slaving properties  
410   tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
411     (*this, &GPS::getCDIDeflection));
412 }
413
414 void
415 GPS::unbind()
416 {
417   _tiedProperties.Untie();
418 }
419
420 void
421 GPS::clearOutput()
422 {
423   _dataValid = false;
424   _last_speed_kts = 0.0;
425   _last_pos = SGGeod();
426   _lastPosValid = false;
427   _indicated_pos = SGGeod();
428   _last_vertical_speed = 0.0;
429   _last_true_track = 0.0;
430   _lastEWVelocity = _lastNSVelocity = 0.0;
431   _currentWaypt = _prevWaypt = NULL;
432   _legDistanceNm = -1.0;
433   
434   _raim_node->setDoubleValue(0.0);
435   _indicated_pos = SGGeod();
436   _odometer_node->setDoubleValue(0);
437   _trip_odometer_node->setDoubleValue(0);
438   _tracking_bug_node->setDoubleValue(0);
439   _true_bug_error_node->setDoubleValue(0);
440   _magnetic_bug_error_node->setDoubleValue(0);
441   _northSouthVelocity->setDoubleValue(0.0);
442   _eastWestVelocity->setDoubleValue(0.0);
443 }
444
445 void
446 GPS::update (double delta_time_sec)
447 {
448   if (!_realismSimpleGps->getBoolValue()) {
449     // If it's off, don't bother.
450     if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
451       clearOutput();
452       return;
453     }
454   }
455   
456   if (delta_time_sec <= 0.0) {
457     return; // paused, don't bother
458   }    
459   
460   _raim_node->setDoubleValue(1.0);
461   _indicated_pos = _position.get();
462   updateBasicData(delta_time_sec);
463
464   if (_dataValid) {
465     if (_wayptController.get()) {
466       _wayptController->update();
467       SGGeod p(_wayptController->position());
468       _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
469       _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
470       _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
471       
472       _desiredCourse = getLegMagCourse();
473       
474       updateTurn();
475       updateRouteData();
476     }
477
478     
479     updateTrackingBug();
480     updateReferenceNavaid(delta_time_sec);
481     driveAutopilot();
482   }
483   
484   if (_dataValid && (_mode == "init")) {
485         
486     if (_route_active_node->getBoolValue()) {
487       // GPS init with active route
488       SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
489       selectLegMode();
490     } else {
491       // initialise in OBS mode, with waypt set to the nearest airport.
492       // keep in mind at this point, _dataValid is not set
493     
494       auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
495       FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
496       if (apt) {
497         setScratchFromPositioned(apt, 0);
498         selectOBSMode();
499       }
500     }
501
502     if (_mode != "init")
503     {
504       // allow a realistic delay in the future, here
505       SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
506     }
507   } // of init mode check
508   
509   _last_pos = _indicated_pos;
510   _lastPosValid = !(_last_pos == SGGeod());
511 }
512
513 ///////////////////////////////////////////////////////////////////////////
514 // implement the RNAV interface 
515 SGGeod GPS::position()
516 {
517   if (!_dataValid) {
518     return SGGeod();
519   }
520   
521   return _indicated_pos;
522 }
523
524 double GPS::trackDeg()
525 {
526   return _last_true_track;
527 }
528
529 double GPS::groundSpeedKts()
530 {
531   return _last_speed_kts;
532 }
533
534 double GPS::vspeedFPM()
535 {
536   return _last_vertical_speed;
537 }
538
539 double GPS::magvarDeg()
540 {
541   return _magvar_node->getDoubleValue();
542 }
543
544 double GPS::overflightArmDistanceM()
545 {
546   return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
547 }
548
549 double GPS::selectedMagCourse()
550 {
551   return _selectedCourse;
552 }
553
554 ///////////////////////////////////////////////////////////////////////////
555
556 void
557 GPS::updateBasicData(double dt)
558 {
559   if (!_lastPosValid) {
560     return;
561   }
562   
563   double distance_m;
564   double track2_deg;
565   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
566     
567   double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
568   double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
569   _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
570   
571   speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
572   _last_speed_kts = speed_kt;
573   
574   SGGeod g = _indicated_pos;
575   g.setLongitudeDeg(_last_pos.getLongitudeDeg());
576   double northSouthM = SGGeodesy::distanceM(_last_pos, g);
577   northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
578   
579   double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
580   _lastNSVelocity = nsMSec;
581   _northSouthVelocity->setDoubleValue(nsMSec);
582
583
584   g = _indicated_pos;
585   g.setLatitudeDeg(_last_pos.getLatitudeDeg());
586   double eastWestM = SGGeodesy::distanceM(_last_pos, g);
587   eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
588   
589   double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
590   _lastEWVelocity = ewMSec;
591   _eastWestVelocity->setDoubleValue(ewMSec);
592   
593   double odometer = _odometer_node->getDoubleValue();
594   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
595   odometer = _trip_odometer_node->getDoubleValue();
596   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
597   
598   if (!_dataValid) {
599     SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
600     _dataValid = true;
601   }
602 }
603
604 void
605 GPS::updateTrackingBug()
606 {
607   double tracking_bug = _tracking_bug_node->getDoubleValue();
608   double true_bug_error = tracking_bug - getTrueTrack();
609   double magnetic_bug_error = tracking_bug - getMagTrack();
610
611   // Get the errors into the (-180,180) range.
612   SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
613   SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
614
615   _true_bug_error_node->setDoubleValue(true_bug_error);
616   _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
617 }
618
619 void GPS::updateReferenceNavaid(double dt)
620 {
621   if (!_ref_navaid_set) {
622     _ref_navaid_elapsed += dt;
623     if (_ref_navaid_elapsed > 5.0) {
624
625       FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
626       FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
627       if (!nav) {
628         SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navaid");
629         _ref_navaid_id_node->setStringValue("");
630         _ref_navaid_name_node->setStringValue("");
631         _ref_navaid_bearing_node->setDoubleValue(0.0);
632         _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
633         _ref_navaid_distance_node->setDoubleValue(0.0);
634         _ref_navaid_frequency_node->setStringValue("");
635       } else if (nav != _ref_navaid) {
636         SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
637         _listener->setGuard(true);
638         _ref_navaid_id_node->setStringValue(nav->ident().c_str());
639         _ref_navaid_name_node->setStringValue(nav->name().c_str());
640         FGNavRecord* vor = (FGNavRecord*) nav.ptr();
641         _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
642         _listener->setGuard(false);
643       } else {
644         // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
645       }
646       
647       _ref_navaid = nav;
648       // reset elapsed time (do not do that before updating the properties above, since their
649       // listeners may request another update (_ref_navaid_elapsed = 9999), which results in
650       // excessive load (FGPositioned::findClosest called in every update loop...)
651       _ref_navaid_elapsed = 0.0; 
652     }
653   }
654   
655   if (_ref_navaid) {
656     double trueCourse, distanceM, az2;
657     SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
658     _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
659     _ref_navaid_bearing_node->setDoubleValue(trueCourse);
660     _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
661   }
662 }
663
664 void GPS::referenceNavaidSet(const std::string& aNavaid)
665 {
666   _ref_navaid = NULL;
667   // allow setting an empty string to restore normal nearest-vor selection
668   if (aNavaid.size() > 0) {
669     FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
670     _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid, 
671       _position.get(), &vorFilter);
672     
673     if (!_ref_navaid) {
674       SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
675     }
676   }
677
678   if (_ref_navaid) {
679     _ref_navaid_set = true;
680     SG_LOG(SG_INSTR, SG_INFO, "GPS code set explicit ref-navaid:" << _ref_navaid->ident());
681     _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
682     _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
683     FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
684     _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
685   } else {
686     _ref_navaid_set = false;
687     _ref_navaid_elapsed = 9999.0; // update next tick
688   }
689 }
690
691 void GPS::routeActivated()
692 {
693   if (_route_active_node->getBoolValue()) {
694     SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
695     selectLegMode();
696     
697     // if we've already passed the current waypoint, sequence.
698     if (_dataValid && getWP1FromFlag()) {
699       SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
700       _routeMgr->sequence();
701     }
702   } else if (_mode == "leg") {
703     SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
704     // select OBS mode, but keep current waypoint-as is
705     _mode = "obs";
706     wp1Changed();
707   }
708 }
709
710 void GPS::routeManagerSequenced()
711 {
712   if (_mode != "leg") {
713     SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
714     return;
715   }
716   
717   int index = _routeMgr->currentIndex(),
718     count = _routeMgr->numWaypts();
719   if ((index < 0) || (index >= count)) {
720     _currentWaypt=NULL;
721     _prevWaypt=NULL;
722     SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
723     return;
724   }
725   
726   SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
727   
728   if (index > 0) {
729     _prevWaypt = _routeMgr->wayptAtIndex(index - 1);
730     if (_prevWaypt->flag(WPT_DYNAMIC)) {
731       _wp0_position = _indicated_pos;
732     } else {
733       _wp0_position = _prevWaypt->position();
734     }
735   }
736   
737   _currentWaypt = _routeMgr->currentWaypt();
738
739   _desiredCourse = getLegMagCourse();
740   _desiredCourseNode->fireValueChanged();
741   wp1Changed();
742 }
743
744 void GPS::routeEdited()
745 {
746   if (_mode != "leg") {
747     return;
748   }
749   
750   SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
751   routeManagerSequenced();
752 }
753
754 void GPS::routeFinished()
755 {
756   if (_mode != "leg") {
757     return;
758   }
759   
760   SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
761   // select OBS mode, but keep current waypoint-as is
762   _mode = "obs";
763   wp1Changed();
764 }
765
766 void GPS::updateTurn()
767 {
768   bool printProgress = false;
769   
770   if (_computeTurnData) {
771     if (_last_speed_kts < 60) {
772       // need valid leg course and sensible ground speed to compute the turn
773       return;
774     }
775     
776     computeTurnData();
777     printProgress = true;
778   }
779   
780   if (!_anticipateTurn) {
781     updateOverflight();
782     return;
783   }
784
785   updateTurnData();
786   // find bearing to turn centre
787   double bearing, az2, distanceM;
788   SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
789   double progress = computeTurnProgress(bearing);
790   
791   if (printProgress) {
792     SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
793   }
794   
795   if (!_inTurn && (progress > 0.0)) {
796     beginTurn();
797   }
798   
799   if (_inTurn && !_turnSequenced && (progress > 0.5)) {
800     _turnSequenced = true;
801      SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
802      _routeMgr->sequence();
803   }
804   
805   if (_inTurn && (progress >= 1.0)) {
806     endTurn();
807   }
808   
809   if (_inTurn) {
810     // drive deviation and desired course
811     double desiredCourse = bearing - copysign(90, _turnAngle);
812     SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
813     double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
814     double deviationDeg = desiredCourse - getMagTrack();
815     deviationNm = copysign(deviationNm, deviationDeg);
816     // FIXME
817     //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
818     //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
819     //_cdiDeflectionNode->setDoubleValue(deviationDeg);
820   }
821 }
822
823 void GPS::updateOverflight()
824 {
825   if (!_wayptController->isDone()) {
826     return;
827   }
828   
829   if (_mode == "dto") {
830     SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
831     
832     // check for wp1 being on active route - resume leg mode
833     if (_routeMgr->isRouteActive()) {
834       int index = _routeMgr->flightPlan()->findWayptIndex(_currentWaypt->position());
835       if (index >= 0) {
836         SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
837         _mode = "leg";
838         _routeMgr->jumpToIndex(index);
839       }
840     }
841     
842     if (_mode == "dto") {
843       // if we didn't enter leg mode, drop back to OBS mode
844       // select OBS mode, but keep current waypoint-as is
845       _mode = "obs";
846       wp1Changed();
847     }
848   } else if (_mode == "leg") {
849     SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
850     _routeMgr->sequence();
851   } else if (_mode == "obs") {
852     // nothing to do here, TO/FROM will update but that's fine
853   }
854   
855   _computeTurnData = true;
856 }
857
858 void GPS::beginTurn()
859 {
860   _inTurn = true;
861   _turnSequenced = false;
862   SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
863 }
864
865 void GPS::endTurn()
866 {
867   _inTurn = false;
868   SG_LOG(SG_INSTR, SG_INFO, "ending turn");
869   _computeTurnData = true;
870 }
871
872 double GPS::computeTurnProgress(double aBearing) const
873 {
874   double startBearing = _turnStartBearing + copysign(90, _turnAngle);
875   return (aBearing - startBearing) / _turnAngle;
876 }
877
878 void GPS::computeTurnData()
879 {
880   _computeTurnData = false;
881   if (_mode != "leg") { // and approach modes in the future
882     _anticipateTurn = false;
883     return;
884   }
885   
886   WayptRef next = _routeMgr->wayptAtIndex(_routeMgr->currentIndex() + 1);
887   if (!next || next->flag(WPT_DYNAMIC)) {
888     _anticipateTurn = false;
889     return;
890   }
891   
892   if (!_config.turnAnticipationEnabled()) {
893     _anticipateTurn = false;
894     return;
895   }
896   
897   _turnStartBearing = _desiredCourse;
898 // compute next leg course
899   double crs, dist;
900   boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
901     
902
903 // compute offset bearing
904   _turnAngle = crs - _turnStartBearing;
905   SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
906   double median = _turnStartBearing + (_turnAngle * 0.5);
907   double offsetBearing = median + copysign(90, _turnAngle);
908   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
909   
910   SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
911     ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median 
912     << ", offset=" << offsetBearing);
913
914   SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
915
916   _turnPt = _currentWaypt->position();
917   _anticipateTurn = true;
918 }
919
920 void GPS::updateTurnData()
921 {
922   // depends on ground speed, so needs to be updated per-frame
923   _turnRadius = computeTurnRadiusNm(_last_speed_kts);
924   
925   // compute the turn centre, based on the turn radius.
926   // key thing is to understand that we're working a right-angle triangle,
927   // where the right-angle is the point we start the turn. From that point,
928   // one side is the inbound course to the turn pt, and the other is the
929   // perpendicular line, of length 'r', to the turn centre.
930   // the triangle's hypotenuse, which we need to find, is the distance from the
931   // turn pt to the turn center (in the direction of the offset bearing)
932   // note that d - _turnRadius tell us how much we're 'cutting' the corner.
933   
934   double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
935   double d = _turnRadius / cos(halfTurnAngle);
936   
937  // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
938  //   << " (cut distance=" << d - _turnRadius << ")");
939   
940   double median = _turnStartBearing + (_turnAngle * 0.5);
941   double offsetBearing = median + copysign(90, _turnAngle);
942   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
943   
944   double az2;
945   SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2); 
946 }
947
948 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
949 {
950         // turn time is seconds to execute a 360 turn. 
951   double turnTime = 360.0 / _config.turnRateDegSec();
952   
953   // c is ground distance covered in that time (circumference of the circle)
954         double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
955   
956   // divide by 2PI to go from circumference -> radius
957         return c / (2 * M_PI);
958 }
959
960 void GPS::updateRouteData()
961 {
962   double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
963   // walk all waypoints from wp2 to route end, and sum
964   for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
965     //totalDistance += _routeMgr->get_waypoint(i).get_distance();
966   }
967   
968   _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
969   if (_last_speed_kts > 1.0) {
970     double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
971     _routeETE->setStringValue(makeTTWString(TTW));    
972   }
973 }
974
975 void GPS::driveAutopilot()
976 {
977   if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
978     _apDrivingFlag->setBoolValue(false);
979     return;
980   }
981  
982   // compatability feature - allow the route-manager / GPS to drive the
983   // generic autopilot heading hold *in leg mode only* 
984   
985   bool drive = _mode == "leg";
986   _apDrivingFlag->setBoolValue(drive);
987   
988   if (drive) {
989     // FIXME: we want to set desired track, not heading, here
990     _apTrueHeading->setDoubleValue(getWP1Bearing());
991   }
992 }
993
994 void GPS::wp1Changed()
995 {
996   if (!_currentWaypt)
997     return;
998   if (_mode == "leg") {
999     _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
1000   } else if (_mode == "obs") {
1001     _wayptController.reset(new OBSController(this, _currentWaypt));
1002   } else if (_mode == "dto") {
1003     _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
1004   }
1005
1006   _wayptController->init();
1007
1008   if (_mode == "obs") {
1009     _legDistanceNm = -1.0;
1010   } else {
1011     _wayptController->update();
1012     _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1013   }
1014   
1015   if (!_config.driveAutopilot()) {
1016     return;
1017   }
1018   
1019   RouteRestriction ar = _currentWaypt->altitudeRestriction();
1020   double restrictAlt = _currentWaypt->altitudeFt();
1021   double alt = _indicated_pos.getElevationFt();
1022   if ((ar == RESTRICT_AT) ||
1023        ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
1024        ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
1025   {
1026     SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
1027     _apTargetAltitudeFt->setDoubleValue(restrictAlt);
1028   }
1029 }
1030
1031 /////////////////////////////////////////////////////////////////////////////
1032 // property getter/setters
1033
1034 void GPS::setSelectedCourse(double crs)
1035 {
1036   if (_selectedCourse == crs) {
1037     return;
1038   }
1039   
1040   _selectedCourse = crs;
1041   if ((_mode == "obs") || _config.courseSelectable()) {
1042     _desiredCourse = _selectedCourse;
1043     _desiredCourseNode->fireValueChanged();
1044   }
1045 }
1046
1047 double GPS::getLegDistance() const
1048 {
1049   if (!_dataValid || (_mode == "obs")) {
1050     return -1;
1051   }
1052   
1053   return _legDistanceNm;
1054 }
1055
1056 double GPS::getLegCourse() const
1057 {
1058   if (!_dataValid || !_wayptController.get()) {
1059     return -9999.0;
1060   }
1061   
1062   return _wayptController->targetTrackDeg();
1063 }
1064
1065 double GPS::getLegMagCourse() const
1066 {
1067   if (!_dataValid) {
1068     return 0.0;
1069   }
1070   
1071   double m = getLegCourse() - _magvar_node->getDoubleValue();
1072   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1073   return m;
1074 }
1075
1076 double GPS::getMagTrack() const
1077 {
1078   if (!_dataValid) {
1079     return 0.0;
1080   }
1081   
1082   double m = getTrueTrack() - _magvar_node->getDoubleValue();
1083   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1084   return m;
1085 }
1086
1087 double GPS::getCDIDeflection() const
1088 {
1089   if (!_dataValid) {
1090     return 0.0;
1091   }
1092   
1093   double defl;
1094   if (_config.cdiDeflectionIsAngular()) {
1095     defl = getWP1CourseDeviation();
1096     SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1097   } else {
1098     double fullScale = _config.cdiDeflectionLinearPeg();
1099     double normError = getWP1CourseErrorNm() / fullScale;
1100     SG_CLAMP_RANGE(normError, -1.0, 1.0);
1101     defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1102   }
1103   
1104   return defl;
1105 }
1106
1107 const char* GPS::getWP0Ident() const
1108 {
1109   if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
1110     return "";
1111   }
1112   
1113   return _prevWaypt->ident().c_str();
1114 }
1115
1116 const char* GPS::getWP0Name() const
1117 {
1118   return "";
1119 }
1120
1121 const char* GPS::getWP1Ident() const
1122 {
1123   if ((!_dataValid)||(!_currentWaypt)) {
1124     return "";
1125   }
1126   
1127   return _currentWaypt->ident().c_str();
1128 }
1129
1130 const char* GPS::getWP1Name() const
1131 {
1132   return "";
1133 }
1134
1135 double GPS::getWP1Distance() const
1136 {
1137   if (!_dataValid || !_wayptController.get()) {
1138     return -1.0;
1139   }
1140   
1141   return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1142 }
1143
1144 double GPS::getWP1TTW() const
1145 {
1146   if (!_dataValid || !_wayptController.get()) {
1147     return -1.0;
1148   }
1149   
1150   return _wayptController->timeToWaypt();
1151 }
1152
1153 const char* GPS::getWP1TTWString() const
1154 {
1155   double t = getWP1TTW();
1156   if (t <= 0.0) {
1157     return "";
1158   }
1159   
1160   return makeTTWString(t);
1161 }
1162
1163 double GPS::getWP1Bearing() const
1164 {
1165   if (!_dataValid || !_wayptController.get()) {
1166     return -9999.0;
1167   }
1168   
1169   return _wayptController->trueBearingDeg();
1170 }
1171
1172 double GPS::getWP1MagBearing() const
1173 {
1174   if (!_dataValid || !_wayptController.get()) {
1175     return -9999.0;
1176   }
1177
1178   double magBearing =  _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1179   SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1180   return magBearing;
1181 }
1182
1183 double GPS::getWP1CourseDeviation() const
1184 {
1185   if (!_dataValid || !_wayptController.get()) {
1186     return 0.0;
1187   }
1188
1189   return _wayptController->courseDeviationDeg();
1190 }
1191
1192 double GPS::getWP1CourseErrorNm() const
1193 {
1194   if (!_dataValid || !_wayptController.get()) {
1195     return 0.0;
1196   }
1197   
1198   return _wayptController->xtrackErrorNm();
1199 }
1200
1201 bool GPS::getWP1ToFlag() const
1202 {
1203   if (!_dataValid || !_wayptController.get()) {
1204     return false;
1205   }
1206   
1207   return _wayptController->toFlag();
1208 }
1209
1210 bool GPS::getWP1FromFlag() const
1211 {
1212   if (!_dataValid || !_wayptController.get()) {
1213     return false;
1214   }
1215   
1216   return !getWP1ToFlag();
1217 }
1218
1219 double GPS::getScratchDistance() const
1220 {
1221   if (!_scratchValid) {
1222     return 0.0;
1223   }
1224   
1225   return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1226 }
1227
1228 double GPS::getScratchTrueBearing() const
1229 {
1230   if (!_scratchValid) {
1231     return 0.0;
1232   }
1233
1234   return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1235 }
1236
1237 double GPS::getScratchMagBearing() const
1238 {
1239   if (!_scratchValid) {
1240     return 0.0;
1241   }
1242   
1243   double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1244   SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1245   return crs;
1246 }
1247
1248 /////////////////////////////////////////////////////////////////////////////
1249 // command / scratch / search system
1250
1251 void GPS::setCommand(const char* aCmd)
1252 {
1253   SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1254   
1255   if (!strcmp(aCmd, "direct")) {
1256     directTo();
1257   } else if (!strcmp(aCmd, "obs")) {
1258     selectOBSMode();
1259   } else if (!strcmp(aCmd, "leg")) {
1260     selectLegMode();
1261   } else if (!strcmp(aCmd, "load-route-wpt")) {
1262     loadRouteWaypoint();
1263   } else if (!strcmp(aCmd, "nearest")) {
1264     loadNearest();
1265   } else if (!strcmp(aCmd, "search")) {
1266     _searchNames = false;
1267     search();
1268   } else if (!strcmp(aCmd, "search-names")) {
1269     _searchNames = true;
1270     search();
1271   } else if (!strcmp(aCmd, "next")) {
1272     nextResult();
1273   } else if (!strcmp(aCmd, "previous")) {
1274     previousResult();
1275   } else if (!strcmp(aCmd, "define-user-wpt")) {
1276     defineWaypoint();
1277   } else if (!strcmp(aCmd, "route-insert-before")) {
1278     int index = _scratchNode->getIntValue("index");
1279     if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1280       index = _routeMgr->numWaypts();
1281     } else if (index >= _routeMgr->numWaypts()) {
1282       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1283       return;
1284     }
1285     
1286     insertWaypointAtIndex(index);
1287   } else if (!strcmp(aCmd, "route-insert-after")) {
1288     int index = _scratchNode->getIntValue("index");
1289     if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1290       index = _routeMgr->numWaypts();
1291     } else if (index >= _routeMgr->numWaypts()) {
1292       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1293       return;
1294     } else {
1295       ++index; 
1296     }
1297   
1298     insertWaypointAtIndex(index);
1299   } else if (!strcmp(aCmd, "route-delete")) {
1300     int index = _scratchNode->getIntValue("index");
1301     if (index < 0) {
1302       index = _routeMgr->numWaypts();
1303     } else if (index >= _routeMgr->numWaypts()) {
1304       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1305       return;
1306     }
1307     
1308     removeWaypointAtIndex(index);
1309   } else {
1310     SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1311   }
1312 }
1313
1314 void GPS::clearScratch()
1315 {
1316   _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1317   _scratchValid = false;  
1318   _scratchNode->setStringValue("type", "");
1319   _scratchNode->setStringValue("query", "");
1320 }
1321
1322 bool GPS::isScratchPositionValid() const
1323 {
1324   if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1325       (_scratchPos.getLatitudeDeg() < -9990.0)) {
1326    return false;   
1327   }
1328   
1329   return true;
1330 }
1331
1332 void GPS::directTo()
1333 {  
1334   if (!isScratchPositionValid()) {
1335     return;
1336   }
1337   
1338   _prevWaypt = NULL;
1339   _wp0_position = _indicated_pos;
1340   _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1341   _mode = "dto";
1342
1343   clearScratch();
1344   wp1Changed();
1345 }
1346
1347 void GPS::loadRouteWaypoint()
1348 {
1349   _scratchValid = false;
1350 //  if (!_routeMgr->isRouteActive()) {
1351 //    SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1352 //    return;
1353 //  }
1354   
1355   int index = _scratchNode->getIntValue("index", -9999);
1356   clearScratch();
1357   
1358   if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1359     index = _routeMgr->currentIndex();
1360   }
1361   
1362   _searchIsRoute = true;
1363   setScratchFromRouteWaypoint(index);
1364 }
1365
1366 void GPS::setScratchFromRouteWaypoint(int aIndex)
1367 {
1368   assert(_searchIsRoute);
1369   if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1370     SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1371     return;
1372   }
1373   
1374   _searchResultIndex = aIndex;
1375   WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1376   _scratchNode->setStringValue("ident", wp->ident());
1377   _scratchPos = wp->position();
1378   _scratchValid = true;
1379   _scratchNode->setIntValue("index", aIndex);
1380 }
1381
1382 void GPS::loadNearest()
1383 {
1384   string sty(_scratchNode->getStringValue("type"));
1385   FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1386   if (ty == FGPositioned::INVALID) {
1387     SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1388     return;
1389   }
1390   
1391   auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1392   int limitCount = _scratchNode->getIntValue("max-results", 1);
1393   double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1394   
1395   SGGeod searchPos = _indicated_pos;
1396   if (isScratchPositionValid()) {
1397     searchPos = _scratchPos;
1398   }
1399   
1400   clearScratch(); // clear now, regardless of whether we find a match or not
1401     
1402   _searchResults = 
1403     FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1404   _searchResultIndex = 0;
1405   _searchIsRoute = false;
1406   
1407   if (_searchResults.empty()) {
1408     SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1409     return;
1410   }
1411   
1412   setScratchFromCachedSearchResult();
1413 }
1414
1415 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1416 {
1417   switch (aPos->type()) {
1418   case FGPositioned::AIRPORT:
1419   // heliport and seaport too?
1420   case FGPositioned::VOR:
1421   case FGPositioned::NDB:
1422   case FGPositioned::FIX:
1423   case FGPositioned::TACAN:
1424   case FGPositioned::WAYPOINT:
1425     return true;
1426   default:
1427     return false;
1428   }
1429 }
1430
1431 FGPositioned::Type GPS::SearchFilter::minType() const
1432 {
1433   return FGPositioned::AIRPORT;
1434 }
1435
1436 FGPositioned::Type GPS::SearchFilter::maxType() const
1437 {
1438   return FGPositioned::WAYPOINT;
1439 }
1440
1441 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1442 {
1443   if (aTy == FGPositioned::AIRPORT) {
1444     return new FGAirport::HardSurfaceFilter();
1445   }
1446   
1447   // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1448   if (aTy == FGPositioned::INVALID) {
1449     return new SearchFilter;
1450   }
1451   
1452   return new FGPositioned::TypeFilter(aTy);
1453 }
1454
1455 void GPS::search()
1456 {
1457   // parse search terms into local members, and exec the first search
1458   string sty(_scratchNode->getStringValue("type"));
1459   _searchType = FGPositioned::typeFromName(sty);
1460   _searchQuery = _scratchNode->getStringValue("query");
1461   if (_searchQuery.empty()) {
1462     SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1463     clearScratch();
1464     return;
1465   }
1466   
1467   _searchExact = _scratchNode->getBoolValue("exact", true);
1468   _searchResultIndex = 0;
1469   _searchIsRoute = false;
1470
1471   auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1472   if (_searchNames) {
1473     _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1474   } else {
1475     _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1476   }
1477   
1478   bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1479   if (orderByRange) {
1480     FGPositioned::sortByRange(_searchResults, _indicated_pos);
1481   }
1482   
1483   if (_searchResults.empty()) {
1484     clearScratch();
1485     return;
1486   }
1487   
1488   setScratchFromCachedSearchResult();
1489 }
1490
1491 bool GPS::getScratchHasNext() const
1492 {
1493   int lastResult;
1494   if (_searchIsRoute) {
1495     lastResult = _routeMgr->numWaypts() - 1;
1496   } else {
1497     lastResult = (int) _searchResults.size() - 1;
1498   }
1499
1500   if (lastResult < 0) { // search array might be empty
1501     return false;
1502   }
1503   
1504   return (_searchResultIndex < lastResult);
1505 }
1506
1507 void GPS::setScratchFromCachedSearchResult()
1508 {
1509   int index = _searchResultIndex;
1510   
1511   if ((index < 0) || (index >= (int) _searchResults.size())) {
1512     SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1513     return;
1514   }
1515   
1516   setScratchFromPositioned(_searchResults[index], index);
1517 }
1518
1519 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1520 {
1521   clearScratch();
1522   assert(aPos);
1523
1524   _scratchPos = aPos->geod();
1525   _scratchNode->setStringValue("name", aPos->name());
1526   _scratchNode->setStringValue("ident", aPos->ident());
1527   _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1528     
1529   if (aIndex >= 0) {
1530     _scratchNode->setIntValue("index", aIndex);
1531   }
1532   
1533   _scratchValid = true;
1534   _scratchNode->setIntValue("result-count", _searchResults.size());
1535   
1536   switch (aPos->type()) {
1537   case FGPositioned::VOR:
1538     _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1539     break;
1540   
1541   case FGPositioned::NDB:
1542     _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1543     break;
1544   
1545   case FGPositioned::AIRPORT:
1546     addAirportToScratch((FGAirport*)aPos);
1547     break;
1548   
1549   default:
1550       // no-op
1551       break;
1552   }
1553   
1554   // look for being on the route and set?
1555 }
1556
1557 void GPS::addAirportToScratch(FGAirport* aAirport)
1558 {
1559   for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1560     SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1561     FGRunway* rwy = aAirport->getRunwayByIndex(r);
1562     // TODO - filter out unsuitable runways in the future
1563     // based on config again
1564     
1565     rwyNd->setStringValue("id", rwy->ident().c_str());
1566     rwyNd->setIntValue("length-ft", rwy->lengthFt());
1567     rwyNd->setIntValue("width-ft", rwy->widthFt());
1568     rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1569     // map surface code to a string
1570     // TODO - lighting information
1571     
1572     if (rwy->ILS()) {
1573       rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1574     }
1575   } // of runways iteration
1576 }
1577
1578
1579 void GPS::selectOBSMode()
1580 {
1581   if (!isScratchPositionValid()) {
1582     return;
1583   }
1584   
1585   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1586   _mode = "obs";
1587
1588   _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1589   _wp0_position = _indicated_pos;
1590   wp1Changed();
1591 }
1592
1593 void GPS::selectLegMode()
1594 {
1595   if (_mode == "leg") {
1596     return;
1597   }
1598   
1599   if (!_routeMgr->isRouteActive()) {
1600     SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1601     return;
1602   }
1603
1604   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1605   _mode = "leg";
1606   
1607   // depending on the situation, this will either get over-written 
1608   // in routeManagerSequenced or not; either way it does no harm to
1609   // set it here.
1610   _wp0_position = _indicated_pos;
1611
1612   // not really sequenced, but does all the work of updating wp0/1
1613   routeManagerSequenced();
1614 }
1615
1616 void GPS::nextResult()
1617 {
1618   if (!getScratchHasNext()) {
1619     return;
1620   }
1621   
1622   clearScratch();
1623   if (_searchIsRoute) {
1624     setScratchFromRouteWaypoint(++_searchResultIndex);
1625   } else {
1626     ++_searchResultIndex;
1627     setScratchFromCachedSearchResult();
1628   }
1629 }
1630
1631 void GPS::previousResult()
1632 {
1633   if (_searchResultIndex <= 0) {
1634     return;
1635   }
1636   
1637   clearScratch();
1638   --_searchResultIndex;
1639   
1640   if (_searchIsRoute) {
1641     setScratchFromRouteWaypoint(_searchResultIndex);
1642   } else {
1643     setScratchFromCachedSearchResult();
1644   }
1645 }
1646
1647 void GPS::defineWaypoint()
1648 {
1649   if (!isScratchPositionValid()) {
1650     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1651     return;
1652   }
1653   
1654   string ident = _scratchNode->getStringValue("ident");
1655   if (ident.size() < 2) {
1656     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1657     return;
1658   }
1659     
1660 // check for duplicate idents
1661   FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1662   FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1663   if (!dups.empty()) {
1664     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1665   }
1666   
1667   SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1668   FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1669   _searchResults.clear();
1670   _searchResults.push_back(wpt);
1671   setScratchFromPositioned(wpt.get(), -1);
1672 }
1673
1674 void GPS::insertWaypointAtIndex(int aIndex)
1675 {
1676   // note we do allow index = routeMgr->size(), that's an append
1677   if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1678     throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1679   }
1680   
1681   if (!isScratchPositionValid()) {
1682     SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1683     return;
1684   }
1685   
1686   string ident = _scratchNode->getStringValue("ident");
1687
1688   WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1689   _routeMgr->flightPlan()->insertWayptAtIndex(wpt, aIndex);
1690 }
1691
1692 void GPS::removeWaypointAtIndex(int aIndex)
1693 {
1694   if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1695     throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1696   }
1697   
1698   _routeMgr->removeLegAtIndex(aIndex);
1699 }
1700
1701 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
1702   const char* lonStr, const char* latStr, const char* altStr)
1703 {
1704   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1705   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1706   
1707   if (altStr) {
1708     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1709   }
1710 }
1711
1712 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
1713   const char* lonStr, const char* latStr, const char* altStr)
1714 {
1715   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1716   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1717   
1718   if (altStr) {
1719     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
1720   }
1721 }
1722
1723 // end of gps.cxx