1 // dclgps.cxx - a class to extend the operation of FG's current GPS
2 // code, and provide support for a KLN89-specific instrument. It
3 // is envisioned that eventually this file and class will be split
4 // up between current FG code and new KLN89-specific code and removed.
6 // Written by David Luff, started 2005.
8 // Copyright (C) 2005 - David C Luff - david.luff@nottingham.ac.uk
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <simgear/sg_inlines.h>
29 #include <simgear/structure/commands.hxx>
30 #include <Main/fg_props.hxx>
34 //using namespace std;
36 // Command callbacks for FlightGear
38 static bool do_kln89_msg_pressed(const SGPropertyNode* arg) {
39 //cout << "do_kln89_msg_pressed called!\n";
40 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
45 static bool do_kln89_obs_pressed(const SGPropertyNode* arg) {
46 //cout << "do_kln89_obs_pressed called!\n";
47 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
52 static bool do_kln89_alt_pressed(const SGPropertyNode* arg) {
53 //cout << "do_kln89_alt_pressed called!\n";
54 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
59 static bool do_kln89_nrst_pressed(const SGPropertyNode* arg) {
60 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
65 static bool do_kln89_dto_pressed(const SGPropertyNode* arg) {
66 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
71 static bool do_kln89_clr_pressed(const SGPropertyNode* arg) {
72 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
77 static bool do_kln89_ent_pressed(const SGPropertyNode* arg) {
78 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
83 static bool do_kln89_crsr_pressed(const SGPropertyNode* arg) {
84 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
89 static bool do_kln89_knob1left1(const SGPropertyNode* arg) {
90 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
95 static bool do_kln89_knob1right1(const SGPropertyNode* arg) {
96 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
101 static bool do_kln89_knob2left1(const SGPropertyNode* arg) {
102 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
107 static bool do_kln89_knob2right1(const SGPropertyNode* arg) {
108 DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
113 // End command callbacks
115 GPSWaypoint::GPSWaypoint() {
116 appType = GPS_APP_NONE;
119 GPSWaypoint::~GPSWaypoint() {}
121 string GPSWaypoint::GetAprId() {
122 if(appType == GPS_IAF) return(id + 'i');
123 else if(appType == GPS_FAF) return(id + 'f');
124 else if(appType == GPS_MAP) return(id + 'm');
125 else if(appType == GPS_MAHP) return(id + 'h');
129 ostream& operator << (ostream& os, GPSAppWpType type) {
131 case(GPS_IAF): return(os << "IAF");
132 case(GPS_IAP): return(os << "IAP");
133 case(GPS_FAF): return(os << "FAF");
134 case(GPS_MAP): return(os << "MAP");
135 case(GPS_MAHP): return(os << "MAHP");
136 case(GPS_HDR): return(os << "HEADER");
137 case(GPS_FENCE): return(os << "FENCE");
138 case(GPS_APP_NONE): return(os << "NONE");
140 return(os << "ERROR - Unknown switch in GPSAppWpType operator << ");
152 FGNPIAP::~FGNPIAP() {
155 GPSPage::GPSPage(DCLGPS* parent) {
160 GPSPage::~GPSPage() {
163 void GPSPage::Update(double dt) {}
165 void GPSPage::Knob1Left1() {}
166 void GPSPage::Knob1Right1() {}
168 void GPSPage::Knob2Left1() {
169 _parent->_activePage->LooseFocus();
171 if(_subPage < 0) _subPage = _nSubPages - 1;
174 void GPSPage::Knob2Right1() {
175 _parent->_activePage->LooseFocus();
177 if(_subPage >= _nSubPages) _subPage = 0;
180 void GPSPage::CrsrPressed() {}
181 void GPSPage::EntPressed() {}
182 void GPSPage::ClrPressed() {}
183 void GPSPage::DtoPressed() {}
184 void GPSPage::NrstPressed() {}
185 void GPSPage::AltPressed() {}
186 void GPSPage::OBSPressed() {}
187 void GPSPage::MsgPressed() {}
189 string GPSPage::GPSitoa(int n) {
191 // TODO - sanity check n!
192 sprintf(buf, "%i", n);
197 void GPSPage::CleanUp() {}
198 void GPSPage::LooseFocus() {}
199 void GPSPage::SetId(const string& s) {}
201 // ------------------------------------------------------------------------------------- //
203 DCLGPS::DCLGPS(RenderArea2D* instrument) {
204 _instrument = instrument;
209 // Units - lets default to US units - FG can set them to other units from config during startup if desired.
210 _altUnits = GPS_ALT_UNITS_FT;
211 _baroUnits = GPS_PRES_UNITS_IN;
212 _velUnits = GPS_VEL_UNITS_KT;
213 _distUnits = GPS_DIST_UNITS_NM;
215 _lon_node = fgGetNode("/instrumentation/gps/indicated-longitude-deg", true);
216 _lat_node = fgGetNode("/instrumentation/gps/indicated-latitude-deg", true);
217 _alt_node = fgGetNode("/instrumentation/gps/indicated-altitude-ft", true);
218 _grnd_speed_node = fgGetNode("/instrumentation/gps/indicated-ground-speed-kt", true);
219 _true_track_node = fgGetNode("/instrumentation/gps/indicated-track-true-deg", true);
220 _mag_track_node = fgGetNode("/instrumentation/gps/indicated-track-magnetic-deg", true);
222 // Use FG's position values at construction in case FG's gps has not run first update yet.
223 _lon = fgGetDouble("/position/longitude-deg") * SG_DEGREES_TO_RADIANS;
224 _lat = fgGetDouble("/position/latitude-deg") * SG_DEGREES_TO_RADIANS;
225 _alt = fgGetDouble("/position/altitude-ft");
226 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
227 // gps code and not our own.
232 _groundSpeed_ms = 0.0;
233 _groundSpeed_kts = 0.0;
237 // Sensible defaults. These can be overriden by derived classes if desired.
239 _cdiScales.push_back(5.0);
240 _cdiScales.push_back(1.0);
241 _cdiScales.push_back(0.3);
242 _currentCdiScaleIndex = 0;
243 _targetCdiScaleIndex = 0;
244 _sourceCdiScaleIndex = 0;
245 _cdiScaleTransition = false;
246 _currentCdiScale = 5.0;
250 _activeWaypoint.id.clear();
252 _crosstrackDist = 0.0;
253 _headingBugTo = true;
255 _waypointAlert = false;
257 _departureTimeString = "----";
260 // Configuration Initialisation
261 // Should this be in kln89.cxx ?
262 _turnAnticipationEnabled = false;
263 _suaAlertEnabled = false;
264 _altAlertEnabled = false;
268 _messageStack.clear();
272 _approachLoaded = false;
273 _approachArm = false;
274 _approachReallyArmed = false;
275 _approachActive = false;
276 _approachFP = new GPSFlightPlan;
281 for(gps_waypoint_map_iterator itr = _waypoints.begin(); itr != _waypoints.end(); ++itr) {
282 for(unsigned int i = 0; i < (*itr).second.size(); ++i) {
283 delete(((*itr).second)[i]);
286 delete _approachFP; // Don't need to delete the waypoints inside since they point to
287 // the waypoints in the approach database.
288 // TODO - may need to delete the approach database!!
291 void DCLGPS::draw() {
292 //cout << "draw called!\n";
296 void DCLGPS::init() {
297 globals->get_commands()->addCommand("kln89_msg_pressed", do_kln89_msg_pressed);
298 globals->get_commands()->addCommand("kln89_obs_pressed", do_kln89_obs_pressed);
299 globals->get_commands()->addCommand("kln89_alt_pressed", do_kln89_alt_pressed);
300 globals->get_commands()->addCommand("kln89_nrst_pressed", do_kln89_nrst_pressed);
301 globals->get_commands()->addCommand("kln89_dto_pressed", do_kln89_dto_pressed);
302 globals->get_commands()->addCommand("kln89_clr_pressed", do_kln89_clr_pressed);
303 globals->get_commands()->addCommand("kln89_ent_pressed", do_kln89_ent_pressed);
304 globals->get_commands()->addCommand("kln89_crsr_pressed", do_kln89_crsr_pressed);
305 globals->get_commands()->addCommand("kln89_knob1left1", do_kln89_knob1left1);
306 globals->get_commands()->addCommand("kln89_knob1right1", do_kln89_knob1right1);
307 globals->get_commands()->addCommand("kln89_knob2left1", do_kln89_knob2left1);
308 globals->get_commands()->addCommand("kln89_knob2right1", do_kln89_knob2right1);
310 // Build the GPS-specific databases.
311 // TODO - consider splitting into real life GPS database regions - eg Americas, Europe etc.
312 // Note that this needs to run after FG's airport and nav databases are up and running
314 const airport_list* apts = globals->get_airports()->getAirportList();
315 for(unsigned int i = 0; i < apts->size(); ++i) {
316 FGAirport* a = (*apts)[i];
317 GPSWaypoint* w = new GPSWaypoint;
319 w->lat = a->getLatitude() * SG_DEGREES_TO_RADIANS;
320 w->lon = a->getLongitude() * SG_DEGREES_TO_RADIANS;
321 w->type = GPS_WP_APT;
322 gps_waypoint_map_iterator wtr = _waypoints.find(a->getId());
323 if(wtr == _waypoints.end()) {
324 gps_waypoint_array arr;
326 _waypoints[w->id] = arr;
328 wtr->second.push_back(w);
331 nav_map_type navs = globals->get_navlist()->get_navaids();
332 for(nav_map_iterator itr = navs.begin(); itr != navs.end(); ++itr) {
333 nav_list_type nlst = itr->second;
334 for(unsigned int i = 0; i < nlst.size(); ++i) {
335 FGNavRecord* n = nlst[i];
336 if(n->get_fg_type() == FG_NAV_VOR || n->get_fg_type() == FG_NAV_NDB) { // We don't bother with ILS etc.
337 GPSWaypoint* w = new GPSWaypoint;
338 w->id = n->get_ident();
339 w->lat = n->get_lat() * SG_DEGREES_TO_RADIANS;
340 w->lon = n->get_lon() * SG_DEGREES_TO_RADIANS;
341 w->type = (n->get_fg_type() == FG_NAV_VOR ? GPS_WP_VOR : GPS_WP_NDB);
342 gps_waypoint_map_iterator wtr = _waypoints.find(n->get_ident());
343 if(wtr == _waypoints.end()) {
344 gps_waypoint_array arr;
346 _waypoints[w->id] = arr;
348 wtr->second.push_back(w);
353 const fix_map_type* fixes = globals->get_fixlist()->getFixList();
354 for(fix_map_const_iterator itr = fixes->begin(); itr != fixes->end(); ++itr) {
355 FGFix f = itr->second;
356 GPSWaypoint* w = new GPSWaypoint;
357 w->id = f.get_ident();
358 w->lat = f.get_lat() * SG_DEGREES_TO_RADIANS;
359 w->lon = f.get_lon() * SG_DEGREES_TO_RADIANS;
360 w->type = GPS_WP_INT;
361 gps_waypoint_map_iterator wtr = _waypoints.find(f.get_ident());
362 if(wtr == _waypoints.end()) {
363 gps_waypoint_array arr;
365 _waypoints[w->id] = arr;
367 wtr->second.push_back(w);
370 // TODO - add USR waypoints as well.
372 // Not sure if this should be here, but OK for now.
373 CreateDefaultFlightPlans();
375 // Hack - hardwire some instrument approaches for testing.
376 // TODO - read these from file - either all at startup or as needed.
377 FGNPIAP* iap = new FGNPIAP;
379 iap->_name = "VOR/DME OR GPS-B";
380 iap->_abbrev = "VOR/D";
386 GPSWaypoint* wp = new GPSWaypoint;
389 // Nasty using the find any function here, but it saves converting data from FGFix etc.
390 const GPSWaypoint* fp = FindFirstById(wp->id, multi, true);
392 wp->appType = GPS_IAF;
393 iap->_IAF.push_back(wp);
395 wp = new GPSWaypoint;
397 fp = FindFirstById(wp->id, multi, true);
399 wp->appType = GPS_IAF;
400 iap->_IAF.push_back(wp);
402 wp = new GPSWaypoint;
404 fp = FindFirstById(wp->id, multi, true);
406 wp->appType = GPS_IAP;
407 iap->_IAP.push_back(wp);
409 wp = new GPSWaypoint;
411 fp = FindFirstById(wp->id, multi, true);
413 wp->appType = GPS_FAF;
414 iap->_IAP.push_back(wp);
416 wp = new GPSWaypoint;
418 fp = FindFirstById(wp->id, multi, true);
420 wp->appType = GPS_MAP;
421 iap->_IAP.push_back(wp);
423 wp = new GPSWaypoint;
425 fp = FindFirstById(wp->id, multi, true);
427 wp->appType = GPS_MAHP;
428 iap->_MAP.push_back(wp);
430 _np_iap[iap->_id].push_back(iap);
431 // -----------------------
432 // -----------------------
435 iap->_name = "VOR OR GPS-A";
436 iap->_abbrev = "VOR-";
442 wp = new GPSWaypoint;
444 // Nasty using the find any function here, but it saves converting data from FGFix etc.
445 fp = FindFirstById(wp->id, multi, true);
447 wp->appType = GPS_IAF;
448 iap->_IAF.push_back(wp);
450 wp = new GPSWaypoint;
452 fp = FindFirstById(wp->id, multi, true);
454 wp->appType = GPS_IAF;
455 iap->_IAF.push_back(wp);
457 wp = new GPSWaypoint;
459 fp = FindFirstById(wp->id, multi, true);
461 wp->appType = GPS_IAP;
462 iap->_IAP.push_back(wp);
464 wp = new GPSWaypoint;
466 fp = FindFirstById(wp->id, multi, true);
468 wp->appType = GPS_FAF;
469 iap->_IAP.push_back(wp);
471 wp = new GPSWaypoint;
473 fp = FindFirstById(wp->id, multi, true);
475 wp->appType = GPS_MAP;
476 iap->_IAP.push_back(wp);
478 wp = new GPSWaypoint;
480 fp = FindFirstById(wp->id, multi, true);
482 wp->appType = GPS_MAHP;
483 iap->_MAP.push_back(wp);
485 _np_iap[iap->_id].push_back(iap);
486 // ------------------
487 // ------------------
489 // Ugh - don't load this one - the waypoints required aren't in fix.dat.gz - result: program crash!
490 // TODO - make the IAP loader robust to absent waypoints.
493 iap->_name = "GPS RWY 28L";
494 iap->_abbrev = "GPS";
495 iap->_rwyStr = "28L";
500 wp = new GPSWaypoint;
502 // Nasty using the find any function here, but it saves converting data from FGFix etc.
503 fp = FindFirstById(wp->id, multi, true);
505 wp->appType = GPS_IAF;
506 iap->_IAF.push_back(wp);
508 wp = new GPSWaypoint;
510 fp = FindFirstById(wp->id, multi, true);
512 wp->appType = GPS_IAF;
513 iap->_IAF.push_back(wp);
515 wp = new GPSWaypoint;
517 fp = FindFirstById(wp->id, multi, true);
519 wp->appType = GPS_IAP;
520 iap->_IAP.push_back(wp);
522 wp = new GPSWaypoint;
524 fp = FindFirstById(wp->id, multi, true);
526 wp->appType = GPS_FAF;
527 iap->_IAP.push_back(wp);
529 wp = new GPSWaypoint;
531 wp->appType = GPS_MAP;
532 if(wp->id.substr(0, 2) == "RW" && wp->appType == GPS_MAP) {
533 // Assume that this is a missed-approach point based on the runway number
534 // Get the runway threshold location etc
536 fp = FindFirstById(wp->id, multi, true);
538 cout << "Failed to find waypoint " << wp->id << " in database...\n";
543 iap->_IAP.push_back(wp);
545 wp = new GPSWaypoint;
547 fp = FindFirstById(wp->id, multi, true);
549 wp->appType = GPS_MAHP;
550 iap->_MAP.push_back(wp);
552 _np_iap[iap->_id].push_back(iap);
556 iap->_name = "GPS RWY 30";
557 iap->_abbrev = "GPS";
563 wp = new GPSWaypoint;
565 // Nasty using the find any function here, but it saves converting data from FGFix etc.
566 fp = FindFirstById(wp->id, multi, true);
569 wp->appType = GPS_IAF;
570 iap->_IAF.push_back(wp);
573 wp = new GPSWaypoint;
575 fp = FindFirstById(wp->id, multi, true);
578 wp->appType = GPS_IAF;
579 iap->_IAF.push_back(wp);
582 wp = new GPSWaypoint;
584 fp = FindFirstById(wp->id, multi, true);
587 wp->appType = GPS_IAF;
588 iap->_IAF.push_back(wp);
591 wp = new GPSWaypoint;
593 fp = FindFirstById(wp->id, multi, true);
596 wp->appType = GPS_IAP;
597 iap->_IAP.push_back(wp);
600 wp = new GPSWaypoint;
602 fp = FindFirstById(wp->id, multi, true);
605 wp->appType = GPS_FAF;
606 iap->_IAP.push_back(wp);
609 wp = new GPSWaypoint;
611 wp->appType = GPS_MAP;
612 if(wp->id.substr(0, 2) == "RW" && wp->appType == GPS_MAP) {
613 // Assume that this is a missed-approach point based on the runway number
614 // TODO: Get the runway threshold location etc
615 cout << "TODO - implement missed-approach point based on rwy no.\n";
617 fp = FindFirstById(wp->id, multi, true);
619 cout << "Failed to find waypoint " << wp->id << " in database...\n";
622 wp->appType = GPS_MAP;
625 iap->_IAP.push_back(wp);
627 wp = new GPSWaypoint;
629 fp = FindFirstById(wp->id, multi, true);
631 wp->appType = GPS_MAHP;
632 iap->_MAP.push_back(wp);
634 _np_iap[iap->_id].push_back(iap);
637 void DCLGPS::bind() {
638 fgTie("/instrumentation/gps/waypoint-alert", this, &DCLGPS::GetWaypointAlert);
639 fgTie("/instrumentation/gps/leg-mode", this, &DCLGPS::GetLegMode);
640 fgTie("/instrumentation/gps/obs-mode", this, &DCLGPS::GetOBSMode);
641 fgTie("/instrumentation/gps/approach-arm", this, &DCLGPS::GetApproachArm);
642 fgTie("/instrumentation/gps/approach-active", this, &DCLGPS::GetApproachActive);
643 fgTie("/instrumentation/gps/cdi-deflection", this, &DCLGPS::GetCDIDeflection);
644 fgTie("/instrumentation/gps/to-flag", this, &DCLGPS::GetToFlag);
647 void DCLGPS::unbind() {
648 fgUntie("/instrumentation/gps/waypoint-alert");
649 fgUntie("/instrumentation/gps/leg-mode");
650 fgUntie("/instrumentation/gps/obs-mode");
651 fgUntie("/instrumentation/gps/approach-arm");
652 fgUntie("/instrumentation/gps/approach-active");
653 fgUntie("/instrumentation/gps/cdi-deflection");
656 void DCLGPS::update(double dt) {
657 //cout << "update called!\n";
659 _lon = _lon_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
660 _lat = _lat_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
661 _alt = _alt_node->getDoubleValue();
662 _groundSpeed_kts = _grnd_speed_node->getDoubleValue();
663 _groundSpeed_ms = _groundSpeed_kts * 0.5144444444;
664 _track = _true_track_node->getDoubleValue();
665 _magTrackDeg = _mag_track_node->getDoubleValue();
666 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
667 // gps code and not our own.
670 // Check for abnormal position slew
671 if(GetGreatCircleDistance(_gpsLat, _gpsLon, _checkLat, _checkLon) > 1.0) {
672 OrientateToActiveFlightPlan();
678 if(_groundSpeed_kts > 30.0) {
680 string th = fgGetString("/instrumentation/clock/indicated-hour");
681 string tm = fgGetString("/instrumentation/clock/indicated-min");
682 if(th.size() == 1) th = "0" + th;
683 if(tm.size() == 1) tm = "0" + tm;
684 _departureTimeString = th + tm;
687 // TODO - check - is this prone to drift error over time?
688 // Should we difference the departure and current times?
689 // What about when the user resets the time of day from the menu?
693 _time->update(_gpsLon * SG_DEGREES_TO_RADIANS, _gpsLat * SG_DEGREES_TO_RADIANS, 0, 0);
694 // FIXME - currently all the below assumes leg mode and no DTO or OBS cancelled.
695 if(_activeFP->IsEmpty()) {
696 // Not sure if we need to reset these each update or only when fp altered
697 _activeWaypoint.id.clear();
699 } else if(_activeFP->waypoints.size() == 1) {
700 _activeWaypoint.id.clear();
703 if(_activeWaypoint.id.empty() || _fromWaypoint.id.empty()) {
704 //cout << "Error, in leg mode with flightplan of 2 or more waypoints, but either active or from wp is NULL!\n";
705 OrientateToActiveFlightPlan();
709 if(_approachLoaded) {
710 if(!_approachReallyArmed && !_approachActive) {
711 // arm if within 30nm of airport.
712 // TODO - let user cancel approach arm using external GPS-APR switch
714 const FGAirport* ap = FindFirstAptById(_approachID, multi, true);
716 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, ap->getLatitude() * SG_DEGREES_TO_RADIANS, ap->getLongitude() * SG_DEGREES_TO_RADIANS);
719 _approachReallyArmed = true;
720 _messageStack.push_back("*Press ALT To Set Baro");
721 // Not sure what we do if the user has already set CDI to 0.3 nm?
722 _targetCdiScaleIndex = 1;
723 if(_currentCdiScaleIndex == 1) {
725 } else if(_currentCdiScaleIndex == 0) {
726 _sourceCdiScaleIndex = 0;
727 _cdiScaleTransition = true;
728 _cdiTransitionTime = 30.0;
729 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
734 // Check for approach active - we can only activate approach if it is really armed.
735 if(_activeWaypoint.appType == GPS_FAF) {
736 //cout << "Active waypoint is FAF, id is " << _activeWaypoint.id << '\n';
737 if(GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) <= 2.0 && !_obsMode) {
738 // Assume heading is OK for now
739 _approachArm = false; // TODO - check - maybe arm is left on when actv comes on?
740 _approachReallyArmed = false;
741 _approachActive = true;
742 _targetCdiScaleIndex = 2;
743 if(_currentCdiScaleIndex == 2) {
745 } else if(_currentCdiScaleIndex == 1) {
746 _sourceCdiScaleIndex = 1;
747 _cdiScaleTransition = true;
748 _cdiTransitionTime = 30.0; // TODO - compress it if time to FAF < 30sec
749 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
751 // Abort going active?
752 _approachActive = false;
759 // CDI scale transition stuff
760 if(_cdiScaleTransition) {
761 if(fabs(_currentCdiScale - _cdiScales[_targetCdiScaleIndex]) < 0.001) {
762 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
763 _currentCdiScaleIndex = _targetCdiScaleIndex;
764 _cdiScaleTransition = false;
766 double scaleDiff = (_targetCdiScaleIndex > _sourceCdiScaleIndex
767 ? _cdiScales[_sourceCdiScaleIndex] - _cdiScales[_targetCdiScaleIndex]
768 : _cdiScales[_targetCdiScaleIndex] - _cdiScales[_sourceCdiScaleIndex]);
769 //cout << "ScaleDiff = " << scaleDiff << '\n';
770 if(_targetCdiScaleIndex > _sourceCdiScaleIndex) {
771 // Scaling down eg. 5nm -> 1nm
772 _currentCdiScale -= (scaleDiff * dt / _cdiTransitionTime);
773 if(_currentCdiScale < _cdiScales[_targetCdiScaleIndex]) {
774 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
775 _currentCdiScaleIndex = _targetCdiScaleIndex;
776 _cdiScaleTransition = false;
779 _currentCdiScale += (scaleDiff * dt / _cdiTransitionTime);
780 if(_currentCdiScale > _cdiScales[_targetCdiScaleIndex]) {
781 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
782 _currentCdiScaleIndex = _targetCdiScaleIndex;
783 _cdiScaleTransition = false;
786 //cout << "_currentCdiScale = " << _currentCdiScale << '\n';
789 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
793 // Urgh - I've been setting the heading bug based on DTK,
794 // bug I think it should be based on heading re. active waypoint
795 // based on what the sim does after the final waypoint is passed.
796 // (DTK remains the same, but if track is held == DTK heading bug
797 // reverses to from once wp is passed).
799 if(_fromWaypoint != NULL) {
800 // TODO - how do we handle the change of track with distance over long legs?
801 _dtkTrue = GetGreatCircleCourse(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon) * SG_RADIANS_TO_DEGREES;
802 _dtkMag = GetMagHeadingFromTo(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon);
803 // Don't change the heading bug if speed is too low otherwise it flickers to/from at rest
804 if(_groundSpeed_ms > 5) {
805 //cout << "track = " << _track << ", dtk = " << _dtkTrue << '\n';
806 double courseDev = _track - _dtkTrue;
807 //cout << "courseDev = " << courseDev << ", normalized = ";
808 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
809 //cout << courseDev << '\n';
810 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
815 // TODO - in DTO operation the position of initiation of DTO defines the "from waypoint".
818 if(!_activeWaypoint.id.empty()) {
819 double hdgTrue = GetGreatCircleCourse(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
820 if(_groundSpeed_ms > 5) {
821 //cout << "track = " << _track << ", hdgTrue = " << hdgTrue << '\n';
822 double courseDev = _track - hdgTrue;
823 //cout << "courseDev = " << courseDev << ", normalized = ";
824 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
825 //cout << courseDev << '\n';
826 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
828 if(!_fromWaypoint.id.empty()) {
829 _dtkTrue = GetGreatCircleCourse(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
830 _dtkMag = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
837 _dist2Act = GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_NM_TO_METER;
838 if(_groundSpeed_ms > 10.0) {
839 _eta = _dist2Act / _groundSpeed_ms;
840 if(_eta <= 36) { // TODO - this is slightly different if turn anticipation is enabled.
842 _waypointAlert = true; // TODO - not if the from flag is set.
846 // Check if we should sequence to next leg.
847 // Perhaps this should be done on distance instead, but 60s time (about 1 - 2 nm) seems reasonable for now.
848 //double reverseHeading = GetGreatCircleCourse(_activeWaypoint->lat, _activeWaypoint->lon, _fromWaypoint->lat, _fromWaypoint->lon);
849 // Hack - let's cheat and do it on heading bug for now. TODO - that stops us 'cutting the corner'
850 // when we happen to approach the inside turn of a waypoint - we should probably sequence at the midpoint
851 // of the heading difference between legs in this instance.
852 int idx = GetActiveWaypointIndex();
853 bool finalLeg = (idx == (int)(_activeFP->waypoints.size()) - 1 ? true : false);
854 bool finalDto = (_dto && idx == -1); // Dto operation to a waypoint not in the flightplan - we don't sequence in this instance
857 // Do nothing - not sure if Dto should switch off when arriving at the final waypoint of a flightplan
858 } else if(finalDto) {
860 } else if(_activeWaypoint.appType == GPS_MAP) {
861 // Don't sequence beyond the missed approach point
862 cout << "ACTIVE WAYPOINT is MAP - not sequencing!!!!!\n";
864 cout << "Sequencing...\n";
865 _fromWaypoint = _activeWaypoint;
866 _activeWaypoint = *_activeFP->waypoints[idx + 1];
868 // TODO - course alteration message format is dependent on whether we are slaved HSI/CDI indicator or not.
869 // For now assume we are not.
871 if(fgGetBool("/instrumentation/nav[0]/slaved-to-gps")) {
872 // TODO - avoid the hardwiring on nav[0]
873 s = "Adj Nav Crs to ";
875 string s = "GPS Course is ";
877 double d = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
878 while(d < 0.0) d += 360.0;
879 while(d >= 360.0) d -= 360.0;
881 snprintf(buf, 4, "%03i", (int)(d + 0.5));
883 _messageStack.push_back(s);
885 _waypointAlert = false;
893 // First attempt at a sensible cross-track correction calculation
894 // Uh? - I think this is implemented further down the file!
895 if(_fromWaypoint != NULL) {
898 _crosstrackDist = 0.0;
904 double DCLGPS::GetCDIDeflection() const {
905 double xtd = CalcCrossTrackDeviation(); //nm
906 return((xtd / _currentCdiScale) * 5.0 * 2.5 * -1.0);
909 void DCLGPS::DtoInitiate(const string& s) {
910 //cout << "DtoInitiate, s = " << s << '\n';
912 const GPSWaypoint* wp = FindFirstById(s, multi, true);
914 //cout << "Waypoint found, starting dto operation!\n";
916 _activeWaypoint = *wp;
917 _fromWaypoint.lat = _gpsLat;
918 _fromWaypoint.lon = _gpsLon;
919 _fromWaypoint.type = GPS_WP_VIRT;
920 _fromWaypoint.id = "DTOWP";
922 //cout << "Waypoint not found, ignoring dto request\n";
923 // Should bring up the user waypoint page, but we're not implementing that yet.
924 _dto = false; // TODO - implement this some day.
928 void DCLGPS::DtoCancel() {
930 // i.e. don't bother reorientating if we're just cancelling a DTO button press
931 // without having previously initiated DTO.
932 OrientateToActiveFlightPlan();
937 void DCLGPS::Knob1Left1() {}
938 void DCLGPS::Knob1Right1() {}
939 void DCLGPS::Knob2Left1() {}
940 void DCLGPS::Knob2Right1() {}
941 void DCLGPS::CrsrPressed() { _activePage->CrsrPressed(); }
942 void DCLGPS::EntPressed() { _activePage->EntPressed(); }
943 void DCLGPS::ClrPressed() { _activePage->ClrPressed(); }
944 void DCLGPS::DtoPressed() {}
945 void DCLGPS::NrstPressed() {}
946 void DCLGPS::AltPressed() {}
948 void DCLGPS::OBSPressed() {
949 _obsMode = !_obsMode;
951 if(!_activeWaypoint.id.empty()) {
952 _obsHeading = static_cast<int>(_dtkMag);
954 // TODO - the _fromWaypoint location will change as the OBS heading changes.
955 // Might need to store the OBS initiation position somewhere in case it is needed again.
956 SetOBSFromWaypoint();
960 // Set the _fromWaypoint position based on the active waypoint and OBS radial.
961 void DCLGPS::SetOBSFromWaypoint() {
962 if(!_obsMode) return;
963 if(_activeWaypoint.id.empty()) return;
965 // TODO - base the 180 deg correction on the to/from flag.
966 _fromWaypoint = GetPositionOnMagRadial(_activeWaypoint, 10, _obsHeading + 180.0);
967 _fromWaypoint.id = "OBSWP";
970 void DCLGPS::MsgPressed() {}
972 void DCLGPS::CDIFSDIncrease() {
973 if(_currentCdiScaleIndex == 0) {
974 _currentCdiScaleIndex = _cdiScales.size() - 1;
976 _currentCdiScaleIndex--;
980 void DCLGPS::CDIFSDDecrease() {
981 _currentCdiScaleIndex++;
982 if(_currentCdiScaleIndex == _cdiScales.size()) {
983 _currentCdiScaleIndex = 0;
987 void DCLGPS::DrawChar(char c, int field, int px, int py, bool bold) {
990 void DCLGPS::DrawText(const string& s, int field, int px, int py, bool bold) {
993 void DCLGPS::SetBaroUnits(int n, bool wrap) {
995 _baroUnits = (GPSPressureUnits)(wrap ? 3 : 1);
997 _baroUnits = (GPSPressureUnits)(wrap ? 1 : 3);
999 _baroUnits = (GPSPressureUnits)n;
1003 void DCLGPS::CreateDefaultFlightPlans() {}
1005 // Get the time to the active waypoint in seconds.
1006 // Returns -1 if groundspeed < 30 kts
1007 double DCLGPS::GetTimeToActiveWaypoint() {
1008 if(_groundSpeed_kts < 30.0) {
1015 // Get the time to the final waypoint in seconds.
1016 // Returns -1 if groundspeed < 30 kts
1017 double DCLGPS::GetETE() {
1018 if(_groundSpeed_kts < 30.0) {
1021 // TODO - handle OBS / DTO operation appropriately
1022 if(_activeFP->waypoints.empty()) {
1025 return(GetTimeToWaypoint(_activeFP->waypoints[_activeFP->waypoints.size() - 1]->id));
1030 // Get the time to a given waypoint (spec'd by ID) in seconds.
1031 // returns -1 if groundspeed is less than 30kts.
1032 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
1033 // otherwise it will be a direct-to time.
1034 double DCLGPS::GetTimeToWaypoint(const string& id) {
1035 if(_groundSpeed_kts < 30.0) {
1040 int n1 = GetActiveWaypointIndex();
1041 int n2 = GetWaypointIndex(id);
1044 for(unsigned int i=n1+1; i<_activeFP->waypoints.size(); ++i) {
1045 GPSWaypoint* wp1 = _activeFP->waypoints[i-1];
1046 GPSWaypoint* wp2 = _activeFP->waypoints[i];
1047 double distm = GetGreatCircleDistance(wp1->lat, wp1->lon, wp2->lat, wp2->lon) * SG_NM_TO_METER;
1048 eta += (distm / _groundSpeed_ms);
1051 } else if(id == _activeWaypoint.id) {
1055 const GPSWaypoint* wp = FindFirstById(id, multi, true);
1056 if(wp == NULL) return(-1.0);
1057 double distm = GetGreatCircleDistance(_gpsLat, _gpsLon, wp->lat, wp->lon);
1058 return(distm / _groundSpeed_ms);
1060 return(-1.0); // Hopefully we never get here!
1063 // Returns magnetic great-circle heading
1064 // TODO - document units.
1065 float DCLGPS::GetHeadingToActiveWaypoint() {
1066 if(_activeWaypoint.id.empty()) {
1069 double h = GetMagHeadingFromTo(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon);
1070 while(h <= 0.0) h += 360.0;
1071 while(h > 360.0) h -= 360.0;
1076 // Returns magnetic great-circle heading
1077 // TODO - what units?
1078 float DCLGPS::GetHeadingFromActiveWaypoint() {
1079 if(_activeWaypoint.id.empty()) {
1082 double h = GetMagHeadingFromTo(_activeWaypoint.lat, _activeWaypoint.lon, _gpsLat, _gpsLon);
1083 while(h <= 0.0) h += 360.0;
1084 while(h > 360.0) h -= 360.0;
1089 void DCLGPS::ClearFlightPlan(int n) {
1090 for(unsigned int i=0; i<_flightPlans[n]->waypoints.size(); ++i) {
1091 delete _flightPlans[n]->waypoints[i];
1093 _flightPlans[n]->waypoints.clear();
1096 void DCLGPS::ClearFlightPlan(GPSFlightPlan* fp) {
1097 for(unsigned int i=0; i<fp->waypoints.size(); ++i) {
1098 delete fp->waypoints[i];
1100 fp->waypoints.clear();
1103 int DCLGPS::GetActiveWaypointIndex() {
1104 for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
1105 if(_flightPlans[0]->waypoints[i]->id == _activeWaypoint.id) return((int)i);
1110 int DCLGPS::GetWaypointIndex(const string& id) {
1111 for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
1112 if(_flightPlans[0]->waypoints[i]->id == id) return((int)i);
1117 void DCLGPS::OrientateToFlightPlan(GPSFlightPlan* fp) {
1118 //cout << "Orientating...\n";
1119 //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n';
1121 _activeWaypoint.id.clear();
1124 _navFlagged = false;
1125 if(fp->waypoints.size() == 1) {
1126 // TODO - may need to flag nav here if not dto or obs, or possibly handle it somewhere else.
1127 _activeWaypoint = *fp->waypoints[0];
1128 _fromWaypoint.id.clear();
1130 // FIXME FIXME FIXME
1131 _fromWaypoint = *fp->waypoints[0];
1132 _activeWaypoint = *fp->waypoints[1];
1133 double dmin = 1000000; // nm!!
1134 // For now we will simply start on the leg closest to our current position.
1135 // It's possible that more fancy algorithms may take either heading or track
1136 // into account when setting inital leg - I'm not sure.
1137 // This method should handle most cases perfectly OK though.
1138 for(unsigned int i = 1; i < fp->waypoints.size(); ++i) {
1139 //cout << "Pass " << i << ", dmin = " << dmin << ", leg is " << fp->waypoints[i-1]->id << " to " << fp->waypoints[i]->id << '\n';
1140 // First get the cross track correction.
1141 double d0 = fabs(CalcCrossTrackDeviation(*fp->waypoints[i-1], *fp->waypoints[i]));
1142 // That is the shortest distance away we could be though - check for
1143 // longer distances if we are 'off the end' of the leg.
1144 double ht1 = GetGreatCircleCourse(fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon,
1145 fp->waypoints[i]->lat, fp->waypoints[i]->lon)
1146 * SG_RADIANS_TO_DEGREES;
1147 // not simply the reverse of the above due to great circle navigation.
1148 double ht2 = GetGreatCircleCourse(fp->waypoints[i]->lat, fp->waypoints[i]->lon,
1149 fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
1150 * SG_RADIANS_TO_DEGREES;
1151 double hw1 = GetGreatCircleCourse(_gpsLat, _gpsLon,
1152 fp->waypoints[i]->lat, fp->waypoints[i]->lon)
1153 * SG_RADIANS_TO_DEGREES;
1154 double hw2 = GetGreatCircleCourse(_gpsLat, _gpsLon,
1155 fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
1156 * SG_RADIANS_TO_DEGREES;
1157 double h1 = ht1 - hw1;
1158 double h2 = ht2 - hw2;
1159 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
1160 //cout << "Normalizing...\n";
1161 SG_NORMALIZE_RANGE(h1, -180.0, 180.0);
1162 SG_NORMALIZE_RANGE(h2, -180.0, 180.0);
1163 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
1164 if(fabs(h1) > 90.0) {
1165 // We are past the end of the to waypoint
1166 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i]->lat, fp->waypoints[i]->lon);
1168 //cout << "h1 triggered, d0 now = " << d0 << '\n';
1169 } else if(fabs(h2) > 90.0) {
1170 // We are past the end (not yet at!) the from waypoint
1171 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon);
1173 //cout << "h2 triggered, d0 now = " << d0 << '\n';
1176 //cout << "THIS LEG NOW ACTIVE!\n";
1178 _fromWaypoint = *fp->waypoints[i-1];
1179 _activeWaypoint = *fp->waypoints[i];
1186 void DCLGPS::OrientateToActiveFlightPlan() {
1187 OrientateToFlightPlan(_activeFP);
1190 /***************************************/
1192 // Utility function - create a flightplan from a list of waypoint ids and types
1193 void DCLGPS::CreateFlightPlan(GPSFlightPlan* fp, vector<string> ids, vector<GPSWpType> wps) {
1194 if(fp == NULL) fp = new GPSFlightPlan;
1196 if(!fp->waypoints.empty()) {
1197 for(i=0; i<fp->waypoints.size(); ++i) {
1198 delete fp->waypoints[i];
1200 fp->waypoints.clear();
1202 if(ids.size() != wps.size()) {
1203 cout << "ID and Waypoint types list size mismatch in GPS::CreateFlightPlan - no flightplan created!\n";
1206 for(i=0; i<ids.size(); ++i) {
1208 const FGAirport* ap;
1210 GPSWaypoint* wp = new GPSWaypoint;
1214 ap = FindFirstAptById(ids[i], multi, true);
1219 wp->lat = ap->getLatitude() * SG_DEGREES_TO_RADIANS;
1220 wp->lon = ap->getLongitude() * SG_DEGREES_TO_RADIANS;
1222 fp->waypoints.push_back(wp);
1226 np = FindFirstVorById(ids[i], multi, true);
1231 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1232 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1234 fp->waypoints.push_back(wp);
1238 np = FindFirstNDBById(ids[i], multi, true);
1243 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1244 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1246 fp->waypoints.push_back(wp);
1259 /***************************************/
1261 const GPSWaypoint* DCLGPS::ActualFindFirstById(const string& id, bool exact) {
1262 gps_waypoint_map_const_iterator itr;
1264 itr = _waypoints.find(id);
1266 itr = _waypoints.lower_bound(id);
1268 if(itr == _waypoints.end()) {
1271 // TODO - don't just return the first one - either return all or the nearest one.
1272 return((itr->second)[0]);
1276 const GPSWaypoint* DCLGPS::FindFirstById(const string& id, bool &multi, bool exact) {
1278 if(exact) return(ActualFindFirstById(id, exact));
1280 // OK, that was the easy case, now the fuzzy case
1281 const GPSWaypoint* w1 = ActualFindFirstById(id);
1282 if(w1 == NULL) return(w1);
1284 // The non-trivial code from here to the end of the function is all to deal with the fact that
1285 // the KLN89 alphabetical order (numbers AFTER letters) differs from ASCII order (numbers BEFORE letters).
1287 //string id3 = id+'0';
1288 string id4 = id+'A';
1289 // Increment the last char to provide the boundary. Note that 'Z' -> '[' but we also need to check '0' for all since GPS has numbers after letters
1290 //bool alfa = isalpha(id2[id2.size() - 1]);
1291 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1292 const GPSWaypoint* w2 = ActualFindFirstById(id2);
1293 //FGAirport* a3 = globals->get_airports()->findFirstById(id3);
1294 const GPSWaypoint* w4 = ActualFindFirstById(id4);
1295 //cout << "Strings sent were " << id << ", " << id2 << " and " << id4 << '\n';
1296 //cout << "Airports returned were (a1, a2, a4): " << a1->getId() << ", " << a2->getId() << ", " << a4->getId() << '\n';
1297 //cout << "Pointers were " << a1 << ", " << a2 << ", " << a4 << '\n';
1299 // TODO - the below handles the imediately following char OK
1300 // eg id = "KD" returns "KDAA" instead of "KD5"
1301 // but it doesn't handle numbers / letters further down the string,
1302 // eg - id = "I" returns "IA01" instead of "IAN"
1303 // We either need to provide a custom comparison operator, or recurse this function if !isalpha further down the string.
1304 // (Currenly fixed with recursion).
1306 if(w4 != w2) { // A-Z match - preferred
1307 //cout << "A-Z match!\n";
1308 if(w4->id.size() - id.size() > 2) {
1309 // Check for numbers further on
1310 for(unsigned int i=id.size(); i<w4->id.size(); ++i) {
1311 if(!isalpha(w4->id[i])) {
1312 //cout << "SUBSTR is " << (a4->getId()).substr(0, i) << '\n';
1313 return(FindFirstById(w4->id.substr(0, i), multi, exact));
1318 } else if(w1 != w2) { // 0-9 match
1319 //cout << "0-9 match!\n";
1320 if(w1->id.size() - id.size() > 2) {
1321 // Check for numbers further on
1322 for(unsigned int i=id.size(); i<w1->id.size(); ++i) {
1323 if(!isalpha(w1->id[i])) {
1324 //cout << "SUBSTR2 is " << (a4->getId()).substr(0, i) << '\n';
1325 return(FindFirstById(w1->id.substr(0, i), multi, exact));
1330 } else { // No match
1336 // Host specific lookup functions
1337 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1338 FGNavRecord* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact) {
1339 // NOTE - at the moment multi is never set.
1341 //if(exact) return(_overlays->FindFirstVorById(id, exact));
1343 nav_list_type nav = globals->get_navlist()->findFirstByIdent(id, FG_NAV_VOR, exact);
1345 if(nav.size() > 1) multi = true;
1346 //return(nav.empty() ? NULL : *(nav.begin()));
1348 // The above is sort of what we want - unfortunately we can't guarantee no NDB/ILS at the moment
1349 if(nav.empty()) return(NULL);
1351 for(nav_list_iterator it = nav.begin(); it != nav.end(); ++it) {
1352 if((*it)->get_type() == 3) return(*it);
1354 return(NULL); // Shouldn't get here!
1357 Overlays::NAV* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact) {
1358 // NOTE - at the moment multi is never set.
1360 if(exact) return(_overlays->FindFirstVorById(id, exact));
1362 // OK, that was the easy case, now the fuzzy case
1363 Overlays::NAV* n1 = _overlays->FindFirstVorById(id);
1364 if(n1 == NULL) return(n1);
1367 string id3 = id+'0';
1368 string id4 = id+'A';
1369 // Increment the last char to provide the boundary. Note that 'Z' -> '[' but we also need to check '0' for all since GPS has numbers after letters
1370 bool alfa = isalpha(id2[id2.size() - 1]);
1371 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1372 Overlays::NAV* n2 = _overlays->FindFirstVorById(id2);
1373 //Overlays::NAV* n3 = _overlays->FindFirstVorById(id3);
1374 //Overlays::NAV* n4 = _overlays->FindFirstVorById(id4);
1375 //cout << "Strings sent were " << id << ", " << id2 << ", " << id3 << ", " << id4 << '\n';
1379 if(n1 != n2) { // match
1388 // Something matches - the problem is the number/letter preference order is reversed between the GPS and the STL
1390 // There's a letter match - return that
1393 // By definition we must have a number match
1394 if(n3 == n2) cout << "HELP - LOGIC FLAW in find VOR!\n";
1406 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1407 FGNavRecord* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact) {
1408 // NOTE - at the moment multi is never set.
1410 //if(exact) return(_overlays->FindFirstVorById(id, exact));
1412 nav_list_type nav = globals->get_navlist()->findFirstByIdent(id, FG_NAV_NDB, exact);
1414 if(nav.size() > 1) multi = true;
1415 //return(nav.empty() ? NULL : *(nav.begin()));
1417 // The above is sort of what we want - unfortunately we can't guarantee no NDB/ILS at the moment
1418 if(nav.empty()) return(NULL);
1420 for(nav_list_iterator it = nav.begin(); it != nav.end(); ++it) {
1421 if((*it)->get_type() == 2) return(*it);
1423 return(NULL); // Shouldn't get here!
1426 Overlays::NAV* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact) {
1427 // NOTE - at the moment multi is never set.
1429 if(exact) return(_overlays->FindFirstNDBById(id, exact));
1431 // OK, that was the easy case, now the fuzzy case
1432 Overlays::NAV* n1 = _overlays->FindFirstNDBById(id);
1433 if(n1 == NULL) return(n1);
1436 string id3 = id+'0';
1437 string id4 = id+'A';
1438 // Increment the last char to provide the boundary. Note that 'Z' -> '[' but we also need to check '0' for all since GPS has numbers after letters
1439 bool alfa = isalpha(id2[id2.size() - 1]);
1440 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1441 Overlays::NAV* n2 = _overlays->FindFirstNDBById(id2);
1442 //Overlays::NAV* n3 = _overlays->FindFirstNDBById(id3);
1443 //Overlays::NAV* n4 = _overlays->FindFirstNDBById(id4);
1444 //cout << "Strings sent were " << id << ", " << id2 << ", " << id3 << ", " << id4 << '\n';
1448 if(n1 != n2) { // match
1457 // Something matches - the problem is the number/letter preference order is reversed between the GPS and the STL
1459 // There's a letter match - return that
1462 // By definition we must have a number match
1463 if(n3 == n2) cout << "HELP - LOGIC FLAW in find VOR!\n";
1475 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1476 const FGFix* DCLGPS::FindFirstIntById(const string& id, bool &multi, bool exact) {
1477 // NOTE - at the moment multi is never set, and indeed can't be
1478 // since FG can only map one Fix per ID at the moment.
1480 if(exact) return(globals->get_fixlist()->findFirstByIdent(id, exact));
1482 const FGFix* f1 = globals->get_fixlist()->findFirstByIdent(id, exact);
1483 if(f1 == NULL) return(f1);
1485 // The non-trivial code from here to the end of the function is all to deal with the fact that
1486 // the KLN89 alphabetical order (numbers AFTER letters) differs from ASCII order (numbers BEFORE letters).
1487 // It is copied from the airport version which is definately needed, but at present I'm not actually
1488 // sure if any fixes in FG or real-life have numbers in them!
1490 //string id3 = id+'0';
1491 string id4 = id+'A';
1492 // Increment the last char to provide the boundary. Note that 'Z' -> '[' but we also need to check '0' for all since GPS has numbers after letters
1493 //bool alfa = isalpha(id2[id2.size() - 1]);
1494 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1495 const FGFix* f2 = globals->get_fixlist()->findFirstByIdent(id2);
1496 //const FGFix* a3 = globals->get_fixlist()->findFirstByIdent(id3);
1497 const FGFix* f4 = globals->get_fixlist()->findFirstByIdent(id4);
1499 // TODO - the below handles the imediately following char OK
1500 // eg id = "KD" returns "KDAA" instead of "KD5"
1501 // but it doesn't handle numbers / letters further down the string,
1502 // eg - id = "I" returns "IA01" instead of "IAN"
1503 // We either need to provide a custom comparison operator, or recurse this function if !isalpha further down the string.
1504 // (Currenly fixed with recursion).
1506 if(f4 != f2) { // A-Z match - preferred
1507 //cout << "A-Z match!\n";
1508 if(f4->get_ident().size() - id.size() > 2) {
1509 // Check for numbers further on
1510 for(unsigned int i=id.size(); i<f4->get_ident().size(); ++i) {
1511 if(!isalpha(f4->get_ident()[i])) {
1512 //cout << "SUBSTR is " << (a4->getId()).substr(0, i) << '\n';
1513 return(FindFirstIntById(f4->get_ident().substr(0, i), multi, exact));
1518 } else if(f1 != f2) { // 0-9 match
1519 //cout << "0-9 match!\n";
1520 if(f1->get_ident().size() - id.size() > 2) {
1521 // Check for numbers further on
1522 for(unsigned int i=id.size(); i<f1->get_ident().size(); ++i) {
1523 if(!isalpha(f1->get_ident()[i])) {
1524 //cout << "SUBSTR2 is " << (a4->getId()).substr(0, i) << '\n';
1525 return(FindFirstIntById(f1->get_ident().substr(0, i), multi, exact));
1530 } else { // No match
1534 return NULL; // Don't think we can ever get here.
1537 const FGAirport* DCLGPS::FindFirstAptById(const string& id, bool &multi, bool exact) {
1538 // NOTE - at the moment multi is never set.
1539 //cout << "FindFirstAptById, id = " << id << '\n';
1541 if(exact) return(globals->get_airports()->findFirstById(id, exact));
1543 // OK, that was the easy case, now the fuzzy case
1544 const FGAirport* a1 = globals->get_airports()->findFirstById(id);
1545 if(a1 == NULL) return(a1);
1547 // The non-trivial code from here to the end of the function is all to deal with the fact that
1548 // the KLN89 alphabetical order (numbers AFTER letters) differs from ASCII order (numbers BEFORE letters).
1550 //string id3 = id+'0';
1551 string id4 = id+'A';
1552 // Increment the last char to provide the boundary. Note that 'Z' -> '[' but we also need to check '0' for all since GPS has numbers after letters
1553 //bool alfa = isalpha(id2[id2.size() - 1]);
1554 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1555 const FGAirport* a2 = globals->get_airports()->findFirstById(id2);
1556 //FGAirport* a3 = globals->get_airports()->findFirstById(id3);
1557 const FGAirport* a4 = globals->get_airports()->findFirstById(id4);
1558 //cout << "Strings sent were " << id << ", " << id2 << " and " << id4 << '\n';
1559 //cout << "Airports returned were (a1, a2, a4): " << a1->getId() << ", " << a2->getId() << ", " << a4->getId() << '\n';
1560 //cout << "Pointers were " << a1 << ", " << a2 << ", " << a4 << '\n';
1562 // TODO - the below handles the imediately following char OK
1563 // eg id = "KD" returns "KDAA" instead of "KD5"
1564 // but it doesn't handle numbers / letters further down the string,
1565 // eg - id = "I" returns "IA01" instead of "IAN"
1566 // We either need to provide a custom comparison operator, or recurse this function if !isalpha further down the string.
1567 // (Currenly fixed with recursion).
1569 if(a4 != a2) { // A-Z match - preferred
1570 //cout << "A-Z match!\n";
1571 if(a4->getId().size() - id.size() > 2) {
1572 // Check for numbers further on
1573 for(unsigned int i=id.size(); i<a4->getId().size(); ++i) {
1574 if(!isalpha(a4->getId()[i])) {
1575 //cout << "SUBSTR is " << (a4->getId()).substr(0, i) << '\n';
1576 return(FindFirstAptById(a4->getId().substr(0, i), multi, exact));
1581 } else if(a1 != a2) { // 0-9 match
1582 //cout << "0-9 match!\n";
1583 if(a1->getId().size() - id.size() > 2) {
1584 // Check for numbers further on
1585 for(unsigned int i=id.size(); i<a1->getId().size(); ++i) {
1586 if(!isalpha(a1->getId()[i])) {
1587 //cout << "SUBSTR2 is " << (a4->getId()).substr(0, i) << '\n';
1588 return(FindFirstAptById(a1->getId().substr(0, i), multi, exact));
1593 } else { // No match
1600 FGNavRecord* DCLGPS::FindClosestVor(double lat_rad, double lon_rad) {
1601 return(globals->get_navlist()->findClosest(lon_rad, lat_rad, 0.0, FG_NAV_VOR));
1604 //----------------------------------------------------------------------------------------------------------
1606 // Takes lat and lon in RADIANS!!!!!!!
1607 double DCLGPS::GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB) {
1608 double h = GetGreatCircleCourse(latA, lonA, latB, lonB);
1609 h *= SG_RADIANS_TO_DEGREES;
1610 // TODO - use the real altitude below instead of 0.0!
1611 //cout << "MagVar = " << sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES << '\n';
1612 h -= sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1613 while(h >= 360.0) h -= 360.0;
1614 while(h < 0.0) h += 360.0;
1618 // ---------------- Great Circle formulae from "The Aviation Formulary" -------------
1619 // Note that all of these assume that the world is spherical.
1621 double Rad2Nm(double theta) {
1622 return(((180.0*60.0)/SG_PI)*theta);
1625 double Nm2Rad(double d) {
1626 return((SG_PI/(180.0*60.0))*d);
1631 The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
1633 d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
1635 A mathematically equivalent formula, which is less subject to rounding error for short distances is:
1637 d=2*asin(sqrt((sin((lat1-lat2)/2))^2 +
1638 cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
1642 // Returns distance in nm, takes lat & lon in RADIANS
1643 double DCLGPS::GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const {
1644 double d = 2.0 * asin(sqrt(((sin((lat1-lat2)/2.0))*(sin((lat1-lat2)/2.0))) +
1645 cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2.0))*(sin((lon1-lon2)/2.0))));
1649 // fmod dosen't do what we want :-(
1650 static double mod(double d1, double d2) {
1651 return(d1 - d2*floor(d1/d2));
1654 // Returns great circle course from point 1 to point 2
1655 // Input and output in RADIANS.
1656 double DCLGPS::GetGreatCircleCourse (double lat1, double lon1, double lat2, double lon2) const {
1659 // Special case the poles
1660 if(cos(lat1) < SG_EPSILON) {
1662 // Starting from North Pole
1665 // Starting from South Pole
1669 // Urgh - the formula below is for negative lon +ve !!!???
1670 double d = GetGreatCircleDistance(lat1, lon1, lat2, lon2);
1671 cout << "d = " << d;
1673 //cout << ", d_theta = " << d;
1674 //cout << ", and d = " << Rad2Nm(d) << ' ';
1675 if(sin(lon2 - lon1) < 0) {
1677 h = acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1680 h = 2.0 * SG_PI - acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1683 cout << h * SG_RADIANS_TO_DEGREES << '\n';
1686 return( mod(atan2(sin(lon2-lon1)*cos(lat2),
1687 cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)),
1691 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
1692 // Note that d should be less that 1/4 Earth diameter!
1693 GPSWaypoint DCLGPS::GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h) {
1694 h += sgGetMagVar(wp1.lon, wp1.lat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1695 return(GetPositionOnRadial(wp1, d, h));
1698 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
1699 // Note that d should be less that 1/4 Earth diameter!
1700 GPSWaypoint DCLGPS::GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h) {
1701 while(h < 0.0) h += 360.0;
1702 while(h > 360.0) h -= 360.0;
1704 h *= SG_DEGREES_TO_RADIANS;
1705 d *= (SG_PI / (180.0 * 60.0));
1707 double lat=asin(sin(wp1.lat)*cos(d)+cos(wp1.lat)*sin(d)*cos(h));
1710 lon=wp1.lon; // endpoint a pole
1712 lon=mod(wp1.lon+asin(sin(h)*sin(d)/cos(lat))+SG_PI,2*SG_PI)-SG_PI;
1718 wp.type = GPS_WP_VIRT;
1722 // Returns cross-track deviation in Nm.
1723 double DCLGPS::CalcCrossTrackDeviation() const {
1724 return(CalcCrossTrackDeviation(_fromWaypoint, _activeWaypoint));
1727 // Returns cross-track deviation of the current position between two arbitary waypoints in nm.
1728 double DCLGPS::CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const {
1729 //if(wp1 == NULL || wp2 == NULL) return(0.0);
1730 if(wp1.id.empty() || wp2.id.empty()) return(0.0);
1731 double xtd = asin(sin(Nm2Rad(GetGreatCircleDistance(wp1.lat, wp1.lon, _gpsLat, _gpsLon)))
1732 * sin(GetGreatCircleCourse(wp1.lat, wp1.lon, _gpsLat, _gpsLon) - GetGreatCircleCourse(wp1.lat, wp1.lon, wp2.lat, wp2.lon)));
1733 return(Rad2Nm(xtd));