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