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