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