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., 675 Mass Ave, Cambridge, MA 02139, 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);
568 wp->appType = GPS_IAF;
569 iap->_IAF.push_back(wp);
571 wp = new GPSWaypoint;
573 fp = FindFirstById(wp->id, multi, true);
575 wp->appType = GPS_IAF;
576 iap->_IAF.push_back(wp);
578 wp = new GPSWaypoint;
580 fp = FindFirstById(wp->id, multi, true);
582 wp->appType = GPS_IAP;
583 iap->_IAP.push_back(wp);
585 wp = new GPSWaypoint;
587 fp = FindFirstById(wp->id, multi, true);
589 wp->appType = GPS_FAF;
590 iap->_IAP.push_back(wp);
592 wp = new GPSWaypoint;
594 wp->appType = GPS_MAP;
595 if(wp->id.substr(0, 2) == "RW" && wp->appType == GPS_MAP) {
596 // Assume that this is a missed-approach point based on the runway number
597 // TODO: Get the runway threshold location etc
598 cout << "TODO - implement missed-approach point based on rwy no.\n";
600 fp = FindFirstById(wp->id, multi, true);
602 cout << "Failed to find waypoint " << wp->id << " in database...\n";
605 wp->appType = GPS_MAP;
608 iap->_IAP.push_back(wp);
610 wp = new GPSWaypoint;
612 fp = FindFirstById(wp->id, multi, true);
614 wp->appType = GPS_MAHP;
615 iap->_MAP.push_back(wp);
617 _np_iap[iap->_id].push_back(iap);
620 void DCLGPS::bind() {
621 fgTie("/instrumentation/gps/waypoint-alert", this, &DCLGPS::GetWaypointAlert);
622 fgTie("/instrumentation/gps/leg-mode", this, &DCLGPS::GetLegMode);
623 fgTie("/instrumentation/gps/obs-mode", this, &DCLGPS::GetOBSMode);
624 fgTie("/instrumentation/gps/approach-arm", this, &DCLGPS::GetApproachArm);
625 fgTie("/instrumentation/gps/approach-active", this, &DCLGPS::GetApproachActive);
626 fgTie("/instrumentation/gps/cdi-deflection", this, &DCLGPS::GetCDIDeflection);
627 fgTie("/instrumentation/gps/to-flag", this, &DCLGPS::GetToFlag);
630 void DCLGPS::unbind() {
631 fgUntie("/instrumentation/gps/waypoint-alert");
632 fgUntie("/instrumentation/gps/leg-mode");
633 fgUntie("/instrumentation/gps/obs-mode");
634 fgUntie("/instrumentation/gps/approach-arm");
635 fgUntie("/instrumentation/gps/approach-active");
636 fgUntie("/instrumentation/gps/cdi-deflection");
639 void DCLGPS::update(double dt) {
640 //cout << "update called!\n";
642 _lon = _lon_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
643 _lat = _lat_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
644 _alt = _alt_node->getDoubleValue();
645 _groundSpeed_kts = _grnd_speed_node->getDoubleValue();
646 _groundSpeed_ms = _groundSpeed_kts * 0.5144444444;
647 _track = _true_track_node->getDoubleValue();
648 _magTrackDeg = _mag_track_node->getDoubleValue();
649 // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
650 // gps code and not our own.
653 // Check for abnormal position slew
654 if(GetGreatCircleDistance(_gpsLat, _gpsLon, _checkLat, _checkLon) > 1.0) {
655 OrientateToActiveFlightPlan();
661 if(_groundSpeed_kts > 30.0) {
663 string th = fgGetString("/instrumentation/clock/indicated-hour");
664 string tm = fgGetString("/instrumentation/clock/indicated-min");
665 if(th.size() == 1) th = "0" + th;
666 if(tm.size() == 1) tm = "0" + tm;
667 _departureTimeString = th + tm;
670 // TODO - check - is this prone to drift error over time?
671 // Should we difference the departure and current times?
672 // What about when the user resets the time of day from the menu?
676 _time->update(_gpsLon * SG_DEGREES_TO_RADIANS, _gpsLat * SG_DEGREES_TO_RADIANS, 0, 0);
677 // FIXME - currently all the below assumes leg mode and no DTO or OBS cancelled.
678 if(_activeFP->IsEmpty()) {
679 // Not sure if we need to reset these each update or only when fp altered
680 _activeWaypoint.id.clear();
682 } else if(_activeFP->waypoints.size() == 1) {
683 _activeWaypoint.id.clear();
686 if(_activeWaypoint.id.empty() || _fromWaypoint.id.empty()) {
687 //cout << "Error, in leg mode with flightplan of 2 or more waypoints, but either active or from wp is NULL!\n";
688 OrientateToActiveFlightPlan();
692 if(_approachLoaded) {
693 if(!_approachReallyArmed && !_approachActive) {
694 // arm if within 30nm of airport.
695 // TODO - let user cancel approach arm using external GPS-APR switch
697 const FGAirport* ap = FindFirstAptById(_approachID, multi, true);
699 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, ap->getLatitude() * SG_DEGREES_TO_RADIANS, ap->getLongitude() * SG_DEGREES_TO_RADIANS);
702 _approachReallyArmed = true;
703 _messageStack.push_back("*Press ALT To Set Baro");
704 // Not sure what we do if the user has already set CDI to 0.3 nm?
705 _targetCdiScaleIndex = 1;
706 if(_currentCdiScaleIndex == 1) {
708 } else if(_currentCdiScaleIndex == 0) {
709 _sourceCdiScaleIndex = 0;
710 _cdiScaleTransition = true;
711 _cdiTransitionTime = 30.0;
712 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
717 // Check for approach active - we can only activate approach if it is really armed.
718 if(_activeWaypoint.appType == GPS_FAF) {
719 //cout << "Active waypoint is FAF, id is " << _activeWaypoint.id << '\n';
720 if(GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) <= 2.0 && !_obsMode) {
721 // Assume heading is OK for now
722 _approachArm = false; // TODO - check - maybe arm is left on when actv comes on?
723 _approachReallyArmed = false;
724 _approachActive = true;
725 _targetCdiScaleIndex = 2;
726 if(_currentCdiScaleIndex == 2) {
728 } else if(_currentCdiScaleIndex == 1) {
729 _sourceCdiScaleIndex = 1;
730 _cdiScaleTransition = true;
731 _cdiTransitionTime = 30.0; // TODO - compress it if time to FAF < 30sec
732 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
734 // Abort going active?
735 _approachActive = false;
742 // CDI scale transition stuff
743 if(_cdiScaleTransition) {
744 if(fabs(_currentCdiScale - _cdiScales[_targetCdiScaleIndex]) < 0.001) {
745 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
746 _currentCdiScaleIndex = _targetCdiScaleIndex;
747 _cdiScaleTransition = false;
749 double scaleDiff = (_targetCdiScaleIndex > _sourceCdiScaleIndex
750 ? _cdiScales[_sourceCdiScaleIndex] - _cdiScales[_targetCdiScaleIndex]
751 : _cdiScales[_targetCdiScaleIndex] - _cdiScales[_sourceCdiScaleIndex]);
752 //cout << "ScaleDiff = " << scaleDiff << '\n';
753 if(_targetCdiScaleIndex > _sourceCdiScaleIndex) {
754 // Scaling down eg. 5nm -> 1nm
755 _currentCdiScale -= (scaleDiff * dt / _cdiTransitionTime);
756 if(_currentCdiScale < _cdiScales[_targetCdiScaleIndex]) {
757 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
758 _currentCdiScaleIndex = _targetCdiScaleIndex;
759 _cdiScaleTransition = false;
762 _currentCdiScale += (scaleDiff * dt / _cdiTransitionTime);
763 if(_currentCdiScale > _cdiScales[_targetCdiScaleIndex]) {
764 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
765 _currentCdiScaleIndex = _targetCdiScaleIndex;
766 _cdiScaleTransition = false;
769 //cout << "_currentCdiScale = " << _currentCdiScale << '\n';
772 _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
776 // Urgh - I've been setting the heading bug based on DTK,
777 // bug I think it should be based on heading re. active waypoint
778 // based on what the sim does after the final waypoint is passed.
779 // (DTK remains the same, but if track is held == DTK heading bug
780 // reverses to from once wp is passed).
782 if(_fromWaypoint != NULL) {
783 // TODO - how do we handle the change of track with distance over long legs?
784 _dtkTrue = GetGreatCircleCourse(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon) * SG_RADIANS_TO_DEGREES;
785 _dtkMag = GetMagHeadingFromTo(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon);
786 // Don't change the heading bug if speed is too low otherwise it flickers to/from at rest
787 if(_groundSpeed_ms > 5) {
788 //cout << "track = " << _track << ", dtk = " << _dtkTrue << '\n';
789 double courseDev = _track - _dtkTrue;
790 //cout << "courseDev = " << courseDev << ", normalized = ";
791 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
792 //cout << courseDev << '\n';
793 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
798 // TODO - in DTO operation the position of initiation of DTO defines the "from waypoint".
801 if(!_activeWaypoint.id.empty()) {
802 double hdgTrue = GetGreatCircleCourse(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
803 if(_groundSpeed_ms > 5) {
804 //cout << "track = " << _track << ", hdgTrue = " << hdgTrue << '\n';
805 double courseDev = _track - hdgTrue;
806 //cout << "courseDev = " << courseDev << ", normalized = ";
807 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
808 //cout << courseDev << '\n';
809 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
811 if(!_fromWaypoint.id.empty()) {
812 _dtkTrue = GetGreatCircleCourse(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
813 _dtkMag = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
820 _dist2Act = GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_NM_TO_METER;
821 if(_groundSpeed_ms > 10.0) {
822 _eta = _dist2Act / _groundSpeed_ms;
823 if(_eta <= 36) { // TODO - this is slightly different if turn anticipation is enabled.
825 _waypointAlert = true; // TODO - not if the from flag is set.
829 // Check if we should sequence to next leg.
830 // Perhaps this should be done on distance instead, but 60s time (about 1 - 2 nm) seems reasonable for now.
831 //double reverseHeading = GetGreatCircleCourse(_activeWaypoint->lat, _activeWaypoint->lon, _fromWaypoint->lat, _fromWaypoint->lon);
832 // Hack - let's cheat and do it on heading bug for now. TODO - that stops us 'cutting the corner'
833 // when we happen to approach the inside turn of a waypoint - we should probably sequence at the midpoint
834 // of the heading difference between legs in this instance.
835 int idx = GetActiveWaypointIndex();
836 bool finalLeg = (idx == (int)(_activeFP->waypoints.size()) - 1 ? true : false);
837 bool finalDto = (_dto && idx == -1); // Dto operation to a waypoint not in the flightplan - we don't sequence in this instance
840 // Do nothing - not sure if Dto should switch off when arriving at the final waypoint of a flightplan
841 } else if(finalDto) {
843 } else if(_activeWaypoint.appType == GPS_MAP) {
844 // Don't sequence beyond the missed approach point
845 cout << "ACTIVE WAYPOINT is MAP - not sequencing!!!!!\n";
847 cout << "Sequencing...\n";
848 _fromWaypoint = _activeWaypoint;
849 _activeWaypoint = *_activeFP->waypoints[idx + 1];
851 // TODO - course alteration message format is dependent on whether we are slaved HSI/CDI indicator or not.
852 // For now assume we are not.
854 if(fgGetBool("/instrumentation/nav[0]/slaved-to-gps")) {
855 // TODO - avoid the hardwiring on nav[0]
856 s = "Adj Nav Crs to ";
858 string s = "GPS Course is ";
860 double d = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
861 while(d < 0.0) d += 360.0;
862 while(d >= 360.0) d -= 360.0;
864 snprintf(buf, 4, "%03i", (int)(d + 0.5));
866 _messageStack.push_back(s);
868 _waypointAlert = false;
876 // First attempt at a sensible cross-track correction calculation
877 // Uh? - I think this is implemented further down the file!
878 if(_fromWaypoint != NULL) {
881 _crosstrackDist = 0.0;
887 double DCLGPS::GetCDIDeflection() const {
888 double xtd = CalcCrossTrackDeviation(); //nm
889 return((xtd / _currentCdiScale) * 5.0 * 2.5 * -1.0);
892 void DCLGPS::DtoInitiate(const string& s) {
893 cout << "DtoInitiate, s = " << s << '\n';
895 const GPSWaypoint* wp = FindFirstById(s, multi, true);
897 cout << "Waypoint found, starting dto operation!\n";
899 _activeWaypoint = *wp;
900 _fromWaypoint.lat = _gpsLat;
901 _fromWaypoint.lon = _gpsLon;
902 _fromWaypoint.type = GPS_WP_VIRT;
903 _fromWaypoint.id = "DTOWP";
905 cout << "Waypoint not found, ignoring dto request\n";
906 // Should bring up the user waypoint page, but we're not implementing that yet.
907 _dto = false; // TODO - implement this some day.
911 void DCLGPS::DtoCancel() {
913 // i.e. don't bother reorientating if we're just cancelling a DTO button press
914 // without having previously initiated DTO.
915 OrientateToActiveFlightPlan();
920 void DCLGPS::Knob1Left1() {}
921 void DCLGPS::Knob1Right1() {}
922 void DCLGPS::Knob2Left1() {}
923 void DCLGPS::Knob2Right1() {}
924 void DCLGPS::CrsrPressed() { _activePage->CrsrPressed(); }
925 void DCLGPS::EntPressed() { _activePage->EntPressed(); }
926 void DCLGPS::ClrPressed() { _activePage->ClrPressed(); }
927 void DCLGPS::DtoPressed() {}
928 void DCLGPS::NrstPressed() {}
929 void DCLGPS::AltPressed() {}
931 void DCLGPS::OBSPressed() {
932 _obsMode = !_obsMode;
934 if(!_activeWaypoint.id.empty()) {
935 _obsHeading = _dtkMag;
937 // TODO - the _fromWaypoint location will change as the OBS heading changes.
938 // Might need to store the OBS initiation position somewhere in case it is needed again.
939 SetOBSFromWaypoint();
943 // Set the _fromWaypoint position based on the active waypoint and OBS radial.
944 void DCLGPS::SetOBSFromWaypoint() {
945 if(!_obsMode) return;
946 if(_activeWaypoint.id.empty()) return;
948 // TODO - base the 180 deg correction on the to/from flag.
949 _fromWaypoint = GetPositionOnMagRadial(_activeWaypoint, 10, _obsHeading + 180.0);
950 _fromWaypoint.id = "OBSWP";
953 void DCLGPS::MsgPressed() {}
955 void DCLGPS::CDIFSDIncrease() {
956 if(_currentCdiScaleIndex == 0) {
957 _currentCdiScaleIndex = _cdiScales.size() - 1;
959 _currentCdiScaleIndex--;
963 void DCLGPS::CDIFSDDecrease() {
964 _currentCdiScaleIndex++;
965 if(_currentCdiScaleIndex == _cdiScales.size()) {
966 _currentCdiScaleIndex = 0;
970 void DCLGPS::DrawChar(char c, int field, int px, int py, bool bold) {
973 void DCLGPS::DrawText(const string& s, int field, int px, int py, bool bold) {
976 void DCLGPS::SetBaroUnits(int n, bool wrap) {
978 _baroUnits = (GPSPressureUnits)(wrap ? 3 : 1);
980 _baroUnits = (GPSPressureUnits)(wrap ? 1 : 3);
982 _baroUnits = (GPSPressureUnits)n;
986 void DCLGPS::CreateDefaultFlightPlans() {}
988 // Get the time to the active waypoint in seconds.
989 // Returns -1 if groundspeed < 30 kts
990 double DCLGPS::GetTimeToActiveWaypoint() {
991 if(_groundSpeed_kts < 30.0) {
998 // Get the time to the final waypoint in seconds.
999 // Returns -1 if groundspeed < 30 kts
1000 double DCLGPS::GetETE() {
1001 if(_groundSpeed_kts < 30.0) {
1004 // TODO - handle OBS / DTO operation appropriately
1005 if(_activeFP->waypoints.empty()) {
1008 return(GetTimeToWaypoint(_activeFP->waypoints[_activeFP->waypoints.size() - 1]->id));
1013 // Get the time to a given waypoint (spec'd by ID) in seconds.
1014 // returns -1 if groundspeed is less than 30kts.
1015 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
1016 // otherwise it will be a direct-to time.
1017 double DCLGPS::GetTimeToWaypoint(const string& id) {
1018 if(_groundSpeed_kts < 30.0) {
1023 int n1 = GetActiveWaypointIndex();
1024 int n2 = GetWaypointIndex(id);
1027 for(unsigned int i=n1+1; i<_activeFP->waypoints.size(); ++i) {
1028 GPSWaypoint* wp1 = _activeFP->waypoints[i-1];
1029 GPSWaypoint* wp2 = _activeFP->waypoints[i];
1030 double distm = GetGreatCircleDistance(wp1->lat, wp1->lon, wp2->lat, wp2->lon) * SG_NM_TO_METER;
1031 eta += (distm / _groundSpeed_ms);
1034 } else if(id == _activeWaypoint.id) {
1038 const GPSWaypoint* wp = FindFirstById(id, multi, true);
1039 if(wp == NULL) return(-1.0);
1040 double distm = GetGreatCircleDistance(_gpsLat, _gpsLon, wp->lat, wp->lon);
1041 return(distm / _groundSpeed_ms);
1043 return(-1.0); // Hopefully we never get here!
1046 // Returns magnetic great-circle heading
1047 // TODO - document units.
1048 float DCLGPS::GetHeadingToActiveWaypoint() {
1049 if(_activeWaypoint.id.empty()) {
1052 double h = GetMagHeadingFromTo(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon);
1053 while(h <= 0.0) h += 360.0;
1054 while(h > 360.0) h -= 360.0;
1059 // Returns magnetic great-circle heading
1060 // TODO - what units?
1061 float DCLGPS::GetHeadingFromActiveWaypoint() {
1062 if(_activeWaypoint.id.empty()) {
1065 double h = GetMagHeadingFromTo(_activeWaypoint.lat, _activeWaypoint.lon, _gpsLat, _gpsLon);
1066 while(h <= 0.0) h += 360.0;
1067 while(h > 360.0) h -= 360.0;
1072 void DCLGPS::ClearFlightPlan(int n) {
1073 for(unsigned int i=0; i<_flightPlans[n]->waypoints.size(); ++i) {
1074 delete _flightPlans[n]->waypoints[i];
1076 _flightPlans[n]->waypoints.clear();
1079 void DCLGPS::ClearFlightPlan(GPSFlightPlan* fp) {
1080 for(unsigned int i=0; i<fp->waypoints.size(); ++i) {
1081 delete fp->waypoints[i];
1083 fp->waypoints.clear();
1086 int DCLGPS::GetActiveWaypointIndex() {
1087 for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
1088 if(_flightPlans[0]->waypoints[i]->id == _activeWaypoint.id) return((int)i);
1093 int DCLGPS::GetWaypointIndex(const string& id) {
1094 for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
1095 if(_flightPlans[0]->waypoints[i]->id == id) return((int)i);
1100 void DCLGPS::OrientateToFlightPlan(GPSFlightPlan* fp) {
1101 //cout << "Orientating...\n";
1102 //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n';
1104 _activeWaypoint.id.clear();
1107 _navFlagged = false;
1108 if(fp->waypoints.size() == 1) {
1109 // TODO - may need to flag nav here if not dto or obs, or possibly handle it somewhere else.
1110 _activeWaypoint = *fp->waypoints[0];
1111 _fromWaypoint.id.clear();
1113 // FIXME FIXME FIXME
1114 _fromWaypoint = *fp->waypoints[0];
1115 _activeWaypoint = *fp->waypoints[1];
1116 double dmin = 1000000; // nm!!
1117 // For now we will simply start on the leg closest to our current position.
1118 // It's possible that more fancy algorithms may take either heading or track
1119 // into account when setting inital leg - I'm not sure.
1120 // This method should handle most cases perfectly OK though.
1121 for(unsigned int i = 1; i < fp->waypoints.size(); ++i) {
1122 //cout << "Pass " << i << ", dmin = " << dmin << ", leg is " << fp->waypoints[i-1]->id << " to " << fp->waypoints[i]->id << '\n';
1123 // First get the cross track correction.
1124 double d0 = fabs(CalcCrossTrackDeviation(*fp->waypoints[i-1], *fp->waypoints[i]));
1125 // That is the shortest distance away we could be though - check for
1126 // longer distances if we are 'off the end' of the leg.
1127 double ht1 = GetGreatCircleCourse(fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon,
1128 fp->waypoints[i]->lat, fp->waypoints[i]->lon)
1129 * SG_RADIANS_TO_DEGREES;
1130 // not simply the reverse of the above due to great circle navigation.
1131 double ht2 = GetGreatCircleCourse(fp->waypoints[i]->lat, fp->waypoints[i]->lon,
1132 fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
1133 * SG_RADIANS_TO_DEGREES;
1134 double hw1 = GetGreatCircleCourse(_gpsLat, _gpsLon,
1135 fp->waypoints[i]->lat, fp->waypoints[i]->lon)
1136 * SG_RADIANS_TO_DEGREES;
1137 double hw2 = GetGreatCircleCourse(_gpsLat, _gpsLon,
1138 fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon)
1139 * SG_RADIANS_TO_DEGREES;
1140 double h1 = ht1 - hw1;
1141 double h2 = ht2 - hw2;
1142 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
1143 //cout << "Normalizing...\n";
1144 SG_NORMALIZE_RANGE(h1, -180.0, 180.0);
1145 SG_NORMALIZE_RANGE(h2, -180.0, 180.0);
1146 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
1147 if(fabs(h1) > 90.0) {
1148 // We are past the end of the to waypoint
1149 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i]->lat, fp->waypoints[i]->lon);
1151 //cout << "h1 triggered, d0 now = " << d0 << '\n';
1152 } else if(fabs(h2) > 90.0) {
1153 // We are past the end (not yet at!) the from waypoint
1154 double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon);
1156 //cout << "h2 triggered, d0 now = " << d0 << '\n';
1159 //cout << "THIS LEG NOW ACTIVE!\n";
1161 _fromWaypoint = *fp->waypoints[i-1];
1162 _activeWaypoint = *fp->waypoints[i];
1169 void DCLGPS::OrientateToActiveFlightPlan() {
1170 OrientateToFlightPlan(_activeFP);
1173 /***************************************/
1175 // Utility function - create a flightplan from a list of waypoint ids and types
1176 void DCLGPS::CreateFlightPlan(GPSFlightPlan* fp, vector<string> ids, vector<GPSWpType> wps) {
1177 if(fp == NULL) fp = new GPSFlightPlan;
1179 if(!fp->waypoints.empty()) {
1180 for(i=0; i<fp->waypoints.size(); ++i) {
1181 delete fp->waypoints[i];
1183 fp->waypoints.clear();
1185 if(ids.size() != wps.size()) {
1186 cout << "ID and Waypoint types list size mismatch in GPS::CreateFlightPlan - no flightplan created!\n";
1189 for(i=0; i<ids.size(); ++i) {
1191 const FGAirport* ap;
1193 GPSWaypoint* wp = new GPSWaypoint;
1197 ap = FindFirstAptById(ids[i], multi, true);
1202 wp->lat = ap->getLatitude() * SG_DEGREES_TO_RADIANS;
1203 wp->lon = ap->getLongitude() * SG_DEGREES_TO_RADIANS;
1205 fp->waypoints.push_back(wp);
1209 np = FindFirstVorById(ids[i], multi, true);
1214 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1215 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1217 fp->waypoints.push_back(wp);
1221 np = FindFirstNDBById(ids[i], multi, true);
1226 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1227 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1229 fp->waypoints.push_back(wp);
1242 /***************************************/
1244 const GPSWaypoint* DCLGPS::ActualFindFirstById(const string& id, bool exact) {
1245 gps_waypoint_map_const_iterator itr;
1247 itr = _waypoints.find(id);
1249 itr = _waypoints.lower_bound(id);
1251 if(itr == _waypoints.end()) {
1254 // TODO - don't just return the first one - either return all or the nearest one.
1255 return((itr->second)[0]);
1259 const GPSWaypoint* DCLGPS::FindFirstById(const string& id, bool &multi, bool exact) {
1261 if(exact) return(ActualFindFirstById(id, exact));
1263 // OK, that was the easy case, now the fuzzy case
1264 const GPSWaypoint* w1 = ActualFindFirstById(id);
1265 if(w1 == NULL) return(w1);
1267 // The non-trivial code from here to the end of the function is all to deal with the fact that
1268 // the KLN89 alphabetical order (numbers AFTER letters) differs from ASCII order (numbers BEFORE letters).
1270 //string id3 = id+'0';
1271 string id4 = id+'A';
1272 // 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
1273 //bool alfa = isalpha(id2[id2.size() - 1]);
1274 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1275 const GPSWaypoint* w2 = ActualFindFirstById(id2);
1276 //FGAirport* a3 = globals->get_airports()->findFirstById(id3);
1277 const GPSWaypoint* w4 = ActualFindFirstById(id4);
1278 //cout << "Strings sent were " << id << ", " << id2 << " and " << id4 << '\n';
1279 //cout << "Airports returned were (a1, a2, a4): " << a1->getId() << ", " << a2->getId() << ", " << a4->getId() << '\n';
1280 //cout << "Pointers were " << a1 << ", " << a2 << ", " << a4 << '\n';
1282 // TODO - the below handles the imediately following char OK
1283 // eg id = "KD" returns "KDAA" instead of "KD5"
1284 // but it doesn't handle numbers / letters further down the string,
1285 // eg - id = "I" returns "IA01" instead of "IAN"
1286 // We either need to provide a custom comparison operator, or recurse this function if !isalpha further down the string.
1287 // (Currenly fixed with recursion).
1289 if(w4 != w2) { // A-Z match - preferred
1290 //cout << "A-Z match!\n";
1291 if(w4->id.size() - id.size() > 2) {
1292 // Check for numbers further on
1293 for(unsigned int i=id.size(); i<w4->id.size(); ++i) {
1294 if(!isalpha(w4->id[i])) {
1295 //cout << "SUBSTR is " << (a4->getId()).substr(0, i) << '\n';
1296 return(FindFirstById(w4->id.substr(0, i), multi, exact));
1301 } else if(w1 != w2) { // 0-9 match
1302 //cout << "0-9 match!\n";
1303 if(w1->id.size() - id.size() > 2) {
1304 // Check for numbers further on
1305 for(unsigned int i=id.size(); i<w1->id.size(); ++i) {
1306 if(!isalpha(w1->id[i])) {
1307 //cout << "SUBSTR2 is " << (a4->getId()).substr(0, i) << '\n';
1308 return(FindFirstById(w1->id.substr(0, i), multi, exact));
1313 } else { // No match
1319 // Host specific lookup functions
1320 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1321 FGNavRecord* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact) {
1322 // NOTE - at the moment multi is never set.
1324 //if(exact) return(_overlays->FindFirstVorById(id, exact));
1326 nav_list_type nav = globals->get_navlist()->findFirstByIdent(id, FG_NAV_VOR, exact);
1328 if(nav.size() > 1) multi = true;
1329 //return(nav.empty() ? NULL : *(nav.begin()));
1331 // The above is sort of what we want - unfortunately we can't guarantee no NDB/ILS at the moment
1332 if(nav.empty()) return(NULL);
1334 for(nav_list_iterator it = nav.begin(); it != nav.end(); ++it) {
1335 if((*it)->get_type() == 3) return(*it);
1337 return(NULL); // Shouldn't get here!
1340 Overlays::NAV* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact) {
1341 // NOTE - at the moment multi is never set.
1343 if(exact) return(_overlays->FindFirstVorById(id, exact));
1345 // OK, that was the easy case, now the fuzzy case
1346 Overlays::NAV* n1 = _overlays->FindFirstVorById(id);
1347 if(n1 == NULL) return(n1);
1350 string id3 = id+'0';
1351 string id4 = id+'A';
1352 // 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
1353 bool alfa = isalpha(id2[id2.size() - 1]);
1354 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1355 Overlays::NAV* n2 = _overlays->FindFirstVorById(id2);
1356 //Overlays::NAV* n3 = _overlays->FindFirstVorById(id3);
1357 //Overlays::NAV* n4 = _overlays->FindFirstVorById(id4);
1358 //cout << "Strings sent were " << id << ", " << id2 << ", " << id3 << ", " << id4 << '\n';
1362 if(n1 != n2) { // match
1371 // Something matches - the problem is the number/letter preference order is reversed between the GPS and the STL
1373 // There's a letter match - return that
1376 // By definition we must have a number match
1377 if(n3 == n2) cout << "HELP - LOGIC FLAW in find VOR!\n";
1389 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1390 FGNavRecord* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact) {
1391 // NOTE - at the moment multi is never set.
1393 //if(exact) return(_overlays->FindFirstVorById(id, exact));
1395 nav_list_type nav = globals->get_navlist()->findFirstByIdent(id, FG_NAV_NDB, exact);
1397 if(nav.size() > 1) multi = true;
1398 //return(nav.empty() ? NULL : *(nav.begin()));
1400 // The above is sort of what we want - unfortunately we can't guarantee no NDB/ILS at the moment
1401 if(nav.empty()) return(NULL);
1403 for(nav_list_iterator it = nav.begin(); it != nav.end(); ++it) {
1404 if((*it)->get_type() == 2) return(*it);
1406 return(NULL); // Shouldn't get here!
1409 Overlays::NAV* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact) {
1410 // NOTE - at the moment multi is never set.
1412 if(exact) return(_overlays->FindFirstNDBById(id, exact));
1414 // OK, that was the easy case, now the fuzzy case
1415 Overlays::NAV* n1 = _overlays->FindFirstNDBById(id);
1416 if(n1 == NULL) return(n1);
1419 string id3 = id+'0';
1420 string id4 = id+'A';
1421 // 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
1422 bool alfa = isalpha(id2[id2.size() - 1]);
1423 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1424 Overlays::NAV* n2 = _overlays->FindFirstNDBById(id2);
1425 //Overlays::NAV* n3 = _overlays->FindFirstNDBById(id3);
1426 //Overlays::NAV* n4 = _overlays->FindFirstNDBById(id4);
1427 //cout << "Strings sent were " << id << ", " << id2 << ", " << id3 << ", " << id4 << '\n';
1431 if(n1 != n2) { // match
1440 // Something matches - the problem is the number/letter preference order is reversed between the GPS and the STL
1442 // There's a letter match - return that
1445 // By definition we must have a number match
1446 if(n3 == n2) cout << "HELP - LOGIC FLAW in find VOR!\n";
1458 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1459 const FGFix* DCLGPS::FindFirstIntById(const string& id, bool &multi, bool exact) {
1460 // NOTE - at the moment multi is never set, and indeed can't be
1461 // since FG can only map one Fix per ID at the moment.
1463 if(exact) return(globals->get_fixlist()->findFirstByIdent(id, exact));
1465 const FGFix* f1 = globals->get_fixlist()->findFirstByIdent(id, exact);
1466 if(f1 == NULL) return(f1);
1468 // The non-trivial code from here to the end of the function is all to deal with the fact that
1469 // the KLN89 alphabetical order (numbers AFTER letters) differs from ASCII order (numbers BEFORE letters).
1470 // It is copied from the airport version which is definately needed, but at present I'm not actually
1471 // sure if any fixes in FG or real-life have numbers in them!
1473 //string id3 = id+'0';
1474 string id4 = id+'A';
1475 // 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
1476 //bool alfa = isalpha(id2[id2.size() - 1]);
1477 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1478 const FGFix* f2 = globals->get_fixlist()->findFirstByIdent(id2);
1479 //const FGFix* a3 = globals->get_fixlist()->findFirstByIdent(id3);
1480 const FGFix* f4 = globals->get_fixlist()->findFirstByIdent(id4);
1482 // TODO - the below handles the imediately following char OK
1483 // eg id = "KD" returns "KDAA" instead of "KD5"
1484 // but it doesn't handle numbers / letters further down the string,
1485 // eg - id = "I" returns "IA01" instead of "IAN"
1486 // We either need to provide a custom comparison operator, or recurse this function if !isalpha further down the string.
1487 // (Currenly fixed with recursion).
1489 if(f4 != f2) { // A-Z match - preferred
1490 //cout << "A-Z match!\n";
1491 if(f4->get_ident().size() - id.size() > 2) {
1492 // Check for numbers further on
1493 for(unsigned int i=id.size(); i<f4->get_ident().size(); ++i) {
1494 if(!isalpha(f4->get_ident()[i])) {
1495 //cout << "SUBSTR is " << (a4->getId()).substr(0, i) << '\n';
1496 return(FindFirstIntById(f4->get_ident().substr(0, i), multi, exact));
1501 } else if(f1 != f2) { // 0-9 match
1502 //cout << "0-9 match!\n";
1503 if(f1->get_ident().size() - id.size() > 2) {
1504 // Check for numbers further on
1505 for(unsigned int i=id.size(); i<f1->get_ident().size(); ++i) {
1506 if(!isalpha(f1->get_ident()[i])) {
1507 //cout << "SUBSTR2 is " << (a4->getId()).substr(0, i) << '\n';
1508 return(FindFirstIntById(f1->get_ident().substr(0, i), multi, exact));
1513 } else { // No match
1517 return NULL; // Don't think we can ever get here.
1520 const FGAirport* DCLGPS::FindFirstAptById(const string& id, bool &multi, bool exact) {
1521 // NOTE - at the moment multi is never set.
1522 //cout << "FindFirstAptById, id = " << id << '\n';
1524 if(exact) return(globals->get_airports()->findFirstById(id, exact));
1526 // OK, that was the easy case, now the fuzzy case
1527 const FGAirport* a1 = globals->get_airports()->findFirstById(id);
1528 if(a1 == NULL) return(a1);
1530 // The non-trivial code from here to the end of the function is all to deal with the fact that
1531 // the KLN89 alphabetical order (numbers AFTER letters) differs from ASCII order (numbers BEFORE letters).
1533 //string id3 = id+'0';
1534 string id4 = id+'A';
1535 // 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
1536 //bool alfa = isalpha(id2[id2.size() - 1]);
1537 id2[id2.size() - 1] = id2[id2.size() - 1] + 1;
1538 const FGAirport* a2 = globals->get_airports()->findFirstById(id2);
1539 //FGAirport* a3 = globals->get_airports()->findFirstById(id3);
1540 const FGAirport* a4 = globals->get_airports()->findFirstById(id4);
1541 //cout << "Strings sent were " << id << ", " << id2 << " and " << id4 << '\n';
1542 //cout << "Airports returned were (a1, a2, a4): " << a1->getId() << ", " << a2->getId() << ", " << a4->getId() << '\n';
1543 //cout << "Pointers were " << a1 << ", " << a2 << ", " << a4 << '\n';
1545 // TODO - the below handles the imediately following char OK
1546 // eg id = "KD" returns "KDAA" instead of "KD5"
1547 // but it doesn't handle numbers / letters further down the string,
1548 // eg - id = "I" returns "IA01" instead of "IAN"
1549 // We either need to provide a custom comparison operator, or recurse this function if !isalpha further down the string.
1550 // (Currenly fixed with recursion).
1552 if(a4 != a2) { // A-Z match - preferred
1553 //cout << "A-Z match!\n";
1554 if(a4->getId().size() - id.size() > 2) {
1555 // Check for numbers further on
1556 for(unsigned int i=id.size(); i<a4->getId().size(); ++i) {
1557 if(!isalpha(a4->getId()[i])) {
1558 //cout << "SUBSTR is " << (a4->getId()).substr(0, i) << '\n';
1559 return(FindFirstAptById(a4->getId().substr(0, i), multi, exact));
1564 } else if(a1 != a2) { // 0-9 match
1565 //cout << "0-9 match!\n";
1566 if(a1->getId().size() - id.size() > 2) {
1567 // Check for numbers further on
1568 for(unsigned int i=id.size(); i<a1->getId().size(); ++i) {
1569 if(!isalpha(a1->getId()[i])) {
1570 //cout << "SUBSTR2 is " << (a4->getId()).substr(0, i) << '\n';
1571 return(FindFirstAptById(a1->getId().substr(0, i), multi, exact));
1576 } else { // No match
1583 FGNavRecord* DCLGPS::FindClosestVor(double lat_rad, double lon_rad) {
1584 return(globals->get_navlist()->findClosest(lon_rad, lat_rad, 0.0, FG_NAV_VOR));
1587 //----------------------------------------------------------------------------------------------------------
1589 // Takes lat and lon in RADIANS!!!!!!!
1590 double DCLGPS::GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB) {
1591 double h = GetGreatCircleCourse(latA, lonA, latB, lonB);
1592 h *= SG_RADIANS_TO_DEGREES;
1593 // TODO - use the real altitude below instead of 0.0!
1594 //cout << "MagVar = " << sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES << '\n';
1595 h -= sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1596 while(h >= 360.0) h -= 360.0;
1597 while(h < 0.0) h += 360.0;
1601 // ---------------- Great Circle formulae from "The Aviation Formulary" -------------
1602 // Note that all of these assume that the world is spherical.
1604 double Rad2Nm(double theta) {
1605 return(((180.0*60.0)/SG_PI)*theta);
1608 double Nm2Rad(double d) {
1609 return((SG_PI/(180.0*60.0))*d);
1614 The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
1616 d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
1618 A mathematically equivalent formula, which is less subject to rounding error for short distances is:
1620 d=2*asin(sqrt((sin((lat1-lat2)/2))^2 +
1621 cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
1625 // Returns distance in nm, takes lat & lon in RADIANS
1626 double DCLGPS::GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const {
1627 double d = 2.0 * asin(sqrt(((sin((lat1-lat2)/2.0))*(sin((lat1-lat2)/2.0))) +
1628 cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2.0))*(sin((lon1-lon2)/2.0))));
1632 // fmod dosen't do what we want :-(
1633 static double mod(double d1, double d2) {
1634 return(d1 - d2*floor(d1/d2));
1637 // Returns great circle course from point 1 to point 2
1638 // Input and output in RADIANS.
1639 double DCLGPS::GetGreatCircleCourse (double lat1, double lon1, double lat2, double lon2) const {
1642 // Special case the poles
1643 if(cos(lat1) < SG_EPSILON) {
1645 // Starting from North Pole
1648 // Starting from South Pole
1652 // Urgh - the formula below is for negative lon +ve !!!???
1653 double d = GetGreatCircleDistance(lat1, lon1, lat2, lon2);
1654 cout << "d = " << d;
1656 //cout << ", d_theta = " << d;
1657 //cout << ", and d = " << Rad2Nm(d) << ' ';
1658 if(sin(lon2 - lon1) < 0) {
1660 h = acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1663 h = 2.0 * SG_PI - acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1666 cout << h * SG_RADIANS_TO_DEGREES << '\n';
1669 return( mod(atan2(sin(lon2-lon1)*cos(lat2),
1670 cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)),
1674 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
1675 // Note that d should be less that 1/4 Earth diameter!
1676 GPSWaypoint DCLGPS::GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h) {
1677 h += sgGetMagVar(wp1.lon, wp1.lat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1678 return(GetPositionOnRadial(wp1, d, h));
1681 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
1682 // Note that d should be less that 1/4 Earth diameter!
1683 GPSWaypoint DCLGPS::GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h) {
1684 while(h < 0.0) h += 360.0;
1685 while(h > 360.0) h -= 360.0;
1687 h *= SG_DEGREES_TO_RADIANS;
1688 d *= (SG_PI / (180.0 * 60.0));
1690 double lat=asin(sin(wp1.lat)*cos(d)+cos(wp1.lat)*sin(d)*cos(h));
1693 lon=wp1.lon; // endpoint a pole
1695 lon=mod(wp1.lon+asin(sin(h)*sin(d)/cos(lat))+SG_PI,2*SG_PI)-SG_PI;
1701 wp.type = GPS_WP_VIRT;
1705 // Returns cross-track deviation in Nm.
1706 double DCLGPS::CalcCrossTrackDeviation() const {
1707 return(CalcCrossTrackDeviation(_fromWaypoint, _activeWaypoint));
1710 // Returns cross-track deviation of the current position between two arbitary waypoints in nm.
1711 double DCLGPS::CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const {
1712 //if(wp1 == NULL || wp2 == NULL) return(0.0);
1713 if(wp1.id.empty() || wp2.id.empty()) return(0.0);
1714 double xtd = asin(sin(Nm2Rad(GetGreatCircleDistance(wp1.lat, wp1.lon, _gpsLat, _gpsLon)))
1715 * sin(GetGreatCircleCourse(wp1.lat, wp1.lon, _gpsLat, _gpsLon) - GetGreatCircleCourse(wp1.lat, wp1.lon, wp2.lat, wp2.lon)));
1716 return(Rad2Nm(xtd));