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