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