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