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