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