]> git.mxchange.org Git - flightgear.git/blob - src/Cockpit/panel.cxx
Lazy-loading of the 2D panel node.
[flightgear.git] / src / Cockpit / panel.cxx
1 //  panel.cxx - default, 2D single-engine prop instrument panel
2 //
3 //  Written by David Megginson, started January 2000.
4 //
5 //  This program is free software; you can redistribute it and/or
6 //  modify it under the terms of the GNU General Public License as
7 //  published by the Free Software Foundation; either version 2 of the
8 //  License, or (at your option) any later version.
9 // 
10 //  This program is distributed in the hope that it will be useful, but
11 //  WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 //  General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program; if not, write to the Free Software
17 //  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 //  $Id$
20
21 //JVK
22 // On 2D panels all instruments include light sources were in night displayed
23 // with a red mask (instrument light). It is not correct for light sources
24 // (bulbs). There is added new layer property "emissive" (boolean) (only for
25 // textured layers).
26 // If a layer has to shine set it in the "instrument_def_file.xml" inside the
27 // <layer> tag by adding <emissive>true</emissive> tag. When omitted the default
28 // value is for backward compatibility set to false.
29
30 #ifdef HAVE_CONFIG_H
31 #  include <config.h>
32 #endif
33
34 #include "panel.hxx"
35
36 #include <stdio.h>      // sprintf
37 #include <string.h>
38 #include <iostream>
39 #include <cassert>
40
41 #include <osg/CullFace>
42 #include <osg/Depth>
43 #include <osg/Material>
44 #include <osg/Matrixf>
45 #include <osg/TexEnv>
46 #include <osg/PolygonOffset>
47
48 #include <simgear/compiler.h>
49
50 #include <plib/fnt.h>
51
52 #include <boost/foreach.hpp>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/misc/sg_path.hxx>
55 #include <simgear/scene/model/model.hxx>
56 #include <osg/GLU>
57
58 #include <Main/globals.hxx>
59 #include <Main/fg_props.hxx>
60 #include <Viewer/viewmgr.hxx>
61 #include <Viewer/viewer.hxx>
62 #include <Time/light.hxx>
63 #include <GUI/FGFontCache.hxx>  
64 #include <Instrumentation/dclgps.hxx>
65
66 #define WIN_X 0
67 #define WIN_Y 0
68 #define WIN_W 1024
69 #define WIN_H 768
70
71 // The number of polygon-offset "units" to place between layers.  In
72 // principle, one is supposed to be enough.  In practice, I find that
73 // my hardware/driver requires many more.
74 #define POFF_UNITS 8
75
76 const double MOUSE_ACTION_REPEAT_DELAY = 0.5; // 500msec initial delay
77 const double MOUSE_ACTION_REPEAT_INTERVAL = 0.1; // 10Hz repeat rate
78
79 using std::map;
80
81 ////////////////////////////////////////////////////////////////////////
82 // Local functions.
83 ////////////////////////////////////////////////////////////////////////
84
85
86 /**
87  * Calculate the aspect adjustment for the panel.
88  */
89 static float
90 get_aspect_adjust (int xsize, int ysize)
91 {
92   float ideal_aspect = float(WIN_W) / float(WIN_H);
93   float real_aspect = float(xsize) / float(ysize);
94   return (real_aspect / ideal_aspect);
95 }
96 \f
97 ////////////////////////////////////////////////////////////////////////
98 // Implementation of FGTextureManager.
99 ////////////////////////////////////////////////////////////////////////
100
101 map<string,osg::ref_ptr<osg::Texture2D> > FGTextureManager::_textureMap;
102
103 osg::Texture2D*
104 FGTextureManager::createTexture (const string &relativePath, bool staticTexture)
105 {
106   osg::Texture2D* texture = _textureMap[relativePath].get();
107   if (texture == 0) {
108     SGPath tpath = globals->resolve_aircraft_path(relativePath);
109     texture = SGLoadTexture2D(staticTexture, tpath);
110
111     _textureMap[relativePath] = texture;
112     if (!_textureMap[relativePath].valid()) 
113       SG_LOG( SG_COCKPIT, SG_ALERT, "Texture *still* doesn't exist" );
114     SG_LOG( SG_COCKPIT, SG_DEBUG, "Created texture " << relativePath );
115   }
116
117   return texture;
118 }
119
120
121 void FGTextureManager::addTexture(const string &relativePath,
122                                   osg::Texture2D* texture)
123 {
124     _textureMap[relativePath] = texture;
125 }
126 \f
127 ////////////////////////////////////////////////////////////////////////
128 // Implementation of FGCropped Texture.
129 ////////////////////////////////////////////////////////////////////////
130
131
132 FGCroppedTexture::FGCroppedTexture ()
133   : _path(""), _texture(0),
134     _minX(0.0), _minY(0.0), _maxX(1.0), _maxY(1.0)
135 {
136 }
137
138
139 FGCroppedTexture::FGCroppedTexture (const string &path,
140                                     float minX, float minY,
141                                     float maxX, float maxY)
142   : _path(path), _texture(0),
143     _minX(minX), _minY(minY), _maxX(maxX), _maxY(maxY)
144 {
145 }
146
147
148 FGCroppedTexture::~FGCroppedTexture ()
149 {
150 }
151
152
153 osg::StateSet*
154 FGCroppedTexture::getTexture ()
155 {
156   if (_texture == 0) {
157     _texture = new osg::StateSet;
158     _texture->setTextureAttribute(0, FGTextureManager::createTexture(_path));
159     _texture->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
160     _texture->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
161   }
162   return _texture.get();
163 }
164
165
166 \f
167 ////////////////////////////////////////////////////////////////////////
168 // Implementation of FGPanel.
169 ////////////////////////////////////////////////////////////////////////
170
171 static fntRenderer text_renderer;
172 static sgVec4 panel_color;
173 static sgVec4 emissive_panel_color = {1,1,1,1};
174
175 /**
176  * Constructor.
177  */
178 FGPanel::FGPanel ()
179   : _mouseDown(false),
180     _mouseInstrument(0),
181     _width(WIN_W), _height(int(WIN_H * 0.5768 + 1)),
182     _x_offset(fgGetNode("/sim/panel/x-offset", true)),
183     _y_offset(fgGetNode("/sim/panel/y-offset", true)),
184     _jitter(fgGetNode("/sim/panel/jitter", true)),
185     _flipx(fgGetNode("/sim/panel/flip-x", true)),
186     _xsize_node(fgGetNode("/sim/startup/xsize", true)),
187     _ysize_node(fgGetNode("/sim/startup/ysize", true)),
188     _enable_depth_test(false),
189     _autohide(true),
190     _drawPanelHotspots("/sim/panel-hotspots")
191 {
192 }
193
194
195 /**
196  * Destructor.
197  */
198 FGPanel::~FGPanel ()
199 {
200   for (instrument_list_type::iterator it = _instruments.begin();
201        it != _instruments.end();
202        it++) {
203     delete *it;
204     *it = 0;
205   }
206 }
207
208
209 /**
210  * Add an instrument to the panel.
211  */
212 void
213 FGPanel::addInstrument (FGPanelInstrument * instrument)
214 {
215   _instruments.push_back(instrument);
216 }
217
218 double
219 FGPanel::getAspectScale() const
220 {
221   // set corner-coordinates correctly
222   
223   int xsize = _xsize_node->getIntValue();
224   int ysize = _ysize_node->getIntValue();
225   float aspect_adjust = get_aspect_adjust(xsize, ysize);
226   
227   if (aspect_adjust < 1.0)
228     return ysize / (double) WIN_H;
229   else
230     return xsize /(double) WIN_W;  
231 }
232
233 /**
234  * Handle repeatable mouse events.  Called from update() and from
235  * fgUpdate3DPanels().  This functionality needs to move into the
236  * input subsystem.  Counting a tick every two frames is clumsy...
237  */
238 void FGPanel::updateMouseDelay(double dt)
239 {
240   if (!_mouseDown) {
241     return;
242   }
243
244   _mouseActionRepeat -= dt;
245   while (_mouseActionRepeat < 0.0) {
246     _mouseActionRepeat += MOUSE_ACTION_REPEAT_INTERVAL;
247     _mouseInstrument->doMouseAction(_mouseButton, 0, _mouseX, _mouseY);
248     
249   }
250 }
251
252 void
253 FGPanel::draw(osg::State& state)
254 {
255     
256   // In 3D mode, it's possible that we are being drawn exactly on top
257   // of an existing polygon.  Use an offset to prevent z-fighting.  In
258   // 2D mode, this is a no-op.
259   static osg::ref_ptr<osg::StateSet> panelStateSet;
260   if (!panelStateSet.valid()) {
261     panelStateSet = new osg::StateSet;
262     panelStateSet->setAttributeAndModes(new osg::PolygonOffset(-1, -POFF_UNITS));
263     panelStateSet->setTextureAttribute(0, new osg::TexEnv);
264
265     // Draw the background
266     panelStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
267     panelStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
268     panelStateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
269     panelStateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
270   
271     osg::Material* material = new osg::Material;
272     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
273     material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
274     material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4(1, 1, 1, 1));
275     material->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
276     material->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4(0, 0, 0, 1));
277     panelStateSet->setAttribute(material);
278     
279     panelStateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
280     panelStateSet->setAttributeAndModes(new osg::CullFace(osg::CullFace::BACK));
281     panelStateSet->setAttributeAndModes(new osg::Depth(osg::Depth::LEQUAL));
282   }
283   if ( _enable_depth_test )
284     panelStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
285   else
286     panelStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
287   state.pushStateSet(panelStateSet.get());
288   state.apply();
289   state.setActiveTextureUnit(0);
290   state.setClientActiveTextureUnit(0);
291
292   FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
293   sgCopyVec4( panel_color, l->scene_diffuse().data());
294   if ( fgGetDouble("/systems/electrical/outputs/instrument-lights") > 1.0 ) {
295       if ( panel_color[0] < 0.7 ) panel_color[0] = 0.7;
296       if ( panel_color[1] < 0.2 ) panel_color[1] = 0.2;
297       if ( panel_color[2] < 0.2 ) panel_color[2] = 0.2;
298   }
299   glColor4fv( panel_color );
300   if (_bg != 0) {
301     state.pushStateSet(_bg.get());
302     state.apply();
303     state.setActiveTextureUnit(0);
304     state.setClientActiveTextureUnit(0);
305
306     glBegin(GL_POLYGON);
307     glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X, WIN_Y);
308     glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + _width, WIN_Y);
309     glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + _width, WIN_Y + _height);
310     glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X, WIN_Y + _height);
311     glEnd();
312     state.popStateSet();
313     state.apply();
314     state.setActiveTextureUnit(0);
315     state.setClientActiveTextureUnit(0);
316
317   } else {
318     for (int i = 0; i < 4; i ++) {
319       // top row of textures...(1,3,5,7)
320       state.pushStateSet(_mbg[i*2].get());
321       state.apply();
322       state.setActiveTextureUnit(0);
323       state.setClientActiveTextureUnit(0);
324
325       glBegin(GL_POLYGON);
326       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
327       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
328       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + _height);
329       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + _height);
330       glEnd();
331       state.popStateSet();
332       state.apply();
333       state.setActiveTextureUnit(0);
334       state.setClientActiveTextureUnit(0);
335
336       // bottom row of textures...(2,4,6,8)
337       state.pushStateSet(_mbg[i*2+1].get());
338       state.apply();
339       state.setActiveTextureUnit(0);
340       state.setClientActiveTextureUnit(0);
341
342       glBegin(GL_POLYGON);
343       glTexCoord2f(0.0, 0.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y);
344       glTexCoord2f(1.0, 0.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y);
345       glTexCoord2f(1.0, 1.0); glVertex2f(WIN_X + (_width/4) * (i+1), WIN_Y + (_height/2));
346       glTexCoord2f(0.0, 1.0); glVertex2f(WIN_X + (_width/4) * i, WIN_Y + (_height/2));
347       glEnd();
348       state.popStateSet();
349       state.apply();
350       state.setActiveTextureUnit(0);
351       state.setClientActiveTextureUnit(0);
352
353     }
354   }
355
356   // Draw the instruments.
357   // Syd Adams: added instrument clipping
358   instrument_list_type::const_iterator current = _instruments.begin();
359   instrument_list_type::const_iterator end = _instruments.end();
360
361   GLdouble blx[4]={1.0,0.0,0.0,0.0};
362   GLdouble bly[4]={0.0,1.0,0.0,0.0};
363   GLdouble urx[4]={-1.0,0.0,0.0,0.0};
364   GLdouble ury[4]={0.0,-1.0,0.0,0.0};
365
366   for ( ; current != end; current++) {
367     FGPanelInstrument * instr = *current;
368     glPushMatrix();
369     glTranslated(instr->getXPos(), instr->getYPos(), 0);
370
371     int ix= instr->getWidth();
372     int iy= instr->getHeight();
373     glPushMatrix();
374     glTranslated(-ix/2,-iy/2,0);
375     glClipPlane(GL_CLIP_PLANE0,blx);
376     glClipPlane(GL_CLIP_PLANE1,bly);
377     glEnable(GL_CLIP_PLANE0);
378     glEnable(GL_CLIP_PLANE1);
379
380     glTranslated(ix,iy,0);
381     glClipPlane(GL_CLIP_PLANE2,urx);
382     glClipPlane(GL_CLIP_PLANE3,ury);
383     glEnable(GL_CLIP_PLANE2);
384     glEnable(GL_CLIP_PLANE3);
385     glPopMatrix();
386     instr->draw(state);
387
388     glPopMatrix();
389   }
390
391   glDisable(GL_CLIP_PLANE0);
392   glDisable(GL_CLIP_PLANE1);
393   glDisable(GL_CLIP_PLANE2);
394   glDisable(GL_CLIP_PLANE3);
395
396   state.popStateSet();
397   state.apply();
398   state.setActiveTextureUnit(0);
399   state.setClientActiveTextureUnit(0);
400
401
402   // Draw yellow "hotspots" if directed to.  This is a panel authoring
403   // feature; not intended to be high performance or to look good.
404   if ( _drawPanelHotspots ) {
405     static osg::ref_ptr<osg::StateSet> hotspotStateSet;
406     if (!hotspotStateSet.valid()) {
407       hotspotStateSet = new osg::StateSet;
408       hotspotStateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
409       hotspotStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
410     }
411
412     state.pushStateSet(hotspotStateSet.get());
413     state.apply();
414     state.setActiveTextureUnit(0);
415     state.setClientActiveTextureUnit(0);
416
417
418     glPushAttrib(GL_ENABLE_BIT);
419     glDisable(GL_COLOR_MATERIAL);
420     glColor3f(1, 1, 0);
421     
422     for ( unsigned int i = 0; i < _instruments.size(); i++ )
423       _instruments[i]->drawHotspots(state);
424
425     glColor3f(0, 1, 1);
426
427     int x0, y0, x1, y1;
428     getLogicalExtent(x0, y0, x1, y1);
429     
430     glBegin(GL_LINE_LOOP);
431     glVertex2f(x0, y0);
432     glVertex2f(x1, y0);
433     glVertex2f(x1, y1);
434     glVertex2f(x0, y1);
435     glEnd();
436
437     
438     glPopAttrib();
439
440     state.popStateSet();
441     state.apply();
442     state.setActiveTextureUnit(0);
443     state.setClientActiveTextureUnit(0);
444
445   }
446 }
447
448 /**
449  * Set the panel's background texture.
450  */
451 void
452 FGPanel::setBackground (osg::Texture2D* texture)
453 {
454   osg::StateSet* stateSet = new osg::StateSet;
455   stateSet->setTextureAttribute(0, texture);
456   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
457   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
458   _bg = stateSet;
459 }
460
461 /**
462  * Set the panel's multiple background textures.
463  */
464 void
465 FGPanel::setMultiBackground (osg::Texture2D* texture, int idx)
466 {
467   _bg = 0;
468
469   osg::StateSet* stateSet = new osg::StateSet;
470   stateSet->setTextureAttribute(0, texture);
471   stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
472   stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
473   _mbg[idx] = stateSet;
474 }
475
476 /**
477  * Set the panel's x-offset.
478  */
479 void
480 FGPanel::setXOffset (int offset)
481 {
482   if (offset <= 0 && offset >= -_width + WIN_W)
483     _x_offset->setIntValue( offset );
484 }
485
486
487 /**
488  * Set the panel's y-offset.
489  */
490 void
491 FGPanel::setYOffset (int offset)
492 {
493   if (offset <= 0 && offset >= -_height)
494     _y_offset->setIntValue( offset );
495 }
496
497 /**
498  * Handle a mouse action in panel-local (not screen) coordinates.
499  * Used by the 3D panel code in Model/panelnode.cxx, in situations
500  * where the panel doesn't control its own screen location.
501  */
502 bool
503 FGPanel::doLocalMouseAction(int button, int updown, int x, int y)
504 {
505   // Note a released button and return
506   if (updown == 1) {
507     if (_mouseInstrument != 0)
508         _mouseInstrument->doMouseAction(_mouseButton, 1, _mouseX, _mouseY);
509     _mouseDown = false;
510     _mouseInstrument = 0;
511     return false;
512   }
513
514   // Search for a matching instrument.
515   for (int i = 0; i < (int)_instruments.size(); i++) {
516     FGPanelInstrument *inst = _instruments[i];
517     int ix = inst->getXPos();
518     int iy = inst->getYPos();
519     int iw = inst->getWidth() / 2;
520     int ih = inst->getHeight() / 2;
521     if (x >= ix - iw && x < ix + iw && y >= iy - ih && y < iy + ih) {
522       _mouseDown = true;
523       _mouseActionRepeat = MOUSE_ACTION_REPEAT_DELAY;
524       _mouseInstrument = inst;
525       _mouseButton = button;
526       _mouseX = x - ix;
527       _mouseY = y - iy;
528       // Always do the action once.
529       return _mouseInstrument->doMouseAction(_mouseButton, 0,
530                                              _mouseX, _mouseY);
531     }
532   }
533   return false;
534 }
535
536 /**
537  * Perform a mouse action.
538  */
539 bool
540 FGPanel::doMouseAction (int button, int updown, int x, int y)
541 {
542                                 // FIXME: this same code appears in update()
543   int xsize = _xsize_node->getIntValue();
544   int ysize = _ysize_node->getIntValue();
545   float aspect_adjust = get_aspect_adjust(xsize, ysize);
546
547                                 // Scale for the real window size.
548   if (aspect_adjust < 1.0) {
549     x = int(((float)x / xsize) * WIN_W * aspect_adjust);
550     y = int(WIN_H - ((float(y) / ysize) * WIN_H));
551   } else {
552     x = int(((float)x / xsize) * WIN_W);
553     y = int((WIN_H - ((float(y) / ysize) * WIN_H)) / aspect_adjust);
554   }
555
556                                 // Adjust for offsets.
557   x -= _x_offset->getIntValue();
558   y -= _y_offset->getIntValue();
559
560   // Having fixed up the coordinates, fall through to the local
561   // coordinate handler.
562   return doLocalMouseAction(button, updown, x, y);
563
564
565 void FGPanel::setDepthTest (bool enable) {
566     _enable_depth_test = enable;
567 }
568
569 class IntRect
570 {
571   
572 public:
573   IntRect() : 
574     x0(std::numeric_limits<int>::max()), 
575     y0(std::numeric_limits<int>::max()), 
576     x1(std::numeric_limits<int>::min()), 
577     y1(std::numeric_limits<int>::min()) 
578   { }
579   
580   IntRect(int x, int y, int w, int h) :
581     x0(x), y0(y), x1(x + w), y1( y + h)
582   { 
583     if (x1 < x0) {
584       std::swap(x0, x1);
585     }
586     
587     if (y1 < y0) {
588       std::swap(y0, y1);
589     }
590     
591     assert(x0 <= x1);
592     assert(y0 <= y1);
593   }
594   
595   void extend(const IntRect& r)
596   {
597     x0 = std::min(x0, r.x0);
598     y0 = std::min(y0, r.y0);
599     x1 = std::max(x1, r.x1);
600     y1 = std::max(y1, r.y1);
601   }
602   
603   int x0, y0, x1, y1;
604 };
605
606 void FGPanel::getLogicalExtent(int &x0, int& y0, int& x1, int &y1)
607 {  
608   IntRect result;
609   BOOST_FOREACH(FGPanelInstrument *inst, _instruments) {
610     inst->extendRect(result);
611   }
612   
613   x0 = result.x0;
614   y0 = result.y0;
615   x1 = result.x1;
616   y1 = result.y1;
617 }
618 \f
619 ////////////////////////////////////////////////////////////////////////.
620 // Implementation of FGPanelAction.
621 ////////////////////////////////////////////////////////////////////////
622
623 FGPanelAction::FGPanelAction ()
624 {
625 }
626
627 FGPanelAction::FGPanelAction (int button, int x, int y, int w, int h,
628                               bool repeatable)
629     : _button(button), _x(x), _y(y), _w(w), _h(h), _repeatable(repeatable)
630 {
631 }
632
633 FGPanelAction::~FGPanelAction ()
634 {
635   for (unsigned int i = 0; i < 2; i++) {
636       for (unsigned int j = 0; j < _bindings[i].size(); j++)
637           delete _bindings[i][j];
638   }
639 }
640
641 void
642 FGPanelAction::addBinding (SGBinding * binding, int updown)
643 {
644   _bindings[updown].push_back(binding);
645 }
646
647 bool
648 FGPanelAction::doAction (int updown)
649 {
650   if (test()) {
651     if ((updown != _last_state) || (updown == 0 && _repeatable)) {
652         int nBindings = _bindings[updown].size();
653         for (int i = 0; i < nBindings; i++)
654             _bindings[updown][i]->fire();
655     }
656     _last_state = updown;
657     return true;
658   } else {
659     return false;
660   }
661 }
662
663
664 \f
665 ////////////////////////////////////////////////////////////////////////
666 // Implementation of FGPanelTransformation.
667 ////////////////////////////////////////////////////////////////////////
668
669 FGPanelTransformation::FGPanelTransformation ()
670   : table(0)
671 {
672 }
673
674 FGPanelTransformation::~FGPanelTransformation ()
675 {
676   delete table;
677 }
678
679
680 \f
681 ////////////////////////////////////////////////////////////////////////
682 // Implementation of FGPanelInstrument.
683 ////////////////////////////////////////////////////////////////////////
684
685
686 FGPanelInstrument::FGPanelInstrument ()
687 {
688   setPosition(0, 0);
689   setSize(0, 0);
690 }
691
692 FGPanelInstrument::FGPanelInstrument (int x, int y, int w, int h)
693 {
694   setPosition(x, y);
695   setSize(w, h);
696 }
697
698 FGPanelInstrument::~FGPanelInstrument ()
699 {
700   for (action_list_type::iterator it = _actions.begin();
701        it != _actions.end();
702        it++) {
703     delete *it;
704     *it = 0;
705   }
706 }
707
708 void
709 FGPanelInstrument::drawHotspots(osg::State& state)
710 {
711   for ( unsigned int i = 0; i < _actions.size(); i++ ) {
712     FGPanelAction* a = _actions[i];
713     float x1 = getXPos() + a->getX();
714     float x2 = x1 + a->getWidth();
715     float y1 = getYPos() + a->getY();
716     float y2 = y1 + a->getHeight();
717
718     glBegin(GL_LINE_LOOP);
719     glVertex2f(x1, y1);
720     glVertex2f(x1, y2);
721     glVertex2f(x2, y2);
722     glVertex2f(x2, y1);
723     glEnd();
724   }
725 }
726
727 void
728 FGPanelInstrument::setPosition (int x, int y)
729 {
730   _x = x;
731   _y = y;
732 }
733
734 void
735 FGPanelInstrument::setSize (int w, int h)
736 {
737   _w = w;
738   _h = h;
739 }
740
741 int
742 FGPanelInstrument::getXPos () const
743 {
744   return _x;
745 }
746
747 int
748 FGPanelInstrument::getYPos () const
749 {
750   return _y;
751 }
752
753 int
754 FGPanelInstrument::getWidth () const
755 {
756   return _w;
757 }
758
759 int
760 FGPanelInstrument::getHeight () const
761 {
762   return _h;
763 }
764
765 void
766 FGPanelInstrument::extendRect(IntRect& r) const
767 {
768   IntRect instRect(_x, _y, _w, _h);
769   r.extend(instRect);
770   
771   BOOST_FOREACH(FGPanelAction* act, _actions) {
772     r.extend(IntRect(getXPos() + act->getX(), 
773                      getYPos() + act->getY(),
774                      act->getWidth(),
775                      act->getHeight()
776                      ));
777   }
778 }
779
780 void
781 FGPanelInstrument::addAction (FGPanelAction * action)
782 {
783   _actions.push_back(action);
784 }
785
786                                 // Coordinates relative to centre.
787 bool
788 FGPanelInstrument::doMouseAction (int button, int updown, int x, int y)
789 {
790   if (test()) {
791     action_list_type::iterator it = _actions.begin();
792     action_list_type::iterator last = _actions.end();
793     for ( ; it != last; it++) {
794       if ((*it)->inArea(button, x, y) &&
795           (*it)->doAction(updown))
796         return true;
797     }
798   }
799   return false;
800 }
801
802
803 \f
804 ////////////////////////////////////////////////////////////////////////
805 // Implementation of FGLayeredInstrument.
806 ////////////////////////////////////////////////////////////////////////
807
808 FGLayeredInstrument::FGLayeredInstrument (int x, int y, int w, int h)
809   : FGPanelInstrument(x, y, w, h)
810 {
811 }
812
813 FGLayeredInstrument::~FGLayeredInstrument ()
814 {
815   for (layer_list::iterator it = _layers.begin(); it != _layers.end(); it++) {
816     delete *it;
817     *it = 0;
818   }
819 }
820
821 void
822 FGLayeredInstrument::draw (osg::State& state)
823 {
824   if (!test())
825     return;
826   
827   for (int i = 0; i < (int)_layers.size(); i++) {
828     glPushMatrix();
829     _layers[i]->draw(state);
830     glPopMatrix();
831   }
832 }
833
834 int
835 FGLayeredInstrument::addLayer (FGInstrumentLayer *layer)
836 {
837   int n = _layers.size();
838   if (layer->getWidth() == -1) {
839     layer->setWidth(getWidth());
840   }
841   if (layer->getHeight() == -1) {
842     layer->setHeight(getHeight());
843   }
844   _layers.push_back(layer);
845   return n;
846 }
847
848 int
849 FGLayeredInstrument::addLayer (const FGCroppedTexture &texture,
850                                int w, int h)
851 {
852   return addLayer(new FGTexturedLayer(texture, w, h));
853 }
854
855 void
856 FGLayeredInstrument::addTransformation (FGPanelTransformation * transformation)
857 {
858   int layer = _layers.size() - 1;
859   _layers[layer]->addTransformation(transformation);
860 }
861
862
863 \f
864 ////////////////////////////////////////////////////////////////////////
865 // Implementation of FGSpecialInstrument.
866 ////////////////////////////////////////////////////////////////////////
867
868 FGSpecialInstrument::FGSpecialInstrument (DCLGPS* sb)
869   : FGPanelInstrument()
870 {
871   complex = sb;
872 }
873
874 FGSpecialInstrument::~FGSpecialInstrument ()
875 {
876 }
877
878 void
879 FGSpecialInstrument::draw (osg::State& state)
880 {
881   complex->draw(state);
882 }
883
884
885 \f
886 ////////////////////////////////////////////////////////////////////////
887 // Implementation of FGInstrumentLayer.
888 ////////////////////////////////////////////////////////////////////////
889
890 FGInstrumentLayer::FGInstrumentLayer (int w, int h)
891   : _w(w),
892     _h(h)
893 {
894 }
895
896 FGInstrumentLayer::~FGInstrumentLayer ()
897 {
898   for (transformation_list::iterator it = _transformations.begin();
899        it != _transformations.end();
900        it++) {
901     delete *it;
902     *it = 0;
903   }
904 }
905
906 void
907 FGInstrumentLayer::transform () const
908 {
909   transformation_list::const_iterator it = _transformations.begin();
910   transformation_list::const_iterator last = _transformations.end();
911   while (it != last) {
912     FGPanelTransformation *t = *it;
913     if (t->test()) {
914       float val = (t->node == 0 ? 0.0 : t->node->getFloatValue());
915
916       if (t->has_mod)
917           val = fmod(val, t->mod);
918       if (val < t->min) {
919         val = t->min;
920       } else if (val > t->max) {
921         val = t->max;
922       }
923
924       if (t->table==0) {
925         val = val * t->factor + t->offset;
926       } else {
927         val = t->table->interpolate(val) * t->factor + t->offset;
928       }
929       
930       switch (t->type) {
931       case FGPanelTransformation::XSHIFT:
932         glTranslatef(val, 0.0, 0.0);
933         break;
934       case FGPanelTransformation::YSHIFT:
935         glTranslatef(0.0, val, 0.0);
936         break;
937       case FGPanelTransformation::ROTATION:
938         glRotatef(-val, 0.0, 0.0, 1.0);
939         break;
940       }
941     }
942     it++;
943   }
944 }
945
946 void
947 FGInstrumentLayer::addTransformation (FGPanelTransformation * transformation)
948 {
949   _transformations.push_back(transformation);
950 }
951
952
953 \f
954 ////////////////////////////////////////////////////////////////////////
955 // Implementation of FGGroupLayer.
956 ////////////////////////////////////////////////////////////////////////
957
958 FGGroupLayer::FGGroupLayer ()
959 {
960 }
961
962 FGGroupLayer::~FGGroupLayer ()
963 {
964   for (unsigned int i = 0; i < _layers.size(); i++)
965     delete _layers[i];
966 }
967
968 void
969 FGGroupLayer::draw (osg::State& state)
970 {
971   if (test()) {
972     transform();
973     int nLayers = _layers.size();
974     for (int i = 0; i < nLayers; i++)
975       _layers[i]->draw(state);
976   }
977 }
978
979 void
980 FGGroupLayer::addLayer (FGInstrumentLayer * layer)
981 {
982   _layers.push_back(layer);
983 }
984
985
986 \f
987 ////////////////////////////////////////////////////////////////////////
988 // Implementation of FGTexturedLayer.
989 ////////////////////////////////////////////////////////////////////////
990
991
992 FGTexturedLayer::FGTexturedLayer (const FGCroppedTexture &texture, int w, int h)
993   : FGInstrumentLayer(w, h),
994     _emissive(false)
995 {
996   setTexture(texture);
997 }
998
999
1000 FGTexturedLayer::~FGTexturedLayer ()
1001 {
1002 }
1003
1004
1005 void
1006 FGTexturedLayer::draw (osg::State& state)
1007 {
1008   if (test()) {
1009     int w2 = _w / 2;
1010     int h2 = _h / 2;
1011     
1012     transform();
1013     state.pushStateSet(_texture.getTexture());
1014     state.apply();
1015     state.setActiveTextureUnit(0);
1016     state.setClientActiveTextureUnit(0);
1017
1018     glBegin(GL_POLYGON);
1019
1020     if (_emissive) {
1021       glColor4fv( emissive_panel_color );
1022     } else {
1023                                 // From Curt: turn on the panel
1024                                 // lights after sundown.
1025       glColor4fv( panel_color );
1026     }
1027
1028     glTexCoord2f(_texture.getMinX(), _texture.getMinY()); glVertex2f(-w2, -h2);
1029     glTexCoord2f(_texture.getMaxX(), _texture.getMinY()); glVertex2f(w2, -h2);
1030     glTexCoord2f(_texture.getMaxX(), _texture.getMaxY()); glVertex2f(w2, h2);
1031     glTexCoord2f(_texture.getMinX(), _texture.getMaxY()); glVertex2f(-w2, h2);
1032     glEnd();
1033     state.popStateSet();
1034     state.apply();
1035     state.setActiveTextureUnit(0);
1036     state.setClientActiveTextureUnit(0);
1037
1038   }
1039 }
1040
1041
1042 \f
1043 ////////////////////////////////////////////////////////////////////////
1044 // Implementation of FGTextLayer.
1045 ////////////////////////////////////////////////////////////////////////
1046
1047 FGTextLayer::FGTextLayer (int w, int h)
1048   : FGInstrumentLayer(w, h), _pointSize(14.0), _font_name("Helvetica.txf")
1049 {
1050   _then.stamp();
1051   _color[0] = _color[1] = _color[2] = 0.0;
1052   _color[3] = 1.0;
1053 }
1054
1055 FGTextLayer::~FGTextLayer ()
1056 {
1057   chunk_list::iterator it = _chunks.begin();
1058   chunk_list::iterator last = _chunks.end();
1059   for ( ; it != last; it++) {
1060     delete *it;
1061   }
1062 }
1063
1064 void
1065 FGTextLayer::draw (osg::State& state)
1066 {
1067   if (test()) {
1068     glColor4fv(_color);
1069     transform();
1070
1071     FGFontCache *fc = globals->get_fontcache();
1072     fntFont* font = fc->getTexFont(_font_name.c_str());
1073     if (!font) {
1074         return; // don't crash on missing fonts
1075     }
1076     
1077     text_renderer.setFont(font);
1078
1079     text_renderer.setPointSize(_pointSize);
1080     text_renderer.begin();
1081     text_renderer.start3f(0, 0, 0);
1082
1083     _now.stamp();
1084     double diff = (_now - _then).toUSecs();
1085
1086     if (diff > 100000 || diff < 0 ) {
1087       // ( diff < 0 ) is a sanity check and indicates our time stamp
1088       // difference math probably overflowed.  We can handle a max
1089       // difference of 35.8 minutes since the returned value is in
1090       // usec.  So if the panel is left off longer than that we can
1091       // over flow the math with it is turned back on.  This (diff <
1092       // 0) catches that situation, get's us out of trouble, and
1093       // back on track.
1094       recalc_value();
1095       _then = _now;
1096     }
1097
1098     // Something is goofy.  The code in this file renders only CCW
1099     // polygons, and I have verified that the font code in plib
1100     // renders only CCW trianbles.  Yet they come out backwards.
1101     // Something around here or in plib is either changing the winding
1102     // order or (more likely) pushing a left-handed matrix onto the
1103     // stack.  But I can't find it; get out the chainsaw...
1104     glFrontFace(GL_CW);
1105     text_renderer.puts((char *)(_value.c_str()));
1106     glFrontFace(GL_CCW);
1107
1108     text_renderer.end();
1109     glColor4f(1.0, 1.0, 1.0, 1.0);      // FIXME
1110   }
1111 }
1112
1113 void
1114 FGTextLayer::addChunk (FGTextLayer::Chunk * chunk)
1115 {
1116   _chunks.push_back(chunk);
1117 }
1118
1119 void
1120 FGTextLayer::setColor (float r, float g, float b)
1121 {
1122   _color[0] = r;
1123   _color[1] = g;
1124   _color[2] = b;
1125   _color[3] = 1.0;
1126 }
1127
1128 void
1129 FGTextLayer::setPointSize (float size)
1130 {
1131   _pointSize = size;
1132 }
1133
1134 void
1135 FGTextLayer::setFontName(const string &name)
1136 {
1137   _font_name = name + ".txf";
1138   FGFontCache *fc = globals->get_fontcache();
1139   fntFont* font = fc->getTexFont(_font_name.c_str());
1140   if (!font) {
1141       SG_LOG(SG_COCKPIT, SG_WARN, "unable to find font:" << name);
1142   }
1143 }
1144
1145
1146 void
1147 FGTextLayer::setFont(fntFont * font)
1148 {
1149   text_renderer.setFont(font);
1150 }
1151
1152
1153 void
1154 FGTextLayer::recalc_value () const
1155 {
1156   _value = "";
1157   chunk_list::const_iterator it = _chunks.begin();
1158   chunk_list::const_iterator last = _chunks.end();
1159   for ( ; it != last; it++) {
1160     _value += (*it)->getValue();
1161   }
1162 }
1163
1164
1165 \f
1166 ////////////////////////////////////////////////////////////////////////
1167 // Implementation of FGTextLayer::Chunk.
1168 ////////////////////////////////////////////////////////////////////////
1169
1170 FGTextLayer::Chunk::Chunk (const string &text, const string &fmt)
1171   : _type(FGTextLayer::TEXT), _fmt(fmt)
1172 {
1173   _text = text;
1174   if (_fmt.empty()) 
1175     _fmt = "%s";
1176 }
1177
1178 FGTextLayer::Chunk::Chunk (ChunkType type, const SGPropertyNode * node,
1179                            const string &fmt, float mult, float offs,
1180                            bool truncation)
1181   : _type(type), _fmt(fmt), _mult(mult), _offs(offs), _trunc(truncation)
1182 {
1183   if (_fmt.empty()) {
1184     if (type == TEXT_VALUE)
1185       _fmt = "%s";
1186     else
1187       _fmt = "%.2f";
1188   }
1189   _node = node;
1190 }
1191
1192 const char *
1193 FGTextLayer::Chunk::getValue () const
1194 {
1195   if (test()) {
1196     _buf[0] = '\0';
1197     switch (_type) {
1198     case TEXT:
1199       sprintf(_buf, _fmt.c_str(), _text.c_str());
1200       return _buf;
1201     case TEXT_VALUE:
1202       sprintf(_buf, _fmt.c_str(), _node->getStringValue());
1203       break;
1204     case DOUBLE_VALUE:
1205       double d = _offs + _node->getFloatValue() * _mult;
1206       if (_trunc)  d = (d < 0) ? -floor(-d) : floor(d);
1207       sprintf(_buf, _fmt.c_str(), d);
1208       break;
1209     }
1210     return _buf;
1211   } else {
1212     return "";
1213   }
1214 }
1215
1216
1217 \f
1218 ////////////////////////////////////////////////////////////////////////
1219 // Implementation of FGSwitchLayer.
1220 ////////////////////////////////////////////////////////////////////////
1221
1222 FGSwitchLayer::FGSwitchLayer ()
1223   : FGGroupLayer()
1224 {
1225 }
1226
1227 void
1228 FGSwitchLayer::draw (osg::State& state)
1229 {
1230   if (test()) {
1231     transform();
1232     int nLayers = _layers.size();
1233     for (int i = 0; i < nLayers; i++) {
1234       if (_layers[i]->test()) {
1235           _layers[i]->draw(state);
1236           return;
1237       }
1238     }
1239   }
1240 }
1241
1242 \f
1243 // end of panel.cxx