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