]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/KLN89/kln89.cxx
KLN89: Add initial implemenation of ALT pages.
[flightgear.git] / src / Instrumentation / KLN89 / kln89.cxx
1 // kln89_page.cxx - a class to manage the simulation of a KLN89
2 //                  GPS unit.  Note that this is primarily the 
3 //                  simulation of the user interface and display
4 //                  - the core GPS calculations such as position
5 //                  and waypoint sequencing are done (or should 
6 //                  be done) by FG code. 
7 //
8 // Written by David Luff, started 2005.
9 //
10 // Copyright (C) 2005 - David C Luff - daveluff AT ntlworld.com
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27
28 #include "kln89.hxx"
29 #include "kln89_page.hxx"
30 #include "kln89_page_apt.hxx"
31 #include "kln89_page_vor.hxx"
32 #include "kln89_page_ndb.hxx"
33 #include "kln89_page_int.hxx"
34 #include "kln89_page_usr.hxx"
35 #include "kln89_page_act.hxx"
36 #include "kln89_page_nav.hxx"
37 #include "kln89_page_fpl.hxx"
38 #include "kln89_page_cal.hxx"
39 #include "kln89_page_set.hxx"
40 #include "kln89_page_oth.hxx"
41 #include "kln89_page_alt.hxx"
42 #include "kln89_page_dir.hxx"
43 #include "kln89_page_nrst.hxx"
44 #include "kln89_symbols.hxx"
45 #include <iostream>
46
47 #if ENABLE_ATCDCL
48 #include <ATCDCL/ATCProjection.hxx>
49 #else
50 #include <ATC/atcutils.hxx>
51 #endif
52
53 #include <Main/fg_props.hxx>
54 #include <simgear/math/SGMath.hxx>
55 #include <simgear/structure/commands.hxx>
56 #include <Airports/simple.hxx>
57
58 using std::cout;
59
60 // Command callbacks for FlightGear
61
62 static bool do_kln89_msg_pressed(const SGPropertyNode* arg) {
63         //cout << "do_kln89_msg_pressed called!\n";
64         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
65         gps->MsgPressed();
66         return(true);
67 }
68
69 static bool do_kln89_obs_pressed(const SGPropertyNode* arg) {
70         //cout << "do_kln89_obs_pressed called!\n";
71         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
72         gps->OBSPressed();
73         return(true);
74 }
75
76 static bool do_kln89_alt_pressed(const SGPropertyNode* arg) {
77         //cout << "do_kln89_alt_pressed called!\n";
78         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
79         gps->AltPressed();
80         return(true);
81 }
82
83 static bool do_kln89_nrst_pressed(const SGPropertyNode* arg) {
84         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
85         gps->NrstPressed();
86         return(true);
87 }
88
89 static bool do_kln89_dto_pressed(const SGPropertyNode* arg) {
90         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
91         gps->DtoPressed();
92         return(true);
93 }
94
95 static bool do_kln89_clr_pressed(const SGPropertyNode* arg) {
96         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
97         gps->ClrPressed();
98         return(true);
99 }
100
101 static bool do_kln89_ent_pressed(const SGPropertyNode* arg) {
102         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
103         gps->EntPressed();
104         return(true);
105 }
106
107 static bool do_kln89_crsr_pressed(const SGPropertyNode* arg) {
108         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
109         gps->CrsrPressed();
110         return(true);
111 }
112
113 static bool do_kln89_knob1left1(const SGPropertyNode* arg) {
114         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
115         gps->Knob1Left1();
116         return(true);
117 }
118
119 static bool do_kln89_knob1right1(const SGPropertyNode* arg) {
120         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
121         gps->Knob1Right1();
122         return(true);
123 }
124
125 static bool do_kln89_knob2left1(const SGPropertyNode* arg) {
126         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
127         gps->Knob2Left1();
128         return(true);
129 }
130
131 static bool do_kln89_knob2right1(const SGPropertyNode* arg) {
132         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
133         gps->Knob2Right1();
134         return(true);
135 }
136
137 // End command callbacks
138
139 KLN89::KLN89(RenderArea2D* instrument) 
140 : DCLGPS(instrument) {
141         _mode = KLN89_MODE_DISP;
142         _blink = false;
143         _cum_dt = 0.0;
144         _nFields = 2;
145         _maxFields = 2;
146         _xBorder = 0;
147         _yBorder = 4;
148         // ..Field..[0] => no fields in action
149         _xFieldBorder[0] = 0;
150         _xFieldBorder[1] = 0;
151         _yFieldBorder[0] = 0;
152         _yFieldBorder[1] = 0;
153         _xFieldBorder[2] = 2;
154         _yFieldBorder[2] = 0;
155         _xFieldStart[0] = 0;
156         _xFieldStart[1] = 0;
157         _xFieldStart[2] = 45;
158         _yFieldStart[0] = 0;
159         _yFieldStart[1] = 0;
160         _yFieldStart[2] = 0;
161         
162         //_pixelated = true;
163         _pixelated = false;
164
165         // Cyclic pages
166         _pages.clear();
167         KLN89Page* apt_page = new KLN89AptPage(this);
168         _pages.push_back(apt_page);
169         KLN89Page* vor_page = new KLN89VorPage(this);
170         _pages.push_back(vor_page);
171         KLN89Page* ndb_page = new KLN89NDBPage(this);
172         _pages.push_back(ndb_page);
173         KLN89Page* int_page = new KLN89IntPage(this);
174         _pages.push_back(int_page);
175         KLN89Page* usr_page = new KLN89UsrPage(this);
176         _pages.push_back(usr_page);
177         KLN89Page* act_page = new KLN89ActPage(this);
178         _pages.push_back(act_page);
179         KLN89Page* nav_page = new KLN89NavPage(this);
180         _pages.push_back(nav_page);
181         KLN89Page* fpl_page = new KLN89FplPage(this);
182         _pages.push_back(fpl_page);
183         KLN89Page* cal_page = new KLN89CalPage(this);
184         _pages.push_back(cal_page);
185         KLN89Page* set_page = new KLN89SetPage(this);
186         _pages.push_back(set_page);
187         KLN89Page* oth_page = new KLN89OthPage(this);
188         _pages.push_back(oth_page);
189         _nPages = _pages.size();
190         _curPage = 0;
191         
192         // Other pages
193         _alt_page = new KLN89AltPage(this);
194         _dir_page = new KLN89DirPage(this);
195         _nrst_page = new KLN89NrstPage(this);
196         
197         _activePage = apt_page;
198         _obsMode = false;
199         _dto = false;
200         _fullLegMode = true;
201         _obsHeading = 215;
202         
203         if(_baroUnits == GPS_PRES_UNITS_IN) {
204                 _userBaroSetting = 2992;
205         } else {
206                 _userBaroSetting = 1013;
207         }
208         
209         _maxFlightPlans = 26;
210         for(unsigned int i=0; i<_maxFlightPlans; ++i) {
211                 GPSFlightPlan* fp = new GPSFlightPlan;
212                 fp->waypoints.clear();
213                 _flightPlans.push_back(fp);
214         }
215         _activeFP = _flightPlans[0];
216         
217         _entJump = _clrJump = -1;
218         _jumpRestoreCrsr = false;
219         
220         _dispMsg = false;
221         
222         _dtoReview = false;
223
224         // Moving map stuff
225         _mapOrientation = 0;
226         _mapHeading = 0.0;
227         _mapHeadingUpdateTimer = 0.0;
228         _drawSUA = false;
229         _drawVOR = false;
230         _drawApt = true;
231         //_mapScaleIndex = 20;
232         _mapScaleIndex = 7;     // I think that the above is more accurate for no-flightplan default, but this is more sane for initial testing!
233         _mapScaleAuto = true;
234         
235         // Configuration.  Eventually this may be user-achivable in order that settings can be persistent between sessions.
236         _suaAlertEnabled = false;
237         _altAlertEnabled = false;
238         _minDisplayBrightness = 4;
239         _defaultFirstChar = 'A';
240         
241         // Mega-hack - hardwire airport town and state names for the FG base area since we don't have any data for these at the moment
242         // TODO - do this better one day!
243         _airportTowns["KSFO"] = "San Francisco";
244         _airportTowns["KSQL"] = "San Carlos";
245         _airportTowns["KPAO"] = "Palo Alto";
246         _airportTowns["KNUQ"] = "Mountain View";
247         _airportTowns["KSJC"] = "San Jose";
248         _airportTowns["KRHV"] = "San Jose";
249         _airportTowns["E16"] = "San Martin";
250         _airportTowns["KWVI"] = "Watsonville";
251         _airportTowns["KOAK"] = "Oakland";
252         _airportTowns["KHWD"] = "Hayward";
253         _airportTowns["KLVK"] = "Livermore";
254         _airportTowns["KCCR"] = "Concord";
255         _airportTowns["KTCY"] = "Tracy";
256         _airportTowns["KSCK"] = "Stockton";
257         _airportTowns["KHAF"] = "Half Moon Bay";
258         
259         _airportStates["KSFO"] = "CA";
260         _airportStates["KSQL"] = "CA";
261         _airportStates["KPAO"] = "CA";
262         _airportStates["KNUQ"] = "CA";
263         _airportStates["KSJC"] = "CA";
264         _airportStates["KRHV"] = "CA";
265         _airportStates["E16"] = "CA";
266         _airportStates["KWVI"] = "CA";
267         _airportStates["KOAK"] = "CA";
268         _airportStates["KHWD"] = "CA";
269         _airportStates["KLVK"] = "CA";
270         _airportStates["KCCR"] = "CA";
271         _airportStates["KTCY"] = "CA";
272         _airportStates["KSCK"] = "CA";
273         _airportStates["KHAF"] = "CA";
274 }
275
276 KLN89::~KLN89() {
277         for(unsigned int i=0; i<_pages.size(); ++i) {
278                 delete _pages[i];
279         }
280         
281         delete _alt_page;
282         delete _dir_page;
283         delete _nrst_page;
284         
285         for(unsigned int i=0; i<_maxFlightPlans; ++i) {
286                 ClearFlightPlan(i);
287                 delete _flightPlans[i];
288         }
289 }
290
291 void KLN89::bind() {
292         fgTie("/instrumentation/gps/message-alert", this, &KLN89::GetMsgAlert);
293         DCLGPS::bind();
294 }
295
296 void KLN89::unbind() {
297         fgUntie("/instrumentation/gps/message-alert");
298         DCLGPS::unbind();
299 }
300
301 void KLN89::init() {
302         globals->get_commands()->addCommand("kln89_msg_pressed", do_kln89_msg_pressed);
303         globals->get_commands()->addCommand("kln89_obs_pressed", do_kln89_obs_pressed);
304         globals->get_commands()->addCommand("kln89_alt_pressed", do_kln89_alt_pressed);
305         globals->get_commands()->addCommand("kln89_nrst_pressed", do_kln89_nrst_pressed);
306         globals->get_commands()->addCommand("kln89_dto_pressed", do_kln89_dto_pressed);
307         globals->get_commands()->addCommand("kln89_clr_pressed", do_kln89_clr_pressed);
308         globals->get_commands()->addCommand("kln89_ent_pressed", do_kln89_ent_pressed);
309         globals->get_commands()->addCommand("kln89_crsr_pressed", do_kln89_crsr_pressed);
310         globals->get_commands()->addCommand("kln89_knob1left1", do_kln89_knob1left1);
311         globals->get_commands()->addCommand("kln89_knob1right1", do_kln89_knob1right1);
312         globals->get_commands()->addCommand("kln89_knob2left1", do_kln89_knob2left1);
313         globals->get_commands()->addCommand("kln89_knob2right1", do_kln89_knob2right1);
314         
315         DCLGPS::init();
316 }
317
318 void KLN89::update(double dt) {
319         // Run any positional calc's required first
320         DCLGPS::update(dt);
321         
322         // Set the display brightness.  This should be reduced in response to falling light
323         // (i.e. nighttime), or the user covering the photocell that detects the light level.
324         // At the moment I don't know how to detect nighttime or actual light level, so only
325         // respond to the photocell being obscured.
326         // TODO - reduce the brightness in response to nighttime / lowlight.
327         float rgba[4] = {1.0, 0.0, 0.0, 1.0};
328         if(fgGetBool("/instrumentation/kln89/photocell-obscured")) {
329                 rgba[0] -= (9 - _minDisplayBrightness) * 0.05;
330         }
331         _instrument->SetPixelColor(rgba);
332         
333         _cum_dt += dt;
334         if(_blink) {
335                 if(_cum_dt > 0.2) {
336                         _cum_dt = 0.0;
337                         _blink = false;
338                 }
339         } else {
340                 if(_cum_dt > 0.8) {
341                         _cum_dt = 0.0;
342                         _blink = true;
343                 }
344         }
345         
346         _mapHeadingUpdateTimer += dt;
347         if(_mapHeadingUpdateTimer > 1.0) {
348                 UpdateMapHeading();
349                 _mapHeadingUpdateTimer = 0.0;
350         }
351         
352         _instrument->Flush();
353         _instrument->DrawBackground();
354         
355         if(_dispMsg) {
356                 if(_messageStack.empty()) {
357                         DrawText("No Message", 0, 5, 2);
358                 } else {
359                         // TODO - parse the message string for special strings that indicate degrees signs etc!
360                         DrawText(*_messageStack.begin(), 0, 0, 3);
361                 }
362                 return;
363         } else {
364                 if(!_messageStack.empty()) {
365                         DrawMessageAlert();
366                 }
367         }
368         
369         // Draw the indicator that shows which page we are on.
370         if(_curPage == 6 && _activePage->GetSubPage() == 3) {
371                 // Don't draw the bar on the nav-4 page
372         } else if((_activePage != _nrst_page) && (_activePage != _dir_page) && (_activePage != _alt_page) && (!_dispMsg)) {
373                 // Don't draw the bar on the NRST, DTO or MSG pages
374                 DrawBar(_curPage);
375         }
376         
377         _activePage->Update(dt);
378 }
379
380 void KLN89::CreateDefaultFlightPlans() {
381         // TODO - read these in from preferences.xml or similar instead!!!!
382         // Create some hardwired default flightplans for testing.
383         vector<string> ids;
384         vector<GPSWpType> wps;
385         
386         ids.clear();
387         wps.clear();
388         ids.push_back("KLSN");
389         wps.push_back(GPS_WP_APT);
390         ids.push_back("VOLTA");
391         wps.push_back(GPS_WP_INT);
392         ids.push_back("C83");
393         wps.push_back(GPS_WP_APT);
394         CreateFlightPlan(_flightPlans[5], ids, wps);
395         
396         ids.clear();
397         wps.clear();
398         ids.push_back("KCCR");
399         wps.push_back(GPS_WP_APT);
400         ids.push_back("KHAF");
401         wps.push_back(GPS_WP_APT);
402         CreateFlightPlan(_flightPlans[4], ids, wps);
403         
404         ids.clear();
405         wps.clear();
406         ids.push_back("KLVK");
407         wps.push_back(GPS_WP_APT);
408         ids.push_back("OAK");
409         wps.push_back(GPS_WP_VOR);
410         ids.push_back("PORTE");
411         wps.push_back(GPS_WP_INT);
412         ids.push_back("KHAF");
413         wps.push_back(GPS_WP_APT);
414         CreateFlightPlan(_flightPlans[3], ids, wps);
415         
416         ids.clear();
417         wps.clear();
418         ids.push_back("KDPA");
419         wps.push_back(GPS_WP_APT);
420         ids.push_back("OBK");
421         wps.push_back(GPS_WP_VOR);
422         ids.push_back("ENW");
423         wps.push_back(GPS_WP_VOR);
424         ids.push_back("KRAC");
425         wps.push_back(GPS_WP_APT);
426         CreateFlightPlan(_flightPlans[2], ids, wps);
427         //cout << "Size of FP2 WP list is " << _flightPlans[2]->waypoints.size() << '\n';
428         
429         ids.clear();
430         wps.clear();
431         ids.push_back("KSFO");
432         ids.push_back("KOAK");
433         wps.push_back(GPS_WP_APT);
434         wps.push_back(GPS_WP_APT);
435         CreateFlightPlan(_flightPlans[1], ids, wps);
436         
437         ids.clear();
438         wps.clear();
439         //ids.push_back("KOSH");
440         ids.push_back("KSFO");
441         ids.push_back("KHAF");
442         ids.push_back("OSI");
443         ids.push_back("KSQL");
444         //ids.push_back("KPAO");
445         //ids.push_back("KHWD");
446         wps.push_back(GPS_WP_APT);
447         wps.push_back(GPS_WP_APT);
448         wps.push_back(GPS_WP_VOR);
449         wps.push_back(GPS_WP_APT);
450         //wps.push_back(GPS_WP_APT);
451         //wps.push_back(GPS_WP_APT);
452         CreateFlightPlan(_flightPlans[0], ids, wps);
453         
454         /*
455         ids.clear();
456         wps.clear();
457         ids.push_back("KLVK");
458         ids.push_back("KHWD");
459         wps.push_back(GPS_WP_APT);
460         wps.push_back(GPS_WP_APT);
461         CreateFlightPlan(_flightPlans[0], ids, wps);
462         */
463 }
464
465 void KLN89::Knob1Right1() {
466         if(_mode == KLN89_MODE_DISP) {
467                 _activePage->LooseFocus();
468                 if(_cleanUpPage >= 0) {
469                         _pages[(unsigned int)_cleanUpPage]->CleanUp();
470                         _cleanUpPage = -1;
471                 }
472                 _curPage++;
473                 if(_curPage >= _pages.size()) _curPage = 0;
474                 _activePage = _pages[_curPage];
475         } else {
476                 _activePage->Knob1Right1();
477         }
478         update(0.0);
479 }
480
481 void KLN89::Knob1Left1() {
482         if(_mode == KLN89_MODE_DISP) {
483                 _activePage->LooseFocus();
484                 if(_cleanUpPage >= 0) {
485                         _pages[(unsigned int)_cleanUpPage]->CleanUp();
486                         _cleanUpPage = -1;
487                 }
488                 if(_curPage == 0) {
489                         _curPage = _pages.size() - 1;
490                 } else {
491                         _curPage--;
492                 }
493                 _activePage = _pages[_curPage];
494         } else {
495                 _activePage->Knob1Left1();
496         }
497         update(0.0);
498 }
499
500 void KLN89::Knob2Left1() {
501         _activePage->Knob2Left1();
502 }
503
504 void KLN89::Knob2Right1() {
505         _activePage->Knob2Right1();
506 }
507
508 void KLN89::CrsrPressed() {
509         _dispMsg = false;
510         // CRSR cannot be switched off on nrst page.
511         if(_activePage == _nrst_page) { return; }
512         // CRSR is always off when inner-knob is out on nav4 page.
513         if(_curPage == 6 && _activePage->GetSubPage() == 3 && fgGetBool("/instrumentation/kln89/scan-pull")) { return; }
514         if(_cleanUpPage >= 0) {
515                 _pages[(unsigned int)_cleanUpPage]->CleanUp();
516                 _cleanUpPage = -1;
517         }
518         _jumpRestoreCrsr = false;
519         _entJump = _clrJump = -1;
520         ((KLN89Page*)_activePage)->SetEntInvert(false);
521         if(_mode == KLN89_MODE_DISP) {
522                 _mode = KLN89_MODE_CRSR;
523                 _activePage->CrsrPressed();
524         } else {
525                 _mode = KLN89_MODE_DISP;
526                 _activePage->CrsrPressed();
527         }
528         update(0.0);
529 }
530
531 void KLN89::EntPressed() {
532         if(_entJump >= 0) {
533                 if(_curPage < 5) {
534                         // one of the data pages.  Signal ent pressed to it here, and ent pressed to the call back page a few lines further down.
535                         // Ie. 2 ent pressed signals in this case is deliberate.
536                         _activePage->EntPressed();
537                 }
538                 _curPage = _entJump;
539                 _activePage = _pages[(unsigned int)_entJump];
540                 if(_jumpRestoreCrsr) _mode = KLN89_MODE_CRSR;
541                 _entJump = _clrJump = -1;
542         }
543         if(_activePage == _dir_page) {
544                 _dir_page->EntPressed();
545                 _mode = KLN89_MODE_DISP;
546                 _activePage = _pages[_curPage];
547         } else {
548                 _activePage->EntPressed();
549         }
550 }
551
552 void KLN89::ClrPressed() {
553         if(_clrJump >= 0) {
554                 _curPage = _clrJump;
555                 _activePage = _pages[(unsigned int)_clrJump];
556                 if(_jumpRestoreCrsr) _mode = KLN89_MODE_CRSR;
557                 _entJump = _clrJump = -1;
558         }
559         _activePage->ClrPressed();
560 }
561
562 void KLN89::DtoPressed() {
563         if(_activePage != _dir_page) {
564                 // Figure out which waypoint the dir page should display, according to the following rules:
565                 // 1. If the FPL 0 page is displayed AND the cursor is over one of the waypoints, display that waypoint.
566                 // 2. If the NAV 4 page is displayed with the inner knob pulled out, display the waypoint highlighted in the lower RH corner of the nav page.
567                 // 3. If any of APT, VOR, NDB, INT, USR or ACT pages is displayed then display the waypoint being viewed.
568                 // 4. If none of the above, display the active waypoint, unless the active waypoint is the MAP of an approach and it has been flown past 
569                 // (no waypoint sequence past the MAP), in which case display the first waypoint of the missed approach procedure.
570                 // 5. If none of the above (i.e. no active waypoint) then display blanks.
571                 if(_curPage <= 5) {
572                         // APT, VOR, NDB, INT, USR or ACT
573                         if(!_activePage->GetId().empty()) {     // Guard against no user waypoints defined
574                                 _dir_page->SetId(_activePage->GetId());
575                         } else {
576                                 _dir_page->SetId(_activeWaypoint.id);
577                         }
578                 } else if(_curPage == 6 && _activePage->GetSubPage() == 3 && fgGetBool("/instrumentation/kln89/scan-pull") && _activeFP->waypoints.size()) {
579                         // NAV 4
580                         _dir_page->SetId(((KLN89NavPage*)_activePage)->GetNav4WpId());
581                 } else if(_curPage == 7 && _activePage->GetSubPage() == 0 && _mode == KLN89_MODE_CRSR) {
582                         // FPL 0
583                         if(!_activePage->GetId().empty()) {
584                                 //cout << "Not empty!!!\n";
585                                 _dir_page->SetId(_activePage->GetId());
586                         } else {
587                                 //cout << "empty :-(\n";
588                                 _dir_page->SetId(_activeWaypoint.id);
589                         }
590                 } else {
591                         _dir_page->SetId(_activeWaypoint.id);
592                 }
593                 // This need to come after the bit before otherwise the FPL or NAV4 page clears their current ID when it looses focus.
594                 _activePage->LooseFocus();
595                 _activePage = _dir_page;
596                 _mode = KLN89_MODE_CRSR;
597         }
598 }
599
600 void KLN89::NrstPressed() {
601         if(_activePage != _nrst_page) {
602                 _activePage->LooseFocus();      // TODO - check whether we should call loose focus here
603                 _lastActivePage = _activePage;
604                 _activePage = _nrst_page;
605                 _lastMode = _mode;
606                 _mode = KLN89_MODE_CRSR;
607         } else {
608                 _activePage = _lastActivePage;
609                 _mode = _lastMode;
610         }
611 }
612         
613 void KLN89::AltPressed() {
614         if(_activePage != _alt_page) {
615                 _activePage->LooseFocus();      // TODO - check whether we should call loose focus here
616                 _lastActivePage = _activePage;
617                 _alt_page->SetSubPage(0);
618                 _activePage = _alt_page;
619                 _lastMode = _mode;
620                 _mode = KLN89_MODE_CRSR;
621         } else {
622                 _alt_page->LooseFocus();
623                 if(_alt_page->GetSubPage() == 0) {
624                         _alt_page->SetSubPage(1);
625                         _mode = KLN89_MODE_CRSR;
626                 } else {
627                         _activePage = _lastActivePage;
628                         _mode = _lastMode;
629                 }
630         }
631 }
632
633 void KLN89::OBSPressed() {
634         ToggleOBSMode();
635         if(_obsMode) {
636                 if(!fgGetBool("/instrumentation/nav/slaved-to-gps")) {
637                         // NOTE: this only applies to ORS 02 firmware, in ORS 01
638                         // CRSR mode is not automatically set when OBS is started.
639                         _mode = KLN89_MODE_CRSR;
640                 }
641                 _activePage->OBSPressed();
642         }
643 }
644
645 void KLN89::MsgPressed() {
646         // TODO - handle persistent messages such as SUA alerting.
647         // (The message annunciation flashes before first view, but afterwards remains continuously lit with the message available
648         // until the potential conflict no longer pertains).
649         if(_dispMsg && _messageStack.size()) {
650                 _messageStack.pop_front();
651         }
652         _dispMsg = !_dispMsg;
653 }
654
655 void KLN89::ToggleOBSMode() {
656         DCLGPS::ToggleOBSMode();
657 }
658
659 void KLN89::DtoInitiate(const string& id) {
660         _dtoReview = false;
661         // Set the current page to NAV1
662         _curPage = 6;
663         _activePage = _pages[_curPage];
664         _activePage->SetSubPage(0);
665         // TODO - need to output a scratchpad message with the new course, but we don't know it yet!
666         // Call the base class to actually initiate the DTO.
667         DCLGPS::DtoInitiate(id);
668 }
669
670 void KLN89::SetMinDisplayBrightness(int n) {
671         _minDisplayBrightness = n;
672         if(_minDisplayBrightness < 1) _minDisplayBrightness = 1;
673         if(_minDisplayBrightness > 9) _minDisplayBrightness = 9;
674 }
675
676 void KLN89::DecrementMinDisplayBrightness() {
677         _minDisplayBrightness--;
678         if(_minDisplayBrightness < 1) _minDisplayBrightness = 1;
679 }
680
681 void KLN89::IncrementMinDisplayBrightness() {
682         _minDisplayBrightness++;
683         if(_minDisplayBrightness > 9) _minDisplayBrightness = 9;
684 }
685
686 void KLN89::DrawBar(int page) {
687         int px = 1 + (page * 15);
688         int py = 1;
689         for(int i=0; i<7; ++i) {
690                 // Ugh - this is crude and inefficient!
691                 _instrument->DrawPixel(px+i, py);
692                 _instrument->DrawPixel(px+i, py+1);
693         }
694 }
695
696 // Convert moving map to instrument co-ordinates
697 void KLN89::MapToInstrument(int &x, int &y) {
698         x += _xBorder + _xFieldBorder[2] + _xFieldStart[2];
699 }
700
701 // Draw a pixel specified in instrument co-ords, but clipped to the map region
702 //void KLN89::DrawInstrMapPixel(int x, int y) {
703
704 /*
705 // Clip, translate and draw a map pixel
706 // If we didn't need per-pixel clipping, it would be cheaper to translate object rather than pixel positions.
707 void KLN89::DrawMapPixel(int x, int y, bool invert) {
708         if(x < 0 || x > 111 || y < 0 || y > 39)  return;
709         x += _xBorder + _xFieldBorder[2] + _xFieldStart[2];
710         _instrument->DrawPixel(x, y, invert);
711 }
712 */
713
714 // HACK - use something FG provides
715 static double gps_min(const double &a, const double &b) {
716         return(a <= b ? a : b);
717 }
718
719 static double gps_max(const double &a, const double &b) {
720         return(a >= b ? a : b);
721 }
722
723 void KLN89::UpdateMapHeading() {
724         switch(_mapOrientation) {
725         case 0:         // North up
726                 _mapHeading = 0.0;
727                 break;
728         case 1:         // DTK up
729                 _mapHeading = _dtkTrue;
730                 break;
731         case 2:         // Track up
732                 _mapHeading = _track;
733                 break;
734         }
735 }               
736
737 // The screen area allocated to the moving map is 111 x 40 pixels.
738 // In North up mode, the user position marker is at 57, 20. (Map co-ords).
739 void KLN89::DrawMap(bool draw_avs) {
740         // Set the clipping region to the moving map part of the display
741         int xstart = _xBorder + _xFieldBorder[2] + _xFieldStart[2];
742         _instrument->SetClipRegion(xstart, 0, xstart + 110, 39);
743         
744         _mapScaleUnits = (int)_distUnits;
745         _mapScale = (double)(KLN89MapScales[_mapScaleUnits][_mapScaleIndex]);
746         
747         //cout << "Map scale = " << _mapScale << '\n';
748         
749         double mapScaleMeters = _mapScale * (_mapScaleUnits == 0 ? SG_NM_TO_METER : 1000);
750         
751         // TODO - use an aligned projection when either DTK or TK up!
752 #if ENABLE_ATCDCL
753         FGATCAlignedProjection mapProj(SGGeod::fromRad(_gpsLon, _gpsLat), _mapHeading);
754 #else   
755         FGKln89AlignedProjection mapProj(SGGeod::fromRad(_gpsLon, _gpsLat), _mapHeading);
756 #endif
757         double meter_per_pix = (_mapOrientation == 0 ? mapScaleMeters / 20.0f : mapScaleMeters / 29.0f);
758         SGGeod bottomLeft = mapProj.ConvertFromLocal(SGVec3d(gps_max(-57.0 * meter_per_pix, -50000), gps_max((_mapOrientation == 0 ? -20.0 * meter_per_pix : -11.0 * meter_per_pix), -25000), 0.0));
759         SGGeod topRight = mapProj.ConvertFromLocal(SGVec3d(gps_min(54.0 * meter_per_pix, 50000), gps_min((_mapOrientation == 0 ? 20.0 * meter_per_pix : 29.0 * meter_per_pix), 25000), 0.0));
760
761
762
763         
764         // Draw Airport labels first (but not one's that are waypoints)
765         // Draw Airports first (but not one's that are waypoints)
766         // Ditto for VORs (not sure if SUA/VOR/Airport ordering is important or not).
767         // Ditto for SUA
768         // Then flighttrack
769         // Then waypoints
770         // Then waypoint labels (not sure if this should be before or after waypoints)
771         // Then user pos.
772         // Annotation then gets drawn by Nav page, NOT this function.
773
774         if(_drawApt && draw_avs) {
775                 /*
776                 bool have_apt = _overlays->FindArpByRegion(&apt, bottomLeft.lat(), bottomLeft.lon(), topRight.lat(), topRight.lon());
777                 //cout << "Vors enclosed are: ";
778                 // Draw all the labels first...
779                 for(unsigned int i=0; i<apt.size(); ++i) {
780                         //cout << nav[i]->id << ' ';
781                         Point3D p = mapProj.ConvertToLocal(Point3D(apt[i]->lon * SG_RADIANS_TO_DEGREES, apt[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
782                         //cout << p << " .... ";
783                         int mx = int(p.x() / meter_per_pix) + 56;
784                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
785                         //cout << "mx = " << mx << ", my = " << my << '\n';
786                         bool right_align = (p.x() < 0.0);
787                         DrawLabel(apt[i]->id, mx + (right_align ? -2 : 3), my + (p.y() < 0.0 ? -7 : 3), right_align);
788                         // I think that we probably should have -1 in the right_align case above to match the real life instrument.
789                 }
790                 // ...and then all the Apts.
791                 for(unsigned int i=0; i<apt.size(); ++i) {
792                         //cout << nav[i]->id << ' ';
793                         Point3D p = mapProj.ConvertToLocal(Point3D(apt[i]->lon * SG_RADIANS_TO_DEGREES, apt[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
794                         //cout << p << " .... ";
795                         int mx = int(p.x() / meter_per_pix) + 56;
796                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
797                         //cout << "mx = " << mx << ", my = " << my << '\n';
798                         DrawApt(mx, my);
799                 }
800                 //cout << '\n';
801                 */
802         }
803         /*
804         if(_drawVOR && draw_avs) {
805                 Overlays::nav_array_type nav;
806                 bool have_vor = _overlays->FindVorByRegion(&nav, bottomLeft.lat(), bottomLeft.lon(), topRight.lat(), topRight.lon());
807                 //cout << "Vors enclosed are: ";
808                 // Draw all the labels first...
809                 for(unsigned int i=0; i<nav.size(); ++i) {
810                         //cout << nav[i]->id << ' ';
811                         Point3D p = mapProj.ConvertToLocal(Point3D(nav[i]->lon * SG_RADIANS_TO_DEGREES, nav[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
812                         //cout << p << " .... ";
813                         int mx = int(p.x() / meter_per_pix) + 56;
814                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
815                         //cout << "mx = " << mx << ", my = " << my << '\n';
816                         bool right_align = (p.x() < 0.0);
817                         DrawLabel(nav[i]->id, mx + (right_align ? -2 : 3), my + (p.y() < 0.0 ? -7 : 3), right_align);
818                         // I think that we probably should have -1 in the right_align case above to match the real life instrument.
819                 }
820                 // ...and then all the VORs.
821                 for(unsigned int i=0; i<nav.size(); ++i) {
822                         //cout << nav[i]->id << ' ';
823                         Point3D p = mapProj.ConvertToLocal(Point3D(nav[i]->lon * SG_RADIANS_TO_DEGREES, nav[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
824                         //cout << p << " .... ";
825                         int mx = int(p.x() / meter_per_pix) + 56;
826                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
827                         //cout << "mx = " << mx << ", my = " << my << '\n';
828                         DrawVOR(mx, my);
829                 }
830                 //cout << '\n';
831         }
832         */
833         
834         // FlightTrack
835         if(_activeFP->waypoints.size() > 1) {
836                 vector<int> xvec, yvec, qvec;   // qvec stores the quadrant that each waypoint label should
837                                                                                 // be drawn in (relative to the waypoint). 
838                                                                                 // 1 = NE, 2 = SE, 3 = SW, 4 = NW.
839                 double save_h = 0.0; // Each pass, save a heading from the previous one for label quadrant determination.
840                 bool drawTrack = true;
841                 for(unsigned int i=1; i<_activeFP->waypoints.size(); ++i) {
842                         GPSWaypoint* wp0 = _activeFP->waypoints[i-1];
843                         GPSWaypoint* wp1 = _activeFP->waypoints[i];
844                         SGVec3d p0 = mapProj.ConvertToLocal(SGGeod::fromRad(wp0->lon, wp0->lat));
845                         SGVec3d p1 = mapProj.ConvertToLocal(SGGeod::fromRad(wp1->lon, wp1->lat));
846                         int mx0 = int(p0.x() / meter_per_pix + 0.5) + 56;
847                         int my0 = int(p0.y() / meter_per_pix + 0.5) + (_mapOrientation == 0 ? 19 : 10);
848                         int mx1 = int(p1.x() / meter_per_pix + 0.5) + 56;
849                         int my1 = int(p1.y() / meter_per_pix + 0.5) + (_mapOrientation == 0 ? 19 : 10);
850                         if(i == 1) {
851                                 xvec.push_back(mx0);
852                                 yvec.push_back(my0);
853                                 double h = GetGreatCircleCourse(wp0->lat, wp0->lon, wp1->lat, wp1->lon) * SG_RADIANS_TO_DEGREES;
854                                 // Adjust for map orientation
855                                 h -= _mapHeading;
856                                 qvec.push_back(GetLabelQuadrant(h));
857                                 //cout << "i = " << i << ", h = " << h << ", qvec[0] = " << qvec[0] << '\n';
858                         }
859                         xvec.push_back(mx1);
860                         yvec.push_back(my1);
861                         if(drawTrack) { DrawLine(mx0, my0, mx1, my1); }
862                         if(i != 1) {
863                                 double h = GetGreatCircleCourse(wp0->lat, wp0->lon, wp1->lat, wp1->lon) * SG_RADIANS_TO_DEGREES;
864                                 // Adjust for map orientation
865                                 h -= _mapHeading;
866                                 qvec.push_back(GetLabelQuadrant(save_h, h));
867                         }
868                         save_h = GetGreatCircleCourse(wp1->lat, wp1->lon, wp0->lat, wp0->lon) * SG_RADIANS_TO_DEGREES;
869                         // Adjust for map orientation
870                         save_h -= _mapHeading;
871                         if(i == _activeFP->waypoints.size() - 1) {
872                                 qvec.push_back(GetLabelQuadrant(save_h));
873                         }
874                         // Don't draw flight track beyond the missed approach point of an approach
875                         if(_approachLoaded) {
876                                 //cout << "Waypoints are " << wp0->id << " and " << wp1->id << '\n';
877                                 //cout << "Types are " << wp0->appType << " and " << wp1->appType << '\n';
878                                 if(wp1->appType == GPS_MAP) {
879                                         drawTrack = false;
880                                 }
881                         }
882                 }
883                 // ASSERT(xvec.size() == yvec.size() == qvec.size() == _activeFP->waypoints.size());
884                 for(unsigned int i=0; i<xvec.size(); ++i) {
885                         DrawWaypoint(xvec[i], yvec[i]);
886                         bool right_align = (qvec[i] > 2);
887                         bool top = (qvec[i] == 1 || qvec[i] == 4);
888                         // TODO - not sure if labels should be drawn in sequence with waypoints and flightpaths,
889                         // or all before or all afterwards.  Doesn't matter a huge deal though.
890                         DrawLabel(_activeFP->waypoints[i]->id, xvec[i] + (right_align ? -2 : 3), yvec[i] + (top ? 3 : -7), right_align);
891                 }
892         }
893         
894         // User pos
895         if(_mapOrientation == 0) {
896                 // North up
897                 DrawUser1(56, 19);
898         } else if(_mapOrientation == 1) {
899                 // DTK up
900                 DrawUser1(56, 10);
901         } else if(_mapOrientation == 2) {
902                 // TK up
903                 DrawUser2(56, 10);
904         } else {
905                 // Heading up
906                 // TODO - don't know what to do here!
907         }
908         
909         // And finally, reset the clip region to stop the rest of the code going pear-shaped!
910         _instrument->ResetClipRegion();
911 }
912
913 // Get the quadrant to draw the label of the start or end waypoint (i.e. one with only one track from it).
914 // Heading specified FROM the waypoint.
915 // 4 | 1
916 // -----
917 // 3 | 2
918 int KLN89::GetLabelQuadrant(double h) {
919         while(h < 0.0) h += 360.0;
920         while(h > 360.0) h -= 360.0;
921         if(h < 90.0) return(3);
922         if(h < 180.0) return(4);
923         if(h < 270.0) return(1);
924         return(2);
925 }
926
927 // Get the quadrant to draw the label of an en-route waypoint,
928 // with BOTH tracks specified as headings FROM the waypoint.
929 // 4 | 1
930 // -----
931 // 3 | 2
932 int KLN89::GetLabelQuadrant(double h1, double h2) {
933         while(h1 < 0.0) h1 += 360.0;
934         while(h1 > 360.0) h1 -= 360.0;
935         while(h2 < 0.0) h2 += 360.0;
936         while(h2 > 360.0) h2 -= 360.0;
937         double max_min_diff = 0.0;
938         int quad = 1;
939         for(int i=0; i<4; ++i) {
940                 double h = 45 + (90 * i);
941                 double diff1 = fabs(h - h1);
942                 if(diff1 > 180) diff1 = 360 - diff1;
943                 double diff2 = fabs(h - h2);
944                 if(diff2 > 180) diff2 = 360 - diff2;
945                 double min_diff = gps_min(diff1, diff2);
946                 if(min_diff > max_min_diff) {
947                         max_min_diff = min_diff;
948                         quad = i + 1;
949                 }
950         }
951         //cout << "GetLabelQuadrant, h1 = " << h1 << ", h2 = " << h2 << ", quad = " << quad << '\n';
952         return(quad);
953 }
954
955 // Draw the diamond style of user pos
956 // 
957 //    o
958 //   oxo
959 //  oxxxo
960 // oxxxxxo
961 //  oxxxo
962 //   oxo
963 //    o
964 // 
965 void KLN89::DrawUser1(int x, int y) {
966         MapToInstrument(x, y);
967         int min_j = 0, max_j = 0;
968         for(int i=-3; i<=3; ++i) {
969                 for(int j=min_j; j<=max_j; ++j) {
970                         _instrument->DrawPixel(x+j, y+i, (j == min_j || j == max_j ? true : false));
971                 }
972                 if(i < 0) {
973                         min_j--;
974                         max_j++;
975                 } else {
976                         min_j++;
977                         max_j--;
978                 }
979         }
980 }
981
982 // Draw the airplane style of user pos
983 // Define the origin to be the midpoint of the *fuselage*
984 void KLN89::DrawUser2(int x, int y) {
985         MapToInstrument(x, y);
986         
987         // Draw the background as three black quads first
988         _instrument->DrawQuad(x-2, y-3, x+2, y-1, true);
989         _instrument->DrawQuad(x-3, y, x+3, y+2, true);
990         _instrument->DrawQuad(x-1, y+3, x+1, y+3, true);
991         
992         if(_pixelated) {
993                 for(int j=y-2; j<=y+2; ++j) {
994                         _instrument->DrawPixel(x, j);
995                 }
996                 for(int i=x-1; i<=x+1; ++i) {
997                         _instrument->DrawPixel(i, y-2);
998                 }
999                 for(int i=x-2; i<=x+2; ++i) {
1000                         _instrument->DrawPixel(i, y+1);
1001                 }
1002         } else {
1003                 _instrument->DrawQuad(x, y-2, x, y+2);
1004                 _instrument->DrawQuad(x-1, y-2, x+1, y-2);
1005                 _instrument->DrawQuad(x-2, y+1, x+2, y+1);
1006         }
1007 }
1008
1009 // Draw an airport symbol on the moving map
1010 //
1011 //  ooo
1012 // ooxoo
1013 // oxxxo
1014 // ooxoo
1015 //  ooo
1016 //
1017 void KLN89::DrawApt(int x, int y) {
1018         MapToInstrument(x, y);
1019         
1020         int j = y-2;
1021         int i;
1022         for(i=x-1; i<=x+1; ++i) _instrument->DrawPixel(i, j, true);
1023         ++j;
1024         for(i=x-2; i<=x+2; ++i) _instrument->DrawPixel(i, j, (i != x ? true : false));
1025         ++j;
1026         for(i=x-2; i<=x+2; ++i) _instrument->DrawPixel(i, j, (abs(i - x) > 1 ? true : false));
1027         ++j;
1028         for(i=x-2; i<=x+2; ++i) _instrument->DrawPixel(i, j, (i != x ? true : false));
1029         ++j;
1030         for(i=x-1; i<=x+1; ++i) _instrument->DrawPixel(i, j, true);
1031 }
1032
1033 // Draw a waypoint on the moving map
1034 //
1035 // ooooo
1036 // oxxxo
1037 // oxxxo
1038 // oxxxo
1039 // ooooo
1040 //
1041 void KLN89::DrawWaypoint(int x, int y) {
1042         MapToInstrument(x, y);
1043         _instrument->SetDebugging(true);
1044         
1045         // Draw black background
1046         _instrument->DrawQuad(x-2, y-2, x+2, y+2, true);
1047         
1048         // Draw the coloured square
1049         if(_pixelated) {
1050                 for(int i=x-1; i<=x+1; ++i) {
1051                         for(int j=y-1; j<=y+1; ++j) {
1052                                 _instrument->DrawPixel(i, j);
1053                         }
1054                 }
1055         } else {
1056                 _instrument->DrawQuad(x-1, y-1, x+1, y+1);
1057         }
1058         _instrument->SetDebugging(false);
1059 }
1060
1061 // Draw a VOR on the moving map
1062 //
1063 // ooooo
1064 // oxxxo
1065 // oxoxo
1066 // oxxxo
1067 // ooooo
1068 //
1069 void KLN89::DrawVOR(int x, int y) {
1070         // Cheat - draw a waypoint and then a black pixel in the middle.
1071         // Need to call Waypoint draw *before* translating co-ords.
1072         DrawWaypoint(x, y);
1073         MapToInstrument(x, y);
1074         _instrument->DrawPixel(x, y, true);
1075 }
1076
1077 // Draw a line on the moving map
1078 void KLN89::DrawLine(int x1, int y1, int x2, int y2) {
1079         MapToInstrument(x1, y1);
1080         MapToInstrument(x2, y2);
1081         _instrument->DrawLine(x1, y1, x2, y2);
1082 }
1083
1084 void KLN89::DrawMapUpArrow(int x, int y) {
1085         MapToInstrument(x, y);
1086         if(_pixelated) {
1087                 for(int j=0; j<7; ++j) {
1088                         _instrument->DrawPixel(x + 2, y + j);
1089                 }
1090         } else {
1091                 _instrument->DrawQuad(x+2, y, x+2, y+6);
1092         }
1093         _instrument->DrawPixel(x, y+4);
1094         _instrument->DrawPixel(x+1, y+5);
1095         _instrument->DrawPixel(x+3, y+5);
1096         _instrument->DrawPixel(x+4, y+4);
1097 }
1098
1099 // Draw a quad on the moving map
1100 void KLN89::DrawMapQuad(int x1, int y1, int x2, int y2, bool invert) {
1101         MapToInstrument(x1, y1);
1102         MapToInstrument(x2, y2);
1103         _instrument->DrawQuad(x1, y1, x2, y2, invert);
1104 }
1105
1106 // Draw an airport or waypoint label on the moving map
1107 // Specify position by the map pixel co-ordinate of the left or right, bottom, of the *visible* portion of the label.
1108 // The black background quad will automatically overlap this by 1 pixel.
1109 void KLN89::DrawLabel(const string& s, int x1, int y1, bool right_align) {
1110         MapToInstrument(x1, y1);
1111         if(!right_align) {
1112                 for(unsigned int i=0; i<s.size(); ++i) {
1113                         char c = s[i];
1114                         x1 += DrawSmallChar(c, x1, y1);
1115                         x1 ++;
1116                 }
1117         } else {
1118                 for(int i=(int)(s.size()-1); i>=0; --i) {
1119                         char c = s[i];
1120                         x1 -= DrawSmallChar(c, x1, y1, right_align);
1121                         x1--;
1122                 }
1123         }
1124 }
1125
1126 void KLN89::DrawCDI() {
1127         // Scale
1128         for(int i=0; i<5; ++i) {
1129                 DrawSpecialChar(2, 2, 3+i, 2);
1130                 DrawSpecialChar(1, 2, 9+i, 2);
1131         }
1132         
1133         int field = 2;
1134         int px = 8 * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field] + 2;
1135         int py = 2 * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1136         
1137         // Deflection bar
1138         // Every 7 pixels deflection left or right is one dot on the scale, and hence 1/5 FSD.
1139         // Maximum deflection is 37 pixels left, or 38 pixels right !?!
1140         double xtd = CalcCrossTrackDeviation();
1141         int deflect;
1142         if(_cdiScaleTransition) {
1143                 double dots = (xtd / _currentCdiScale) * 5.0;
1144                 deflect = (int)(dots * 7.0 * -1.0);
1145                 // TODO - for all these I think I should add 0.5 before casting to int, and *then* multiply by -1.  Possibly!
1146         } else {
1147                 if(0 == _currentCdiScaleIndex) {        // 5.0nm FSD => 1 nm per dot => 7 pixels per nm.
1148                         deflect = (int)(xtd * 7.0 * -1.0);      // The -1.0 is because we move the 'needle' indicating the course, not the plane.
1149                 } else if(1 == _currentCdiScaleIndex) {
1150                         deflect = (int)(xtd * 35.0 * -1.0);
1151                 } else {        // 0.3 == _cdiScale
1152                         deflect = (int)(xtd * 116.6666666667 * -1.0);
1153                 }
1154         }
1155         if(deflect > 38) deflect = 38;
1156         if(deflect < -37) deflect = -37;
1157         if(_pixelated) {
1158                 for(int j=0; j<9; ++j) {
1159                         _instrument->DrawPixel(px + deflect, py+j);
1160                         _instrument->DrawPixel(px + deflect + 1, py+j);
1161                 }
1162         } else {
1163                 _instrument->DrawQuad(px + deflect, py, px + deflect + 1, py + 8);
1164         }
1165         
1166         // To/From indicator
1167         px-=4;
1168         py+=2;
1169         for(int j=4; j>=0; --j) {
1170                 int k = 10 - (2*j);
1171                 for(int i=0; i<k; ++i) {                
1172                         _instrument->DrawPixel(px+j+i, (_headingBugTo ? py+j : py+4-j));
1173                         // At the extremities, draw the outlining dark pixel
1174                         if(i == 0 || i == k-1) {
1175                                 _instrument->DrawPixel(px+j+i, (_headingBugTo ? py+j+1 : py+3-j), true);
1176                         }
1177                 }
1178         }
1179 }
1180
1181 void KLN89::DrawLegTail(int py) {
1182         int px = 0 * 7 + _xBorder + _xFieldBorder[2] + _xFieldStart[2];
1183         py = py * 9 + _yBorder + _yFieldBorder[2] + _yFieldStart[2];
1184         
1185         px++;
1186         py+=3;
1187         py++;   // Hack - not sure if this represents a border issue.
1188         
1189         for(int i=0; i<9; ++i) _instrument->DrawPixel(px, py+i);
1190         for(int i2=0; i2<5; ++i2) _instrument->DrawPixel(px+i2, py+9);
1191 }
1192
1193 void KLN89::DrawLongLegTail(int py) {
1194         int px = 0 * 7 + _xBorder + _xFieldBorder[2] + _xFieldStart[2];
1195         py = py * 9 + _yBorder + _yFieldBorder[2] + _yFieldStart[2];
1196         
1197         px++;
1198         py+=3;
1199         py++;   // Hack - not sure if this represents a border issue.
1200         
1201         for(int i=0; i<18; ++i) _instrument->DrawPixel(px, py+i);
1202         for(int i2=0; i2<5; ++i2) _instrument->DrawPixel(px+i2, py+18);
1203 }
1204
1205 void KLN89::DrawHalfLegTail(int py) {
1206 }
1207
1208 void KLN89::DrawDivider() {
1209         int px = _xFieldStart[2] - 1;
1210         int py = _yBorder;
1211         for(int i=0; i<36; ++i) {
1212                 _instrument->DrawPixel(px, py+i);
1213         }
1214 }
1215
1216 void KLN89::DrawEnt(int field, int px, int py) {
1217         px = px * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1218         py = py * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field] + 1;
1219         
1220         px++;   // Not sure why we need px++, but it seems to work!
1221         py++;
1222         
1223         // E
1224         for(int i=0; i<5; ++i) _instrument->DrawPixel(px, py+i);
1225         _instrument->DrawPixel(px+1, py);
1226         _instrument->DrawPixel(px+2, py);
1227         _instrument->DrawPixel(px+1, py+2);
1228         _instrument->DrawPixel(px+1, py+4);
1229         _instrument->DrawPixel(px+2, py+4);
1230         
1231         px += 4;
1232         // N
1233         for(int i=0; i<4; ++i) _instrument->DrawPixel(px, py+i);
1234         _instrument->DrawPixel(px+1, py+2);
1235         _instrument->DrawPixel(px+2, py+1);
1236         for(int i=0; i<4; ++i) _instrument->DrawPixel(px+3, py+i);
1237         
1238         px += 5;
1239         // T
1240         _instrument->DrawPixel(px, py+3);
1241         for(int i=0; i<4; ++i) _instrument->DrawPixel(px+1, py+i);
1242         _instrument->DrawPixel(px+2, py+3);
1243 }
1244
1245 void KLN89::DrawMessageAlert() {
1246         // TODO - draw the proper message indicator
1247         if(!_blink) {
1248                 int px = _xBorder + _xFieldBorder[1] + _xFieldStart[1];
1249                 int py = 1 * 9 + _yBorder + _yFieldBorder[1] + _yFieldStart[1] + 1;
1250                 
1251                 px++;   // Not sure why we need px++, but it seems to work!
1252                 py++;
1253
1254                 DrawText("  ", 1, 0, 1, false, 99);
1255                 _instrument->DrawQuad(px+1, py-1, px+2, py+5, true);
1256                 _instrument->DrawQuad(px+3, py+3, px+3, py+5, true);
1257                 _instrument->DrawQuad(px+4, py+2, px+4, py+4, true);
1258                 _instrument->DrawQuad(px+5, py+1, px+6, py+3, true);
1259                 _instrument->DrawQuad(px+7, py+2, px+7, py+4, true);
1260                 _instrument->DrawQuad(px+8, py+3, px+8, py+5, true);
1261                 _instrument->DrawQuad(px+9, py-1, px+10, py+5, true);
1262         }
1263 }
1264
1265 void KLN89::Underline(int field, int px, int py, int len) {
1266         px = px * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1267         py = py * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1268         for(int i=0; i<(len*7); ++i) {
1269                 _instrument->DrawPixel(px, py);
1270                 ++px;
1271         }
1272 }
1273
1274 void KLN89::DrawKPH(int field, int cx, int cy) {
1275         // Add some border
1276         int px = cx * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1277         int py = cy * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1278         
1279         px++;
1280         py++;
1281         
1282         for(int j=0; j<=4; ++j) {
1283                 _instrument->DrawPixel(px, py + 2 +j);
1284                 _instrument->DrawPixel(px + 8, py + j);
1285                 if(j <= 1) {
1286                         _instrument->DrawPixel(px + 11, py + j);
1287                         _instrument->DrawPixel(px + 9 + j, py + 2);
1288                 }
1289         }
1290         
1291         for(int i=0; i<=6; ++i) {
1292                 if(i <= 2) {
1293                         _instrument->DrawPixel(px + 1 + i, py + 4 + i);
1294                         _instrument->DrawPixel(px + 1 + i, py + (4 - i));
1295                 }
1296                 _instrument->DrawPixel(px + 2 + i, py + i);
1297         }
1298 }
1299
1300 void KLN89::DrawDTO(int field, int cx, int cy) {
1301         DrawSpecialChar(6, field, cx, cy);
1302         if(!(_waypointAlert && _blink)) {
1303                 DrawSpecialChar(3, field, cx+1, cy);
1304         }
1305         
1306         int px = cx * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1307         int py = cy * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1308         
1309         px++;
1310         py++;
1311         
1312         // Fill in the gap between the 'D' and the arrow.
1313         _instrument->DrawPixel(px+5, py+3);
1314 }
1315
1316 // Takes character position
1317 void KLN89::DrawChar(char c, int field, int px, int py, bool bold, bool invert) {
1318         // Ignore field for now
1319         // Add some border
1320         px = px * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1321         py = py * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1322         
1323         // Draw an orange background for inverted characters
1324         if(invert) {
1325                 for(int i=0; i<7; ++i) {
1326                         for(int j=0; j<9; ++j) {
1327                                 _instrument->DrawPixel(px + i, py + j);
1328                         }
1329                 }
1330         }
1331                                 
1332         if(c < 33) return;  // space
1333         
1334         // Render normal decimal points in bold floats
1335         if(c == '.') bold = false;
1336         
1337         ++py;   // Shift the char up by one pixel
1338         for(int j=7; j>=0; --j) {
1339                 char c1 = (bold ? NumbersBold[c-48][j] : UpperAlpha[c-33][j]);
1340                 // Don't do the last column for now (ie. j = 1, not 0)
1341                 for(int i=5; i>=0; --i) {
1342                         if(c1 & (01 << i)) {
1343                                 _instrument->DrawPixel(px, py, invert);
1344                         }
1345                         ++px;
1346                 }
1347                 px -= 6;
1348                 ++py;
1349         }
1350 }
1351
1352 // Takes pixel position
1353 void KLN89::DrawFreeChar(char c, int x, int y, bool draw_background) {
1354         
1355         if(draw_background) {
1356                 _instrument->DrawQuad(x, y, x+6, y+8, true);
1357         }               
1358                                 
1359         if(c < 33) return;  // space
1360         
1361         ++y;    // Shift the char up by one pixel
1362         for(int j=7; j>=0; --j) {
1363                 char c1 = UpperAlpha[c-33][j];
1364                 // Don't do the last column for now (ie. j = 1, not 0)
1365                 for(int i=5; i>=0; --i) {
1366                         if(c1 & (01 << i)) {
1367                                 _instrument->DrawPixel(x, y);
1368                         }
1369                         ++x;
1370                 }
1371                 x -= 6;
1372                 ++y;
1373         }
1374 }
1375
1376 // Takes instrument pixel co-ordinates.
1377 // Position is specified by the bottom of the *visible* portion, by default the left position unless align_right is true.
1378 // The return value is the pixel width of the visible portion
1379 int KLN89::DrawSmallChar(char c, int x, int y, bool align_right) {
1380         // calculate the index into the SmallChar array
1381         int idx;
1382         if(c > 47 && c < 58) {
1383                 // number
1384                 idx = c - 48;
1385         } else if(c > 64 && c < 91) {
1386                 // Uppercase letter
1387                 idx = c - 55;
1388         } else {
1389                 return(0);
1390         }
1391         
1392         char n = SmallChar[idx][0];             // Width of visible portion
1393         if(align_right) x -= n;
1394         
1395         // background
1396         _instrument->DrawQuad(x - 1, y - 1, x + n, y + 5, true);
1397         
1398         for(int j=7; j>=3; --j) {
1399                 char c1 = SmallChar[idx][j];
1400                 for(int i=n-1; i>=0; --i) {
1401                         if(c1 & (01 << i)) {
1402                                 _instrument->DrawPixel(x, y);
1403                         }
1404                         ++x;
1405                 }
1406                 x -= n;
1407                 ++y;
1408         }
1409         
1410         return(n);
1411 }
1412
1413 // Takes character position
1414 void KLN89::DrawSpecialChar(char c, int field, int cx, int cy, bool bold) {
1415         if(c > 7) {
1416                 cout << "ERROR - requested special char outside array bounds!\n";
1417                 return;  // Increment this as SpecialChar grows
1418         }
1419         
1420         // Convert character to pixel position.
1421         // Ignore field for now
1422         // Add some border
1423         int px = cx * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1424         int py = cy * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1425         ++py;   // Total hack - the special chars were coming out 1 pixel too low!
1426         for(int i=7; i>=0; --i) {
1427                 char c1 = SpecialChar[(int)c][i];
1428                 // Don't do the last column for now (ie. j = 1, not 0)
1429                 for(int j=5; j>=0; --j) {
1430                         if(c1 & (01 << j)) {
1431                                 _instrument->DrawPixel(px, py);
1432                         }
1433                         ++px;
1434                 }
1435                 px -= 6;
1436                 ++py;
1437         }
1438 }
1439
1440 void KLN89::DrawText(const string& s, int field, int px, int py, bool bold, int invert) {
1441         for(int i = 0; i < (int)s.size(); ++i) {
1442                 DrawChar(s[(unsigned int)i], field, px+i, py, bold, (invert == i || invert == 99));
1443         }
1444 }
1445
1446 void KLN89::DrawMapText(const string& s, int x, int y, bool draw_background) {
1447         MapToInstrument(x, y);
1448         if(draw_background) {
1449                 //_instrument->DrawQuad(x, y, x + (7 * s.size()) - 1, y + 8, true);
1450                 _instrument->DrawQuad(x - 1, y, x + (7 * s.size()) - 2, y + 8, true);
1451                 // The minus 1 and minus 2 are an ugly hack to disguise the fact that I've lost track of exactly what's going on!
1452         }
1453         
1454         for(int i = 0; i < (int)s.size(); ++i) {
1455                 DrawFreeChar(s[(unsigned int)i], x+(i * 7)-1, y);
1456         }
1457 }
1458
1459 void KLN89::DrawLatitude(double d, int field, int px, int py) {
1460         DrawChar((d >= 0 ? 'N' : 'S'), field, px, py);
1461         d = fabs(d);
1462         px += 1;
1463         // TODO - sanity check input to ensure major lat field can only ever by 2 chars wide
1464         char buf[8];
1465         // Don't know whether to zero pad the below for single digits or not?
1466         //cout << d << ", " << (int)d << '\n';
1467         // 3 not 2 in size before for trailing \0
1468         int n = snprintf(buf, 3, "%i", (int)d);
1469         string s = buf;
1470         //cout << s << "... " << n << '\n';
1471         DrawText(s, field, px+(3-n), py);
1472         n = snprintf(buf, 7, "%05.2f'", ((double)(d - (int)d)) * 60.0f);
1473         s = buf;
1474         px += 3;
1475         DrawSpecialChar(0, field, px, py);      // Degrees symbol
1476         px++;
1477         DrawText(s, field, px, py);
1478 }
1479
1480 void KLN89::DrawLongitude(double d, int field, int px, int py) {
1481         DrawChar((d >= 0 ? 'E' : 'W'), field, px, py);
1482         d = fabs(d);
1483         px += 1;
1484         // TODO - sanity check input to ensure major lat field can only ever be 2 chars wide
1485         char buf[8];
1486         // Don't know whether to zero pad the below for single digits or not?
1487         //cout << d << ", " << (int)d << '\n';
1488         // 4 not 3 in size before for trailing \0
1489         int n = snprintf(buf, 4, "%i", (int)d);
1490         string s = buf;
1491         //cout << s << "... " << n << '\n';
1492         DrawText(s, field, px+(3-n), py);
1493         n = snprintf(buf, 7, "%05.2f'", ((double)(d - (int)d)) * 60.0f);
1494         s = buf;
1495         px += 3;
1496         DrawSpecialChar(0, field, px, py);      // Degrees symbol
1497         px++;
1498         DrawText(s, field, px, py);
1499 }
1500
1501 void KLN89::DrawFreq(double d, int field, int px, int py) {
1502         if(d >= 1000) d /= 100.0f;
1503         char buf[8];
1504         snprintf(buf, 7, "%6.2f", d);
1505         string s = buf;
1506         DrawText(s, field, px, py);
1507 }
1508
1509 void KLN89::DrawTime(double time, int field, int px, int py) {
1510         int hrs = (int)(time / 3600);
1511         int mins = (int)(ceil((time - (hrs * 3600)) / 60.0));
1512         char buf[10];
1513         int n;
1514         if(time >= 60.0) {
1515                 // Draw hr:min
1516                 n = snprintf(buf, 9, "%i:%02i", hrs, mins);
1517         } else {
1518                 // Draw :secs
1519                 n = snprintf(buf, 4, ":%02i", (int)time);
1520         }
1521         string s = buf;
1522         DrawText(s, field, px - n + 1, py);
1523 }
1524
1525 void KLN89::DrawHeading(int h, int field, int px, int py) {
1526         char buf[4];
1527         snprintf(buf, 4, "%i", h);
1528         string s = buf;
1529         DrawText(s, field, px - s.size(), py);
1530         DrawSpecialChar(0, field, px, py);      // Degrees symbol
1531 }
1532
1533 void KLN89::DrawDist(double d, int field, int px, int py) {
1534         d *= (_distUnits == GPS_DIST_UNITS_NM ? 1.0 : SG_NM_TO_METER * 0.001);
1535         char buf[10];
1536         snprintf(buf, 9, "%i", (int)(d + 0.5));
1537         string s = buf;
1538         s += (_distUnits == GPS_DIST_UNITS_NM ? "nm" : "Km");
1539         DrawText(s, field, px - s.size() + 1, py);
1540 }
1541
1542 void KLN89::DrawSpeed(double v, int field, int px, int py, int decimal) {
1543         // TODO - implement variable decimal places
1544         v *= (_velUnits == GPS_VEL_UNITS_KT ? 1.0 : 0.51444444444 * 0.001 * 3600.0);
1545         char buf[10];
1546         snprintf(buf, 9, "%i", (int)(v + 0.5));
1547         string s = buf;
1548         if(_velUnits == GPS_VEL_UNITS_KT) {
1549                 s += "kt";
1550                 DrawText(s, field, px - s.size() + 1, py);
1551         } else {
1552                 DrawText(s, field, px - s.size() - 1, py);
1553                 DrawKPH(field, px - 1, py);
1554         }
1555 }
1556
1557 void KLN89::DrawDirDistField(double lat, double lon, int field, int px, int py, bool to_flag, bool cursel) {
1558         DrawChar('>', field, px, py);
1559         char buf[8];
1560         double h;
1561         if(to_flag) {
1562                 h = GetMagHeadingFromTo(_gpsLat, _gpsLon, lat, lon);
1563         } else {
1564                 h = GetMagHeadingFromTo(lat, lon, _gpsLat, _gpsLon);
1565         }
1566         while(h < 0.0) h += 360.0;
1567         while(h > 360.0) h -= 360.0;
1568         snprintf(buf, 4, "%3i", (int)(h + 0.5));
1569         string s = buf;
1570         if(!(cursel && _blink)) { 
1571                 DrawText(s, field, px + 4 - s.size(), py);
1572                 DrawSpecialChar(0, field, px+4, py);
1573                 DrawText((to_flag ? "To" : "Fr"), field, px+5, py);
1574                 if(cursel) Underline(field, px + 1, py, 6);
1575         }
1576         //double d = GetHorizontalSeparation(_gpsLat, _gpsLon, lat, lon);
1577         //d *= (_distUnits == GPS_DIST_UNITS_NM ? SG_METER_TO_NM : 0.001);
1578         double d = GetGreatCircleDistance(_gpsLat, _gpsLon, lat, lon);
1579         d *= (_distUnits == GPS_DIST_UNITS_NM ? 1.0 : SG_NM_TO_METER * 0.001);
1580         if(d >= 100.0) {
1581                 snprintf(buf, 7, "%5i", (int)(d + 0.5));
1582         } else {
1583                 snprintf(buf, 7, "%4.1f", d);
1584         }
1585         s = buf;
1586         DrawText(s, field, px + 12 - s.size(), py);
1587         DrawText((_distUnits == GPS_DIST_UNITS_NM ? "nm" : "Km"), field, px + 12, py);
1588 }
1589
1590 char KLN89::IncChar(char c, bool gap, bool wrap) {
1591         if(c == '9') return(wrap ? (gap ? ' ' : 'A') : '9');
1592         if(c == 'Z') return('0');
1593         if(c == ' ') return('A');
1594         return(c + 1);
1595 }
1596
1597 char KLN89::DecChar(char c, bool gap, bool wrap) {
1598         if(c == 'A') return(wrap ? (gap ? ' ' : '9') : 'A');
1599         if(c == '0') return('Z');
1600         if(c == ' ') return('9');
1601         return(c - 1);
1602 }