]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/hud.cxx
Another round of memory leak fixes from Till Busch
[flightgear.git] / src / Cockpit / hud.cxx
1 // hud.cxx -- hud defines and prototypes
2 //
3 // Written by Michele America, started September 1997.
4 //
5 // Copyright (C) 1997  Michele F. America  - micheleamerica@geocities.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #include <simgear/compiler.h>
24 #include <simgear/structure/exception.hxx>
25
26 #include STL_STRING
27 #include STL_FSTREAM
28
29 #ifdef HAVE_CONFIG_H
30 #  include <config.h>
31 #endif
32
33 #ifdef HAVE_WINDOWS_H
34 #  include <windows.h>
35 #endif
36
37 #ifdef __BORLANDC__
38 #  define exception c_exception
39 #endif
40
41 #include <math.h>
42
43 #include <stdlib.h>
44 #include <stdio.h>              // char related functions
45 #include <string.h>             // strcmp()
46
47 #include SG_GLU_H
48
49 #include <simgear/constants.h>
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/misc/sg_path.hxx>
52
53 #include <Aircraft/aircraft.hxx>
54 //#include <Autopilot/xmlauto.hxx>
55 #include <GUI/new_gui.hxx>           // FGFontCache
56 #include <Main/globals.hxx>
57 #include <Scenery/scenery.hxx>
58
59 #include "hud.hxx"
60
61
62 static HUD_Properties *HUDprop = 0;
63
64 static char units[5];
65
66 deque<SGSharedPtr<instr_item> > HUD_deque;
67
68 fgTextList HUD_TextList;
69 fgLineList HUD_LineList;
70 fgLineList HUD_StippleLineList;
71
72 fntRenderer *HUDtext = 0;
73 fntTexFont *HUD_Font = 0;
74 float HUD_TextSize = 0;
75 int HUD_style = 0;
76
77 float HUD_matrix[16];
78
79 int readHud( istream &input );
80 int readInstrument ( const SGPropertyNode * node);
81
82 static void drawHUD(osg::State*);
83 static void fgUpdateHUDVirtual(osg::State*);
84
85
86 class locRECT {
87 public:
88     RECT rect;
89
90     locRECT( UINT left, UINT top, UINT right, UINT bottom);
91     RECT get_rect(void) { return rect; }
92 };
93
94 locRECT :: locRECT( UINT left, UINT top, UINT right, UINT bottom)
95 {
96     rect.left   =  left;
97     rect.top    =  top;
98     rect.right  =  right;
99     rect.bottom =  bottom;
100
101 }
102 // #define DEBUG
103
104
105
106
107 int readInstrument(const SGPropertyNode * node)
108 {
109     static const SGPropertyNode *startup_units_node
110         = fgGetNode("/sim/startup/units");
111
112     instr_item *HIptr;
113
114     if ( !strcmp(startup_units_node->getStringValue(), "feet") ) {
115         strcpy(units, " ft");
116     } else {
117         strcpy(units, " m");
118     }
119
120     const SGPropertyNode * ladder_group = node->getNode("ladders");
121
122     if (ladder_group != 0) {
123         int nLadders = ladder_group->nChildren();
124         for (int j = 0; j < nLadders; j++) {
125             HIptr = static_cast<instr_item *>(new HudLadder(ladder_group->getChild(j)));
126             HUD_deque.insert(HUD_deque.begin(), HIptr);
127         }
128     }
129
130     const SGPropertyNode * card_group = node->getNode("cards");
131     if (card_group != 0) {
132         int nCards = card_group->nChildren();
133         for (int j = 0; j < nCards; j++) {
134             const char *type = card_group->getChild(j)->getStringValue("type", "gauge");
135
136             if (!strcmp(type, "gauge"))
137                 HIptr = static_cast<instr_item *>(new gauge_instr(card_group->getChild(j)));
138             else if (!strcmp(type, "dial") || !strcmp(type, "tape"))
139                 HIptr = static_cast<instr_item *>(new hud_card(card_group->getChild(j)));
140             else {
141                 SG_LOG(SG_INPUT, SG_WARN, "HUD: unknown 'card' type: " << type);
142                 continue;
143             }
144             HUD_deque.insert(HUD_deque.begin(), HIptr);
145         }
146     }
147
148     const SGPropertyNode * label_group = node->getNode("labels");
149     if (label_group != 0) {
150         int nLabels = label_group->nChildren();
151         for (int j = 0; j < nLabels; j++) {
152             HIptr = static_cast<instr_item *>(new instr_label(label_group->getChild(j)));
153             HUD_deque.insert(HUD_deque.begin(), HIptr);
154         }
155     }
156
157     const SGPropertyNode * tbi_group = node->getNode("tbis");
158     if (tbi_group != 0) {
159         int nTbis = tbi_group->nChildren();
160         for (int j = 0; j < nTbis; j++) {
161             HIptr = static_cast<instr_item *>(new fgTBI_instr(tbi_group->getChild(j)));
162             HUD_deque.insert(HUD_deque.begin(), HIptr);
163         }
164     }
165
166     const SGPropertyNode * rwy_group = node->getNode("runways");
167     if (rwy_group != 0) {
168         int nRwy = rwy_group->nChildren();
169         for (int j = 0; j < nRwy; j++) {
170             HIptr = static_cast<instr_item *>(new runway_instr(rwy_group->getChild(j)));
171             HUD_deque.insert(HUD_deque.begin(), HIptr);
172         }
173     }
174     return 0;
175 } //end readinstrument
176
177
178 int readHud( istream &input )
179 {
180
181     SGPropertyNode root;
182
183     try {
184         readProperties(input, &root);
185     } catch (const sg_exception &e) {
186         guiErrorMessage("Error reading HUD: ", e);
187         return 0;
188     }
189
190
191     SG_LOG(SG_INPUT, SG_INFO, "Read properties for  " <<
192            root.getStringValue("name"));
193
194     if (!root.getNode("depreciated"))
195         SG_LOG(SG_INPUT, SG_ALERT, "WARNING: use of depreciated old HUD");
196
197     HUD_deque.erase( HUD_deque.begin(), HUD_deque.end());
198
199
200     SG_LOG(SG_INPUT, SG_INFO, "Reading Hud instruments");
201
202     const SGPropertyNode * instrument_group = root.getChild("instruments");
203     int nInstruments = instrument_group->nChildren();
204
205     for (int i = 0; i < nInstruments; i++) {
206
207         const SGPropertyNode * node = instrument_group->getChild(i);
208
209         SGPath path( globals->get_fg_root() );
210         path.append(node->getStringValue("path"));
211
212         SG_LOG(SG_INPUT, SG_INFO, "Reading Instrument "
213                << node->getName()
214                << " from "
215                << path.str());
216
217         SGPropertyNode root2;
218         try {
219             readProperties(path.str(), &root2);
220         } catch (const sg_exception &e) {
221             guiErrorMessage("Error reading HUD instrument: ", e);
222             continue;
223         }
224         readInstrument(&root2);
225     }//for loop(i)
226
227     return 0;
228 }
229
230
231 // fgHUDInit
232 //
233 // Constructs a HUD object and then adds in instruments. At the present
234 // the instruments are hard coded into the routine. Ultimately these need
235 // to be defined by the aircraft's instrumentation records so that the
236 // display for a Piper Cub doesn't show the speed range of a North American
237 // mustange and the engine readouts of a B36!
238 //
239 int fgHUDInit( fgAIRCRAFT * /* current_aircraft */ )
240 {
241
242     HUD_style = 1;
243
244     SG_LOG( SG_COCKPIT, SG_INFO, "Initializing current aircraft HUD" );
245
246     string hud_path =
247         fgGetString("/sim/hud/path", "Huds/Default/default.xml");
248     SGPath path(globals->get_fg_root());
249     path.append(hud_path);
250
251     ifstream input(path.c_str());
252     if (!input.good()) {
253         SG_LOG(SG_INPUT, SG_ALERT,
254                "Cannot read Hud configuration from " << path.str());
255     } else {
256         readHud(input);
257         input.close();
258     }
259
260     if ( HUDtext ) {
261         // this chunk of code is not necessarily thread safe if the
262         // compiler optimizer reorders these statements.  Note that
263         // "delete ptr" does not set "ptr = NULL".  We have to do that
264         // ourselves.
265         fntRenderer *tmp = HUDtext;
266         HUDtext = NULL;
267         delete tmp;
268     }
269
270     FGFontCache *fc = globals->get_fontcache();
271     HUD_Font = fc->getTexFont(fgGetString("/sim/hud/font/name", "Helvetica.txf"));
272     if (!HUD_Font)
273         throw sg_throwable(string("/sim/hud/font/name is not a texture font"));
274
275     HUD_TextSize = fgGetFloat("/sim/hud/font/size", 10);
276
277     HUDtext = new fntRenderer();
278     HUDtext->setFont(HUD_Font);
279     HUDtext->setPointSize(HUD_TextSize);
280     HUD_TextList.setFont( HUDtext );
281
282     if (!HUDprop)
283         HUDprop = new HUD_Properties;
284     return 0;  // For now. Later we may use this for an error code.
285
286 }
287
288
289 int fgHUDInit2( fgAIRCRAFT * /* current_aircraft */ )
290 {
291
292     HUD_style = 2;
293
294     SG_LOG( SG_COCKPIT, SG_INFO, "Initializing current aircraft HUD" );
295
296     SGPath path(globals->get_fg_root());
297     path.append("Huds/Minimal/default.xml");
298
299
300     ifstream input(path.c_str());
301     if (!input.good()) {
302         SG_LOG(SG_INPUT, SG_ALERT,
303                "Cannot read Hud configuration from " << path.str());
304     } else {
305         readHud(input);
306         input.close();
307     }
308
309     if (!HUDprop)
310         HUDprop = new HUD_Properties;
311     return 0;  // For now. Later we may use this for an error code.
312
313 }
314 //$$$ End - added, Neetha, 28 Nov 2k
315
316
317 // fgUpdateHUD
318 //
319 // Performs a once around the list of calls to instruments installed in
320 // the HUD object with requests for redraw. Kinda. It will when this is
321 // all C++.
322 //
323 void fgUpdateHUD( osg::State* state ) {
324
325     static const SGPropertyNode *enable3d_node = fgGetNode("/sim/hud/enable3d");
326     if ( HUD_style == 1 && enable3d_node->getBoolValue() ) {
327         fgUpdateHUDVirtual(state);
328         return;
329     }
330
331     static const float normal_aspect = float(640) / float(480);
332     // note: aspect_ratio is Y/X
333     float current_aspect = 1.0f/globals->get_current_view()->get_aspect_ratio();
334     if ( current_aspect > normal_aspect ) {
335         float aspect_adjust = current_aspect / normal_aspect;
336         float adjust = 320.0f*aspect_adjust - 320.0f;
337         fgUpdateHUD( state, -adjust, 0.0f, 640.0f+adjust, 480.0f );
338     } else {
339         float aspect_adjust = normal_aspect / current_aspect;
340         float adjust = 240.0f*aspect_adjust - 240.0f;
341         fgUpdateHUD( state, 0.0f, -adjust, 640.0f, 480.0f+adjust );
342     }
343 }
344
345 void fgUpdateHUDVirtual(osg::State* state)
346 {
347     FGViewer* view = globals->get_current_view();
348
349     // Standard fgfs projection, with essentially meaningless clip
350     // planes (we'll map the whole HUD plane to z=-1)
351     glMatrixMode(GL_PROJECTION);
352     glPushMatrix();
353     glLoadIdentity();
354     gluPerspective(view->get_v_fov(), 1/view->get_aspect_ratio(), 0.1, 10);
355
356     glMatrixMode(GL_MODELVIEW);
357     glPushMatrix();
358     glLoadIdentity();
359
360     // Standard fgfs view direction computation
361     float lookat[3];
362     lookat[0] = -sin(SG_DEGREES_TO_RADIANS * view->getHeadingOffset_deg());
363     lookat[1] = tan(SG_DEGREES_TO_RADIANS * view->getPitchOffset_deg());
364     lookat[2] = -cos(SG_DEGREES_TO_RADIANS * view->getHeadingOffset_deg());
365     if (fabs(lookat[1]) > 9999)
366         lookat[1] = 9999; // FPU sanity
367     gluLookAt(0, 0, 0, lookat[0], lookat[1], lookat[2], 0, 1, 0);
368
369     // Map the -1:1 square to a 55.0x41.25 degree wide patch at z=1.
370     // This is the default fgfs field of view, which the HUD files are
371     // written to assume.
372     float dx = 0.52056705; // tan(55/2)
373     float dy = dx * 0.75;  // assumes 4:3 aspect ratio
374     float m[16];
375     m[0] = dx; m[4] =  0; m[ 8] = 0; m[12] = 0;
376     m[1] =  0; m[5] = dy; m[ 9] = 0; m[13] = 0;
377     m[2] =  0; m[6] =  0; m[10] = 1; m[14] = 0;
378     m[3] =  0; m[7] =  0; m[11] = 0; m[15] = 1;
379     glMultMatrixf(m);
380
381     // Convert the 640x480 "HUD standard" coordinate space to a square
382     // about the origin in the range [-1:1] at depth of -1
383     glScalef(1./320, 1./240, 1);
384     glTranslatef(-320, -240, -1);
385
386     // Do the deed
387     drawHUD(state);
388
389     // Clean up our mess
390     glMatrixMode(GL_PROJECTION);
391     glPopMatrix();
392     glMatrixMode(GL_MODELVIEW);
393     glPopMatrix();
394 }
395
396
397 void fgUpdateHUD( osg::State* state, GLfloat x_start, GLfloat y_start,
398                   GLfloat x_end, GLfloat y_end )
399 {
400     glMatrixMode(GL_PROJECTION);
401     glPushMatrix();
402     glLoadIdentity();
403     gluOrtho2D(x_start, x_end, y_start, y_end);
404
405     glMatrixMode(GL_MODELVIEW);
406     glPushMatrix();
407     glLoadIdentity();
408
409     drawHUD(state);
410
411     glMatrixMode(GL_PROJECTION);
412     glPopMatrix();
413     glMatrixMode(GL_MODELVIEW);
414     glPopMatrix();
415 }
416
417
418 void drawHUD(osg::State* state)
419 {
420     if ( !HUD_deque.size() ) // Trust everyone, but ALWAYS cut the cards!
421         return;
422
423     HUD_TextList.erase();
424     HUD_LineList.erase();
425     // HUD_StippleLineList.erase();
426
427     glDisable(GL_DEPTH_TEST);
428     glDisable(GL_LIGHTING);
429
430     static const SGPropertyNode *heading_enabled
431         = fgGetNode("/autopilot/locks/heading", true);
432     static const SGPropertyNode *altitude_enabled
433         = fgGetNode("/autopilot/locks/altitude", true);
434
435     static char hud_hdg_text[256];
436     static char hud_wp0_text[256];
437     static char hud_wp1_text[256];
438     static char hud_wp2_text[256];
439     static char hud_alt_text[256];
440
441     glEnable(GL_BLEND);
442     if (HUDprop->isTransparent())
443         glBlendFunc(GL_SRC_ALPHA, GL_ONE);
444     else
445         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
446
447     if (HUDprop->isAntialiased()) {
448         glEnable(GL_LINE_SMOOTH);
449         glAlphaFunc(GL_GREATER, HUDprop->alphaClamp());
450         glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
451         //glLineWidth(1.5);
452     } else {
453         //glLineWidth(1.0);
454     }
455
456     HUDprop->setColor();
457     for_each(HUD_deque.begin(), HUD_deque.end(), HUDdraw());
458
459     //HUD_TextList.add( fgText(40, 10, get_formated_gmt_time(), 0) );
460
461
462     int apY = 480 - 80;
463
464
465     if (strcmp( heading_enabled->getStringValue(), "dg-heading-hold") == 0 ) {
466         snprintf( hud_hdg_text, 256, "hdg = %.1f\n",
467                   fgGetDouble("/autopilot/settings/heading-bug-deg") );
468         HUD_TextList.add( fgText( 40, apY, hud_hdg_text ) );
469         apY -= 15;
470     } else if ( strcmp(heading_enabled->getStringValue(), "true-heading-hold") == 0 ) {
471         snprintf( hud_hdg_text, 256, "hdg = %.1f\n",
472                   fgGetDouble("/autopilot/settings/true-heading-deg") );
473         HUD_TextList.add( fgText( 40, apY, hud_hdg_text ) );
474         apY -= 15;
475
476         string wp0_id = fgGetString( "/autopilot/route-manager/wp[0]/id" );
477         if ( wp0_id.length() > 0 ) {
478             snprintf( hud_wp0_text, 256, "%5s %6.1fnm %s", wp0_id.c_str(),
479                       fgGetDouble( "/autopilot/route-manager/wp[0]/dist" ),
480                       fgGetString( "/autopilot/route-manager/wp[0]/eta" ) );
481             HUD_TextList.add( fgText( 40, apY, hud_wp0_text ) );
482             apY -= 15;
483         }
484         string wp1_id = fgGetString( "/autopilot/route-manager/wp[1]/id" );
485         if ( wp1_id.length() > 0 ) {
486             snprintf( hud_wp1_text, 256, "%5s %6.1fnm %s", wp1_id.c_str(),
487                       fgGetDouble( "/autopilot/route-manager/wp[1]/dist" ),
488                       fgGetString( "/autopilot/route-manager/wp[1]/eta" ) );
489             HUD_TextList.add( fgText( 40, apY, hud_wp1_text ) );
490             apY -= 15;
491         }
492         string wp2_id = fgGetString( "/autopilot/route-manager/wp-last/id" );
493         if ( wp2_id.length() > 0 ) {
494             snprintf( hud_wp2_text, 256, "%5s %6.1fnm %s", wp2_id.c_str(),
495                       fgGetDouble( "/autopilot/route-manager/wp-last/dist" ),
496                       fgGetString( "/autopilot/route-manager/wp-last/eta" ) );
497             HUD_TextList.add( fgText( 40, apY, hud_wp2_text ) );
498             apY -= 15;
499         }
500     }
501
502     if ( strcmp( altitude_enabled->getStringValue(), "altitude-hold" ) == 0 ) {
503         snprintf( hud_alt_text, 256, "alt = %.0f\n",
504                   fgGetDouble("/autopilot/settings/target-altitude-ft") );
505         HUD_TextList.add( fgText( 40, apY, hud_alt_text ) );
506         apY -= 15;
507     } else if ( strcmp( altitude_enabled->getStringValue(), "agl-hold" ) == 0 ){
508         snprintf( hud_alt_text, 256, "agl = %.0f\n",
509                   fgGetDouble("/autopilot/settings/target-agl-ft") );
510         HUD_TextList.add( fgText( 40, apY, hud_alt_text ) );
511         apY -= 15;
512     }
513
514     HUD_TextList.draw();
515     HUD_LineList.draw();
516
517     // glEnable(GL_LINE_STIPPLE);
518     // glLineStipple( 1, 0x00FF );
519     // HUD_StippleLineList.draw();
520     // glDisable(GL_LINE_STIPPLE);
521
522     if (HUDprop->isAntialiased()) {
523         glDisable(GL_ALPHA_TEST);
524         glDisable(GL_LINE_SMOOTH);
525         //glLineWidth(1.0);
526     }
527
528     if (HUDprop->isTransparent())
529         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
530
531     glEnable(GL_DEPTH_TEST);
532     glEnable(GL_LIGHTING);
533 }
534
535
536 void fgTextList::draw()
537 {
538     if (!Font)
539         return;
540
541     vector<fgText>::iterator curString = List.begin();
542     vector<fgText>::iterator lastString = List.end();
543
544     glPushAttrib(GL_COLOR_BUFFER_BIT);
545     glEnable(GL_BLEND);
546     if (HUDprop->isTransparent())
547         glBlendFunc(GL_SRC_ALPHA, GL_ONE);
548     else
549         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
550
551     if (HUDprop->isAntialiased()) {
552         glEnable(GL_ALPHA_TEST);
553         glAlphaFunc(GL_GREATER, HUDprop->alphaClamp());
554     }
555
556     Font->begin();
557     for (; curString != lastString; curString++)
558         curString->Draw(Font);
559     Font->end();
560
561     glDisable(GL_TEXTURE_2D);
562     glPopAttrib();
563 }
564
565
566 // HUD property listener class
567 //
568 HUD_Properties::HUD_Properties() :
569     _current(fgGetNode("/sim/hud/current-color", true)),
570     _visibility(fgGetNode("/sim/hud/visibility", true)),
571     _antialiasing(fgGetNode("/sim/hud/color/antialiased", true)),
572     _transparency(fgGetNode("/sim/hud/color/transparent", true)),
573     _red(fgGetNode("/sim/hud/color/red", true)),
574     _green(fgGetNode("/sim/hud/color/green", true)),
575     _blue(fgGetNode("/sim/hud/color/blue", true)),
576     _alpha(fgGetNode("/sim/hud/color/alpha", true)),
577     _alpha_clamp(fgGetNode("/sim/hud/color/alpha-clamp", true)),
578     _brightness(fgGetNode("/sim/hud/color/brightness", true)),
579     _visible(false),
580     _antialiased(false),
581     _transparent(false),
582     _a(0.67),
583     _cl(0.01)
584 {
585     _visibility->addChangeListener(this);
586     _antialiasing->addChangeListener(this);
587     _transparency->addChangeListener(this);
588     _red->addChangeListener(this);
589     _green->addChangeListener(this);
590     _blue->addChangeListener(this);
591     _alpha->addChangeListener(this);
592     _alpha_clamp->addChangeListener(this);
593     _brightness->addChangeListener(this);
594     _current->addChangeListener(this, true);
595 }
596
597
598 void HUD_Properties::valueChanged(SGPropertyNode *node)
599 {
600     if (!strcmp(node->getName(), "current-color")) {
601         int i = node->getIntValue();
602         if (i < 0)
603             i = 0;
604         SGPropertyNode *n = fgGetNode("/sim/hud/palette", true);
605         if ((n = n->getChild("color", i, false))) {
606             if (n->hasValue("red"))
607                 _red->setFloatValue(n->getFloatValue("red", 1.0));
608             if (n->hasValue("green"))
609                 _green->setFloatValue(n->getFloatValue("green", 1.0));
610             if (n->hasValue("blue"))
611                 _blue->setFloatValue(n->getFloatValue("blue", 1.0));
612             if (n->hasValue("alpha"))
613                 _alpha->setFloatValue(n->getFloatValue("alpha", 0.67));
614             if (n->hasValue("alpha-clamp"))
615                 _alpha_clamp->setFloatValue(n->getFloatValue("alpha-clamp", 0.01));
616             if (n->hasValue("brightness"))
617                 _brightness->setFloatValue(n->getFloatValue("brightness", 0.75));
618             if (n->hasValue("antialiased"))
619                 _antialiasing->setBoolValue(n->getBoolValue("antialiased", false));
620             if (n->hasValue("transparent"))
621                 _transparency->setBoolValue(n->getBoolValue("transparent", false));
622         }
623     }
624     _visible = _visibility->getBoolValue();
625     _transparent = _transparency->getBoolValue();
626     _antialiased = _antialiasing->getBoolValue();
627     float brt = _brightness->getFloatValue();
628     _r = clamp(brt * _red->getFloatValue());
629     _g = clamp(brt * _green->getFloatValue());
630     _b = clamp(brt * _blue->getFloatValue());
631     _a = clamp(_alpha->getFloatValue());
632     _cl = clamp(_alpha_clamp->getFloatValue());
633 }
634
635
636 void HUD_Properties::setColor() const
637 {
638     if (_antialiased)
639         glColor4f(_r, _g, _b, _a);
640     else
641         glColor3f(_r, _g, _b);
642 }
643
644