]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/gps.cxx
Handle libCurl linkage when enabled in SimGear
[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             // ensure computations use runway end, not threshold
468             if (waypt->type() == "runway") {
469                 RunwayWaypt* rwpt = static_cast<RunwayWaypt*>(waypt);
470                 return rwpt->runway()->end();
471             }
472
473                         return waypt->position();
474                 }
475         }
476
477         isValid = false;
478     return SGGeod();
479 }
480 ///////////////////////////////////////////////////////////////////////////
481
482 void
483 GPS::updateBasicData(double dt)
484 {
485   if (!_lastPosValid) {
486     return;
487   }
488   
489   double distance_m;
490   double track2_deg;
491   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
492     
493   double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
494   double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
495   _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
496   
497   speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
498   _last_speed_kts = speed_kt;
499   
500   SGGeod g = _indicated_pos;
501   g.setLongitudeDeg(_last_pos.getLongitudeDeg());
502   double northSouthM = dist(SGVec3d::fromGeod(_last_pos), SGVec3d::fromGeod(g));
503   northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
504   
505   double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
506   _lastNSVelocity = nsMSec;
507   _northSouthVelocity->setDoubleValue(nsMSec);
508
509   g = _indicated_pos;
510   g.setLatitudeDeg(_last_pos.getLatitudeDeg());
511   double eastWestM = dist(SGVec3d::fromGeod(_last_pos), SGVec3d::fromGeod(g));
512   eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
513   
514   double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
515   _lastEWVelocity = ewMSec;
516   _eastWestVelocity->setDoubleValue(ewMSec);
517   
518   double odometer = _odometer_node->getDoubleValue();
519   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
520   odometer = _trip_odometer_node->getDoubleValue();
521   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
522   
523   if (!_dataValid) {
524     _dataValid = true;
525   }
526 }
527
528 void
529 GPS::updateTrackingBug()
530 {
531   double tracking_bug = _tracking_bug_node->getDoubleValue();
532   double true_bug_error = tracking_bug - getTrueTrack();
533   double magnetic_bug_error = tracking_bug - getMagTrack();
534
535   // Get the errors into the (-180,180) range.
536   SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
537   SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
538
539   _true_bug_error_node->setDoubleValue(true_bug_error);
540   _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
541 }
542
543 void GPS::endOfFlightPlan()
544 {
545   selectOBSMode(_currentWaypt);
546 }
547
548 void GPS::currentWaypointChanged()
549 {
550   if (!_route) {
551     return;
552   }
553   
554   int index = _route->currentIndex(),
555     count = _route->numLegs();
556   if ((index < 0) || (index >= count)) {
557     _currentWaypt=NULL;
558     _prevWaypt=NULL;
559     // no active leg on the route
560     return;
561   }
562     
563   if (index > 0) {
564     _prevWaypt = _route->previousLeg()->waypoint();
565     if (_prevWaypt->flag(WPT_DYNAMIC)) {
566       _wp0_position = _indicated_pos;
567     } else {
568       _wp0_position = _prevWaypt->position();
569     }
570   }
571   
572   _currentWaypt = _route->currentLeg()->waypoint();
573     wp1Changed(); // rebuild the active controller
574   _desiredCourse = getLegMagCourse();
575   _desiredCourseNode->fireValueChanged();
576 }
577
578
579 void GPS::waypointsChanged()
580 {
581   if (_mode != "leg") {
582     return;
583   }
584   
585   SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
586   currentWaypointChanged();
587 }
588
589 void GPS::cleared()
590 {
591     if (_mode != "leg") {
592         return;
593     }
594     
595     selectOBSMode(_currentWaypt);
596 }
597
598 void GPS::sequence()
599 {
600     if (!_route) {
601         return;
602     }
603   
604     int nextIndex = _route->currentIndex() + 1;
605     if (nextIndex >= _route->numLegs()) {
606         SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
607         _route->finish();
608         selectOBSMode(_currentWaypt);
609         return;
610     }
611     
612     // will callback into currentWaypointChanged
613     _route->setCurrentIndex(nextIndex);
614 }
615
616 void GPS::updateTurn()
617 {
618   bool printProgress = false;
619   
620   if (_computeTurnData) {
621     if (_last_speed_kts < 10) {
622       // need valid leg course and sensible ground speed to compute the turn
623       return;
624     }
625     
626     computeTurnData();
627     printProgress = true;
628   }
629   
630   if (!_anticipateTurn) {
631     updateOverflight();
632     return;
633   }
634
635   updateTurnData();
636   // find bearing to turn centre
637   double bearing, az2, distanceM;
638   SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
639   double progress = computeTurnProgress(bearing);
640   
641   if (printProgress) {
642     SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
643   }
644   
645   if (!_inTurn && (progress > 0.0)) {
646     beginTurn();
647   }
648   
649   if (_inTurn && !_turnSequenced && (progress > 0.5)) {
650     _turnSequenced = true;
651      SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
652      sequence();
653   }
654   
655   if (_inTurn && (progress >= 1.0)) {
656     endTurn();
657   }
658   
659   if (_inTurn) {
660     // drive deviation and desired course
661     double desiredCourse = bearing - copysign(90, _turnAngle);
662     SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
663     double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
664     double deviationDeg = desiredCourse - getMagTrack();
665     deviationNm = copysign(deviationNm, deviationDeg);
666     // FIXME
667     //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
668     //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
669     //_cdiDeflectionNode->setDoubleValue(deviationDeg);
670   }
671 }
672
673 void GPS::updateOverflight()
674 {
675   if (!_wayptController->isDone()) {
676     return;
677   }
678   
679   if (_mode == "dto") {
680     SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
681     
682     // check for wp1 being on active route - resume leg mode
683     if (_route) {
684       int index = _route->findWayptIndex(_currentWaypt->position());
685       if (index >= 0) {
686         SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
687         _mode = "leg";
688         _route->setCurrentIndex(index);
689         sequence(); // and sequence to the next point
690       }
691     }
692     
693     if (_mode == "dto") {
694       // if we didn't enter leg mode, drop back to OBS mode
695       // select OBS mode, but keep current waypoint-as is
696       _mode = "obs";
697       wp1Changed();
698     }
699   } else if (_mode == "leg") {
700     SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
701     sequence();
702   } else if (_mode == "obs") {
703     // nothing to do here, TO/FROM will update but that's fine
704   }
705   _computeTurnData = true;
706 }
707
708 void GPS::beginTurn()
709 {
710   _inTurn = true;
711   _turnSequenced = false;
712   SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
713 }
714
715 void GPS::endTurn()
716 {
717   _inTurn = false;
718   SG_LOG(SG_INSTR, SG_INFO, "ending turn");
719   _computeTurnData = true;
720 }
721
722 double GPS::computeTurnProgress(double aBearing) const
723 {
724   double startBearing = _turnStartBearing + copysign(90, _turnAngle);
725   return (aBearing - startBearing) / _turnAngle;
726 }
727
728 void GPS::computeTurnData()
729 {
730   _computeTurnData = false;
731   if ((_mode != "leg") || !_route->nextLeg()) {
732     _anticipateTurn = false;
733     return;
734   }
735   
736   WayptRef next = _route->nextLeg()->waypoint();
737   if (next->flag(WPT_DYNAMIC) ||
738       !_config.turnAnticipationEnabled() ||
739       next->flag(WPT_OVERFLIGHT))
740   {
741     _anticipateTurn = false;
742     return;
743   }
744   
745   _turnStartBearing = _desiredCourse;
746 // compute next leg course
747   RoutePath path(_route);
748   double crs = path.trackForIndex(_route->currentIndex() + 1);
749
750 // compute offset bearing
751   _turnAngle = crs - _turnStartBearing;
752   SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
753   double median = _turnStartBearing + (_turnAngle * 0.5);
754   double offsetBearing = median + copysign(90, _turnAngle);
755   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
756   
757   SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
758     ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median 
759     << ", offset=" << offsetBearing);
760
761   SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
762
763   _turnPt = _currentWaypt->position();
764   _anticipateTurn = true;
765 }
766
767 void GPS::updateTurnData()
768 {
769   // depends on ground speed, so needs to be updated per-frame
770   _turnRadius = computeTurnRadiusNm(_last_speed_kts);
771   
772   // compute the turn centre, based on the turn radius.
773   // key thing is to understand that we're working a right-angle triangle,
774   // where the right-angle is the point we start the turn. From that point,
775   // one side is the inbound course to the turn pt, and the other is the
776   // perpendicular line, of length 'r', to the turn centre.
777   // the triangle's hypotenuse, which we need to find, is the distance from the
778   // turn pt to the turn center (in the direction of the offset bearing)
779   // note that d - _turnRadius tell us how much we're 'cutting' the corner.
780   
781   double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
782   double d = _turnRadius / cos(halfTurnAngle);
783   
784  // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
785  //   << " (cut distance=" << d - _turnRadius << ")");
786   
787   double median = _turnStartBearing + (_turnAngle * 0.5);
788   double offsetBearing = median + copysign(90, _turnAngle);
789   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
790   
791   double az2;
792   SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2); 
793 }
794
795 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
796 {
797         // turn time is seconds to execute a 360 turn. 
798   double turnTime = 360.0 / _config.turnRateDegSec();
799   
800   // c is ground distance covered in that time (circumference of the circle)
801         double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
802   
803   // divide by 2PI to go from circumference -> radius
804         return c / (2 * M_PI);
805 }
806
807 void GPS::updateRouteData()
808 {
809   double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
810   // walk all waypoints from wp2 to route end, and sum
811   for (int i=_route->currentIndex()+1; i<_route->numLegs(); ++i) {
812     FlightPlan::Leg* leg = _route->legAtIndex(i);
813     // omit missed-approach waypoints in distance calculation
814     if (leg->waypoint()->flag(WPT_MISS))
815       continue;
816       
817     totalDistance += leg->distanceNm();
818   }
819   
820   _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
821   if (_last_speed_kts > 1.0) {
822     double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
823     _routeETE->setStringValue(makeTTWString(TTW));    
824   }
825 }
826
827 void GPS::driveAutopilot()
828 {
829   if (!_config.driveAutopilot() || !_defaultGPSMode) {
830     _apDrivingFlag->setBoolValue(false);
831     return;
832   }
833  
834   // compatibility feature - allow the route-manager / GPS to drive the
835   // generic autopilot heading hold *in leg mode only* 
836   
837   bool drive = _mode == "leg";
838   _apDrivingFlag->setBoolValue(drive);
839   
840   if (drive) {
841     // FIXME: we want to set desired track, not heading, here
842     _apTrueHeading->setDoubleValue(getWP1Bearing());
843   }
844 }
845
846 void GPS::wp1Changed()
847 {
848   if (!_currentWaypt)
849     return;
850   if (_mode == "leg") {
851     _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
852   } else if (_mode == "obs") {
853     _wayptController.reset(new OBSController(this, _currentWaypt));
854   } else if (_mode == "dto") {
855     _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
856   }
857
858   _wayptController->init();
859
860   if (_mode == "obs") {
861     _legDistanceNm = -1.0;
862   } else {
863     _wayptController->update(0.0);
864     _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
865   }
866 }
867
868 /////////////////////////////////////////////////////////////////////////////
869 // property getter/setters
870
871 void GPS::setSelectedCourse(double crs)
872 {
873   if (_selectedCourse == crs) {
874     return;
875   }
876   
877   _selectedCourse = crs;
878   if ((_mode == "obs") || _config.courseSelectable()) {
879     _desiredCourse = _selectedCourse;
880     _desiredCourseNode->fireValueChanged();
881   }
882 }
883
884 double GPS::getLegDistance() const
885 {
886   if (!_dataValid || (_mode == "obs")) {
887     return -1;
888   }
889   
890   return _legDistanceNm;
891 }
892
893 double GPS::getLegCourse() const
894 {
895   if (!_dataValid || !_wayptController.get()) {
896     return -9999.0;
897   }
898   
899   return _wayptController->targetTrackDeg();
900 }
901
902 double GPS::getLegMagCourse() const
903 {
904   if (!_dataValid) {
905     return 0.0;
906   }
907   
908   double m = getLegCourse() - _magvar_node->getDoubleValue();
909   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
910   return m;
911 }
912
913 double GPS::getMagTrack() const
914 {
915   if (!_dataValid) {
916     return 0.0;
917   }
918   
919   double m = getTrueTrack() - _magvar_node->getDoubleValue();
920   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
921   return m;
922 }
923
924 double GPS::getCDIDeflection() const
925 {
926   if (!_dataValid) {
927     return 0.0;
928   }
929   
930   double defl;
931   if (_config.cdiDeflectionIsAngular()) {
932     defl = getWP1CourseDeviation();
933     SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
934   } else {
935     double fullScale = _config.cdiDeflectionLinearPeg();
936     double normError = getWP1CourseErrorNm() / fullScale;
937     SG_CLAMP_RANGE(normError, -1.0, 1.0);
938     defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
939   }
940   
941   return defl;
942 }
943
944 const char* GPS::getWP0Ident() const
945 {
946   if (!_dataValid || (_mode != "leg") || !_prevWaypt) {
947     return "";
948   }
949   
950 // work around std::string::c_str() storage lifetime with libc++
951 // real fix is to allow tie-ing with std::string instead of char*
952   static char identBuf[8];
953   strncpy(identBuf, _prevWaypt->ident().c_str(), 8);
954
955   return identBuf;
956 }
957
958 const char* GPS::getWP0Name() const
959 {
960     if (!_dataValid || !_prevWaypt || !_prevWaypt->source()) {
961         return "";
962     }
963     
964     return _prevWaypt->source()->name().c_str();
965 }
966
967 bool GPS::getWP1IValid() const
968 {
969     return _dataValid && _currentWaypt.get();
970 }
971
972 const char* GPS::getWP1Ident() const
973 {
974   if (!_dataValid || !_currentWaypt) {
975     return "";
976   }
977   
978 // work around std::string::c_str() storage lifetime with libc++
979 // real fix is to allow tie-ing with std::string instead of char*
980   static char identBuf[8];
981   strncpy(identBuf, _currentWaypt->ident().c_str(), 8);
982     
983   return identBuf;
984 }
985
986 const char* GPS::getWP1Name() const
987 {
988     if (!_dataValid || !_currentWaypt || !_currentWaypt->source()) {
989         return "";
990     }
991     
992     return _currentWaypt->source()->name().c_str();
993 }
994
995 double GPS::getWP1Distance() const
996 {
997   if (!_dataValid || !_wayptController.get()) {
998     return -1.0;
999   }
1000   
1001   return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1002 }
1003
1004 double GPS::getWP1TTW() const
1005 {
1006   if (!_dataValid || !_wayptController.get()) {
1007     return -1.0;
1008   }
1009   
1010   return _wayptController->timeToWaypt();
1011 }
1012
1013 const char* GPS::getWP1TTWString() const
1014 {
1015   double t = getWP1TTW();
1016   if (t <= 0.0) {
1017     return "";
1018   }
1019   
1020   return makeTTWString(t);
1021 }
1022
1023 double GPS::getWP1Bearing() const
1024 {
1025   if (!_dataValid || !_wayptController.get()) {
1026     return -9999.0;
1027   }
1028   
1029   return _wayptController->trueBearingDeg();
1030 }
1031
1032 double GPS::getWP1MagBearing() const
1033 {
1034   if (!_dataValid || !_wayptController.get()) {
1035     return -9999.0;
1036   }
1037
1038   double magBearing =  _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1039   SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1040   return magBearing;
1041 }
1042
1043 double GPS::getWP1CourseDeviation() const
1044 {
1045   if (!_dataValid || !_wayptController.get()) {
1046     return 0.0;
1047   }
1048
1049   return _wayptController->courseDeviationDeg();
1050 }
1051
1052 double GPS::getWP1CourseErrorNm() const
1053 {
1054   if (!_dataValid || !_wayptController.get()) {
1055     return 0.0;
1056   }
1057   
1058   return _wayptController->xtrackErrorNm();
1059 }
1060
1061 bool GPS::getWP1ToFlag() const
1062 {
1063   if (!_dataValid || !_wayptController.get()) {
1064     return false;
1065   }
1066   
1067   return _wayptController->toFlag();
1068 }
1069
1070 bool GPS::getWP1FromFlag() const
1071 {
1072   if (!_dataValid || !_wayptController.get()) {
1073     return false;
1074   }
1075   
1076   return !getWP1ToFlag();
1077 }
1078
1079 #if FG_210_COMPAT
1080 double GPS::getScratchDistance() const
1081 {
1082     if (!_scratchValid) {
1083         return 0.0;
1084     }
1085     
1086     return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1087 }
1088
1089 double GPS::getScratchTrueBearing() const
1090 {
1091     if (!_scratchValid) {
1092         return 0.0;
1093     }
1094     
1095     return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1096 }
1097
1098 double GPS::getScratchMagBearing() const
1099 {
1100     if (!_scratchValid) {
1101         return 0.0;
1102     }
1103     
1104     double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1105     SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1106     return crs;
1107 }
1108
1109 #endif
1110
1111 /////////////////////////////////////////////////////////////////////////////
1112 // scratch system
1113
1114 void GPS::setCommand(const char* aCmd)
1115 {
1116   SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1117   
1118   if (!strcmp(aCmd, "direct")) {
1119     directTo();
1120   } else if (!strcmp(aCmd, "obs")) {
1121     selectOBSMode(NULL);
1122   } else if (!strcmp(aCmd, "leg")) {
1123     selectLegMode();
1124 #if FG_210_COMPAT
1125   } else if (!strcmp(aCmd, "load-route-wpt")) {
1126       loadRouteWaypoint();
1127   } else if (!strcmp(aCmd, "nearest")) {
1128       loadNearest();
1129   } else if (!strcmp(aCmd, "search")) {
1130       _searchNames = false;
1131       search();
1132   } else if (!strcmp(aCmd, "search-names")) {
1133       _searchNames = true;
1134       search();
1135   } else if (!strcmp(aCmd, "next")) {
1136       nextResult();
1137   } else if (!strcmp(aCmd, "previous")) {
1138       previousResult();
1139   } else if (!strcmp(aCmd, "define-user-wpt")) {
1140       defineWaypoint();
1141   } else if (!strcmp(aCmd, "route-insert-before")) {
1142       int index = _scratchNode->getIntValue("index");
1143       if (index < 0 || (_route->numLegs() == 0)) {
1144           index = _route->numLegs();
1145       } else if (index >= _route->numLegs()) {
1146           SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1147           return;
1148       }
1149       
1150       insertWaypointAtIndex(index);
1151   } else if (!strcmp(aCmd, "route-insert-after")) {
1152       int index = _scratchNode->getIntValue("index");
1153       if (index < 0 || (_route->numLegs() == 0)) {
1154           index = _route->numLegs();
1155       } else if (index >= _route->numLegs()) {
1156           SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1157           return;
1158       } else {
1159           ++index;
1160       }
1161       
1162       insertWaypointAtIndex(index);
1163   } else if (!strcmp(aCmd, "route-delete")) {
1164       int index = _scratchNode->getIntValue("index");
1165       if (index < 0) {
1166           index = _route->numLegs();
1167       } else if (index >= _route->numLegs()) {
1168           SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1169           return;
1170       }
1171       
1172       removeWaypointAtIndex(index);
1173 #endif
1174   } else {
1175     SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1176   }
1177 }
1178
1179 void GPS::clearScratch()
1180 {
1181   _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1182   _scratchNode->setBoolValue("valid", false);
1183 #if FG_210_COMPAT
1184     _scratchNode->setStringValue("type", "");
1185     _scratchNode->setStringValue("query", "");
1186 #endif
1187 }
1188
1189 bool GPS::isScratchPositionValid() const
1190 {
1191   if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1192       (_scratchPos.getLatitudeDeg() < -9990.0)) {
1193    return false;   
1194   }
1195   
1196   return true;
1197 }
1198
1199 FGPositionedRef GPS::positionedFromScratch() const
1200 {
1201     if (!isScratchPositionValid()) {
1202         return NULL;
1203     }
1204     
1205     std::string ident(_scratchNode->getStringValue("ident"));
1206     return FGPositioned::findClosestWithIdent(ident, _scratchPos);
1207 }
1208
1209 void GPS::directTo()
1210 {  
1211   if (!isScratchPositionValid()) {
1212     return;
1213   }
1214   
1215   _prevWaypt = NULL;
1216   _wp0_position = _indicated_pos;
1217     
1218     FGPositionedRef pos = positionedFromScratch();
1219     if (pos) {
1220         _currentWaypt = new NavaidWaypoint(pos, NULL);
1221     } else {
1222         _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1223     }
1224     
1225     _mode = "dto";
1226   wp1Changed();
1227 }
1228
1229 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1230 {
1231   if (!waypt && isScratchPositionValid()) {
1232     FGPositionedRef pos = positionedFromScratch();
1233     if (pos) {
1234         waypt = new NavaidWaypoint(pos, NULL);
1235     } else {
1236         waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1237     }
1238   }
1239   
1240   _mode = "obs";
1241   _prevWaypt = NULL;
1242   _wp0_position = _indicated_pos;
1243   _currentWaypt = waypt;
1244   wp1Changed();
1245 }
1246
1247 void GPS::selectLegMode()
1248 {
1249   if (_mode == "leg") {
1250     return;
1251   }
1252   
1253   if (!_route) {
1254     SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1255     return;
1256   }
1257
1258   _mode = "leg";  
1259
1260   // depending on the situation, this will either get over-written 
1261   // in routeManagerSequenced or not; either way it does no harm to
1262   // set it here.
1263   _wp0_position = _indicated_pos;
1264
1265   // not really sequenced, but does all the work of updating wp0/1
1266   currentWaypointChanged();
1267 }
1268
1269 #if FG_210_COMPAT
1270
1271 void GPS::loadRouteWaypoint()
1272 {
1273     _scratchValid = false;    
1274     int index = _scratchNode->getIntValue("index", -9999);
1275     clearScratch();
1276     
1277     if ((index < 0) || (index >= _route->numLegs())) { // no index supplied, use current wp
1278         index = _route->currentIndex();
1279     }
1280     
1281     _searchIsRoute = true;
1282     setScratchFromRouteWaypoint(index);
1283 }
1284
1285 void GPS::setScratchFromRouteWaypoint(int aIndex)
1286 {
1287     assert(_searchIsRoute);
1288     if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1289         SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1290         return;
1291     }
1292     
1293     _searchResultIndex = aIndex;
1294     WayptRef wp = _route->legAtIndex(aIndex)->waypoint();
1295     _scratchNode->setStringValue("ident", wp->ident());
1296     _scratchPos = wp->position();
1297     _scratchValid = true;
1298     _scratchNode->setIntValue("index", aIndex);
1299 }
1300
1301 void GPS::loadNearest()
1302 {
1303     string sty(_scratchNode->getStringValue("type"));
1304     FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1305     if (ty == FGPositioned::INVALID) {
1306         SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1307         return;
1308     }
1309     
1310     auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1311     int limitCount = _scratchNode->getIntValue("max-results", 1);
1312     double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1313     
1314     SGGeod searchPos = _indicated_pos;
1315     if (isScratchPositionValid()) {
1316         searchPos = _scratchPos;
1317     }
1318     
1319     clearScratch(); // clear now, regardless of whether we find a match or not
1320     
1321     _searchResults =
1322     FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1323     _searchResultIndex = 0;
1324     _searchIsRoute = false;
1325     
1326     if (_searchResults.empty()) {
1327         return;
1328     }
1329     
1330     setScratchFromCachedSearchResult();
1331 }
1332
1333 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1334 {
1335     switch (aPos->type()) {
1336         case FGPositioned::AIRPORT:
1337             // heliport and seaport too?
1338         case FGPositioned::VOR:
1339         case FGPositioned::NDB:
1340         case FGPositioned::FIX:
1341         case FGPositioned::TACAN:
1342         case FGPositioned::WAYPOINT:
1343             return true;
1344         default:
1345             return false;
1346     }
1347 }
1348
1349 FGPositioned::Type GPS::SearchFilter::minType() const
1350 {
1351     return FGPositioned::AIRPORT;
1352 }
1353
1354 FGPositioned::Type GPS::SearchFilter::maxType() const
1355 {
1356     return FGPositioned::VOR;
1357 }
1358
1359 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1360 {
1361     if (aTy == FGPositioned::AIRPORT) {
1362         return new FGAirport::HardSurfaceFilter();
1363     }
1364     
1365     // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1366     if (aTy == FGPositioned::INVALID) {
1367         return new SearchFilter;
1368     }
1369     
1370     return new FGPositioned::TypeFilter(aTy);
1371 }
1372
1373 void GPS::search()
1374 {
1375     // parse search terms into local members, and exec the first search
1376     string sty(_scratchNode->getStringValue("type"));
1377     _searchType = FGPositioned::typeFromName(sty);
1378     _searchQuery = _scratchNode->getStringValue("query");
1379     if (_searchQuery.empty()) {
1380         SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1381         clearScratch();
1382         return;
1383     }
1384     
1385     _searchExact = _scratchNode->getBoolValue("exact", true);
1386     _searchResultIndex = 0;
1387     _searchIsRoute = false;
1388     
1389     auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1390     if (_searchNames) {
1391         _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1392     } else {
1393         _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1394     }
1395     
1396     bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1397     if (orderByRange) {
1398         FGPositioned::sortByRange(_searchResults, _indicated_pos);
1399     }
1400     
1401     if (_searchResults.empty()) {
1402         clearScratch();
1403         return;
1404     }
1405     
1406     setScratchFromCachedSearchResult();
1407 }
1408
1409 bool GPS::getScratchHasNext() const
1410 {
1411     int lastResult;
1412     if (_searchIsRoute) {
1413         lastResult = _route->numLegs() - 1;
1414     } else {
1415         lastResult = (int) _searchResults.size() - 1;
1416     }
1417     
1418     if (lastResult < 0) { // search array might be empty
1419         return false;
1420     }
1421     
1422     return (_searchResultIndex < lastResult);
1423 }
1424
1425 void GPS::setScratchFromCachedSearchResult()
1426 {
1427     int index = _searchResultIndex;
1428     
1429     if ((index < 0) || (index >= (int) _searchResults.size())) {
1430         SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1431         return;
1432     }
1433     
1434     setScratchFromPositioned(_searchResults[index], index);
1435 }
1436
1437 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1438 {
1439     clearScratch();
1440     assert(aPos);
1441     
1442     _scratchPos = aPos->geod();
1443     _scratchNode->setStringValue("name", aPos->name());
1444     _scratchNode->setStringValue("ident", aPos->ident());
1445     _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1446     
1447     if (aIndex >= 0) {
1448         _scratchNode->setIntValue("index", aIndex);
1449     }
1450     
1451     _scratchValid = true;
1452     _scratchNode->setIntValue("result-count", _searchResults.size());
1453     
1454     switch (aPos->type()) {
1455         case FGPositioned::VOR:
1456             _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1457             break;
1458             
1459         case FGPositioned::NDB:
1460             _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1461             break;
1462             
1463         case FGPositioned::AIRPORT:
1464             addAirportToScratch((FGAirport*)aPos);
1465             break;
1466             
1467         default:
1468             // no-op
1469             break;
1470     }
1471     
1472     // look for being on the route and set?
1473 }
1474
1475 void GPS::addAirportToScratch(FGAirport* aAirport)
1476 {
1477     for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1478         SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1479         FGRunway* rwy = aAirport->getRunwayByIndex(r);
1480         // TODO - filter out unsuitable runways in the future
1481         // based on config again
1482         
1483         rwyNd->setStringValue("id", rwy->ident().c_str());
1484         rwyNd->setIntValue("length-ft", rwy->lengthFt());
1485         rwyNd->setIntValue("width-ft", rwy->widthFt());
1486         rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1487         // map surface code to a string
1488         // TODO - lighting information
1489         
1490         if (rwy->ILS()) {
1491             rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1492         }
1493     } // of runways iteration
1494 }
1495
1496 void GPS::nextResult()
1497 {
1498     if (!getScratchHasNext()) {
1499         return;
1500     }
1501     
1502     clearScratch();
1503     if (_searchIsRoute) {
1504         setScratchFromRouteWaypoint(++_searchResultIndex);
1505     } else {
1506         ++_searchResultIndex;
1507         setScratchFromCachedSearchResult();
1508     }
1509 }
1510
1511 void GPS::previousResult()
1512 {
1513     if (_searchResultIndex <= 0) {
1514         return;
1515     }
1516     
1517     clearScratch();
1518     --_searchResultIndex;
1519     
1520     if (_searchIsRoute) {
1521         setScratchFromRouteWaypoint(_searchResultIndex);
1522     } else {
1523         setScratchFromCachedSearchResult();
1524     }
1525 }
1526
1527 void GPS::defineWaypoint()
1528 {
1529     if (!isScratchPositionValid()) {
1530         SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1531         return;
1532     }
1533     
1534     string ident = _scratchNode->getStringValue("ident");
1535     if (ident.size() < 2) {
1536         SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1537         return;
1538     }
1539     
1540     // check for duplicate idents
1541     FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1542     FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1543     if (!dups.empty()) {
1544         SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1545     }
1546     
1547     SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1548     FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1549     _searchResults.clear();
1550     _searchResults.push_back(wpt);
1551     setScratchFromPositioned(wpt.get(), -1);
1552 }
1553
1554 void GPS::insertWaypointAtIndex(int aIndex)
1555 {
1556     // note we do allow index = routeMgr->size(), that's an append
1557     if ((aIndex < 0) || (aIndex > _route->numLegs())) {
1558         throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1559     }
1560     
1561     if (!isScratchPositionValid()) {
1562         SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1563         return;
1564     }
1565     
1566     string ident = _scratchNode->getStringValue("ident");
1567     
1568     WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1569     _route->insertWayptAtIndex(wpt, aIndex);
1570 }
1571
1572 void GPS::removeWaypointAtIndex(int aIndex)
1573 {
1574     if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1575         throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1576     }
1577     
1578     _route->deleteIndex(aIndex);
1579 }
1580
1581
1582 #endif // of FG_210_COMPAT
1583
1584 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
1585   const char* lonStr, const char* latStr, const char* altStr)
1586 {
1587   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1588   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1589   
1590   if (altStr) {
1591     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1592   }
1593 }
1594
1595 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
1596   const char* lonStr, const char* latStr, const char* altStr)
1597 {
1598   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1599   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1600   
1601   if (altStr) {
1602     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
1603   }
1604 }
1605
1606 // end of gps.cxx