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