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