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