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