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