]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/gps.cxx
GPSs uses FlightPlans directly.
[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   _overflightArmDistance(1.0),
65   _waypointAlertTime(30.0),
66   _requireHardSurface(true),
67   _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
68   _driveAutopilot(true),
69   _courseSelectable(false)
70 {
71   _enableTurnAnticipation = false;
72 }
73
74 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
75 {
76   aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
77   aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
78   aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
79   aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
80   aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
81   aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
82   aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
83 }
84
85 ////////////////////////////////////////////////////////////////////////////
86
87 GPS::GPS ( SGPropertyNode *node, bool defaultGPSMode) :
88   _selectedCourse(0.0),
89   _desiredCourse(0.0),
90   _dataValid(false),
91   _lastPosValid(false),
92   _defaultGPSMode(defaultGPSMode),
93   _mode("init"),
94   _name(node->getStringValue("name", "gps")),
95   _num(node->getIntValue("number", 0)),
96   _computeTurnData(false),
97   _anticipateTurn(false),
98   _inTurn(false),
99   _callbackFlightPlanChanged(SGPropertyChangeCallback<GPS>(this,&GPS::routeManagerFlightPlanChanged,
100                                                            fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true))),
101   _callbackRouteActivated(SGPropertyChangeCallback<GPS>(this,&GPS::routeActivated,
102                                                       fgGetNode("/autopilot/route-manager/active", true)))
103 {
104   string branch = "/instrumentation/" + _name;
105   _gpsNode = fgGetNode(branch.c_str(), _num, true );
106   _scratchNode = _gpsNode->getChild("scratch", 0, true);
107   
108   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
109   _currentWayptNode = wp_node->getChild("wp", 1, true);
110 }
111
112 GPS::~GPS ()
113 {
114 }
115
116 void
117 GPS::init ()
118 {
119   _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
120   _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
121   _serviceable_node->setBoolValue(true);
122   _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
123
124 // basic GPS outputs
125   _raim_node = _gpsNode->getChild("raim", 0, true);
126   _odometer_node = _gpsNode->getChild("odometer", 0, true);
127   _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
128   _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
129   _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
130   _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
131   _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
132   
133 // waypoints
134   // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
135   SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
136   wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
137
138   _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
139     
140 // route properties
141   // should these move to the route manager?
142   _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
143   _routeETE = _gpsNode->getChild("ETE", 0, true);
144
145     
146 // navradio slaving properties
147   SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
148   toFlag->alias(_currentWayptNode->getChild("to-flag"));
149   
150   SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
151   fromFlag->alias(_currentWayptNode->getChild("from-flag"));
152     
153 // autopilot drive properties
154   _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
155   _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
156     
157   clearOutput();
158 }
159
160 void
161 GPS::reinit ()
162 {
163   clearOutput();
164 }
165
166 void
167 GPS::bind()
168 {
169   _config.bind(this, _gpsNode->getChild("config", 0, true));
170
171 // basic GPS outputs
172   tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
173     (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
174
175   tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
176     (*this, &GPS::getDesiredCourse, NULL));
177   _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
178     
179   tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", 
180         "indicated-latitude-deg", "indicated-altitude-ft");
181
182   tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
183     (*this, &GPS::getVerticalSpeed, NULL));
184   tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
185     (*this, &GPS::getTrueTrack, NULL));
186   tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
187     (*this, &GPS::getMagTrack, NULL));
188   tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
189     (*this, &GPS::getGroundspeedKts, NULL));
190   
191 // command system
192   tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
193   tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
194   tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
195   
196   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
197   SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
198   tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
199   tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
200       (*this, &GPS::getWP0Ident, NULL));
201     
202     
203   tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
204     (*this, &GPS::getWP1Ident, NULL));
205   
206   tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
207     (*this, &GPS::getWP1Distance, NULL));
208   tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
209     (*this, &GPS::getWP1Bearing, NULL));
210   tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
211     (*this, &GPS::getWP1MagBearing, NULL));
212   tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
213     (*this, &GPS::getWP1TTW, NULL));
214   tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
215     (*this, &GPS::getWP1TTWString, NULL));
216   
217   tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
218     (*this, &GPS::getWP1CourseDeviation, NULL));
219   tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
220     (*this, &GPS::getWP1CourseErrorNm, NULL));
221   tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
222     (*this, &GPS::getWP1ToFlag, NULL));
223   tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
224     (*this, &GPS::getWP1FromFlag, NULL));
225
226 // leg properties (only valid in DTO/LEG modes, not OBS)
227   tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
228   tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
229   tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
230
231 // navradio slaving properties  
232   tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
233     (*this, &GPS::getCDIDeflection));
234 }
235
236 void
237 GPS::unbind()
238 {
239   _tiedProperties.Untie();
240 }
241
242 void
243 GPS::clearOutput()
244 {
245   _dataValid = false;
246   _last_speed_kts = 0.0;
247   _last_pos = SGGeod();
248   _lastPosValid = false;
249   _indicated_pos = SGGeod();
250   _last_vertical_speed = 0.0;
251   _last_true_track = 0.0;
252   _lastEWVelocity = _lastNSVelocity = 0.0;
253   _currentWaypt = _prevWaypt = NULL;
254   _legDistanceNm = -1.0;
255   
256   _raim_node->setDoubleValue(0.0);
257   _indicated_pos = SGGeod();
258   _odometer_node->setDoubleValue(0);
259   _trip_odometer_node->setDoubleValue(0);
260   _tracking_bug_node->setDoubleValue(0);
261   _true_bug_error_node->setDoubleValue(0);
262   _magnetic_bug_error_node->setDoubleValue(0);
263   _northSouthVelocity->setDoubleValue(0.0);
264   _eastWestVelocity->setDoubleValue(0.0);
265 }
266
267 void
268 GPS::update (double delta_time_sec)
269 {
270   if (!_defaultGPSMode) {
271     // If it's off, don't bother.
272     if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
273       clearOutput();
274       return;
275     }
276   }
277   
278   if (delta_time_sec <= 0.0) {
279     return; // paused, don't bother
280   }    
281   
282   _raim_node->setDoubleValue(1.0);
283   _indicated_pos = globals->get_aircraft_position();
284   updateBasicData(delta_time_sec);
285
286   if (_dataValid) {
287     if (_wayptController.get()) {
288       _wayptController->update();
289       SGGeod p(_wayptController->position());
290       _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
291       _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
292       _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
293       
294       _desiredCourse = getLegMagCourse();
295       
296       updateTurn();
297       updateRouteData();
298     }
299
300     
301     updateTrackingBug();
302     driveAutopilot();
303   }
304   
305   if (_dataValid && (_mode == "init")) {
306     // will select LEG mode if the route is active
307     routeManagerFlightPlanChanged(NULL);
308     
309     FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
310     if (!routeMgr->isRouteActive()) {
311       // initialise in OBS mode, with waypt set to the nearest airport.
312       // keep in mind at this point, _dataValid is not set
313       auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
314       FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
315       if (apt) {
316         selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
317       }
318     }
319
320     if (_mode != "init")
321     {
322       // allow a realistic delay in the future, here
323     }
324   } // of init mode check
325   
326   _last_pos = _indicated_pos;
327   _lastPosValid = !(_last_pos == SGGeod());
328 }
329
330 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
331 {
332   if (_route) {
333     _route->removeDelegate(this);
334   }
335   
336   SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
337   FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
338   _route = routeMgr->flightPlan();
339   if (_route) {
340     _route->addDelegate(this);
341   }
342   
343   if (routeMgr->isRouteActive()) {
344     selectLegMode();
345   } else {
346     selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
347   }
348 }
349
350 void GPS::routeActivated(SGPropertyNode* aNode)
351 {
352   bool isActive = aNode->getBoolValue();
353   if (isActive) {
354     SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
355     selectLegMode();
356     
357     // if we've already passed the current waypoint, sequence.
358     if (_dataValid && getWP1FromFlag()) {
359       SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
360       sequence();
361     }
362   } else if (_mode == "leg") {
363     SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
364     selectOBSMode(_currentWaypt);
365   }
366 }
367
368 ///////////////////////////////////////////////////////////////////////////
369 // implement the RNAV interface 
370 SGGeod GPS::position()
371 {
372   if (!_dataValid) {
373     return SGGeod();
374   }
375   
376   return _indicated_pos;
377 }
378
379 double GPS::trackDeg()
380 {
381   return _last_true_track;
382 }
383
384 double GPS::groundSpeedKts()
385 {
386   return _last_speed_kts;
387 }
388
389 double GPS::vspeedFPM()
390 {
391   return _last_vertical_speed;
392 }
393
394 double GPS::magvarDeg()
395 {
396   return _magvar_node->getDoubleValue();
397 }
398
399 double GPS::overflightArmDistanceM()
400 {
401   return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
402 }
403
404 double GPS::selectedMagCourse()
405 {
406   return _selectedCourse;
407 }
408
409 ///////////////////////////////////////////////////////////////////////////
410
411 void
412 GPS::updateBasicData(double dt)
413 {
414   if (!_lastPosValid) {
415     return;
416   }
417   
418   double distance_m;
419   double track2_deg;
420   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
421     
422   double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
423   double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
424   _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
425   
426   speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
427   _last_speed_kts = speed_kt;
428   
429   SGGeod g = _indicated_pos;
430   g.setLongitudeDeg(_last_pos.getLongitudeDeg());
431   double northSouthM = SGGeodesy::distanceM(_last_pos, g);
432   northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
433   
434   double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
435   _lastNSVelocity = nsMSec;
436   _northSouthVelocity->setDoubleValue(nsMSec);
437
438
439   g = _indicated_pos;
440   g.setLatitudeDeg(_last_pos.getLatitudeDeg());
441   double eastWestM = SGGeodesy::distanceM(_last_pos, g);
442   eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
443   
444   double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
445   _lastEWVelocity = ewMSec;
446   _eastWestVelocity->setDoubleValue(ewMSec);
447   
448   double odometer = _odometer_node->getDoubleValue();
449   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
450   odometer = _trip_odometer_node->getDoubleValue();
451   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
452   
453   if (!_dataValid) {
454     _dataValid = true;
455   }
456 }
457
458 void
459 GPS::updateTrackingBug()
460 {
461   double tracking_bug = _tracking_bug_node->getDoubleValue();
462   double true_bug_error = tracking_bug - getTrueTrack();
463   double magnetic_bug_error = tracking_bug - getMagTrack();
464
465   // Get the errors into the (-180,180) range.
466   SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
467   SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
468
469   _true_bug_error_node->setDoubleValue(true_bug_error);
470   _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
471 }
472
473 void GPS::endOfFlightPlan()
474 {
475   selectOBSMode(_currentWaypt);
476 }
477
478 void GPS::currentWaypointChanged()
479 {
480   if (!_route) {
481     return;
482   }
483   
484   int index = _route->currentIndex(),
485     count = _route->numLegs();
486   if ((index < 0) || (index >= count)) {
487     _currentWaypt=NULL;
488     _prevWaypt=NULL;
489     // no active leg on the route
490     return;
491   }
492     
493   if (index > 0) {
494     _prevWaypt = _route->previousLeg()->waypoint();
495     if (_prevWaypt->flag(WPT_DYNAMIC)) {
496       _wp0_position = _indicated_pos;
497     } else {
498       _wp0_position = _prevWaypt->position();
499     }
500   }
501   
502   _currentWaypt = _route->currentLeg()->waypoint();
503   _desiredCourse = getLegMagCourse();
504   _desiredCourseNode->fireValueChanged();
505   wp1Changed();
506 }
507
508
509 void GPS::waypointsChanged()
510 {
511   if (_mode != "leg") {
512     return;
513   }
514   
515   SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
516   currentWaypointChanged();
517 }
518
519 void GPS::cleared()
520 {
521     if (_mode != "leg") {
522         return;
523     }
524     
525     selectOBSMode(_currentWaypt);
526 }
527
528 void GPS::sequence()
529 {
530     if (!_route) {
531         return;
532     }
533   
534     int nextIndex = _route->currentIndex() + 1;
535     if (nextIndex >= _route->numLegs()) {
536         SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
537         _route->finish();
538         selectOBSMode(_currentWaypt);
539         return;
540     }
541     
542     // will callback into currentWaypointChanged
543     _route->setCurrentIndex(nextIndex);
544 }
545
546 void GPS::updateTurn()
547 {
548   bool printProgress = false;
549   
550   if (_computeTurnData) {
551     if (_last_speed_kts < 10) {
552       // need valid leg course and sensible ground speed to compute the turn
553       return;
554     }
555     
556     computeTurnData();
557     printProgress = true;
558   }
559   
560   if (!_anticipateTurn) {
561     updateOverflight();
562     return;
563   }
564
565   updateTurnData();
566   // find bearing to turn centre
567   double bearing, az2, distanceM;
568   SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
569   double progress = computeTurnProgress(bearing);
570   
571   if (printProgress) {
572     SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
573   }
574   
575   if (!_inTurn && (progress > 0.0)) {
576     beginTurn();
577   }
578   
579   if (_inTurn && !_turnSequenced && (progress > 0.5)) {
580     _turnSequenced = true;
581      SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
582      sequence();
583   }
584   
585   if (_inTurn && (progress >= 1.0)) {
586     endTurn();
587   }
588   
589   if (_inTurn) {
590     // drive deviation and desired course
591     double desiredCourse = bearing - copysign(90, _turnAngle);
592     SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
593     double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
594     double deviationDeg = desiredCourse - getMagTrack();
595     deviationNm = copysign(deviationNm, deviationDeg);
596     // FIXME
597     //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
598     //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
599     //_cdiDeflectionNode->setDoubleValue(deviationDeg);
600   }
601 }
602
603 void GPS::updateOverflight()
604 {
605   if (!_wayptController->isDone()) {
606     return;
607   }
608   
609   if (_mode == "dto") {
610     SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
611     
612     // check for wp1 being on active route - resume leg mode
613     if (_route) {
614       int index = _route->findWayptIndex(_currentWaypt->position());
615       if (index >= 0) {
616         SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
617         _mode = "leg";
618         _route->setCurrentIndex(index);
619         sequence(); // and sequence to the next point
620       }
621     }
622     
623     if (_mode == "dto") {
624       // if we didn't enter leg mode, drop back to OBS mode
625       // select OBS mode, but keep current waypoint-as is
626       _mode = "obs";
627       wp1Changed();
628     }
629   } else if (_mode == "leg") {
630     SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
631     sequence();
632   } else if (_mode == "obs") {
633     // nothing to do here, TO/FROM will update but that's fine
634   }
635   
636   _computeTurnData = true;
637 }
638
639 void GPS::beginTurn()
640 {
641   _inTurn = true;
642   _turnSequenced = false;
643   SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
644 }
645
646 void GPS::endTurn()
647 {
648   _inTurn = false;
649   SG_LOG(SG_INSTR, SG_INFO, "ending turn");
650   _computeTurnData = true;
651 }
652
653 double GPS::computeTurnProgress(double aBearing) const
654 {
655   double startBearing = _turnStartBearing + copysign(90, _turnAngle);
656   return (aBearing - startBearing) / _turnAngle;
657 }
658
659 void GPS::computeTurnData()
660 {
661   _computeTurnData = false;
662   if ((_mode != "leg") || !_route->nextLeg()) {
663     _anticipateTurn = false;
664     return;
665   }
666   
667   WayptRef next = _route->nextLeg()->waypoint();
668   if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
669     _anticipateTurn = false;
670     return;
671   }
672   
673   _turnStartBearing = _desiredCourse;
674 // compute next leg course
675   double crs, dist;
676   boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
677     
678
679 // compute offset bearing
680   _turnAngle = crs - _turnStartBearing;
681   SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
682   double median = _turnStartBearing + (_turnAngle * 0.5);
683   double offsetBearing = median + copysign(90, _turnAngle);
684   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
685   
686   SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
687     ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median 
688     << ", offset=" << offsetBearing);
689
690   SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
691
692   _turnPt = _currentWaypt->position();
693   _anticipateTurn = true;
694 }
695
696 void GPS::updateTurnData()
697 {
698   // depends on ground speed, so needs to be updated per-frame
699   _turnRadius = computeTurnRadiusNm(_last_speed_kts);
700   
701   // compute the turn centre, based on the turn radius.
702   // key thing is to understand that we're working a right-angle triangle,
703   // where the right-angle is the point we start the turn. From that point,
704   // one side is the inbound course to the turn pt, and the other is the
705   // perpendicular line, of length 'r', to the turn centre.
706   // the triangle's hypotenuse, which we need to find, is the distance from the
707   // turn pt to the turn center (in the direction of the offset bearing)
708   // note that d - _turnRadius tell us how much we're 'cutting' the corner.
709   
710   double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
711   double d = _turnRadius / cos(halfTurnAngle);
712   
713  // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
714  //   << " (cut distance=" << d - _turnRadius << ")");
715   
716   double median = _turnStartBearing + (_turnAngle * 0.5);
717   double offsetBearing = median + copysign(90, _turnAngle);
718   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
719   
720   double az2;
721   SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2); 
722 }
723
724 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
725 {
726         // turn time is seconds to execute a 360 turn. 
727   double turnTime = 360.0 / _config.turnRateDegSec();
728   
729   // c is ground distance covered in that time (circumference of the circle)
730         double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
731   
732   // divide by 2PI to go from circumference -> radius
733         return c / (2 * M_PI);
734 }
735
736 void GPS::updateRouteData()
737 {
738   double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
739   // walk all waypoints from wp2 to route end, and sum
740  // for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
741     //totalDistance += _routeMgr->get_waypoint(i).get_distance();
742   //}
743   
744   _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
745   if (_last_speed_kts > 1.0) {
746     double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
747     _routeETE->setStringValue(makeTTWString(TTW));    
748   }
749 }
750
751 void GPS::driveAutopilot()
752 {
753   if (!_config.driveAutopilot() || !_defaultGPSMode) {
754     _apDrivingFlag->setBoolValue(false);
755     return;
756   }
757  
758   // compatability feature - allow the route-manager / GPS to drive the
759   // generic autopilot heading hold *in leg mode only* 
760   
761   bool drive = _mode == "leg";
762   _apDrivingFlag->setBoolValue(drive);
763   
764   if (drive) {
765     // FIXME: we want to set desired track, not heading, here
766     _apTrueHeading->setDoubleValue(getWP1Bearing());
767   }
768 }
769
770 void GPS::wp1Changed()
771 {
772   if (!_currentWaypt)
773     return;
774   if (_mode == "leg") {
775     _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
776   } else if (_mode == "obs") {
777     _wayptController.reset(new OBSController(this, _currentWaypt));
778   } else if (_mode == "dto") {
779     _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
780   }
781
782   _wayptController->init();
783
784   if (_mode == "obs") {
785     _legDistanceNm = -1.0;
786   } else {
787     _wayptController->update();
788     _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
789   }
790 }
791
792 /////////////////////////////////////////////////////////////////////////////
793 // property getter/setters
794
795 void GPS::setSelectedCourse(double crs)
796 {
797   if (_selectedCourse == crs) {
798     return;
799   }
800   
801   _selectedCourse = crs;
802   if ((_mode == "obs") || _config.courseSelectable()) {
803     _desiredCourse = _selectedCourse;
804     _desiredCourseNode->fireValueChanged();
805   }
806 }
807
808 double GPS::getLegDistance() const
809 {
810   if (!_dataValid || (_mode == "obs")) {
811     return -1;
812   }
813   
814   return _legDistanceNm;
815 }
816
817 double GPS::getLegCourse() const
818 {
819   if (!_dataValid || !_wayptController.get()) {
820     return -9999.0;
821   }
822   
823   return _wayptController->targetTrackDeg();
824 }
825
826 double GPS::getLegMagCourse() const
827 {
828   if (!_dataValid) {
829     return 0.0;
830   }
831   
832   double m = getLegCourse() - _magvar_node->getDoubleValue();
833   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
834   return m;
835 }
836
837 double GPS::getMagTrack() const
838 {
839   if (!_dataValid) {
840     return 0.0;
841   }
842   
843   double m = getTrueTrack() - _magvar_node->getDoubleValue();
844   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
845   return m;
846 }
847
848 double GPS::getCDIDeflection() const
849 {
850   if (!_dataValid) {
851     return 0.0;
852   }
853   
854   double defl;
855   if (_config.cdiDeflectionIsAngular()) {
856     defl = getWP1CourseDeviation();
857     SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
858   } else {
859     double fullScale = _config.cdiDeflectionLinearPeg();
860     double normError = getWP1CourseErrorNm() / fullScale;
861     SG_CLAMP_RANGE(normError, -1.0, 1.0);
862     defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
863   }
864   
865   return defl;
866 }
867
868 const char* GPS::getWP0Ident() const
869 {
870   if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
871     return "";
872   }
873   
874   return _prevWaypt->ident().c_str();
875 }
876
877 const char* GPS::getWP0Name() const
878 {
879   return "";
880 }
881
882 const char* GPS::getWP1Ident() const
883 {
884   if ((!_dataValid)||(!_currentWaypt)) {
885     return "";
886   }
887   
888   return _currentWaypt->ident().c_str();
889 }
890
891 const char* GPS::getWP1Name() const
892 {
893   return "";
894 }
895
896 double GPS::getWP1Distance() const
897 {
898   if (!_dataValid || !_wayptController.get()) {
899     return -1.0;
900   }
901   
902   return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
903 }
904
905 double GPS::getWP1TTW() const
906 {
907   if (!_dataValid || !_wayptController.get()) {
908     return -1.0;
909   }
910   
911   return _wayptController->timeToWaypt();
912 }
913
914 const char* GPS::getWP1TTWString() const
915 {
916   double t = getWP1TTW();
917   if (t <= 0.0) {
918     return "";
919   }
920   
921   return makeTTWString(t);
922 }
923
924 double GPS::getWP1Bearing() const
925 {
926   if (!_dataValid || !_wayptController.get()) {
927     return -9999.0;
928   }
929   
930   return _wayptController->trueBearingDeg();
931 }
932
933 double GPS::getWP1MagBearing() const
934 {
935   if (!_dataValid || !_wayptController.get()) {
936     return -9999.0;
937   }
938
939   double magBearing =  _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
940   SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
941   return magBearing;
942 }
943
944 double GPS::getWP1CourseDeviation() const
945 {
946   if (!_dataValid || !_wayptController.get()) {
947     return 0.0;
948   }
949
950   return _wayptController->courseDeviationDeg();
951 }
952
953 double GPS::getWP1CourseErrorNm() const
954 {
955   if (!_dataValid || !_wayptController.get()) {
956     return 0.0;
957   }
958   
959   return _wayptController->xtrackErrorNm();
960 }
961
962 bool GPS::getWP1ToFlag() const
963 {
964   if (!_dataValid || !_wayptController.get()) {
965     return false;
966   }
967   
968   return _wayptController->toFlag();
969 }
970
971 bool GPS::getWP1FromFlag() const
972 {
973   if (!_dataValid || !_wayptController.get()) {
974     return false;
975   }
976   
977   return !getWP1ToFlag();
978 }
979
980 /////////////////////////////////////////////////////////////////////////////
981 // scratch system
982
983 void GPS::setCommand(const char* aCmd)
984 {
985   SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
986   
987   if (!strcmp(aCmd, "direct")) {
988     directTo();
989   } else if (!strcmp(aCmd, "obs")) {
990     selectOBSMode(NULL);
991   } else if (!strcmp(aCmd, "leg")) {
992     selectLegMode();
993   } else {
994     SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
995   }
996 }
997
998 void GPS::clearScratch()
999 {
1000   _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1001   _scratchNode->setBoolValue("valid", false);
1002 }
1003
1004 bool GPS::isScratchPositionValid() const
1005 {
1006   if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1007       (_scratchPos.getLatitudeDeg() < -9990.0)) {
1008    return false;   
1009   }
1010   
1011   return true;
1012 }
1013
1014 void GPS::directTo()
1015 {  
1016   if (!isScratchPositionValid()) {
1017     return;
1018   }
1019   
1020   _prevWaypt = NULL;
1021   _wp0_position = _indicated_pos;
1022   _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1023   _mode = "dto";
1024
1025   clearScratch();
1026   wp1Changed();
1027 }
1028
1029 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1030 {
1031   if (!waypt) {
1032     // initialise from scratch
1033     if (!isScratchPositionValid()) {
1034       return;
1035     }
1036     
1037     waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1038   }
1039   
1040   _mode = "obs";
1041   _currentWaypt = waypt;
1042   _wp0_position = _indicated_pos;
1043   wp1Changed();
1044 }
1045
1046 void GPS::selectLegMode()
1047 {
1048   if (_mode == "leg") {
1049     return;
1050   }
1051   
1052   if (!_route) {
1053     SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1054     return;
1055   }
1056
1057   _mode = "leg";  
1058   // depending on the situation, this will either get over-written 
1059   // in routeManagerSequenced or not; either way it does no harm to
1060   // set it here.
1061   _wp0_position = _indicated_pos;
1062
1063   // not really sequenced, but does all the work of updating wp0/1
1064   currentWaypointChanged();
1065 }
1066
1067 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
1068   const char* lonStr, const char* latStr, const char* altStr)
1069 {
1070   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1071   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1072   
1073   if (altStr) {
1074     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1075   }
1076 }
1077
1078 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
1079   const char* lonStr, const char* latStr, const char* altStr)
1080 {
1081   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1082   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1083   
1084   if (altStr) {
1085     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
1086   }
1087 }
1088
1089 // end of gps.cxx