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