]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/HUD/HUD.cxx
Merge branch 'maint2' into next
[flightgear.git] / src / Instrumentation / HUD / HUD.cxx
1 // HUD.cxx -- Head Up Display
2 //
3 // Written by Michele America, started September 1997.
4 //
5 // Copyright (C) 1997  Michele F. America  [micheleamerica#geocities:com]
6 // Copyright (C) 2006  Melchior FRANZ  [mfranz#aon:at]
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #include <simgear/compiler.h>
23 #include <simgear/structure/exception.hxx>
24
25 #include <string>
26 #include <fstream>
27
28 #ifdef HAVE_CONFIG_H
29 #  include <config.h>
30 #endif
31
32 #include <simgear/constants.h>
33 #include <simgear/misc/sg_path.hxx>
34 #include <osg/GLU>
35
36 #include <Main/globals.hxx>
37 #include <Main/viewmgr.hxx>
38
39 #include "HUD.hxx"
40
41
42 static float clamp(float f)
43 {
44     return f < 0.0f ? 0.0f : f > 1.0f ? 1.0f : f;
45 }
46
47
48 HUD::HUD() :
49     _current(fgGetNode("/sim/hud/current-color", true)),
50     _visibility(fgGetNode("/sim/hud/visibility[1]", true)),
51     _3DenabledN(fgGetNode("/sim/hud/enable3d[1]", true)),
52     _antialiasing(fgGetNode("/sim/hud/color/antialiased", true)),
53     _transparency(fgGetNode("/sim/hud/color/transparent", true)),
54     _red(fgGetNode("/sim/hud/color/red", true)),
55     _green(fgGetNode("/sim/hud/color/green", true)),
56     _blue(fgGetNode("/sim/hud/color/blue", true)),
57     _alpha(fgGetNode("/sim/hud/color/alpha", true)),
58     _alpha_clamp(fgGetNode("/sim/hud/color/alpha-clamp", true)),
59     _brightness(fgGetNode("/sim/hud/color/brightness", true)),
60     _visible(false),
61     _antialiased(false),
62     _transparent(false),
63     _a(0.67),                                                                   // FIXME better names
64     _cl(0.01),
65     //
66     _scr_widthN(fgGetNode("/sim/startup/xsize", true)),
67     _scr_heightN(fgGetNode("/sim/startup/ysize", true)),
68     _unitsN(fgGetNode("/sim/startup/units", true)),
69     _timer(0.0),
70     //
71     _font_renderer(new fntRenderer()),
72     _font(0),
73     _font_size(0.0),
74     _style(0),
75     _clip_box(0)
76 {
77     SG_LOG(SG_COCKPIT, SG_INFO, "Initializing HUD Instrument");
78
79     _visibility->addChangeListener(this);
80     _3DenabledN->addChangeListener(this);
81     _antialiasing->addChangeListener(this);
82     _transparency->addChangeListener(this);
83     _red->addChangeListener(this);
84     _green->addChangeListener(this);
85     _blue->addChangeListener(this);
86     _alpha->addChangeListener(this);
87     _alpha_clamp->addChangeListener(this);
88     _brightness->addChangeListener(this);
89     _current->addChangeListener(this);
90     _scr_widthN->addChangeListener(this);
91     _scr_heightN->addChangeListener(this);
92     _unitsN->addChangeListener(this, true);
93 }
94
95
96 HUD::~HUD()
97 {
98     _visibility->removeChangeListener(this);
99     _3DenabledN->removeChangeListener(this);
100     _antialiasing->removeChangeListener(this);
101     _transparency->removeChangeListener(this);
102     _red->removeChangeListener(this);
103     _green->removeChangeListener(this);
104     _blue->removeChangeListener(this);
105     _alpha->removeChangeListener(this);
106     _alpha_clamp->removeChangeListener(this);
107     _brightness->removeChangeListener(this);
108     _current->removeChangeListener(this);
109     _scr_widthN->removeChangeListener(this);
110     _scr_heightN->removeChangeListener(this);
111     _unitsN->removeChangeListener(this);
112     delete _font_renderer;
113     delete _clip_box;
114
115     deque<Item *>::const_iterator it, end = _items.end();
116     for (it = _items.begin(); it != end; ++it)
117         delete *it;
118     end = _ladders.end();
119     for (it = _ladders.begin(); it != end; ++it)
120         delete *it;
121 }
122
123
124 void HUD::init()
125 {
126     _font_cache = globals->get_fontcache();
127     if (!_font)
128         _font = _font_cache->getTexFont(fgGetString("/sim/hud/font/name", "Helvetica.txf"));
129     if (!_font)
130         throw sg_throwable(string("/sim/hud/font/name is not a texture font"));
131
132     _font_size = fgGetFloat("/sim/hud/font/size", 8);
133     _font_renderer->setFont(_font);
134     _font_renderer->setPointSize(_font_size);
135     _text_list.setFont(_font_renderer);
136
137     load(fgGetString("/sim/hud/path[1]", "Huds/default.xml"));
138 }
139
140
141 void HUD::update(double dt)
142 {
143     _timer += dt;
144 }
145
146
147 void HUD::draw(osg::State&)
148 {
149     if (!isVisible())
150         return;
151
152     if (!_items.size() && !_ladders.size())
153         return;
154
155     if (is3D()) {
156         draw3D();
157         return;
158     }
159
160     const float normal_aspect = 640.0f / 480.0f;
161     // note: aspect_ratio is Y/X
162     float current_aspect = 1.0f / globals->get_current_view()->get_aspect_ratio();
163     if (current_aspect > normal_aspect) {
164         float aspect_adjust = current_aspect / normal_aspect;
165         float adjust = 320.0f * aspect_adjust - 320.0f;
166         draw2D(-adjust, 0.0f, 640.0f + adjust, 480.0f);
167
168     } else {
169         float aspect_adjust = normal_aspect / current_aspect;
170         float adjust = 240.0f * aspect_adjust - 240.0f;
171         draw2D(0.0f, -adjust, 640.0f, 480.0f + adjust);
172     }
173
174     glViewport(0, 0, _scr_width, _scr_height);
175 }
176
177
178 void HUD::draw3D()
179 {
180     FGViewer* view = globals->get_current_view();
181
182     // Standard fgfs projection, with essentially meaningless clip
183     // planes (we'll map the whole HUD plane to z=-1)
184     glMatrixMode(GL_PROJECTION);
185     glPushMatrix();
186     glLoadIdentity();
187     gluPerspective(view->get_v_fov(), 1.0 / view->get_aspect_ratio(), 0.1, 10);
188
189     glMatrixMode(GL_MODELVIEW);
190     glPushMatrix();
191     glLoadIdentity();
192
193     // Standard fgfs view direction computation
194     float lookat[3];
195     lookat[0] = -sin(SG_DEGREES_TO_RADIANS * view->getHeadingOffset_deg());
196     lookat[1] = tan(SG_DEGREES_TO_RADIANS * view->getPitchOffset_deg());
197     lookat[2] = -cos(SG_DEGREES_TO_RADIANS * view->getHeadingOffset_deg());
198     if (fabs(lookat[1]) > 9999)
199         lookat[1] = 9999; // FPU sanity
200     gluLookAt(0, 0, 0, lookat[0], lookat[1], lookat[2], 0, 1, 0);
201
202     // Map the -1:1 square to a 55.0x41.25 degree wide patch at z=1.
203     // This is the default fgfs field of view, which the HUD files are
204     // written to assume.
205     float dx = 0.52056705; // tan(55/2)
206     float dy = dx * 0.75;  // assumes 4:3 aspect ratio
207     float m[16];
208     m[0] = dx, m[4] =  0, m[ 8] = 0, m[12] = 0;
209     m[1] =  0, m[5] = dy, m[ 9] = 0, m[13] = 0;
210     m[2] =  0, m[6] =  0, m[10] = 1, m[14] = 0;
211     m[3] =  0, m[7] =  0, m[11] = 0, m[15] = 1;
212     glMultMatrixf(m);
213
214     // Convert the 640x480 "HUD standard" coordinate space to a square
215     // about the origin in the range [-1:1] at depth of -1
216     glScalef(1.0 / 320, 1.0 / 240, 1);
217     glTranslatef(-320, -240, -1);
218
219     common_draw();
220
221     glMatrixMode(GL_PROJECTION);
222     glPopMatrix();
223     glMatrixMode(GL_MODELVIEW);
224     glPopMatrix();
225 }
226
227
228 void HUD::draw2D(GLfloat x_start, GLfloat y_start, GLfloat x_end, GLfloat y_end)
229 {
230     glMatrixMode(GL_PROJECTION);
231     glPushMatrix();
232     glLoadIdentity();
233     gluOrtho2D(x_start, x_end, y_start, y_end);
234
235     glMatrixMode(GL_MODELVIEW);
236     glPushMatrix();
237     glLoadIdentity();
238
239     common_draw();
240
241     glMatrixMode(GL_PROJECTION);
242     glPopMatrix();
243     glMatrixMode(GL_MODELVIEW);
244     glPopMatrix();
245 }
246
247
248 void HUD::common_draw()
249 {
250     _text_list.erase();
251     _line_list.erase();
252     _stipple_line_list.erase();
253
254     glDisable(GL_DEPTH_TEST);
255     glDisable(GL_LIGHTING);
256
257     glEnable(GL_BLEND);
258     if (isTransparent())
259         glBlendFunc(GL_SRC_ALPHA, GL_ONE);
260     else
261         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
262
263     if (isAntialiased()) {
264         glEnable(GL_LINE_SMOOTH);
265         glAlphaFunc(GL_GREATER, alphaClamp());
266         glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
267         //glLineWidth(1.5);
268     } else {
269         //glLineWidth(1.0);
270     }
271
272     setColor();
273     _clip_box->set();
274
275     deque<Item *>::const_iterator it, end = _items.end();
276     for (it = _items.begin(); it != end; ++it)
277         if ((*it)->isEnabled())
278             (*it)->draw();
279
280     _text_list.draw();
281     _line_list.draw();
282
283     if (_stipple_line_list.size()) {
284         glEnable(GL_LINE_STIPPLE);
285         glLineStipple(1, 0x00FF);
286         _stipple_line_list.draw();
287         glDisable(GL_LINE_STIPPLE);
288     }
289
290     // ladders last, as they can have their own clip planes
291     end = _ladders.end();
292     for (it = _ladders.begin(); it != end; ++it)
293         if ((*it)->isEnabled())
294             (*it)->draw();
295
296     _clip_box->unset();
297
298     if (isAntialiased()) {
299         glDisable(GL_ALPHA_TEST);
300         glDisable(GL_LINE_SMOOTH);
301         //glLineWidth(1.0);
302     }
303
304     if (isTransparent())
305         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
306
307     glEnable(GL_DEPTH_TEST);
308     glEnable(GL_LIGHTING);
309 }
310
311
312 int HUD::load(const char *file, float x, float y, int level, const string& indent)
313 {
314     const sgDebugPriority TREE = SG_INFO;
315     const int MAXNEST = 10;
316
317     SGPath path(globals->get_fg_root());
318     path.append(file);
319
320     if (!level) {
321         SG_LOG(SG_INPUT, TREE, endl << "load " << file);
322         _items.erase(_items.begin(), _items.end());
323         _ladders.erase(_ladders.begin(), _ladders.end());
324     } else if (level > MAXNEST) {
325         SG_LOG(SG_INPUT, SG_ALERT, "HUD: files nested more than " << MAXNEST << " levels");
326         return 0x1;
327     } else if (!file || !file[0]) {
328         SG_LOG(SG_INPUT, SG_ALERT, "HUD: invalid filename ");
329         return 0x2;
330     }
331
332     int ret = 0;
333     ifstream input(path.c_str());
334     if (!input.good()) {
335         SG_LOG(SG_INPUT, SG_ALERT, "HUD: Cannot read configuration from " << path.str());
336         return 0x4;
337     }
338
339     SGPropertyNode root;
340     try {
341         readProperties(input, &root);
342     } catch (const sg_exception &e) {
343         input.close();
344         guiErrorMessage("HUD: Error ", e);
345         return 0x8;
346     }
347
348     delete _clip_box;
349     _clip_box = new ClipBox(fgGetNode("/sim/hud/clipping"), x, y);
350
351     for (int i = 0; i < root.nChildren(); i++) {
352         SGPropertyNode *n = root.getChild(i);
353         const char *d = n->getStringValue("name", 0);
354         string desc;
355         if (d)
356             desc = string(": \"") + d + '"';
357
358         const char *name = n->getName();
359         if (!strcmp(name, "name")) {
360             continue;
361
362         } else if (!strcmp(name, "enable3d")) {
363             // set in the tree so that valueChanged() picks it up
364             _3DenabledN->setBoolValue(n->getBoolValue());
365             continue;
366
367         } else if (!strcmp(name, "import")) {
368             const char *fn = n->getStringValue("path", "");
369             float xoffs = n->getFloatValue("x-offset", 0.0f);
370             float yoffs = n->getFloatValue("y-offset", 0.0f);
371
372             SG_LOG(SG_INPUT, TREE, indent << "|__import " << fn << desc);
373
374             string ind = indent + string(i + 1 < root.nChildren() ? "|    " : "     ");
375             ret |= load(fn, x + xoffs, y + yoffs, level + 1, ind);
376             continue;
377         }
378
379         SG_LOG(SG_INPUT, TREE, indent << "|__" << name << desc);
380
381         Item *item;
382         if (!strcmp(name, "label")) {
383             item = static_cast<Item *>(new Label(this, n, x, y));
384         } else if (!strcmp(name, "gauge")) {
385             item = static_cast<Item *>(new Gauge(this, n, x, y));
386         } else if (!strcmp(name, "tape")) {
387             item = static_cast<Item *>(new Tape(this, n, x, y));
388         } else if (!strcmp(name, "dial")) {
389             item = static_cast<Item *>(new Dial(this, n, x, y));
390         } else if (!strcmp(name, "turn-bank-indicator")) {
391             item = static_cast<Item *>(new TurnBankIndicator(this, n, x, y));
392         } else if (!strcmp(name, "ladder")) {
393             item = static_cast<Item *>(new Ladder(this, n, x, y));
394             _ladders.insert(_ladders.begin(), item);
395             continue;
396         } else if (!strcmp(name, "runway")) {
397             item = static_cast<Item *>(new Runway(this, n, x, y));
398         } else if (!strcmp(name, "aiming-reticle")) {
399             item = static_cast<Item *>(new AimingReticle(this, n, x, y));
400         } else {
401             SG_LOG(SG_INPUT, TREE, indent << "      \\...unsupported!");
402             continue;
403         }
404         _items.insert(_items.begin(), item);
405     }
406     input.close();
407     SG_LOG(SG_INPUT, TREE, indent);
408     return ret;
409 }
410
411
412 void HUD::valueChanged(SGPropertyNode *node)
413 {
414     if (!strcmp(node->getName(), "current-color")) {
415         int i = node->getIntValue();
416         if (i < 0)
417             i = 0;
418         SGPropertyNode *n = fgGetNode("/sim/hud/palette", true);
419         if ((n = n->getChild("color", i, false))) {
420             if (n->hasValue("red"))
421                 _red->setFloatValue(n->getFloatValue("red", 1.0));
422             if (n->hasValue("green"))
423                 _green->setFloatValue(n->getFloatValue("green", 1.0));
424             if (n->hasValue("blue"))
425                 _blue->setFloatValue(n->getFloatValue("blue", 1.0));
426             if (n->hasValue("alpha"))
427                 _alpha->setFloatValue(n->getFloatValue("alpha", 0.67));
428             if (n->hasValue("alpha-clamp"))
429                 _alpha_clamp->setFloatValue(n->getFloatValue("alpha-clamp", 0.01));
430             if (n->hasValue("brightness"))
431                 _brightness->setFloatValue(n->getFloatValue("brightness", 0.75));
432             if (n->hasValue("antialiased"))
433                 _antialiasing->setBoolValue(n->getBoolValue("antialiased", false));
434             if (n->hasValue("transparent"))
435                 _transparency->setBoolValue(n->getBoolValue("transparent", false));
436         }
437     }
438     _scr_width = _scr_widthN->getIntValue();
439     _scr_height = _scr_heightN->getIntValue();
440
441     _visible = _visibility->getBoolValue();
442     _3Denabled = _3DenabledN->getBoolValue();
443     _transparent = _transparency->getBoolValue();
444     _antialiased = _antialiasing->getBoolValue();
445     float brt = _brightness->getFloatValue();
446     _r = clamp(brt * _red->getFloatValue());
447     _g = clamp(brt * _green->getFloatValue());
448     _b = clamp(brt * _blue->getFloatValue());
449     _a = clamp(_alpha->getFloatValue());
450     _cl = clamp(_alpha_clamp->getFloatValue());
451
452     _units = strcmp(_unitsN->getStringValue(), "feet") ? METER : FEET;
453 }
454
455
456 void HUD::setColor() const
457 {
458     if (_antialiased)
459         glColor4f(_r, _g, _b, _a);
460     else
461         glColor3f(_r, _g, _b);
462 }
463
464
465 void HUD::textAlign(fntRenderer *rend, const char *s, int align,
466         float *x, float *y, float *l, float *r, float *b, float *t)
467 {
468     fntFont *font = rend->getFont();
469     float gap = font->getGap();
470     float left, right, bot, top;
471     font->getBBox(s, rend->getPointSize(), rend->getSlant(), &left, &right, &bot, &top);
472
473     if (align & HUD::HCENTER)
474         *x -= left - gap + (right - left - gap) / 2.0;
475     else if (align & HUD::RIGHT)
476         *x -= right;
477     else if (align & HUD::LEFT)
478         *x -= left;
479
480     if (align & HUD::VCENTER)
481         *y -= bot + (top - bot) / 2.0;
482     else if (align & HUD::TOP)
483         *y -= top;
484     else if (align & HUD::BOTTOM)
485         *y -= bot;
486
487     *l = *x + left;
488     *r = *x + right;
489     *b = *y + bot;
490     *t = *y + top;
491 }
492
493
494
495
496 // HUDText -- text container for TextList vector
497
498
499 HUDText::HUDText(fntRenderer *fnt, float x, float y, const char *s, int align, int d) :
500     _fnt(fnt),
501     _x(x),
502     _y(y),
503     _digits(d)
504 {
505     strncpy(_msg, s, BUFSIZE);
506     if (!align || !s[0])
507         return;
508     float ign;
509     HUD::textAlign(fnt, s, align, &_x, &_y, &ign, &ign, &ign, &ign);
510 }
511
512
513 void HUDText::draw()
514 {
515     if (!_digits) { // show all digits in same size
516         _fnt->start2f(_x, _y);
517         _fnt->puts(_msg);
518         return;
519     }
520
521     // FIXME
522     // this code is changed to display Numbers with big/small digits
523     // according to MIL Standards for example Altitude above 10000 ft
524     // is shown as 10ooo.
525
526     int c = 0, i = 0;
527     char *t = _msg;
528     int p = 4;
529
530     if (t[0] == '-') {
531         //if negative value then increase the c and p values
532         //for '-' sign.
533         c++; // was moved to the comment. Unintentionally?   TODO
534         p++;
535     }
536     char *tmp = _msg;
537     while (tmp[i] != '\0') {
538         if ((tmp[i] >= '0') && (tmp[i] <= '9'))
539             c++;
540         i++;
541     }
542
543     float orig_size = _fnt->getPointSize();
544     if (c > p) {
545         _fnt->setPointSize(orig_size * 0.8);
546         int p1 = c - 3;
547         char *tmp1 = _msg + p1;
548         int p2 = p1 * 8;
549
550         _fnt->start2f(_x + p2, _y);
551         _fnt->puts(tmp1);
552
553         _fnt->setPointSize(orig_size * 1.2);
554         char tmp2[BUFSIZE];
555         strncpy(tmp2, _msg, p1);
556         tmp2[p1] = '\0';
557
558         _fnt->start2f(_x, _y);
559         _fnt->puts(tmp2);
560     } else {
561         _fnt->setPointSize(orig_size * 1.2);
562         _fnt->start2f(_x, _y);
563         _fnt->puts(tmp);
564     }
565     _fnt->setPointSize(orig_size);
566 }
567
568
569 void TextList::align(const char *s, int align, float *x, float *y,
570         float *l, float *r, float *b, float *t) const
571 {
572     HUD::textAlign(_font, s, align, x, y, l, r, b, t);
573 }
574
575
576 void TextList::draw()
577 {
578     assert(_font);
579
580     // FIXME
581     glPushAttrib(GL_COLOR_BUFFER_BIT);
582     glEnable(GL_BLEND);
583
584     _font->begin();
585     vector<HUDText>::iterator it, end = _list.end();
586     for (it = _list.begin(); it != end; ++it)
587         it->draw();
588     _font->end();
589
590     glDisable(GL_TEXTURE_2D);
591     glPopAttrib();
592 }
593
594
595 ClipBox::ClipBox(const SGPropertyNode *n, float xoffset, float yoffset) :
596     _active(false),
597     _xoffs(xoffset),
598     _yoffs(yoffset)
599 {
600     if (!n)
601         return;
602
603     // const_cast is necessary because ATM there's no matching getChild(const ...)
604     // prototype and getNode(const ..., <bool>) is wrongly interpreted as
605     // getNode(const ..., <int>)
606     _top_node = (const_cast<SGPropertyNode *>(n))->getChild("top", 0, true);
607     _bot_node = (const_cast<SGPropertyNode *>(n))->getChild("bottom", 0, true);
608     _left_node = (const_cast<SGPropertyNode *>(n))->getChild("left", 0, true);
609     _right_node = (const_cast<SGPropertyNode *>(n))->getChild("right", 0, true);
610
611     _left[0] = 1.0, _left[1] = _left[2] = 0.0;
612     _right[0] = -1.0, _right[1] = _right[2] = 0.0;
613     _top[0] = 0.0, _top[1] = -1.0, _top[2] = 0.0;
614     _bot[0] = 0.0, _bot[1] = 1.0, _bot[2] = 0.0;
615     _active = true;
616 }
617
618
619 void ClipBox::set()
620 {
621     if (!_active)
622         return;
623
624     _left[3] = -_left_node->getDoubleValue() - _xoffs;
625     _right[3] = _right_node->getDoubleValue() + _xoffs;
626     _bot[3] = -_bot_node->getDoubleValue() - _yoffs;
627     _top[3] = _top_node->getDoubleValue() + _yoffs;
628
629     glClipPlane(GL_CLIP_PLANE0, _top);
630     glEnable(GL_CLIP_PLANE0);
631     glClipPlane(GL_CLIP_PLANE1, _bot);
632     glEnable(GL_CLIP_PLANE1);
633     glClipPlane(GL_CLIP_PLANE2, _left);
634     glEnable(GL_CLIP_PLANE2);
635     glClipPlane(GL_CLIP_PLANE3, _right);
636     glEnable(GL_CLIP_PLANE3);
637 }
638
639
640 void ClipBox::unset()
641 {
642     if (_active) {
643         glDisable(GL_CLIP_PLANE0);
644         glDisable(GL_CLIP_PLANE1);
645         glDisable(GL_CLIP_PLANE2);
646         glDisable(GL_CLIP_PLANE3);
647     }
648 }