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