]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/dclgps.cxx
d4084136f9a318a6359e7c9cc44b4f7efbd6926b
[flightgear.git] / src / Instrumentation / dclgps.cxx
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.
5 //
6 // Written by David Luff, started 2005.
7 //
8 // Copyright (C) 2005 - David C Luff - david.luff@nottingham.ac.uk
9 //
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.
14 //
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.
19 //
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.
23 //
24 // $Id$
25
26 #include "dclgps.hxx"
27
28 #include <simgear/sg_inlines.h>
29 #include <simgear/structure/commands.hxx>
30 #include <Main/fg_props.hxx>
31 #include <iostream>
32 SG_USING_STD(cout);
33
34 //using namespace std;
35
36 // Command callbacks for FlightGear
37
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");
41         gps->MsgPressed();
42         return(true);
43 }
44
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");
48         gps->OBSPressed();
49         return(true);
50 }
51
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");
55         gps->AltPressed();
56         return(true);
57 }
58
59 static bool do_kln89_nrst_pressed(const SGPropertyNode* arg) {
60         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
61         gps->NrstPressed();
62         return(true);
63 }
64
65 static bool do_kln89_dto_pressed(const SGPropertyNode* arg) {
66         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
67         gps->DtoPressed();
68         return(true);
69 }
70
71 static bool do_kln89_clr_pressed(const SGPropertyNode* arg) {
72         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
73         gps->ClrPressed();
74         return(true);
75 }
76
77 static bool do_kln89_ent_pressed(const SGPropertyNode* arg) {
78         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
79         gps->EntPressed();
80         return(true);
81 }
82
83 static bool do_kln89_crsr_pressed(const SGPropertyNode* arg) {
84         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
85         gps->CrsrPressed();
86         return(true);
87 }
88
89 static bool do_kln89_knob1left1(const SGPropertyNode* arg) {
90         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
91         gps->Knob1Left1();
92         return(true);
93 }
94
95 static bool do_kln89_knob1right1(const SGPropertyNode* arg) {
96         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
97         gps->Knob1Right1();
98         return(true);
99 }
100
101 static bool do_kln89_knob2left1(const SGPropertyNode* arg) {
102         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
103         gps->Knob2Left1();
104         return(true);
105 }
106
107 static bool do_kln89_knob2right1(const SGPropertyNode* arg) {
108         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
109         gps->Knob2Right1();
110         return(true);
111 }
112
113 // End command callbacks
114
115 GPSWaypoint::GPSWaypoint() {
116     appType = GPS_APP_NONE;
117 }
118
119 GPSWaypoint::~GPSWaypoint() {}
120
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');
126         else return(id);
127 }
128
129 ostream& operator << (ostream& os, GPSAppWpType type) {
130         switch(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");
139         }
140         return(os << "ERROR - Unknown switch in GPSAppWpType operator << ");
141 }
142
143 FGIAP::FGIAP() {
144 }
145
146 FGIAP::~FGIAP() {
147 }
148
149 FGNPIAP::FGNPIAP() {
150 }
151
152 FGNPIAP::~FGNPIAP() {
153 }
154
155 GPSPage::GPSPage(DCLGPS* parent) {
156         _parent = parent;
157         _subPage = 0;
158 }
159
160 GPSPage::~GPSPage() {
161 }
162
163 void GPSPage::Update(double dt) {}
164
165 void GPSPage::Knob1Left1() {}
166 void GPSPage::Knob1Right1() {}
167
168 void GPSPage::Knob2Left1() {
169         _parent->_activePage->LooseFocus();
170         _subPage--;
171         if(_subPage < 0) _subPage = _nSubPages - 1;
172 }
173
174 void GPSPage::Knob2Right1() {
175         _parent->_activePage->LooseFocus();
176         _subPage++;
177         if(_subPage >= _nSubPages) _subPage = 0;
178 }
179
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() {}
188
189 string GPSPage::GPSitoa(int n) {
190         char buf[4];
191         // TODO - sanity check n!
192         sprintf(buf, "%i", n);
193         string s = buf;
194         return(s);
195 }
196
197 void GPSPage::CleanUp() {}
198 void GPSPage::LooseFocus() {}
199 void GPSPage::SetId(const string& s) {}
200
201 // ------------------------------------------------------------------------------------- //
202
203 DCLGPS::DCLGPS(RenderArea2D* instrument) {
204         _instrument = instrument;
205         _nFields = 1;
206         _maxFields = 2;
207         _pages.clear();
208         
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;
214
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);
221         
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.
228         _gpsLon = _lon;
229         _gpsLat = _lat;
230         _checkLon = _gpsLon;
231         _checkLat = _gpsLat;
232         _groundSpeed_ms = 0.0;
233         _groundSpeed_kts = 0.0;
234         _track = 0.0;
235         _magTrackDeg = 0.0;
236         
237         // Sensible defaults.  These can be overriden by derived classes if desired.
238         _cdiScales.clear();
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;
247         
248         _cleanUpPage = -1;
249         
250         _activeWaypoint.id.clear();
251         _dist2Act = 0.0;
252         _crosstrackDist = 0.0;
253         _headingBugTo = true;
254         _navFlagged = true;
255         _waypointAlert = false;
256         _departed = false;
257         _departureTimeString = "----";
258         _elapsedTime = 0.0;
259         
260         // Configuration Initialisation
261         // Should this be in kln89.cxx ?
262         _turnAnticipationEnabled = false;
263         _suaAlertEnabled = false;
264         _altAlertEnabled = false;
265         
266         _time = new SGTime;
267         
268         _messageStack.clear();
269         
270         _dto = false;
271         
272         _approachLoaded = false;
273         _approachArm = false;
274         _approachReallyArmed = false;
275         _approachActive = false;
276         _approachFP = new GPSFlightPlan;
277 }
278
279 DCLGPS::~DCLGPS() {
280         delete _time;
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]);
284                 }
285         }
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!!
289 }
290
291 void DCLGPS::draw() {
292         //cout << "draw called!\n";
293         _instrument->draw();
294 }
295
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);
309         
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
313         _waypoints.clear();
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;
318                 w->id = a->getId();
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;
325                         arr.push_back(w);
326                         _waypoints[w->id] = arr;
327                 } else {
328                         wtr->second.push_back(w);
329                 }
330         }
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;
345                                         arr.push_back(w);
346                                         _waypoints[w->id] = arr;
347                                 } else {
348                                         wtr->second.push_back(w);
349                                 }
350                         }
351                 }
352         }
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;
364                         arr.push_back(w);
365                         _waypoints[w->id] = arr;
366                 } else {
367                         wtr->second.push_back(w);
368                 }
369         }
370         // TODO - add USR waypoints as well.
371         
372         // Not sure if this should be here, but OK for now.
373         CreateDefaultFlightPlans();
374         
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;
378         iap->_id = "KHWD";
379         iap->_name = "VOR/DME OR GPS-B";
380         iap->_abbrev = "VOR/D";
381         iap->_rwyStr = "B";
382         iap->_IAF.clear();
383         iap->_IAP.clear();
384         iap->_MAP.clear();
385         // -------
386         GPSWaypoint* wp = new GPSWaypoint;
387         wp->id = "SUNOL";
388         bool multi;
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); 
391         *wp = *fp;
392         wp->appType = GPS_IAF;
393         iap->_IAF.push_back(wp);
394         // -------
395         wp = new GPSWaypoint;
396         wp->id = "MABRY";
397         fp = FindFirstById(wp->id, multi, true); 
398         *wp = *fp;
399         wp->appType = GPS_IAF;
400         iap->_IAF.push_back(wp);
401         // -------
402         wp = new GPSWaypoint;
403         wp->id = "IMPLY";
404         fp = FindFirstById(wp->id, multi, true); 
405         *wp = *fp;
406         wp->appType = GPS_IAP;
407         iap->_IAP.push_back(wp);
408         // -------
409         wp = new GPSWaypoint;
410         wp->id = "DECOT";
411         fp = FindFirstById(wp->id, multi, true); 
412         *wp = *fp;
413         wp->appType = GPS_FAF;
414         iap->_IAP.push_back(wp);
415         // -------
416         wp = new GPSWaypoint;
417         wp->id = "MAPVV";
418         fp = FindFirstById(wp->id, multi, true); 
419         *wp = *fp;
420         wp->appType = GPS_MAP;
421         iap->_IAP.push_back(wp);
422         // -------
423         wp = new GPSWaypoint;
424         wp->id = "OAK";
425         fp = FindFirstById(wp->id, multi, true); 
426         *wp = *fp;
427         wp->appType = GPS_MAHP;
428         iap->_MAP.push_back(wp);
429         // -------
430         _np_iap[iap->_id].push_back(iap);
431         // -----------------------
432         // -----------------------
433         iap = new FGNPIAP;
434         iap->_id = "KHWD";
435         iap->_name = "VOR OR GPS-A";
436         iap->_abbrev = "VOR-";
437         iap->_rwyStr = "A";
438         iap->_IAF.clear();
439         iap->_IAP.clear();
440         iap->_MAP.clear();
441         // -------
442         wp = new GPSWaypoint;
443         wp->id = "SUNOL";
444         // Nasty using the find any function here, but it saves converting data from FGFix etc. 
445         fp = FindFirstById(wp->id, multi, true); 
446         *wp = *fp;
447         wp->appType = GPS_IAF;
448         iap->_IAF.push_back(wp);
449         // -------
450         wp = new GPSWaypoint;
451         wp->id = "MABRY";
452         fp = FindFirstById(wp->id, multi, true); 
453         *wp = *fp;
454         wp->appType = GPS_IAF;
455         iap->_IAF.push_back(wp);
456         // -------
457         wp = new GPSWaypoint;
458         wp->id = "IMPLY";
459         fp = FindFirstById(wp->id, multi, true); 
460         *wp = *fp;
461         wp->appType = GPS_IAP;
462         iap->_IAP.push_back(wp);
463         // -------
464         wp = new GPSWaypoint;
465         wp->id = "DECOT";
466         fp = FindFirstById(wp->id, multi, true); 
467         *wp = *fp;
468         wp->appType = GPS_FAF;
469         iap->_IAP.push_back(wp);
470         // -------
471         wp = new GPSWaypoint;
472         wp->id = "MAPVV";
473         fp = FindFirstById(wp->id, multi, true); 
474         *wp = *fp;
475         wp->appType = GPS_MAP;
476         iap->_IAP.push_back(wp);
477         // -------
478         wp = new GPSWaypoint;
479         wp->id = "OAK";
480         fp = FindFirstById(wp->id, multi, true); 
481         *wp = *fp;
482         wp->appType = GPS_MAHP;
483         iap->_MAP.push_back(wp);
484         // -------
485         _np_iap[iap->_id].push_back(iap);
486         // ------------------
487         // ------------------
488         /*
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.
491         iap = new FGNPIAP;
492         iap->_id = "KHWD";
493         iap->_name = "GPS RWY 28L";
494         iap->_abbrev = "GPS";
495         iap->_rwyStr = "28L";
496         iap->_IAF.clear();
497         iap->_IAP.clear();
498         iap->_MAP.clear();
499         // -------
500         wp = new GPSWaypoint;
501         wp->id = "SUNOL";
502         // Nasty using the find any function here, but it saves converting data from FGFix etc. 
503         fp = FindFirstById(wp->id, multi, true); 
504         *wp = *fp;
505         wp->appType = GPS_IAF;
506         iap->_IAF.push_back(wp);
507         // -------
508         wp = new GPSWaypoint;
509         wp->id = "SJC";
510         fp = FindFirstById(wp->id, multi, true); 
511         *wp = *fp;
512         wp->appType = GPS_IAF;
513         iap->_IAF.push_back(wp);
514         // -------
515         wp = new GPSWaypoint;
516         wp->id = "JOCPI";
517         fp = FindFirstById(wp->id, multi, true); 
518         *wp = *fp;
519         wp->appType = GPS_IAP;
520         iap->_IAP.push_back(wp);
521         // -------
522         wp = new GPSWaypoint;
523         wp->id = "SUDGE";
524         fp = FindFirstById(wp->id, multi, true); 
525         *wp = *fp;
526         wp->appType = GPS_FAF;
527         iap->_IAP.push_back(wp);
528         // -------
529         wp = new GPSWaypoint;
530         wp->id = "RW28L";
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
535         } else {
536                 fp = FindFirstById(wp->id, multi, true);
537                 if(fp == NULL) {
538                         cout << "Failed to find waypoint " << wp->id << " in database...\n";
539                 } else {
540                         *wp = *fp;
541                 }
542         }
543         iap->_IAP.push_back(wp);
544         // -------
545         wp = new GPSWaypoint;
546         wp->id = "OAK";
547         fp = FindFirstById(wp->id, multi, true); 
548         *wp = *fp;
549         wp->appType = GPS_MAHP;
550         iap->_MAP.push_back(wp);
551         // -------
552         _np_iap[iap->_id].push_back(iap);
553         */
554         iap = new FGNPIAP;
555         iap->_id = "C83";
556         iap->_name = "GPS RWY 30";
557         iap->_abbrev = "GPS";
558         iap->_rwyStr = "30";
559         iap->_IAF.clear();
560         iap->_IAP.clear();
561         iap->_MAP.clear();
562         // -------
563         wp = new GPSWaypoint;
564         wp->id = "PATYY";
565         // Nasty using the find any function here, but it saves converting data from FGFix etc. 
566         fp = FindFirstById(wp->id, multi, true); 
567         *wp = *fp;
568         wp->appType = GPS_IAF;
569         iap->_IAF.push_back(wp);
570         // -------
571         wp = new GPSWaypoint;
572         wp->id = "TRACY";
573         fp = FindFirstById(wp->id, multi, true); 
574         *wp = *fp;
575         wp->appType = GPS_IAF;
576         iap->_IAF.push_back(wp);
577         // -------
578         wp = new GPSWaypoint;
579         wp->id = "TRACY";
580         fp = FindFirstById(wp->id, multi, true); 
581         *wp = *fp;
582         wp->appType = GPS_IAP;
583         iap->_IAP.push_back(wp);
584         // -------
585         wp = new GPSWaypoint;
586         wp->id = "BABPI";
587         fp = FindFirstById(wp->id, multi, true); 
588         *wp = *fp;
589         wp->appType = GPS_FAF;
590         iap->_IAP.push_back(wp);
591         // -------
592         wp = new GPSWaypoint;
593         wp->id = "AMOSY";
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";
599         } else {
600                 fp = FindFirstById(wp->id, multi, true);
601                 if(fp == NULL) {
602                         cout << "Failed to find waypoint " << wp->id << " in database...\n";
603                 } else {
604                         *wp = *fp;
605                         wp->appType = GPS_MAP;
606                 }
607         }
608         iap->_IAP.push_back(wp);
609         // -------
610         wp = new GPSWaypoint;
611         wp->id = "HAIRE";
612         fp = FindFirstById(wp->id, multi, true); 
613         *wp = *fp;
614         wp->appType = GPS_MAHP;
615         iap->_MAP.push_back(wp);
616         // -------
617         _np_iap[iap->_id].push_back(iap);
618 }
619
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);
628 }
629
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");
637 }
638
639 void DCLGPS::update(double dt) {
640         //cout << "update called!\n";
641         
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.
651         _gpsLon = _lon;
652         _gpsLat = _lat;
653         // Check for abnormal position slew
654         if(GetGreatCircleDistance(_gpsLat, _gpsLon, _checkLat, _checkLon) > 1.0) {
655                 OrientateToActiveFlightPlan();
656         }
657         _checkLon = _gpsLon;
658         _checkLat = _gpsLat;
659         
660         if(!_departed) {
661                 if(_groundSpeed_kts > 30.0) {
662                         _departed = true;
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;
668                 }
669         } else {
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?
673                 _elapsedTime += dt;
674         }
675
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();
681                 _navFlagged = true;
682         } else if(_activeFP->waypoints.size() == 1) {
683                 _activeWaypoint.id.clear();
684         } else {
685                 _navFlagged = false;
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();
689                 }
690                 
691                 // Approach stuff
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
696                                 bool multi;
697                                 const FGAirport* ap = FindFirstAptById(_approachID, multi, true);
698                                 if(ap != NULL) {
699                                         double d = GetGreatCircleDistance(_gpsLat, _gpsLon, ap->getLatitude() * SG_DEGREES_TO_RADIANS, ap->getLongitude() * SG_DEGREES_TO_RADIANS);
700                                         if(d <= 30) {
701                                                 _approachArm = true;
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) {
707                                                         // No problem!
708                                                 } else if(_currentCdiScaleIndex == 0) {
709                                                         _sourceCdiScaleIndex = 0;
710                                                         _cdiScaleTransition = true;
711                                                         _cdiTransitionTime = 30.0;
712                                                         _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
713                                                 }
714                                         }
715                                 }
716                         } else {
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) {
727                                                         // No problem!
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];
733                                                 } else {
734                                                         // Abort going active?
735                                                         _approachActive = false;
736                                                 }
737                                         }
738                                 }
739                         }
740                 }
741                 
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;
748                         } else {
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;
760                                         }
761                                 } else {
762                                         _currentCdiScale += (scaleDiff * dt / _cdiTransitionTime);
763                                         if(_currentCdiScale > _cdiScales[_targetCdiScaleIndex]) {
764                                                 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
765                                                 _currentCdiScaleIndex = _targetCdiScaleIndex;
766                                                 _cdiScaleTransition = false;
767                                         }
768                                 }
769                                 //cout << "_currentCdiScale = " << _currentCdiScale << '\n';
770                         }
771                 } else {
772                         _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
773                 }
774                 
775                 
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).
781                 /*
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);
794                         }
795                 } else {
796                         _dtkTrue = 0.0;
797                         _dtkMag = 0.0;
798                         // TODO - in DTO operation the position of initiation of DTO defines the "from waypoint".
799                 }
800                 */
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);
810                         }
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);
814                         } else {
815                                 _dtkTrue = 0.0;
816                                 _dtkMag = 0.0;
817                         }
818                 }
819                 
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.
824                                 if(_headingBugTo) {
825                                         _waypointAlert = true;  // TODO - not if the from flag is set.
826                                 }
827                         }
828                         if(_eta < 60) {
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
838                                 if(!_headingBugTo) {
839                                         if(finalLeg) {
840                                                 // Do nothing - not sure if Dto should switch off when arriving at the final waypoint of a flightplan
841                                         } else if(finalDto) {
842                                                 // Do nothing
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";
846                                         } else {
847                                                 cout << "Sequencing...\n";
848                                                 _fromWaypoint = _activeWaypoint;
849                                                 _activeWaypoint = *_activeFP->waypoints[idx + 1];
850                                                 _dto = false;
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.
853                                                 string s;
854                                                 if(fgGetBool("/instrumentation/nav[0]/slaved-to-gps")) {
855                                                         // TODO - avoid the hardwiring on nav[0]
856                                                         s = "Adj Nav Crs to ";
857                                                 } else {
858                                                         string s = "GPS Course is ";
859                                                 }
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;
863                                                 char buf[4];
864                                                 snprintf(buf, 4, "%03i", (int)(d + 0.5));
865                                                 s += buf;
866                                                 _messageStack.push_back(s);
867                                         }
868                                         _waypointAlert = false;
869                                 }
870                         }
871                 } else {
872                         _eta = 0.0;
873                 }
874                 
875                 /*
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) {
879                                 
880                 } else {
881                         _crosstrackDist = 0.0;
882                 }
883                 */
884         }
885 }
886
887 double DCLGPS::GetCDIDeflection() const {
888         double xtd = CalcCrossTrackDeviation(); //nm
889         return((xtd / _currentCdiScale) * 5.0 * 2.5 * -1.0);
890 }
891
892 void DCLGPS::DtoInitiate(const string& s) {
893         cout << "DtoInitiate, s = " << s << '\n';
894         bool multi;
895         const GPSWaypoint* wp = FindFirstById(s, multi, true);
896         if(wp) {
897                 cout << "Waypoint found, starting dto operation!\n";
898                 _dto = true;
899                 _activeWaypoint = *wp;
900                 _fromWaypoint.lat = _gpsLat;
901                 _fromWaypoint.lon = _gpsLon;
902                 _fromWaypoint.type = GPS_WP_VIRT;
903                 _fromWaypoint.id = "DTOWP";
904         } else {
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.
908         }
909 }
910
911 void DCLGPS::DtoCancel() {
912         if(_dto) {
913                 // i.e. don't bother reorientating if we're just cancelling a DTO button press
914                 // without having previously initiated DTO.
915                 OrientateToActiveFlightPlan();
916         }
917         _dto = false;
918 }
919
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() {}
930
931 void DCLGPS::OBSPressed() { 
932         _obsMode = !_obsMode;
933         if(_obsMode) {
934                 if(!_activeWaypoint.id.empty()) {
935                         _obsHeading = _dtkMag;
936                 }
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();
940         }
941 }
942
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;
947         
948         // TODO - base the 180 deg correction on the to/from flag.
949         _fromWaypoint = GetPositionOnMagRadial(_activeWaypoint, 10, _obsHeading + 180.0);
950         _fromWaypoint.id = "OBSWP";
951 }
952
953 void DCLGPS::MsgPressed() {}
954
955 void DCLGPS::CDIFSDIncrease() {
956         if(_currentCdiScaleIndex == 0) {
957                 _currentCdiScaleIndex = _cdiScales.size() - 1;
958         } else {
959                 _currentCdiScaleIndex--;
960         }
961 }
962
963 void DCLGPS::CDIFSDDecrease() {
964         _currentCdiScaleIndex++;
965         if(_currentCdiScaleIndex == _cdiScales.size()) {
966                 _currentCdiScaleIndex = 0;
967         }
968 }
969
970 void DCLGPS::DrawChar(char c, int field, int px, int py, bool bold) {
971 }
972
973 void DCLGPS::DrawText(const string& s, int field, int px, int py, bool bold) {
974 }
975
976 void DCLGPS::SetBaroUnits(int n, bool wrap) {
977         if(n < 1) {
978                 _baroUnits = (GPSPressureUnits)(wrap ? 3 : 1);
979         } else if(n > 3) {
980                 _baroUnits = (GPSPressureUnits)(wrap ? 1 : 3);
981         } else {
982                 _baroUnits = (GPSPressureUnits)n;
983         }
984 }
985
986 void DCLGPS::CreateDefaultFlightPlans() {}
987
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) {
992                 return(-1.0);
993         } else {
994                 return(_eta);
995         }
996 }
997
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) {
1002                 return(-1.0);
1003         } else {
1004                 // TODO - handle OBS / DTO operation appropriately
1005                 if(_activeFP->waypoints.empty()) {
1006                         return(-1.0);
1007                 } else {
1008                         return(GetTimeToWaypoint(_activeFP->waypoints[_activeFP->waypoints.size() - 1]->id));
1009                 }
1010         }
1011 }
1012
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) {
1019                 return(-1.0);
1020         }
1021         
1022         double eta = 0.0;
1023         int n1 = GetActiveWaypointIndex();
1024         int n2 = GetWaypointIndex(id);
1025         if(n2 > n1) {
1026                 eta = _eta;
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);
1032                 }
1033                 return(eta);
1034         } else if(id == _activeWaypoint.id) {
1035                 return(_eta);
1036         } else {
1037                 bool multi;
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);
1042         }
1043         return(-1.0);   // Hopefully we never get here!
1044 }
1045
1046 // Returns magnetic great-circle heading
1047 // TODO - document units.
1048 float DCLGPS::GetHeadingToActiveWaypoint() {
1049         if(_activeWaypoint.id.empty()) {
1050                 return(-888);
1051         } else {
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;
1055                 return((float)h);
1056         }
1057 }
1058
1059 // Returns magnetic great-circle heading
1060 // TODO - what units?
1061 float DCLGPS::GetHeadingFromActiveWaypoint() {
1062         if(_activeWaypoint.id.empty()) {
1063                 return(-888);
1064         } else {
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;
1068                 return(h);
1069         }
1070 }
1071
1072 void DCLGPS::ClearFlightPlan(int n) {
1073         for(unsigned int i=0; i<_flightPlans[n]->waypoints.size(); ++i) {
1074                 delete _flightPlans[n]->waypoints[i];
1075         }
1076         _flightPlans[n]->waypoints.clear();
1077 }
1078
1079 void DCLGPS::ClearFlightPlan(GPSFlightPlan* fp) {
1080         for(unsigned int i=0; i<fp->waypoints.size(); ++i) {
1081                 delete fp->waypoints[i];
1082         }
1083         fp->waypoints.clear();
1084 }
1085
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);
1089         }
1090         return(-1);
1091 }
1092
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);
1096         }
1097         return(-1);
1098 }
1099
1100 void DCLGPS::OrientateToFlightPlan(GPSFlightPlan* fp) {
1101         //cout << "Orientating...\n";
1102         //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n'; 
1103         if(fp->IsEmpty()) {
1104                 _activeWaypoint.id.clear();
1105                 _navFlagged = true;
1106         } else {
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();
1112                 } else {
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);
1150                                         if(d > d0) d0 = d;
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);
1155                                         if(d > d0) d0 = d;
1156                                         //cout << "h2 triggered, d0 now = " << d0 << '\n';
1157                                 }
1158                                 if(d0 < dmin) {
1159                                         //cout << "THIS LEG NOW ACTIVE!\n";
1160                                         dmin = d0;
1161                                         _fromWaypoint = *fp->waypoints[i-1];
1162                                         _activeWaypoint = *fp->waypoints[i];
1163                                 }
1164                         }
1165                 }
1166         }
1167 }
1168
1169 void DCLGPS::OrientateToActiveFlightPlan() {
1170         OrientateToFlightPlan(_activeFP);
1171 }       
1172
1173 /***************************************/
1174
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;
1178         unsigned int i;
1179         if(!fp->waypoints.empty()) {
1180                 for(i=0; i<fp->waypoints.size(); ++i) {
1181                         delete fp->waypoints[i];
1182                 }
1183                 fp->waypoints.clear();
1184         }
1185         if(ids.size() != wps.size()) {
1186                 cout << "ID and Waypoint types list size mismatch in GPS::CreateFlightPlan - no flightplan created!\n";
1187                 return;
1188         }
1189         for(i=0; i<ids.size(); ++i) {
1190                 bool multi;
1191                 const FGAirport* ap;
1192                 FGNavRecord* np;
1193                 GPSWaypoint* wp = new GPSWaypoint;
1194                 wp->type = wps[i];
1195                 switch(wp->type) {
1196                 case GPS_WP_APT:
1197                         ap = FindFirstAptById(ids[i], multi, true);
1198                         if(ap == NULL) {
1199                                 // error
1200                                 delete wp;
1201                         } else {
1202                                 wp->lat = ap->getLatitude() * SG_DEGREES_TO_RADIANS;
1203                                 wp->lon = ap->getLongitude() * SG_DEGREES_TO_RADIANS;
1204                                 wp->id = ids[i];
1205                                 fp->waypoints.push_back(wp);
1206                         }
1207                         break;
1208                 case GPS_WP_VOR:
1209                         np = FindFirstVorById(ids[i], multi, true);
1210                         if(np == NULL) {
1211                                 // error
1212                                 delete wp;
1213                         } else {
1214                                 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1215                                 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1216                                 wp->id = ids[i];
1217                                 fp->waypoints.push_back(wp);
1218                         }
1219                         break;
1220                 case GPS_WP_NDB:
1221                         np = FindFirstNDBById(ids[i], multi, true);
1222                         if(np == NULL) {
1223                                 // error
1224                                 delete wp;
1225                         } else {
1226                                 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1227                                 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1228                                 wp->id = ids[i];
1229                                 fp->waypoints.push_back(wp);
1230                         }
1231                         break;
1232                 case GPS_WP_INT:
1233                         // TODO TODO
1234                         break;
1235                 case GPS_WP_USR:
1236                         // TODO
1237                         break;
1238                 }
1239         }
1240 }
1241
1242 /***************************************/
1243
1244 const GPSWaypoint* DCLGPS::ActualFindFirstById(const string& id, bool exact) {
1245     gps_waypoint_map_const_iterator itr;
1246     if(exact) {
1247         itr = _waypoints.find(id);
1248     } else {
1249         itr = _waypoints.lower_bound(id);
1250     }
1251     if(itr == _waypoints.end()) {
1252         return(NULL);
1253     } else {
1254                 // TODO - don't just return the first one - either return all or the nearest one.
1255         return((itr->second)[0]);
1256     }
1257 }
1258
1259 const GPSWaypoint* DCLGPS::FindFirstById(const string& id, bool &multi, bool exact) {
1260         multi = false;
1261         if(exact) return(ActualFindFirstById(id, exact));
1262         
1263         // OK, that was the easy case, now the fuzzy case
1264         const GPSWaypoint* w1 = ActualFindFirstById(id);
1265         if(w1 == NULL) return(w1);
1266         
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).
1269         string id2 = id;
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';
1281         
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).
1288         
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));
1297                                 }
1298                         }
1299                 }
1300                 return(w4);
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));
1309                                 }
1310                         }
1311                 }
1312                 return(w1);
1313         } else {  // No match
1314                 return(NULL);
1315         }
1316         return NULL;
1317 }
1318
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.
1323         multi = false;
1324         //if(exact) return(_overlays->FindFirstVorById(id, exact));
1325         
1326         nav_list_type nav = globals->get_navlist()->findFirstByIdent(id, FG_NAV_VOR, exact);
1327         
1328         if(nav.size() > 1) multi = true;
1329         //return(nav.empty() ? NULL : *(nav.begin()));
1330         
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);
1333         
1334         for(nav_list_iterator it = nav.begin(); it != nav.end(); ++it) {
1335                 if((*it)->get_type() == 3) return(*it);
1336         }
1337         return(NULL);   // Shouldn't get here!
1338 }
1339 #if 0
1340 Overlays::NAV* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact) {
1341         // NOTE - at the moment multi is never set.
1342         multi = false;
1343         if(exact) return(_overlays->FindFirstVorById(id, exact));
1344         
1345         // OK, that was the easy case, now the fuzzy case
1346         Overlays::NAV* n1 = _overlays->FindFirstVorById(id);
1347         if(n1 == NULL) return(n1);
1348         
1349         string id2 = id;
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';
1359         
1360         
1361         if(alfa) {
1362                 if(n1 != n2) { // match
1363                         return(n1);
1364                 } else {
1365                         return(NULL);
1366                 }
1367         }
1368         
1369         /*
1370         if(n1 != n2) {
1371                 // Something matches - the problem is the number/letter preference order is reversed between the GPS and the STL
1372                 if(n4 != n2) {
1373                         // There's a letter match - return that
1374                         return(n4);
1375                 } else {
1376                         // By definition we must have a number match
1377                         if(n3 == n2) cout << "HELP - LOGIC FLAW in find VOR!\n";
1378                         return(n3);
1379                 }
1380         } else {
1381                 // No match
1382                 return(NULL);
1383         }
1384         */
1385         return NULL;
1386 }
1387 #endif //0
1388
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.
1392         multi = false;
1393         //if(exact) return(_overlays->FindFirstVorById(id, exact));
1394         
1395         nav_list_type nav = globals->get_navlist()->findFirstByIdent(id, FG_NAV_NDB, exact);
1396         
1397         if(nav.size() > 1) multi = true;
1398         //return(nav.empty() ? NULL : *(nav.begin()));
1399         
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);
1402         
1403         for(nav_list_iterator it = nav.begin(); it != nav.end(); ++it) {
1404                 if((*it)->get_type() == 2) return(*it);
1405         }
1406         return(NULL);   // Shouldn't get here!
1407 }
1408 #if 0
1409 Overlays::NAV* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact) {
1410         // NOTE - at the moment multi is never set.
1411         multi = false;
1412         if(exact) return(_overlays->FindFirstNDBById(id, exact));
1413         
1414         // OK, that was the easy case, now the fuzzy case
1415         Overlays::NAV* n1 = _overlays->FindFirstNDBById(id);
1416         if(n1 == NULL) return(n1);
1417         
1418         string id2 = id;
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';
1428         
1429         
1430         if(alfa) {
1431                 if(n1 != n2) { // match
1432                         return(n1);
1433                 } else {
1434                         return(NULL);
1435                 }
1436         }
1437         
1438         /*
1439         if(n1 != n2) {
1440                 // Something matches - the problem is the number/letter preference order is reversed between the GPS and the STL
1441                 if(n4 != n2) {
1442                         // There's a letter match - return that
1443                         return(n4);
1444                 } else {
1445                         // By definition we must have a number match
1446                         if(n3 == n2) cout << "HELP - LOGIC FLAW in find VOR!\n";
1447                         return(n3);
1448                 }
1449         } else {
1450                 // No match
1451                 return(NULL);
1452         }
1453         */
1454         return NULL;
1455 }
1456 #endif //0
1457
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.
1462         multi = false;
1463         if(exact) return(globals->get_fixlist()->findFirstByIdent(id, exact));
1464         
1465         const FGFix* f1 = globals->get_fixlist()->findFirstByIdent(id, exact);
1466         if(f1 == NULL) return(f1);
1467         
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!
1472         string id2 = id;
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);
1481         
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).
1488         
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));
1497                                 }
1498                         }
1499                 }
1500                 return(f4);
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));
1509                                 }
1510                         }
1511                 }
1512                 return(f1);
1513         } else {  // No match
1514                 return(NULL);
1515         }
1516                 
1517         return NULL;    // Don't think we can ever get here.
1518 }
1519
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';
1523         multi = false;
1524         if(exact) return(globals->get_airports()->findFirstById(id, exact));
1525         
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);
1529         
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).
1532         string id2 = id;
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';
1544         
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).
1551         
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));
1560                                 }
1561                         }
1562                 }
1563                 return(a4);
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));
1572                                 }
1573                         }
1574                 }
1575                 return(a1);
1576         } else {  // No match
1577                 return(NULL);
1578         }
1579                 
1580         return NULL;
1581 }
1582
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));
1585 }
1586
1587 //----------------------------------------------------------------------------------------------------------
1588
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;
1598         return(h);
1599 }
1600
1601 // ---------------- Great Circle formulae from "The Aviation Formulary" -------------
1602 // Note that all of these assume that the world is spherical.
1603
1604 double Rad2Nm(double theta) {
1605         return(((180.0*60.0)/SG_PI)*theta);
1606 }
1607
1608 double Nm2Rad(double d) {
1609         return((SG_PI/(180.0*60.0))*d);
1610 }
1611
1612 /* QUOTE:
1613
1614 The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
1615
1616 d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
1617
1618 A mathematically equivalent formula, which is less subject to rounding error for short distances is:
1619
1620 d=2*asin(sqrt((sin((lat1-lat2)/2))^2 + 
1621                  cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
1622                                  
1623 */
1624
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))));
1629         return(Rad2Nm(d));
1630 }
1631
1632 // fmod dosen't do what we want :-( 
1633 static double mod(double d1, double d2) {
1634         return(d1 - d2*floor(d1/d2));
1635 }
1636
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 {
1640         //double h = 0.0;
1641         /*
1642         // Special case the poles
1643         if(cos(lat1) < SG_EPSILON) {
1644                 if(lat1 > 0) {
1645                         // Starting from North Pole
1646                         h = SG_PI;
1647                 } else {
1648                         // Starting from South Pole
1649                         h = 2.0 * SG_PI;
1650                 }
1651         } else {
1652                 // Urgh - the formula below is for negative lon +ve !!!???
1653                 double d = GetGreatCircleDistance(lat1, lon1, lat2, lon2);
1654                 cout << "d = " << d;
1655                 d = Nm2Rad(d);
1656                 //cout << ", d_theta = " << d;
1657                 //cout << ", and d = " << Rad2Nm(d) << ' ';
1658                 if(sin(lon2 - lon1) < 0) {
1659                         cout << " A ";
1660                         h = acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1661                 } else {
1662                         cout << " B ";
1663                         h = 2.0 * SG_PI - acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1664                 }
1665         }
1666         cout << h * SG_RADIANS_TO_DEGREES << '\n';
1667         */
1668         
1669         return( mod(atan2(sin(lon2-lon1)*cos(lat2),
1670             cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)),
1671             2.0*SG_PI) );
1672 }
1673
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));
1679 }
1680
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;
1686         
1687         h *= SG_DEGREES_TO_RADIANS;
1688         d *= (SG_PI / (180.0 * 60.0));
1689         
1690         double lat=asin(sin(wp1.lat)*cos(d)+cos(wp1.lat)*sin(d)*cos(h));
1691         double lon;
1692         if(cos(lat)==0) {
1693                 lon=wp1.lon;      // endpoint a pole
1694         } else {
1695                 lon=mod(wp1.lon+asin(sin(h)*sin(d)/cos(lat))+SG_PI,2*SG_PI)-SG_PI;
1696         }
1697         
1698         GPSWaypoint wp;
1699         wp.lat = lat;
1700         wp.lon = lon;
1701         wp.type = GPS_WP_VIRT;
1702         return(wp);
1703 }
1704
1705 // Returns cross-track deviation in Nm.
1706 double DCLGPS::CalcCrossTrackDeviation() const {
1707         return(CalcCrossTrackDeviation(_fromWaypoint, _activeWaypoint));
1708 }
1709
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));
1717 }