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