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