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