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