]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
NavDisplay: fix update lag when switching range or centre.
[flightgear.git] / src / Main / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #ifdef HAVE_WINDOWS_H
27 #  include <windows.h>
28 #endif
29
30 #include <simgear/compiler.h>
31
32 #include <algorithm>
33 #include <iostream>
34 #include <map>
35 #include <vector>
36 #include <typeinfo>
37
38 #include <osg/ref_ptr>
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
41 #include <osg/Camera>
42 #include <osg/CullFace>
43 #include <osg/CullStack>
44 #include <osg/Depth>
45 #include <osg/Fog>
46 #include <osg/Group>
47 #include <osg/Hint>
48 #include <osg/Light>
49 #include <osg/LightModel>
50 #include <osg/LightSource>
51 #include <osg/Material>
52 #include <osg/Math>
53 #include <osg/NodeCallback>
54 #include <osg/Notify>
55 #include <osg/PolygonMode>
56 #include <osg/PolygonOffset>
57 #include <osg/Program>
58 #include <osg/Version>
59 #include <osg/TexEnv>
60
61 #include <osgUtil/LineSegmentIntersector>
62
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
65
66 #include <simgear/math/SGMath.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/placement.hxx>
70 #include <simgear/scene/sky/sky.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/util/RenderConstants.hxx>
73 #include <simgear/scene/util/SGSceneUserData.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/structure/OSGUtils.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
81 #ifdef FG_JPEG_SERVER
82 #include <simgear/screen/jpgfactory.hxx>
83 #endif
84
85 #include <Time/light.hxx>
86 #include <Time/light.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Model/panelnode.hxx>
89 #include <Model/modelmgr.hxx>
90 #include <Model/acmodel.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/redout.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Instrumentation/HUD/HUD.hxx>
95 #include <Environment/precipitation_mgr.hxx>
96 #include <Environment/environment_mgr.hxx>
97
98 #include "splash.hxx"
99 #include "renderer.hxx"
100 #include "main.hxx"
101 #include "CameraGroup.hxx"
102 #include "FGEventHandler.hxx"
103 #include <Main/viewer.hxx>
104 #include <Main/viewmgr.hxx>
105
106 using namespace osg;
107 using namespace simgear;
108 using namespace flightgear;
109
110 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
111 public:
112   FGHintUpdateCallback(const char* configNode) :
113     mConfigNode(fgGetNode(configNode, true))
114   { }
115   virtual void operator()(osg::StateAttribute* stateAttribute,
116                           osg::NodeVisitor*)
117   {
118     assert(dynamic_cast<osg::Hint*>(stateAttribute));
119     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
120
121     const char* value = mConfigNode->getStringValue();
122     if (!value)
123       hint->setMode(GL_DONT_CARE);
124     else if (0 == strcmp(value, "nicest"))
125       hint->setMode(GL_NICEST);
126     else if (0 == strcmp(value, "fastest"))
127       hint->setMode(GL_FASTEST);
128     else
129       hint->setMode(GL_DONT_CARE);
130   }
131 private:
132   SGPropertyNode_ptr mConfigNode;
133 };
134
135
136 class SGPuDrawable : public osg::Drawable {
137 public:
138   SGPuDrawable()
139   {
140     // Dynamic stuff, do not store geometry
141     setUseDisplayList(false);
142     setDataVariance(Object::DYNAMIC);
143
144     osg::StateSet* stateSet = getOrCreateStateSet();
145     stateSet->setRenderBinDetails(1001, "RenderBin");
146     // speed optimization?
147     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
148     // We can do translucent menus, so why not. :-)
149     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
150     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
151     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
152
153     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
154
155     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
156     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
157   }
158   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
159   { drawImplementation(*renderInfo.getState()); }
160   void drawImplementation(osg::State& state) const
161   {
162     state.setActiveTextureUnit(0);
163     state.setClientActiveTextureUnit(0);
164
165     state.disableAllVertexArrays();
166
167     glPushAttrib(GL_ALL_ATTRIB_BITS);
168     glPushClientAttrib(~0u);
169
170     puDisplay();
171
172     glPopClientAttrib();
173     glPopAttrib();
174   }
175
176   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
177   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
178   
179 private:
180 };
181
182 class SGHUDAndPanelDrawable : public osg::Drawable {
183 public:
184   SGHUDAndPanelDrawable()
185   {
186     // Dynamic stuff, do not store geometry
187     setUseDisplayList(false);
188     setDataVariance(Object::DYNAMIC);
189
190     osg::StateSet* stateSet = getOrCreateStateSet();
191     stateSet->setRenderBinDetails(1000, "RenderBin");
192
193     // speed optimization?
194     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
195     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
196     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
197     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
198     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
199
200     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
201   }
202   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
203   { drawImplementation(*renderInfo.getState()); }
204   void drawImplementation(osg::State& state) const
205   {
206     state.setActiveTextureUnit(0);
207     state.setClientActiveTextureUnit(0);
208     state.disableAllVertexArrays();
209
210     glPushAttrib(GL_ALL_ATTRIB_BITS);
211     glPushClientAttrib(~0u);
212
213     HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
214     hud->draw(state);
215
216     // update the panel subsystem
217     if ( globals->get_current_panel() != NULL )
218         globals->get_current_panel()->update(state);
219     // We don't need a state here - can be safely removed when we can pick
220     // correctly
221     fgUpdate3DPanels();
222
223     glPopClientAttrib();
224     glPopAttrib();
225
226   }
227
228   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
229   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
230   
231 private:
232 };
233
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
235 public:
236   
237   /**
238    * @param isSun true if the light is the actual sun i.e., for
239    * illuminating the moon.
240    */
241   FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
242   FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
243                               const CopyOp& op)
244     : NodeCallback(nc, op), _isSun(nc._isSun)
245   {}
246   META_Object(flightgear,FGLightSourceUpdateCallback);
247   
248   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
249   {
250     assert(dynamic_cast<osg::LightSource*>(node));
251     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
252     osg::Light* light = lightSource->getLight();
253     
254     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
255     if (_isSun) {
256       light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257       light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
258       light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259     } else {
260       light->setAmbient(toOsg(l->scene_ambient()));
261       light->setDiffuse(toOsg(l->scene_diffuse()));
262       light->setSpecular(toOsg(l->scene_specular()));
263     }
264     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
265     light->setPosition(position);
266
267     traverse(node, nv);
268   }
269 private:
270   const bool _isSun;
271 };
272
273 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
274 public:
275   FGWireFrameModeUpdateCallback() :
276     mWireframe(fgGetNode("/sim/rendering/wireframe", true))
277   { }
278   virtual void operator()(osg::StateAttribute* stateAttribute,
279                           osg::NodeVisitor*)
280   {
281     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
282     osg::PolygonMode* polygonMode;
283     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
284
285     if (mWireframe->getBoolValue())
286       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287                            osg::PolygonMode::LINE);
288     else
289       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290                            osg::PolygonMode::FILL);
291   }
292 private:
293   SGPropertyNode_ptr mWireframe;
294 };
295
296 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
297 public:
298   FGLightModelUpdateCallback() :
299     mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
300   { }
301   virtual void operator()(osg::StateAttribute* stateAttribute,
302                           osg::NodeVisitor*)
303   {
304     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
305     osg::LightModel* lightModel;
306     lightModel = static_cast<osg::LightModel*>(stateAttribute);
307
308 #if 0
309     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
310     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
311 #else
312     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
313 #endif
314     lightModel->setTwoSided(true);
315     lightModel->setLocalViewer(false);
316
317     if (mHighlights->getBoolValue()) {
318       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
319     } else {
320       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
321     }
322   }
323 private:
324   SGPropertyNode_ptr mHighlights;
325 };
326
327 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
328 public:
329   FGFogEnableUpdateCallback() :
330     mFogEnabled(fgGetNode("/sim/rendering/fog", true))
331   { }
332   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
333   {
334     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
335       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
336     } else {
337       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
338     }
339   }
340 private:
341   SGPropertyNode_ptr mFogEnabled;
342 };
343
344 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
345 public:
346   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
347   {
348     assert(dynamic_cast<SGUpdateVisitor*>(nv));
349     assert(dynamic_cast<osg::Fog*>(sa));
350     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
351     osg::Fog* fog = static_cast<osg::Fog*>(sa);
352     fog->setMode(osg::Fog::EXP2);
353     fog->setColor(toOsg(updateVisitor->getFogColor()));
354     fog->setDensity(updateVisitor->getFogExp2Density());
355   }
356 };
357
358 // update callback for the switch node guarding that splash
359 class FGScenerySwitchCallback : public osg::NodeCallback {
360 public:
361   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
362   {
363     assert(dynamic_cast<osg::Switch*>(node));
364     osg::Switch* sw = static_cast<osg::Switch*>(node);
365
366     bool enabled = scenery_enabled;
367     sw->setValue(0, enabled);
368     if (!enabled)
369       return;
370     traverse(node, nv);
371   }
372
373   static bool scenery_enabled;
374 };
375
376 bool FGScenerySwitchCallback::scenery_enabled = false;
377
378 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
379 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
380
381 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
382
383 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
384
385 #ifdef FG_JPEG_SERVER
386 static void updateRenderer()
387 {
388     globals->get_renderer()->update();
389 }
390 #endif
391
392 FGRenderer::FGRenderer() :
393     _sky(NULL)
394 {
395 #ifdef FG_JPEG_SERVER
396    jpgRenderFrame = updateRenderer;
397 #endif
398    eventHandler = new FGEventHandler;
399 }
400
401 FGRenderer::~FGRenderer()
402 {
403 #ifdef FG_JPEG_SERVER
404    jpgRenderFrame = NULL;
405 #endif
406     delete _sky;
407 }
408
409 // Initialize various GL/view parameters
410 // XXX This should be called "preinit" or something, as it initializes
411 // critical parts of the scene graph in addition to the splash screen.
412 void
413 FGRenderer::splashinit( void ) {
414     osgViewer::Viewer* viewer = getViewer();
415     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
416     mRealRoot->addChild(fgCreateSplashNode());
417     mFrameStamp = viewer->getFrameStamp();
418     // Scene doesn't seem to pass the frame stamp to the update
419     // visitor automatically.
420     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
421     viewer->setUpdateVisitor(mUpdateVisitor.get());
422     fgSetDouble("/sim/startup/splash-alpha", 1.0);
423 }
424
425 void
426 FGRenderer::init( void )
427 {
428     _scenery_loaded   = fgGetNode("/sim/sceneryloaded", true);
429     _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
430     _panel_hotspots   = fgGetNode("/sim/panel-hotspots", true);
431     _virtual_cockpit  = fgGetNode("/sim/virtual-cockpit", true);
432
433     _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
434
435     _xsize         = fgGetNode("/sim/startup/xsize", true);
436     _ysize         = fgGetNode("/sim/startup/ysize", true);
437     _splash_alpha  = fgGetNode("/sim/startup/splash-alpha", true);
438
439     _skyblend             = fgGetNode("/sim/rendering/skyblend", true);
440     _point_sprites        = fgGetNode("/sim/rendering/point-sprites", true);
441     _enhanced_lighting    = fgGetNode("/sim/rendering/enhanced-lighting", true);
442     _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
443     _horizon_effect       = fgGetNode("/sim/rendering/horizon-effect", true);
444     _textures             = fgGetNode("/sim/rendering/textures", true);
445
446     _altitude_ft = fgGetNode("/position/altitude-ft", true);
447
448     _cloud_status = fgGetNode("/environment/clouds/status", true);
449     _visibility_m = fgGetNode("/environment/visibility-m", true);
450     
451     bool use_point_sprites = _point_sprites->getBoolValue();
452     bool enhanced_lighting = _enhanced_lighting->getBoolValue();
453     bool distance_attenuation = _distance_attenuation->getBoolValue();
454
455     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
456                                   distance_attenuation );
457
458     if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
459       if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
460           strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
461           strcmp(tc, "none") == 0) {
462         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
463       } else if (strcmp(tc, "arb") == 0) {
464         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
465       } else if (strcmp(tc, "dxt1") == 0) {
466         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
467       } else if (strcmp(tc, "dxt3") == 0) {
468         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
469       } else if (strcmp(tc, "dxt5") == 0) {
470         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
471       } else {
472         SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
473       }
474     }
475     
476 // create sky, but can't build until setupView, since we depend
477 // on other subsystems to be inited, eg Ephemeris    
478     _sky = new SGSky;
479     
480     SGPath texture_path(globals->get_fg_root());
481     texture_path.append("Textures");
482     texture_path.append("Sky");
483     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
484         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
485         _sky->add_cloud_layer(layer);
486     }
487     
488     _sky->texture_path( texture_path.str() );
489 }
490
491 void
492 FGRenderer::setupView( void )
493 {
494     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
495     osg::initNotifyLevel();
496
497     // The number of polygon-offset "units" to place between layers.  In
498     // principle, one is supposed to be enough.  In practice, I find that
499     // my hardware/driver requires many more.
500     osg::PolygonOffset::setUnitsMultiplier(1);
501     osg::PolygonOffset::setFactorMultiplier(1);
502
503     // Go full screen if requested ...
504     if ( fgGetBool("/sim/startup/fullscreen") )
505         fgOSFullScreen();
506
507 // build the sky    
508     // The sun and moon diameters are scaled down numbers of the
509     // actual diameters. This was needed to fit both the sun and the
510     // moon within the distance to the far clip plane.
511     // Moon diameter:    3,476 kilometers
512     // Sun diameter: 1,390,000 kilometers
513     _sky->build( 80000.0, 80000.0,
514                   463.3, 361.8,
515                   *globals->get_ephem(),
516                   fgGetNode("/environment", true));
517     
518     viewer->getCamera()
519         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
520     
521     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
522
523     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
524     
525     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
526     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
527
528     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
529     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
530     stateSet->setAttribute(new osg::BlendFunc);
531     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
532
533     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
534     
535     // this will be set below
536     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
537
538     osg::Material* material = new osg::Material;
539     stateSet->setAttribute(material);
540     
541     stateSet->setTextureAttribute(0, new osg::TexEnv);
542     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
543
544     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
545     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
546     stateSet->setAttribute(hint);
547     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
548     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
549     stateSet->setAttribute(hint);
550     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
551     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
552     stateSet->setAttribute(hint);
553     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
554     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
555     stateSet->setAttribute(hint);
556     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
557     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
558     stateSet->setAttribute(hint);
559
560     osg::Group* sceneGroup = new osg::Group;
561     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
562     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
563
564     //sceneGroup->addChild(thesky->getCloudRoot());
565
566     stateSet = sceneGroup->getOrCreateStateSet();
567     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
568
569     // need to update the light on every frame
570     // OSG LightSource objects are rather confusing. OSG only supports
571     // the 10 lights specified by OpenGL itself; if more than one
572     // LightSource in the scene graph have the same light number, it's
573     // indeterminate which values will be used to render geometry that
574     // has that light number enabled. Also, adding children to a
575     // LightSource is just a shortcut for setting up a state set that
576     // has the corresponding OpenGL light enabled: a LightSource will
577     // affect geometry anywhere in the scene graph that has its light
578     // number enabled in a state set. 
579     LightSource* lightSource = new LightSource;
580     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
581     // relative because of CameraView being just a clever transform node
582     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
583     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
584     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
585     mRealRoot->addChild(lightSource);
586     // we need a white diffuse light for the phase of the moon
587     osg::LightSource* sunLight = new osg::LightSource;
588     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
589     sunLight->getLight()->setLightNum(1);
590     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
591     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
592     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
593     
594     // Hang a StateSet above the sky subgraph in order to turn off
595     // light 0
596     Group* skyGroup = new Group;
597     StateSet* skySS = skyGroup->getOrCreateStateSet();
598     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
599     skyGroup->addChild(_sky->getPreRoot());
600     sunLight->addChild(skyGroup);
601     mRoot->addChild(sceneGroup);
602     mRoot->addChild(sunLight);
603     
604     // Clouds are added to the scene graph later
605     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
606     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
607     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
608     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
609
610     // enable disable specular highlights.
611     // is the place where we might plug in an other fragment shader ...
612     osg::LightModel* lightModel = new osg::LightModel;
613     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
614     stateSet->setAttribute(lightModel);
615
616     // switch to enable wireframe
617     osg::PolygonMode* polygonMode = new osg::PolygonMode;
618     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
619     stateSet->setAttributeAndModes(polygonMode);
620
621     // scene fog handling
622     osg::Fog* fog = new osg::Fog;
623     fog->setUpdateCallback(new FGFogUpdateCallback);
624     stateSet->setAttributeAndModes(fog);
625     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
626
627     // plug in the GUI
628     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
629     if (guiCamera) {
630         osg::Geode* geode = new osg::Geode;
631         geode->addDrawable(new SGPuDrawable);
632         geode->addDrawable(new SGHUDAndPanelDrawable);
633         guiCamera->addChild(geode);
634     }
635     osg::Switch* sw = new osg::Switch;
636     sw->setUpdateCallback(new FGScenerySwitchCallback);
637     sw->addChild(mRoot.get());
638     mRealRoot->addChild(sw);
639     // The clouds are attached directly to the scene graph root
640     // because, in theory, they don't want the same default state set
641     // as the rest of the scene. This may not be true in practice.
642     mRealRoot->addChild(_sky->getCloudRoot());
643     mRealRoot->addChild(FGCreateRedoutNode());
644     // Attach empty program to the scene root so that shader programs
645     // don't leak into state sets (effects) that shouldn't have one.
646     stateSet = mRealRoot->getOrCreateStateSet();
647     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
648 }
649
650 // Update all Visuals (redraws anything graphics related)
651 void
652 FGRenderer::update( ) {
653     if (!(_scenery_loaded->getBoolValue() || 
654            _scenery_override->getBoolValue()))
655     {
656         _splash_alpha->setDoubleValue(1.0);
657         return;
658     }
659     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
660
661     if (_splash_alpha->getDoubleValue()>0.0)
662     {
663         // Fade out the splash screen
664         const double fade_time = 0.8;
665         const double fade_steps_per_sec = 20;
666         double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
667                                          (SGTimeStamp::now() - _splash_time).toSecs());
668         _splash_time = SGTimeStamp::now();
669         double sAlpha = _splash_alpha->getDoubleValue();
670         sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
671         FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
672         _splash_alpha->setDoubleValue(sAlpha);
673     }
674
675     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
676
677     // update fog params
678     double actual_visibility;
679     if (_cloud_status->getBoolValue()) {
680         actual_visibility = _sky->get_visibility();
681     } else {
682         actual_visibility = _visibility_m->getDoubleValue();
683     }
684
685     // idle_state is now 1000 meaning we've finished all our
686     // initializations and are running the main loop, so this will
687     // now work without seg faulting the system.
688
689     FGViewer *current__view = globals->get_current_view();
690     // Force update of center dependent values ...
691     current__view->set_dirty();
692   
693     osg::Camera *camera = viewer->getCamera();
694
695     bool skyblend = _skyblend->getBoolValue();
696     if ( skyblend ) {
697         
698         if ( _textures->getBoolValue() ) {
699             SGVec4f clearColor(l->adj_fog_color());
700             camera->setClearColor(toOsg(clearColor));
701         }
702     } else {
703         SGVec4f clearColor(l->sky_color());
704         camera->setClearColor(toOsg(clearColor));
705     }
706
707     // update fog params if visibility has changed
708     double visibility_meters = _visibility_m->getDoubleValue();
709     _sky->set_visibility(visibility_meters);
710
711     double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
712     _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
713
714     // update the sky dome
715     if ( skyblend ) {
716
717         // The sun and moon distances are scaled down versions
718         // of the actual distance to get both the moon and the sun
719         // within the range of the far clip plane.
720         // Moon distance:    384,467 kilometers
721         // Sun distance: 150,000,000 kilometers
722
723         double sun_horiz_eff, moon_horiz_eff;
724         if (_horizon_effect->getBoolValue()) {
725             sun_horiz_eff
726                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
727                                              0.0),
728                              0.33) / 3.0;
729             moon_horiz_eff
730                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
731                                              0.0),
732                              0.33)/3.0;
733         } else {
734            sun_horiz_eff = moon_horiz_eff = 1.0;
735         }
736
737         SGSkyState sstate;
738         sstate.pos       = current__view->getViewPosition();
739         sstate.pos_geod  = current__view->getPosition();
740         sstate.ori       = current__view->getViewOrientation();
741         sstate.spin      = l->get_sun_rotation();
742         sstate.gst       = globals->get_time_params()->getGst();
743         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
744         sstate.moon_dist = 40000.0 * moon_horiz_eff;
745         sstate.sun_angle = l->get_sun_angle();
746
747         SGSkyColor scolor;
748         scolor.sky_color   = SGVec3f(l->sky_color().data());
749         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
750         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
751         scolor.cloud_color = SGVec3f(l->cloud_color().data());
752         scolor.sun_angle   = l->get_sun_angle();
753         scolor.moon_angle  = l->get_moon_angle();
754   
755         double delta_time_sec = _sim_delta_sec->getDoubleValue();
756         _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
757         _sky->repaint( scolor, *globals->get_ephem() );
758
759             //OSGFIXME
760 //         shadows->setupShadows(
761 //           current__view->getLongitude_deg(),
762 //           current__view->getLatitude_deg(),
763 //           globals->get_time_params()->getGst(),
764 //           globals->get_ephem()->getSunRightAscension(),
765 //           globals->get_ephem()->getSunDeclination(),
766 //           l->get_sun_angle());
767
768     }
769
770 //     sgEnviro.setLight(l->adj_fog_color());
771 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
772 //         current__view->get_world_up(),
773 //         current__view->getLongitude_deg(),
774 //         current__view->getLatitude_deg(),
775 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
776 //         delta_time_sec);
777
778     // OSGFIXME
779 //     sgEnviro.drawLightning();
780
781 //        double current_view_origin_airspeed_horiz_kt =
782 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
783 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
784 //                                * SGD_DEGREES_TO_RADIANS);
785
786     // OSGFIXME
787 //     if( is_internal )
788 //         shadows->endOfFrame();
789
790     // need to call the update visitor once
791     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
792     mUpdateVisitor->setViewData(current__view->getViewPosition(),
793                                 current__view->getViewOrientation());
794     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
795     mUpdateVisitor->setLight(direction, l->scene_ambient(),
796                              l->scene_diffuse(), l->scene_specular(),
797                              l->adj_fog_color(),
798                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
799     mUpdateVisitor->setVisibility(actual_visibility);
800     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
801     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
802     cullMask |= simgear::GroundLightManager::instance()
803         ->getLightNodeMask(mUpdateVisitor.get());
804     if (_panel_hotspots->getBoolValue())
805         cullMask |= simgear::PICK_BIT;
806     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
807 }
808
809 void
810 FGRenderer::resize( int width, int height )
811 {
812     int curWidth = _xsize->getIntValue(),
813         curHeight = _ysize->getIntValue();
814     SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
815     if ((curHeight != height) || (curWidth != width)) {
816     // must guard setting these, or PLIB-PUI fails with too many live interfaces
817         _xsize->setIntValue(width);
818         _ysize->setIntValue(height);
819     }
820 }
821
822 bool
823 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
824                  const osgGA::GUIEventAdapter* ea)
825 {
826     // wipe out the return ...
827     pickList.clear();
828     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
829     Intersections intersections;
830
831     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
832         return false;
833     for (Intersections::iterator hit = intersections.begin(),
834              e = intersections.end();
835          hit != e;
836          ++hit) {
837         const osg::NodePath& np = hit->nodePath;
838         osg::NodePath::const_reverse_iterator npi;
839         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
840             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
841             if (!ud)
842                 continue;
843             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
844                 SGPickCallback* pickCallback = ud->getPickCallback(i);
845                 if (!pickCallback)
846                     continue;
847                 SGSceneryPick sceneryPick;
848                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
849                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
850                 sceneryPick.callback = pickCallback;
851                 pickList.push_back(sceneryPick);
852             }
853         }
854     }
855     return !pickList.empty();
856 }
857
858 void
859 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
860 {
861     viewer = viewer_;
862 }
863
864 void
865 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
866 {
867     eventHandler = eventHandler_;
868 }
869
870 void
871 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
872 {
873     mRealRoot->addChild(camera);
874 }
875
876 bool
877 fgDumpSceneGraphToFile(const char* filename)
878 {
879     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
880 }
881
882 bool
883 fgDumpTerrainBranchToFile(const char* filename)
884 {
885     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
886                                  filename );
887 }
888
889 // For debugging
890 bool
891 fgDumpNodeToFile(osg::Node* node, const char* filename)
892 {
893     return osgDB::writeNodeFile(*node, filename);
894 }
895
896 namespace flightgear
897 {
898 using namespace osg;
899
900 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
901 {
902 public:
903     VisibleSceneInfoVistor()
904         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
905     {
906         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
907                        | CullSettings::VIEW_FRUSTUM_CULLING);
908         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
909     }
910
911     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
912     {
913     }
914
915     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
916
917     typedef std::map<const std::string,int> InfoMap;
918
919     void getNodeInfo(Node* node)
920     {
921         const char* typeName = typeid(*node).name();
922         classInfo[typeName]++;
923         const std::string& nodeName = node->getName();
924         if (!nodeName.empty())
925             nodeInfo[nodeName]++;
926     }
927
928     void dumpInfo()
929     {
930         using namespace std;
931         typedef vector<InfoMap::iterator> FreqVector;
932         cout << "class info:\n";
933         FreqVector classes;
934         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
935              itr != end;
936              ++itr)
937             classes.push_back(itr);
938         sort(classes.begin(), classes.end(), freqComp);
939         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
940              itr != end;
941              ++itr) {
942             cout << (*itr)->first << " " << (*itr)->second << "\n";
943         }
944         cout << "\nnode info:\n";
945         FreqVector nodes;
946         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
947              itr != end;
948              ++itr)
949             nodes.push_back(itr);
950
951         sort (nodes.begin(), nodes.end(), freqComp);
952         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
953              itr != end;
954              ++itr) {
955             cout << (*itr)->first << " " << (*itr)->second << "\n";
956         }
957         cout << endl;
958     }
959     
960     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
961     {
962         ref_ptr<RefMatrix> projection
963             = createOrReuseMatrix(camera->getProjectionMatrix());
964         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
965         if (!viewport)
966             viewport = camera->getViewport();
967         if (viewport)
968             pushViewport(viewport);
969         pushProjectionMatrix(projection.get());
970         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
971         root->accept(*this);
972         popModelViewMatrix();
973         popProjectionMatrix();
974         if (viewport)
975             popViewport();
976         dumpInfo();
977     }
978
979     void apply(Node& node)
980     {
981         if (isCulled(node))
982             return;
983         pushCurrentMask();
984         getNodeInfo(&node);
985         traverse(node);
986         popCurrentMask();
987     }
988     void apply(Group& node)
989     {
990         if (isCulled(node))
991             return;
992         pushCurrentMask();
993         getNodeInfo(&node);
994         traverse(node);
995         popCurrentMask();
996     }
997
998     void apply(Transform& node)
999     {
1000         if (isCulled(node))
1001             return;
1002         pushCurrentMask();
1003         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1004         node.computeLocalToWorldMatrix(*matrix,this);
1005         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1006         getNodeInfo(&node);
1007         traverse(node);
1008         popModelViewMatrix();
1009         popCurrentMask();
1010     }
1011
1012     void apply(Camera& camera)
1013     {
1014         // Save current cull settings
1015         CullSettings saved_cull_settings(*this);
1016
1017         // set cull settings from this Camera
1018         setCullSettings(camera);
1019         // inherit the settings from above
1020         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1021
1022         // set the cull mask.
1023         unsigned int savedTraversalMask = getTraversalMask();
1024         bool mustSetCullMask = (camera.getInheritanceMask()
1025                                 & osg::CullSettings::CULL_MASK) == 0;
1026         if (mustSetCullMask)
1027             setTraversalMask(camera.getCullMask());
1028
1029         osg::RefMatrix* projection = 0;
1030         osg::RefMatrix* modelview = 0;
1031
1032         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1033             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1034                 projection = createOrReuseMatrix(*getProjectionMatrix()
1035                                                  *camera.getProjectionMatrix());
1036                 modelview = createOrReuseMatrix(*getModelViewMatrix()
1037                                                 * camera.getViewMatrix());
1038             }
1039             else {              // pre multiply 
1040                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1041                                                  * (*getProjectionMatrix()));
1042                 modelview = createOrReuseMatrix(camera.getViewMatrix()
1043                                                 * (*getModelViewMatrix()));
1044             }
1045         } else {
1046             // an absolute reference frame
1047             projection = createOrReuseMatrix(camera.getProjectionMatrix());
1048             modelview = createOrReuseMatrix(camera.getViewMatrix());
1049         }
1050         if (camera.getViewport())
1051             pushViewport(camera.getViewport());
1052
1053         pushProjectionMatrix(projection);
1054         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
1055
1056         traverse(camera);
1057     
1058         // restore the previous model view matrix.
1059         popModelViewMatrix();
1060
1061         // restore the previous model view matrix.
1062         popProjectionMatrix();
1063
1064         if (camera.getViewport()) popViewport();
1065
1066         // restore the previous traversal mask settings
1067         if (mustSetCullMask)
1068             setTraversalMask(savedTraversalMask);
1069
1070         // restore the previous cull settings
1071         setCullSettings(saved_cull_settings);
1072     }
1073
1074 protected:
1075     // sort in reverse
1076     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1077     {
1078         return lhs->second > rhs->second;
1079     }
1080     InfoMap classInfo;
1081     InfoMap nodeInfo;
1082 };
1083
1084 bool printVisibleSceneInfo(FGRenderer* renderer)
1085 {
1086     osgViewer::Viewer* viewer = renderer->getViewer();
1087     VisibleSceneInfoVistor vsv;
1088     Viewport* vp = 0;
1089     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1090         const View::Slave& slave = viewer->getSlave(0);
1091         vp = slave._camera->getViewport();
1092     }
1093     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1094     return true;
1095 }
1096 }
1097 // end of renderer.cxx
1098