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