]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Fix shared library build for metar executable
[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 // create sky, but can't build until setupView, since we depend
459 // on other subsystems to be inited, eg Ephemeris    
460     _sky = new SGSky;
461     
462     SGPath texture_path(globals->get_fg_root());
463     texture_path.append("Textures");
464     texture_path.append("Sky");
465     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
466         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
467         _sky->add_cloud_layer(layer);
468     }
469     
470     _sky->texture_path( texture_path.str() );
471 }
472
473 void
474 FGRenderer::setupView( void )
475 {
476     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
477     osg::initNotifyLevel();
478
479     // The number of polygon-offset "units" to place between layers.  In
480     // principle, one is supposed to be enough.  In practice, I find that
481     // my hardware/driver requires many more.
482     osg::PolygonOffset::setUnitsMultiplier(1);
483     osg::PolygonOffset::setFactorMultiplier(1);
484
485     // Go full screen if requested ...
486     if ( fgGetBool("/sim/startup/fullscreen") )
487         fgOSFullScreen();
488
489 // build the sky    
490     // The sun and moon diameters are scaled down numbers of the
491     // actual diameters. This was needed to fit both the sun and the
492     // moon within the distance to the far clip plane.
493     // Moon diameter:    3,476 kilometers
494     // Sun diameter: 1,390,000 kilometers
495     _sky->build( 80000.0, 80000.0,
496                   463.3, 361.8,
497                   *globals->get_ephem(),
498                   fgGetNode("/environment", true));
499     
500     viewer->getCamera()
501         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
502     
503     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
504
505     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
506     
507     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
508     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
509
510     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
511     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
512     stateSet->setAttribute(new osg::BlendFunc);
513     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
514
515     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
516     
517     // this will be set below
518     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
519
520     osg::Material* material = new osg::Material;
521     stateSet->setAttribute(material);
522     
523     stateSet->setTextureAttribute(0, new osg::TexEnv);
524     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
525
526     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
527     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
528     stateSet->setAttribute(hint);
529     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
530     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
531     stateSet->setAttribute(hint);
532     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
533     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
534     stateSet->setAttribute(hint);
535     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
536     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
537     stateSet->setAttribute(hint);
538     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
539     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
540     stateSet->setAttribute(hint);
541
542     osg::Group* sceneGroup = new osg::Group;
543     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
544     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
545
546     //sceneGroup->addChild(thesky->getCloudRoot());
547
548     stateSet = sceneGroup->getOrCreateStateSet();
549     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
550
551     // need to update the light on every frame
552     // OSG LightSource objects are rather confusing. OSG only supports
553     // the 10 lights specified by OpenGL itself; if more than one
554     // LightSource in the scene graph have the same light number, it's
555     // indeterminate which values will be used to render geometry that
556     // has that light number enabled. Also, adding children to a
557     // LightSource is just a shortcut for setting up a state set that
558     // has the corresponding OpenGL light enabled: a LightSource will
559     // affect geometry anywhere in the scene graph that has its light
560     // number enabled in a state set. 
561     LightSource* lightSource = new LightSource;
562     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
563     // relative because of CameraView being just a clever transform node
564     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
565     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
566     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
567     mRealRoot->addChild(lightSource);
568     // we need a white diffuse light for the phase of the moon
569     osg::LightSource* sunLight = new osg::LightSource;
570     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
571     sunLight->getLight()->setLightNum(1);
572     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
573     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
574     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
575     
576     // Hang a StateSet above the sky subgraph in order to turn off
577     // light 0
578     Group* skyGroup = new Group;
579     StateSet* skySS = skyGroup->getOrCreateStateSet();
580     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
581     skyGroup->addChild(_sky->getPreRoot());
582     sunLight->addChild(skyGroup);
583     mRoot->addChild(sceneGroup);
584     mRoot->addChild(sunLight);
585     
586     // Clouds are added to the scene graph later
587     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
588     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
589     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
590     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
591
592     // enable disable specular highlights.
593     // is the place where we might plug in an other fragment shader ...
594     osg::LightModel* lightModel = new osg::LightModel;
595     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
596     stateSet->setAttribute(lightModel);
597
598     // switch to enable wireframe
599     osg::PolygonMode* polygonMode = new osg::PolygonMode;
600     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
601     stateSet->setAttributeAndModes(polygonMode);
602
603     // scene fog handling
604     osg::Fog* fog = new osg::Fog;
605     fog->setUpdateCallback(new FGFogUpdateCallback);
606     stateSet->setAttributeAndModes(fog);
607     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
608
609     // plug in the GUI
610     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
611     if (guiCamera) {
612         osg::Geode* geode = new osg::Geode;
613         geode->addDrawable(new SGPuDrawable);
614         geode->addDrawable(new SGHUDAndPanelDrawable);
615         guiCamera->addChild(geode);
616     }
617     osg::Switch* sw = new osg::Switch;
618     sw->setUpdateCallback(new FGScenerySwitchCallback);
619     sw->addChild(mRoot.get());
620     mRealRoot->addChild(sw);
621     // The clouds are attached directly to the scene graph root
622     // because, in theory, they don't want the same default state set
623     // as the rest of the scene. This may not be true in practice.
624     mRealRoot->addChild(_sky->getCloudRoot());
625     mRealRoot->addChild(FGCreateRedoutNode());
626     // Attach empty program to the scene root so that shader programs
627     // don't leak into state sets (effects) that shouldn't have one.
628     stateSet = mRealRoot->getOrCreateStateSet();
629     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
630 }
631
632 // Update all Visuals (redraws anything graphics related)
633 void
634 FGRenderer::update( ) {
635     if (!(_scenery_loaded->getBoolValue() || 
636            _scenery_override->getBoolValue()))
637     {
638         _splash_alpha->setDoubleValue(1.0);
639         return;
640     }
641     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
642
643     if (_splash_alpha->getDoubleValue()>0.0)
644     {
645         // Fade out the splash screen
646         const double fade_time = 0.8;
647         const double fade_steps_per_sec = 20;
648         double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
649                                          (SGTimeStamp::now() - _splash_time).toSecs());
650         _splash_time = SGTimeStamp::now();
651         double sAlpha = _splash_alpha->getDoubleValue();
652         sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
653         FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
654         _splash_alpha->setDoubleValue(sAlpha);
655     }
656
657 #if 0 // OSGFIXME
658     // OSGFIXME: features no longer available or no longer run-time configurable
659     {
660         bool use_point_sprites = _point_sprites->getBoolValue();
661         bool enhanced_lighting = _enhanced_lighting->getBoolValue();
662         bool distance_attenuation = _distance_attenuation->getBoolValue();
663     
664         SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
665                                       distance_attenuation );
666     }
667 #endif
668
669     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
670
671     // update fog params
672     double actual_visibility;
673     if (_cloud_status->getBoolValue()) {
674         actual_visibility = _sky->get_visibility();
675     } else {
676         actual_visibility = _visibility_m->getDoubleValue();
677     }
678
679     // idle_state is now 1000 meaning we've finished all our
680     // initializations and are running the main loop, so this will
681     // now work without seg faulting the system.
682
683     FGViewer *current__view = globals->get_current_view();
684     // Force update of center dependent values ...
685     current__view->set_dirty();
686   
687     osg::Camera *camera = viewer->getCamera();
688
689     bool skyblend = _skyblend->getBoolValue();
690     if ( skyblend ) {
691         
692         if ( _textures->getBoolValue() ) {
693             SGVec4f clearColor(l->adj_fog_color());
694             camera->setClearColor(toOsg(clearColor));
695         }
696     } else {
697         SGVec4f clearColor(l->sky_color());
698         camera->setClearColor(toOsg(clearColor));
699     }
700
701     // update fog params if visibility has changed
702     double visibility_meters = _visibility_m->getDoubleValue();
703     _sky->set_visibility(visibility_meters);
704
705     double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
706     _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
707
708     // update the sky dome
709     if ( skyblend ) {
710
711         // The sun and moon distances are scaled down versions
712         // of the actual distance to get both the moon and the sun
713         // within the range of the far clip plane.
714         // Moon distance:    384,467 kilometers
715         // Sun distance: 150,000,000 kilometers
716
717         double sun_horiz_eff, moon_horiz_eff;
718         if (_horizon_effect->getBoolValue()) {
719             sun_horiz_eff
720                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
721                                              0.0),
722                              0.33) / 3.0;
723             moon_horiz_eff
724                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
725                                              0.0),
726                              0.33)/3.0;
727         } else {
728            sun_horiz_eff = moon_horiz_eff = 1.0;
729         }
730
731         SGSkyState sstate;
732         sstate.pos       = current__view->getViewPosition();
733         sstate.pos_geod  = current__view->getPosition();
734         sstate.ori       = current__view->getViewOrientation();
735         sstate.spin      = l->get_sun_rotation();
736         sstate.gst       = globals->get_time_params()->getGst();
737         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
738         sstate.moon_dist = 40000.0 * moon_horiz_eff;
739         sstate.sun_angle = l->get_sun_angle();
740
741         SGSkyColor scolor;
742         scolor.sky_color   = SGVec3f(l->sky_color().data());
743         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
744         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
745         scolor.cloud_color = SGVec3f(l->cloud_color().data());
746         scolor.sun_angle   = l->get_sun_angle();
747         scolor.moon_angle  = l->get_moon_angle();
748   
749         double delta_time_sec = _sim_delta_sec->getDoubleValue();
750         _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
751         _sky->repaint( scolor, *globals->get_ephem() );
752
753             //OSGFIXME
754 //         shadows->setupShadows(
755 //           current__view->getLongitude_deg(),
756 //           current__view->getLatitude_deg(),
757 //           globals->get_time_params()->getGst(),
758 //           globals->get_ephem()->getSunRightAscension(),
759 //           globals->get_ephem()->getSunDeclination(),
760 //           l->get_sun_angle());
761
762     }
763
764 //     sgEnviro.setLight(l->adj_fog_color());
765 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
766 //         current__view->get_world_up(),
767 //         current__view->getLongitude_deg(),
768 //         current__view->getLatitude_deg(),
769 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
770 //         delta_time_sec);
771
772     // OSGFIXME
773 //     sgEnviro.drawLightning();
774
775 //        double current_view_origin_airspeed_horiz_kt =
776 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
777 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
778 //                                * SGD_DEGREES_TO_RADIANS);
779
780     // OSGFIXME
781 //     if( is_internal )
782 //         shadows->endOfFrame();
783
784     // need to call the update visitor once
785     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
786     mUpdateVisitor->setViewData(current__view->getViewPosition(),
787                                 current__view->getViewOrientation());
788     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
789     mUpdateVisitor->setLight(direction, l->scene_ambient(),
790                              l->scene_diffuse(), l->scene_specular(),
791                              l->adj_fog_color(),
792                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
793     mUpdateVisitor->setVisibility(actual_visibility);
794     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
795     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
796     cullMask |= simgear::GroundLightManager::instance()
797         ->getLightNodeMask(mUpdateVisitor.get());
798     if (_panel_hotspots->getBoolValue())
799         cullMask |= simgear::PICK_BIT;
800     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
801 }
802
803 void
804 FGRenderer::resize( int width, int height )
805 {
806     int curWidth = _xsize->getIntValue(),
807         curHeight = _ysize->getIntValue();
808     if ((curHeight != height) || (curWidth != width)) {
809     // must guard setting these, or PLIB-PUI fails with too many live interfaces
810         _xsize->setIntValue(width);
811         _ysize->setIntValue(height);
812     }
813 }
814
815 bool
816 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
817                  const osgGA::GUIEventAdapter* ea)
818 {
819     // wipe out the return ...
820     pickList.clear();
821     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
822     Intersections intersections;
823
824     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
825         return false;
826     for (Intersections::iterator hit = intersections.begin(),
827              e = intersections.end();
828          hit != e;
829          ++hit) {
830         const osg::NodePath& np = hit->nodePath;
831         osg::NodePath::const_reverse_iterator npi;
832         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
833             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
834             if (!ud)
835                 continue;
836             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
837                 SGPickCallback* pickCallback = ud->getPickCallback(i);
838                 if (!pickCallback)
839                     continue;
840                 SGSceneryPick sceneryPick;
841                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
842                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
843                 sceneryPick.callback = pickCallback;
844                 pickList.push_back(sceneryPick);
845             }
846         }
847     }
848     return !pickList.empty();
849 }
850
851 void
852 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
853 {
854     viewer = viewer_;
855 }
856
857 void
858 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
859 {
860     eventHandler = eventHandler_;
861 }
862
863 void
864 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
865 {
866     mRealRoot->addChild(camera);
867 }
868
869 bool
870 fgDumpSceneGraphToFile(const char* filename)
871 {
872     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
873 }
874
875 bool
876 fgDumpTerrainBranchToFile(const char* filename)
877 {
878     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
879                                  filename );
880 }
881
882 // For debugging
883 bool
884 fgDumpNodeToFile(osg::Node* node, const char* filename)
885 {
886     return osgDB::writeNodeFile(*node, filename);
887 }
888
889 namespace flightgear
890 {
891 using namespace osg;
892
893 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
894 {
895 public:
896     VisibleSceneInfoVistor()
897         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
898     {
899         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
900                        | CullSettings::VIEW_FRUSTUM_CULLING);
901         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
902     }
903
904     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
905     {
906     }
907
908     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
909
910     typedef std::map<const std::string,int> InfoMap;
911
912     void getNodeInfo(Node* node)
913     {
914         const char* typeName = typeid(*node).name();
915         classInfo[typeName]++;
916         const std::string& nodeName = node->getName();
917         if (!nodeName.empty())
918             nodeInfo[nodeName]++;
919     }
920
921     void dumpInfo()
922     {
923         using namespace std;
924         typedef vector<InfoMap::iterator> FreqVector;
925         cout << "class info:\n";
926         FreqVector classes;
927         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
928              itr != end;
929              ++itr)
930             classes.push_back(itr);
931         sort(classes.begin(), classes.end(), freqComp);
932         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
933              itr != end;
934              ++itr) {
935             cout << (*itr)->first << " " << (*itr)->second << "\n";
936         }
937         cout << "\nnode info:\n";
938         FreqVector nodes;
939         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
940              itr != end;
941              ++itr)
942             nodes.push_back(itr);
943
944         sort (nodes.begin(), nodes.end(), freqComp);
945         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
946              itr != end;
947              ++itr) {
948             cout << (*itr)->first << " " << (*itr)->second << "\n";
949         }
950         cout << endl;
951     }
952     
953     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
954     {
955         ref_ptr<RefMatrix> projection
956             = createOrReuseMatrix(camera->getProjectionMatrix());
957         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
958         if (!viewport)
959             viewport = camera->getViewport();
960         if (viewport)
961             pushViewport(viewport);
962         pushProjectionMatrix(projection.get());
963         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
964         root->accept(*this);
965         popModelViewMatrix();
966         popProjectionMatrix();
967         if (viewport)
968             popViewport();
969         dumpInfo();
970     }
971
972     void apply(Node& node)
973     {
974         if (isCulled(node))
975             return;
976         pushCurrentMask();
977         getNodeInfo(&node);
978         traverse(node);
979         popCurrentMask();
980     }
981     void apply(Group& node)
982     {
983         if (isCulled(node))
984             return;
985         pushCurrentMask();
986         getNodeInfo(&node);
987         traverse(node);
988         popCurrentMask();
989     }
990
991     void apply(Transform& node)
992     {
993         if (isCulled(node))
994             return;
995         pushCurrentMask();
996         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
997         node.computeLocalToWorldMatrix(*matrix,this);
998         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
999         getNodeInfo(&node);
1000         traverse(node);
1001         popModelViewMatrix();
1002         popCurrentMask();
1003     }
1004
1005     void apply(Camera& camera)
1006     {
1007         // Save current cull settings
1008         CullSettings saved_cull_settings(*this);
1009
1010         // set cull settings from this Camera
1011         setCullSettings(camera);
1012         // inherit the settings from above
1013         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1014
1015         // set the cull mask.
1016         unsigned int savedTraversalMask = getTraversalMask();
1017         bool mustSetCullMask = (camera.getInheritanceMask()
1018                                 & osg::CullSettings::CULL_MASK) == 0;
1019         if (mustSetCullMask)
1020             setTraversalMask(camera.getCullMask());
1021
1022         osg::RefMatrix* projection = 0;
1023         osg::RefMatrix* modelview = 0;
1024
1025         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1026             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1027                 projection = createOrReuseMatrix(*getProjectionMatrix()
1028                                                  *camera.getProjectionMatrix());
1029                 modelview = createOrReuseMatrix(*getModelViewMatrix()
1030                                                 * camera.getViewMatrix());
1031             }
1032             else {              // pre multiply 
1033                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1034                                                  * (*getProjectionMatrix()));
1035                 modelview = createOrReuseMatrix(camera.getViewMatrix()
1036                                                 * (*getModelViewMatrix()));
1037             }
1038         } else {
1039             // an absolute reference frame
1040             projection = createOrReuseMatrix(camera.getProjectionMatrix());
1041             modelview = createOrReuseMatrix(camera.getViewMatrix());
1042         }
1043         if (camera.getViewport())
1044             pushViewport(camera.getViewport());
1045
1046         pushProjectionMatrix(projection);
1047         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
1048
1049         traverse(camera);
1050     
1051         // restore the previous model view matrix.
1052         popModelViewMatrix();
1053
1054         // restore the previous model view matrix.
1055         popProjectionMatrix();
1056
1057         if (camera.getViewport()) popViewport();
1058
1059         // restore the previous traversal mask settings
1060         if (mustSetCullMask)
1061             setTraversalMask(savedTraversalMask);
1062
1063         // restore the previous cull settings
1064         setCullSettings(saved_cull_settings);
1065     }
1066
1067 protected:
1068     // sort in reverse
1069     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1070     {
1071         return lhs->second > rhs->second;
1072     }
1073     InfoMap classInfo;
1074     InfoMap nodeInfo;
1075 };
1076
1077 bool printVisibleSceneInfo(FGRenderer* renderer)
1078 {
1079     osgViewer::Viewer* viewer = renderer->getViewer();
1080     VisibleSceneInfoVistor vsv;
1081     Viewport* vp = 0;
1082     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1083         const View::Slave& slave = viewer->getSlave(0);
1084         vp = slave._camera->getViewport();
1085     }
1086     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1087     return true;
1088 }
1089 }
1090 // end of renderer.cxx
1091