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