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