]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/renderer.cxx
Merge branch 'timoore/optimization' into next
[flightgear.git] / src / Viewer / 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 <boost/foreach.hpp>
39
40 #include <osg/ref_ptr>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
43 #include <osg/Camera>
44 #include <osg/CullFace>
45 #include <osg/CullStack>
46 #include <osg/Depth>
47 #include <osg/Fog>
48 #include <osg/Group>
49 #include <osg/Hint>
50 #include <osg/Light>
51 #include <osg/LightModel>
52 #include <osg/LightSource>
53 #include <osg/Material>
54 #include <osg/Math>
55 #include <osg/NodeCallback>
56 #include <osg/Notify>
57 #include <osg/PolygonMode>
58 #include <osg/PolygonOffset>
59 #include <osg/Program>
60 #include <osg/Version>
61 #include <osg/TexEnv>
62
63 #include <osgUtil/LineSegmentIntersector>
64
65 #include <osg/io_utils>
66 #include <osgDB/WriteFile>
67 #include <osgViewer/Renderer>
68
69 #include <simgear/scene/material/matlib.hxx>
70 #include <simgear/scene/material/EffectCullVisitor.hxx>
71 #include <simgear/scene/material/Effect.hxx>
72 #include <simgear/scene/material/EffectGeode.hxx>
73 #include <simgear/scene/material/EffectBuilder.hxx>
74 #include <simgear/scene/model/animation.hxx>
75 #include <simgear/scene/model/placement.hxx>
76 #include <simgear/scene/sky/sky.hxx>
77 #include <simgear/scene/util/DeletionManager.hxx>
78 #include <simgear/scene/util/SGUpdateVisitor.hxx>
79 #include <simgear/scene/util/RenderConstants.hxx>
80 #include <simgear/scene/util/SGSceneUserData.hxx>
81 #include <simgear/scene/tgdb/GroundLightManager.hxx>
82 #include <simgear/scene/tgdb/pt_lights.hxx>
83 #include <simgear/scene/tgdb/userdata.hxx>
84 #include <simgear/structure/OSGUtils.hxx>
85 #include <simgear/props/props.hxx>
86 #include <simgear/timing/sg_time.hxx>
87 #include <simgear/ephemeris/ephemeris.hxx>
88 #include <simgear/math/sg_random.h>
89 #ifdef FG_JPEG_SERVER
90 #include <simgear/screen/jpgfactory.hxx>
91 #endif
92
93 #include <Time/light.hxx>
94 #include <Time/light.hxx>
95 #include <Cockpit/panel.hxx>
96
97 #include <Model/panelnode.hxx>
98 #include <Model/modelmgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/redout.hxx>
102 #include <GUI/new_gui.hxx>
103 #include <Instrumentation/HUD/HUD.hxx>
104 #include <Environment/precipitation_mgr.hxx>
105 #include <Environment/environment_mgr.hxx>
106
107 //#include <Main/main.hxx>
108 #include "viewer.hxx"
109 #include "viewmgr.hxx"
110 #include "splash.hxx"
111 #include "renderer.hxx"
112 #include "CameraGroup.hxx"
113 #include "FGEventHandler.hxx"
114
115 using namespace osg;
116 using namespace simgear;
117 using namespace flightgear;
118
119 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
120 public:
121   FGHintUpdateCallback(const char* configNode) :
122     mConfigNode(fgGetNode(configNode, true))
123   { }
124   virtual void operator()(osg::StateAttribute* stateAttribute,
125                           osg::NodeVisitor*)
126   {
127     assert(dynamic_cast<osg::Hint*>(stateAttribute));
128     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
129
130     const char* value = mConfigNode->getStringValue();
131     if (!value)
132       hint->setMode(GL_DONT_CARE);
133     else if (0 == strcmp(value, "nicest"))
134       hint->setMode(GL_NICEST);
135     else if (0 == strcmp(value, "fastest"))
136       hint->setMode(GL_FASTEST);
137     else
138       hint->setMode(GL_DONT_CARE);
139   }
140 private:
141   SGPropertyNode_ptr mConfigNode;
142 };
143
144
145 class SGPuDrawable : public osg::Drawable {
146 public:
147   SGPuDrawable()
148   {
149     // Dynamic stuff, do not store geometry
150     setUseDisplayList(false);
151     setDataVariance(Object::DYNAMIC);
152
153     osg::StateSet* stateSet = getOrCreateStateSet();
154     stateSet->setRenderBinDetails(1001, "RenderBin");
155     // speed optimization?
156     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
157     // We can do translucent menus, so why not. :-)
158     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
159     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
160     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
161
162     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
163
164     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
165     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
166   }
167   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
168   { drawImplementation(*renderInfo.getState()); }
169   void drawImplementation(osg::State& state) const
170   {
171     state.setActiveTextureUnit(0);
172     state.setClientActiveTextureUnit(0);
173
174     state.disableAllVertexArrays();
175
176     glPushAttrib(GL_ALL_ATTRIB_BITS);
177     glPushClientAttrib(~0u);
178
179     puDisplay();
180
181     glPopClientAttrib();
182     glPopAttrib();
183   }
184
185   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
186   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
187   
188 private:
189 };
190
191 class SGHUDDrawable : public osg::Drawable {
192 public:
193   SGHUDDrawable()
194   {
195     // Dynamic stuff, do not store geometry
196     setUseDisplayList(false);
197     setDataVariance(Object::DYNAMIC);
198
199     osg::StateSet* stateSet = getOrCreateStateSet();
200     stateSet->setRenderBinDetails(1000, "RenderBin");
201
202     // speed optimization?
203     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
204     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
205     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
206     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
207     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
208
209     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
210   }
211   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
212   { drawImplementation(*renderInfo.getState()); }
213   void drawImplementation(osg::State& state) const
214   {
215     state.setActiveTextureUnit(0);
216     state.setClientActiveTextureUnit(0);
217     state.disableAllVertexArrays();
218
219     glPushAttrib(GL_ALL_ATTRIB_BITS);
220     glPushClientAttrib(~0u);
221       
222     HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
223     hud->draw(state);
224
225     glPopClientAttrib();
226     glPopAttrib();
227   }
228
229   virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
230   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
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", true))
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   SGPropertyNode_ptr mWireframe;
295 };
296
297 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
298 public:
299   FGLightModelUpdateCallback() :
300     mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
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   SGPropertyNode_ptr mHighlights;
326 };
327
328 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
329 public:
330   FGFogEnableUpdateCallback() :
331     mFogEnabled(fgGetNode("/sim/rendering/fog", true))
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   SGPropertyNode_ptr 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     bool enabled = scenery_enabled;
368     sw->setValue(0, enabled);
369     if (!enabled)
370       return;
371     traverse(node, nv);
372   }
373
374   static bool scenery_enabled;
375 };
376
377 bool FGScenerySwitchCallback::scenery_enabled = false;
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 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
384
385 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
386
387 #ifdef FG_JPEG_SERVER
388 static void updateRenderer()
389 {
390     globals->get_renderer()->update();
391 }
392 #endif
393
394 FGRenderer::FGRenderer() :
395     _sky(NULL),
396     _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
397     _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
398     _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
399     _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
400     _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
401     _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
402     _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
403     _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
404     _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
405     _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
406 {
407 #ifdef FG_JPEG_SERVER
408    jpgRenderFrame = updateRenderer;
409 #endif
410    eventHandler = new FGEventHandler;
411
412    _numCascades = 4;
413    _cascadeFar[0] = 5.f;
414    _cascadeFar[1] = 50.f;
415    _cascadeFar[2] = 500.f;
416    _cascadeFar[3] = 5000.f;
417 }
418
419 FGRenderer::~FGRenderer()
420 {
421 #ifdef FG_JPEG_SERVER
422    jpgRenderFrame = NULL;
423 #endif
424     delete _sky;
425 }
426
427 // Initialize various GL/view parameters
428 // XXX This should be called "preinit" or something, as it initializes
429 // critical parts of the scene graph in addition to the splash screen.
430 void
431 FGRenderer::splashinit( void ) {
432     osgViewer::Viewer* viewer = getViewer();
433     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
434     ref_ptr<Node> splashNode = fgCreateSplashNode();
435     if (_classicalRenderer) {
436         mRealRoot->addChild(splashNode.get());
437     } else {
438         for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
439                 ii != CameraGroup::getDefault()->camerasEnd();
440                 ++ii )
441         {
442             CameraInfo* info = ii->get();
443             Camera* camera = info->getCamera(DISPLAY_CAMERA);
444             if (camera == 0) continue;
445
446             camera->addChild(splashNode.get());
447         }
448     }
449     mFrameStamp = viewer->getFrameStamp();
450     // Scene doesn't seem to pass the frame stamp to the update
451     // visitor automatically.
452     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
453     viewer->setUpdateVisitor(mUpdateVisitor.get());
454     fgSetDouble("/sim/startup/splash-alpha", 1.0);
455 }
456
457 class ShadowMapSizeListener : public SGPropertyChangeListener {
458 public:
459     virtual void valueChanged(SGPropertyNode* node) {
460         globals->get_renderer()->updateShadowMapSize(node->getIntValue());
461     }
462 };
463
464 class ShadowEnabledListener : public SGPropertyChangeListener {
465 public:
466     virtual void valueChanged(SGPropertyNode* node) {
467         globals->get_renderer()->enableShadows(node->getBoolValue());
468     }
469 };
470
471 class ShadowNumListener : public SGPropertyChangeListener {
472 public:
473     virtual void valueChanged(SGPropertyNode* node) {
474         globals->get_renderer()->updateCascadeNumber(node->getIntValue());
475     }
476 };
477
478 class ShadowRangeListener : public SGPropertyChangeListener {
479 public:
480     virtual void valueChanged(SGPropertyNode* node) {
481         globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
482     }
483 };
484
485 void
486 FGRenderer::init( void )
487 {
488     sgUserDataInit( globals->get_props() );
489
490     _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
491     _shadowMapSize    = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
492     fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
493     fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
494     ShadowRangeListener* srl = new ShadowRangeListener;
495     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
496     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
497     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
498     fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
499     fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
500     _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
501     _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
502     _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
503     _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
504     _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
505     updateCascadeNumber(_numCascades);
506     updateCascadeFar(0, _cascadeFar[0]);
507     updateCascadeFar(1, _cascadeFar[1]);
508     updateCascadeFar(2, _cascadeFar[2]);
509     updateCascadeFar(3, _cascadeFar[3]);
510     _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
511     _depthInColor->set( _useColorForDepth );
512
513     _renderer         = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
514     if (!_classicalRenderer)
515         _pipeline = makeRenderingPipeline(_renderer, 0);
516     _scenery_loaded   = fgGetNode("/sim/sceneryloaded", true);
517     _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
518     _panel_hotspots   = fgGetNode("/sim/panel-hotspots", true);
519     _virtual_cockpit  = fgGetNode("/sim/virtual-cockpit", true);
520
521     _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
522
523     _xsize         = fgGetNode("/sim/startup/xsize", true);
524     _ysize         = fgGetNode("/sim/startup/ysize", true);
525     _splash_alpha  = fgGetNode("/sim/startup/splash-alpha", true);
526
527     _skyblend             = fgGetNode("/sim/rendering/skyblend", true);
528     _point_sprites        = fgGetNode("/sim/rendering/point-sprites", true);
529     _enhanced_lighting    = fgGetNode("/sim/rendering/enhanced-lighting", true);
530     _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
531     _horizon_effect       = fgGetNode("/sim/rendering/horizon-effect", true);
532     _textures             = fgGetNode("/sim/rendering/textures", true);
533
534     _altitude_ft = fgGetNode("/position/altitude-ft", true);
535
536     _cloud_status = fgGetNode("/environment/clouds/status", true);
537     _visibility_m = fgGetNode("/environment/visibility-m", true);
538     
539     bool use_point_sprites = _point_sprites->getBoolValue();
540     bool enhanced_lighting = _enhanced_lighting->getBoolValue();
541     bool distance_attenuation = _distance_attenuation->getBoolValue();
542
543     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
544                                   distance_attenuation );
545
546     if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
547       if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
548           strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
549           strcmp(tc, "none") == 0) {
550         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
551       } else if (strcmp(tc, "arb") == 0) {
552         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
553       } else if (strcmp(tc, "dxt1") == 0) {
554         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
555       } else if (strcmp(tc, "dxt3") == 0) {
556         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
557       } else if (strcmp(tc, "dxt5") == 0) {
558         SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
559       } else {
560         SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
561       }
562     }
563     
564 // create sky, but can't build until setupView, since we depend
565 // on other subsystems to be inited, eg Ephemeris    
566     _sky = new SGSky;
567     
568     SGPath texture_path(globals->get_fg_root());
569     texture_path.append("Textures");
570     texture_path.append("Sky");
571     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
572         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
573         _sky->add_cloud_layer(layer);
574     }
575     
576     _sky->texture_path( texture_path.str() );
577
578     if (!_classicalRenderer) {
579         eventHandler->setChangeStatsCameraRenderOrder( true );
580         _sky->set_minimum_sky_visibility( 0.0 ); // A black sky appears for below that
581     }
582 }
583
584 void installCullVisitor(Camera* camera)
585 {
586     osgViewer::Renderer* renderer
587         = static_cast<osgViewer::Renderer*>(camera->getRenderer());
588     for (int i = 0; i < 2; ++i) {
589         osgUtil::SceneView* sceneView = renderer->getSceneView(i);
590 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
591         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
592 #else
593         osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
594         identifier = sceneView->getCullVisitor()->getIdentifier();
595         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
596         sceneView->getCullVisitor()->setIdentifier(identifier.get());
597
598         identifier = sceneView->getCullVisitorLeft()->getIdentifier();
599         sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
600         sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
601
602         identifier = sceneView->getCullVisitorRight()->getIdentifier();
603         sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
604         sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
605 #endif
606     }
607 }
608
609 CameraInfo*
610 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
611                                    const Matrix& view,
612                                    const Matrix& projection,
613                                                                    osg::GraphicsContext* gc,
614                                    bool useMasterSceneData)
615 {
616         CameraInfo* info = 0;
617         if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
618                 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
619
620         if (info) {
621                 return info;
622         } else {
623                 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
624                         _classicalRenderer = true;
625                 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
626         }
627 }
628
629 CameraInfo*
630 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
631                                 const osg::Matrix& view,
632                                 const osg::Matrix& projection,
633                                 bool useMasterSceneData)
634 {
635     CameraInfo* info = new CameraInfo(flags);
636     // The camera group will always update the camera
637     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
638
639     Camera* farCamera = 0;
640     if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
641         farCamera = new Camera;
642         farCamera->setAllowEventFocus(camera->getAllowEventFocus());
643         farCamera->setGraphicsContext(camera->getGraphicsContext());
644         farCamera->setCullingMode(camera->getCullingMode());
645         farCamera->setInheritanceMask(camera->getInheritanceMask());
646         farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
647         // Each camera's viewport is written when the window is
648         // resized; if the the viewport isn't copied here, it gets updated
649         // twice and ends up with the wrong value.
650         farCamera->setViewport(simgear::clone(camera->getViewport()));
651         farCamera->setDrawBuffer(camera->getDrawBuffer());
652         farCamera->setReadBuffer(camera->getReadBuffer());
653         farCamera->setRenderTargetImplementation(
654             camera->getRenderTargetImplementation());
655         const Camera::BufferAttachmentMap& bufferMap
656             = camera->getBufferAttachmentMap();
657         if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
658             farCamera->attach(
659                 Camera::COLOR_BUFFER,
660                 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
661         }
662         cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
663         installCullVisitor(farCamera);
664                 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
665                 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
666         farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
667         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
668         camera->setClearMask(GL_DEPTH_BUFFER_BIT);
669     }
670     cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
671     installCullVisitor(camera);
672     int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
673     info->addCamera( MAIN_CAMERA, camera, slaveIndex );
674     camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
675     cgroup->addCamera(info);
676     return info;
677 }
678
679 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
680 public:
681     FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
682     virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
683         simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
684         osg::Camera* camera = static_cast<osg::Camera*>(n);
685
686         cv->clearBufferList();
687         for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
688             cv->addBuffer(ii->first, ii->second.texture);
689         }
690
691         if ( !info->getRenderStageInfo(kind).fullscreen )
692             info->setMatrices( camera );
693
694         if (needsDuDv) {
695             osg::Matrix projInverse;
696             info->projInverse->get( projInverse );
697
698             osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
699             info->du->set( osg::Vec4(  1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
700             info->dv->set( osg::Vec4( -1.0,  1.0, 0.0, 1.0 ) * projInverse - p0 );
701         }
702
703         cv->traverse( *camera );
704
705         if ( kind == GEOMETRY_CAMERA ) {
706             // Remove transparent bins. They will be renderer in the additional light stage (side effect)
707             osgUtil::RenderStage* renderStage = cv->getRenderStage();
708             osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
709             for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
710                 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
711                     rbl.erase( rbi++ );
712                 } else {
713                     ++rbi;
714                 }
715             }
716         } else if ( kind == LIGHTING_CAMERA ) {
717             osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
718             if (mainShadowCamera.valid()) {
719                 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
720                 for (int i = 0; i < 4; ++i ) {
721                     if (!grp->getValue(i))
722                         continue;
723
724                     osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
725                     osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
726                                                 cascadeCam->getViewMatrix() *
727                                                 cascadeCam->getProjectionMatrix() *
728                                                 osg::Matrix::translate(1.0, 1.0, 1.0) *
729                                                 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
730
731                     info->shadowMatrix[i]->set( shadowMatrix );
732                 }
733             }
734         }
735     }
736
737 private:
738     std::string kind;
739     CameraInfo* info;
740     bool needsDuDv;
741 };
742
743 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
744 {
745     osg::Texture2D* tex = new osg::Texture2D;
746     tex->setResizeNonPowerOfTwoHint( false );
747     tex->setInternalFormat( internalFormat );
748     tex->setShadowComparison(shadowComparison);
749     if (shadowComparison) {
750         tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
751         tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
752     }
753     tex->setSourceFormat(sourceFormat);
754     tex->setSourceType(sourceType);
755     tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
756     tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
757     tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
758     tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
759         return tex;
760 }
761
762 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
763 {
764     camera->attach( c, info->getBuffer(bk) );
765     info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
766 }
767
768 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
769     BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
770         if (attachment->valid())
771             attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
772     }
773 }
774
775 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
776 {
777     osg::Camera* camera = new osg::Camera;
778     info->addCamera(name, camera );
779
780     camera->setCullMask( ~simgear::MODELLIGHT_BIT );
781     camera->setName( "GeometryC" );
782     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
783     camera->setGraphicsContext( gc );
784     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
785     camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
786     camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
787     camera->setClearDepth( 1.0 );
788     camera->setColorMask(true, true, true, true);
789     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
790     camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
791     camera->setViewport( new osg::Viewport );
792     buildAttachments(info, camera, name, attachments);
793     camera->setDrawBuffer(GL_FRONT);
794     camera->setReadBuffer(GL_FRONT);
795
796     osg::StateSet* ss = camera->getOrCreateStateSet();
797     ss->addUniform( _depthInColor );
798
799     camera->addChild( mDeferredRealRoot.get() );
800
801     return camera;
802 }
803
804 static void setShadowCascadeStateSet( osg::Camera* cam ) {
805     osg::StateSet* ss = cam->getOrCreateStateSet();
806     ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
807     ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
808     ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
809     ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
810     ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
811     ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
812     osg::Program* program = new osg::Program;
813     ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
814     ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
815     ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
816     //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
817     ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
818     ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
819     ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
820     ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
821     ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
822 }
823
824 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
825     osg::Camera* cascadeCam = new osg::Camera;
826     setShadowCascadeStateSet( cascadeCam );
827
828     std::ostringstream oss;
829     oss << "CascadeCamera" << (no + 1);
830     cascadeCam->setName( oss.str() );
831     cascadeCam->setClearMask(0);
832     cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
833     cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
834     cascadeCam->setAllowEventFocus(false);
835     cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
836     cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
837     cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
838     cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
839     return cascadeCam;
840 }
841
842 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
843 {
844     osg::Camera* mainShadowCamera = new osg::Camera;
845     info->addCamera(name, mainShadowCamera, 0.0f );
846
847     mainShadowCamera->setName( "ShadowC" );
848     mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
849     mainShadowCamera->setClearDepth( 1.0 );
850     mainShadowCamera->setAllowEventFocus(false);
851     mainShadowCamera->setGraphicsContext(gc);
852     mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
853     buildAttachments(info, mainShadowCamera, name, attachments);
854     mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
855     mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
856     mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
857     mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
858     mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
859     mainShadowCamera->setDrawBuffer(GL_FRONT);
860     mainShadowCamera->setReadBuffer(GL_FRONT);
861     mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
862
863     osg::Switch* shadowSwitch = new osg::Switch;
864     mainShadowCamera->addChild( shadowSwitch );
865
866     for (int i = 0; i < 4; ++i ) {
867         osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
868         cascadeCam->addChild( mDeferredRealRoot.get() );
869         shadowSwitch->addChild( cascadeCam );
870     }
871     if (fgGetBool("/sim/rendering/shadows/enabled", true))
872         shadowSwitch->setAllChildrenOn();
873     else
874         shadowSwitch->setAllChildrenOff();
875
876     return mainShadowCamera;
877 }
878
879 void FGRenderer::updateShadowCascade(const CameraInfo* info, osg::Camera* camera, osg::Group* grp, int idx, double left, double right, double bottom, double top, double zNear, double f1, double f2)
880 {
881     osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
882     osg::Matrixd &viewMatrix = cascade->getViewMatrix();
883     osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
884
885     osg::BoundingSphere bs;
886     bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
887     bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
888     bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
889     bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
890
891     osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
892
893     projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
894     osg::Vec3 position( aim.x(), aim.y(), aim.z() );
895     viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
896 }
897
898 osg::Vec3 FGRenderer::getSunDirection() const
899 {
900     osg::Vec3 val;
901     _sunDirection->get( val );
902     return val;
903 }
904
905 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
906 {
907     ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
908     if (mainShadowCamera.valid()) {
909         ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
910         osg::Vec3d up = position,
911             dir = getSunDirection();
912         up.normalize();
913         dir.normalize();
914         // cos(100 deg) == -0.17
915         if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
916             shadowSwitch->setAllChildrenOff();
917         } else {
918             double left,right,bottom,top,zNear,zFar;
919             ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
920             camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
921
922             shadowSwitch->setAllChildrenOn();
923             if (_numCascades == 1) {
924                 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
925                 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
926             } else {
927                 for (int no = 0; no < 4; ++no) {
928                     osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
929                     cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
930                 }
931             }
932             updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
933             if (_numCascades > 1) {
934                 shadowSwitch->setValue(1, true);
935                 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
936             } else {
937                 shadowSwitch->setValue(1, false);
938             }
939             if (_numCascades > 2) {
940                 shadowSwitch->setValue(2, true);
941                 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
942             } else {
943                 shadowSwitch->setValue(2, false);
944             }
945             if (_numCascades > 3) {
946                 shadowSwitch->setValue(3, true);
947                 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
948             } else {
949                 shadowSwitch->setValue(3, false);
950             }
951             {
952             osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
953
954             osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
955
956             osg::Vec3 position( aim.x(), aim.y(), aim.z() );
957             viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
958             }
959         }
960     }
961 }
962
963 void FGRenderer::updateShadowMapSize(int mapSize)
964 {
965     if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
966         SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
967         return;
968     }
969     for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
970             ii != CameraGroup::getDefault()->camerasEnd();
971             ++ii )
972     {
973         CameraInfo* info = ii->get();
974         Camera* camera = info->getCamera(SHADOW_CAMERA);
975         if (camera == 0) continue;
976
977         Texture2D* tex = info->getBuffer("shadow");
978         if (tex == 0) continue;
979
980         tex->setTextureSize( mapSize, mapSize );
981         tex->dirtyTextureObject();
982
983         Viewport* vp = camera->getViewport();
984         vp->width() = mapSize;
985         vp->height() = mapSize;
986
987         osgViewer::Renderer* renderer
988             = static_cast<osgViewer::Renderer*>(camera->getRenderer());
989         for (int i = 0; i < 2; ++i) {
990             osgUtil::SceneView* sceneView = renderer->getSceneView(i);
991             sceneView->getRenderStage()->setFrameBufferObject(0);
992             sceneView->getRenderStage()->setCameraRequiresSetUp(true);
993             if (sceneView->getRenderStageLeft()) {
994                 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
995                 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
996             }
997             if (sceneView->getRenderStageRight()) {
998                 sceneView->getRenderStageRight()->setFrameBufferObject(0);
999                 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1000             }
1001         }
1002
1003         int cascadeSize = mapSize / 2;
1004         Group* grp = camera->getChild(0)->asGroup();
1005         for (int i = 0; i < 4; ++i ) {
1006             Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1007             cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1008         }
1009
1010         _shadowMapSize = mapSize;
1011     }
1012 }
1013
1014 void FGRenderer::enableShadows(bool enabled)
1015 {
1016     for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1017             ii != CameraGroup::getDefault()->camerasEnd();
1018             ++ii )
1019     {
1020         CameraInfo* info = ii->get();
1021         Camera* camera = info->getCamera(SHADOW_CAMERA);
1022         if (camera == 0) continue;
1023
1024         osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1025         if (enabled)
1026             shadowSwitch->setAllChildrenOn();
1027         else
1028             shadowSwitch->setAllChildrenOff();
1029     }
1030 }
1031
1032 void FGRenderer::updateCascadeFar(int index, float far_m)
1033 {
1034     if (index < 0 || index > 3)
1035         return;
1036     _cascadeFar[index] = far_m;
1037     _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1038 }
1039
1040 void FGRenderer::updateCascadeNumber(size_t num)
1041 {
1042     if (num < 1 || num > 4)
1043         return;
1044     _numCascades = num;
1045     _shadowNumber->set( (int)_numCascades );
1046 }
1047
1048 class DebugPassListener : public SGPropertyChangeListener {
1049 public:
1050     DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1051     virtual void valueChanged(SGPropertyNode* node) {
1052         _switch->setValue(_index, node->getBoolValue());
1053     }
1054
1055 private:
1056     osg::ref_ptr<osg::Switch> _switch;
1057     int _index;
1058 };
1059
1060 osg::Camera*
1061 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1062 {
1063     osg::Camera* camera = new osg::Camera;
1064     info->addCamera(stage->name, camera );
1065
1066     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1067     camera->setAllowEventFocus(false);
1068     camera->setGraphicsContext(gc);
1069     camera->setViewport(new Viewport);
1070     camera->setName(stage->name+"C");
1071     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1072     camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1073     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1074     camera->setViewport( new osg::Viewport );
1075     buildAttachments(info, camera, stage->name, stage->attachments);
1076     camera->setDrawBuffer(GL_FRONT);
1077     camera->setReadBuffer(GL_FRONT);
1078     camera->setClearColor( osg::Vec4( 0.5, 0.5, 0.5, 1. ) );
1079     camera->setClearMask( GL_COLOR_BUFFER_BIT );
1080     osg::StateSet* ss = camera->getOrCreateStateSet();
1081     ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1082     ss->addUniform( _depthInColor );
1083
1084     osg::Switch* lightingGroup = new osg::Switch;
1085
1086     BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1087         ref_ptr<Node> node = buildPass(info, pass);
1088         if (node.valid()) {
1089             lightingGroup->addChild(node);
1090             if (!pass->debugProperty.empty()) {
1091                 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1092                 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1093             }
1094         }
1095     }
1096
1097     camera->addChild( lightingGroup );
1098
1099     return camera;
1100 }
1101
1102 CameraInfo*
1103 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1104                                     const osg::Matrix& view,
1105                                     const osg::Matrix& projection,
1106                                     osg::GraphicsContext* gc)
1107 {
1108     return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1109 }
1110
1111 osg::Camera* 
1112 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1113 {
1114     osg::Camera* camera = new osg::Camera;
1115
1116     camera->setClearMask( 0 );
1117     camera->setAllowEventFocus(false);
1118     camera->setName(pass->name+"C");
1119     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1120     camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1121     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1122     camera->setViewMatrix(osg::Matrix::identity());
1123     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1124
1125     osg::StateSet* ss = camera->getOrCreateStateSet();
1126     ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1127     ss->addUniform( info->projInverse );
1128     ss->addUniform( info->viewInverse );
1129     ss->addUniform( info->view );
1130     ss->addUniform( info->bufferSize );
1131     ss->addUniform( info->worldPosCart );
1132     ss->addUniform( info->worldPosGeod );
1133     ss->addUniform( info->shadowMatrix[0] );
1134     ss->addUniform( info->shadowMatrix[1] );
1135     ss->addUniform( info->shadowMatrix[2] );
1136     ss->addUniform( info->shadowMatrix[3] );
1137     ss->addUniform( _ambientFactor );
1138     ss->addUniform( _sunDiffuse );
1139     ss->addUniform( _sunSpecular );
1140     ss->addUniform( _sunDirection );
1141     ss->addUniform( _planes );
1142     ss->addUniform( _shadowNumber );
1143     ss->addUniform( _shadowDistances );
1144     ss->addUniform( _fogColor );
1145     ss->addUniform( _fogDensity );
1146
1147     osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1148     g->setUseDisplayList(false);
1149     simgear::EffectGeode* eg = new simgear::EffectGeode;
1150     simgear::Effect* effect = simgear::makeEffect(pass->effect, true);
1151     if (effect) {
1152         eg->setEffect( effect );
1153     }
1154
1155     eg->setName(pass->name+"Quad");
1156     eg->setCullingActive(false);
1157     eg->addDrawable(g);
1158     camera->addChild(eg);
1159
1160     return camera;
1161 }
1162
1163 osg::Camera* 
1164 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1165 {
1166     osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1167     info->addCamera(stage->name, camera, stage->scaleFactor, true);
1168
1169     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1170     camera->setGraphicsContext(gc);
1171     camera->setViewport(new Viewport);
1172     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1173     buildAttachments(info, camera, stage->name, stage->attachments);
1174     camera->setDrawBuffer(GL_FRONT);
1175     camera->setReadBuffer(GL_FRONT);
1176     camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1177     camera->setClearMask( GL_COLOR_BUFFER_BIT );
1178     camera->setViewMatrix(osg::Matrix::identity());
1179     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1180
1181     osg::StateSet* ss = camera->getOrCreateStateSet();
1182     if (stage->needsDuDv) {
1183         ss->addUniform( info->du );
1184         ss->addUniform( info->dv );
1185     }
1186
1187     return camera;
1188 }
1189
1190 void
1191 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1192 {
1193     camera->setName( "DisplayC" );
1194     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1195     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1196     camera->setAllowEventFocus(false);
1197     osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1198     g->setUseDisplayList(false); //DEBUG
1199     simgear::EffectGeode* eg = new simgear::EffectGeode;
1200     simgear::Effect* effect = simgear::makeEffect(stage->effect, true);
1201     if (!effect) {
1202         SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1203         return;
1204     }
1205     eg->setEffect(effect);
1206     eg->setCullingActive(false);
1207     eg->addDrawable(g);
1208     camera->setViewMatrix(osg::Matrix::identity());
1209     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1210     camera->addChild(eg);
1211
1212     osg::StateSet* ss = camera->getOrCreateStateSet();
1213     ss->addUniform( _depthInColor );
1214     ss->addUniform( info->bufferSize );
1215 }
1216
1217 void
1218 FGRenderer::buildStage(CameraInfo* info,
1219                         FGRenderingPipeline::Stage* stage,
1220                         CameraGroup* cgroup,
1221                         osg::Camera* mainCamera,
1222                         const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1223 {
1224     if (!stage->valid())
1225         return;
1226
1227     ref_ptr<Camera> camera;
1228     bool needOffsets = false;
1229     if (stage->type == "geometry") {
1230         camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1231         needOffsets = true;
1232     } else if (stage->type == "lighting") {
1233         camera = buildDeferredLightingCamera(info, gc, stage);
1234         needOffsets = true;
1235     } else if (stage->type == "shadow")
1236         camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1237     else if (stage->type == "fullscreen")
1238         camera = buildDeferredFullscreenCamera(info, gc, stage);
1239     else if (stage->type == "display") {
1240         camera = mainCamera;
1241         buildDeferredDisplayCamera(camera, info, stage, gc);
1242     } else
1243         throw sg_exception("Stage type is not supported");
1244
1245     if (needOffsets)
1246         cgroup->getViewer()->addSlave(camera, projection, view, false);
1247     else
1248         cgroup->getViewer()->addSlave(camera, false);
1249     installCullVisitor(camera);
1250     int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1251     if (stage->type == "display")
1252         info->addCamera( stage->type, camera, slaveIndex, true );
1253     info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1254 }
1255
1256 osg::Node*
1257 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1258 {
1259     Group* group = new Group;
1260     group->addChild( _sky->getPreRoot() );
1261     group->addChild( _sky->getCloudRoot() );
1262     return group;
1263 }
1264
1265 osg::Node*
1266 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1267 {
1268     osg::Camera* lightCam = new osg::Camera;
1269     StateSet* ss = lightCam->getOrCreateStateSet();
1270     ss->addUniform( _planes );
1271     ss->addUniform( info->bufferSize );
1272     ss->addUniform( _fogColor );
1273     ss->addUniform( _fogDensity );
1274     lightCam->setName( "LightCamera" );
1275     lightCam->setClearMask(0);
1276     lightCam->setAllowEventFocus(false);
1277     lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1278     lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1279     lightCam->setViewMatrix(osg::Matrix::identity());
1280     lightCam->setProjectionMatrix(osg::Matrix::identity());
1281     lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1282     lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1283     lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1284     lightCam->addChild( mDeferredRealRoot.get() );
1285
1286     return lightCam;
1287 }
1288
1289 osg::Node*
1290 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1291 {
1292     if (!pass->valid())
1293         return 0;
1294
1295     ref_ptr<Node> node;
1296     if (pass->type == "sky-clouds")
1297         node = buildLightingSkyCloudsPass(pass);
1298     else if (pass->type == "fullscreen")
1299         node = buildDeferredFullscreenCamera(info, pass);
1300     else if (pass->type == "lights")
1301         node = buildLightingLightsPass(info, pass);
1302     else
1303         throw sg_exception("Pass type is not supported");
1304
1305     return node.release();
1306 }
1307
1308 void
1309 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1310 {
1311     for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1312         osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1313         if (buffer->valid()) {
1314             bool fullscreen = buffer->width == -1 && buffer->height == -1;
1315             info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1316                                                                 buffer->sourceFormat,
1317                                                                 buffer->sourceType,
1318                                                                 buffer->wrapMode,
1319                                                                 buffer->shadowComparison),
1320                             fullscreen ? buffer->scaleFactor : 0.0f);
1321             if (!fullscreen) {
1322                 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1323             }
1324         }
1325     }
1326 }
1327
1328 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1329                                     const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1330 {
1331     CameraInfo* info = new CameraInfo(flags);
1332     buildBuffers(rpipe, info);
1333     
1334     for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1335         osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1336         buildStage(info, stage, cgroup, camera, view, projection, gc);
1337     }
1338
1339     cgroup->addCamera(info);
1340
1341     return info;
1342 }
1343
1344 void
1345 FGRenderer::setupView( void )
1346 {
1347     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1348     osg::initNotifyLevel();
1349
1350     // The number of polygon-offset "units" to place between layers.  In
1351     // principle, one is supposed to be enough.  In practice, I find that
1352     // my hardware/driver requires many more.
1353     osg::PolygonOffset::setUnitsMultiplier(1);
1354     osg::PolygonOffset::setFactorMultiplier(1);
1355
1356     // Go full screen if requested ...
1357     if ( fgGetBool("/sim/startup/fullscreen") )
1358         fgOSFullScreen();
1359
1360 // build the sky    
1361     // The sun and moon diameters are scaled down numbers of the
1362     // actual diameters. This was needed to fit both the sun and the
1363     // moon within the distance to the far clip plane.
1364     // Moon diameter:    3,476 kilometers
1365     // Sun diameter: 1,390,000 kilometers
1366     _sky->build( 80000.0, 80000.0,
1367                   463.3, 361.8,
1368                   *globals->get_ephem(),
1369                   fgGetNode("/environment", true));
1370     
1371     viewer->getCamera()
1372         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1373     
1374     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1375
1376     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1377     
1378     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1379     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1380
1381     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1382     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1383     stateSet->setAttribute(new osg::BlendFunc);
1384     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1385
1386     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1387     
1388     // this will be set below
1389     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1390
1391     osg::Material* material = new osg::Material;
1392     stateSet->setAttribute(material);
1393     
1394     stateSet->setTextureAttribute(0, new osg::TexEnv);
1395     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1396
1397     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1398     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1399     stateSet->setAttribute(hint);
1400     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1401     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1402     stateSet->setAttribute(hint);
1403     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1404     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1405     stateSet->setAttribute(hint);
1406     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1407     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1408     stateSet->setAttribute(hint);
1409     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1410     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1411     stateSet->setAttribute(hint);
1412
1413     osg::Group* sceneGroup = new osg::Group;
1414     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1415     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1416
1417     //sceneGroup->addChild(thesky->getCloudRoot());
1418
1419     stateSet = sceneGroup->getOrCreateStateSet();
1420     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1421
1422     // need to update the light on every frame
1423     // OSG LightSource objects are rather confusing. OSG only supports
1424     // the 10 lights specified by OpenGL itself; if more than one
1425     // LightSource in the scene graph have the same light number, it's
1426     // indeterminate which values will be used to render geometry that
1427     // has that light number enabled. Also, adding children to a
1428     // LightSource is just a shortcut for setting up a state set that
1429     // has the corresponding OpenGL light enabled: a LightSource will
1430     // affect geometry anywhere in the scene graph that has its light
1431     // number enabled in a state set. 
1432     LightSource* lightSource = new LightSource;
1433     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1434     // relative because of CameraView being just a clever transform node
1435     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1436     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1437     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1438     mRealRoot->addChild(lightSource);
1439     // we need a white diffuse light for the phase of the moon
1440     osg::LightSource* sunLight = new osg::LightSource;
1441     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1442     sunLight->getLight()->setLightNum(1);
1443     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1444     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1445     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1446     
1447     // Hang a StateSet above the sky subgraph in order to turn off
1448     // light 0
1449     Group* skyGroup = new Group;
1450     StateSet* skySS = skyGroup->getOrCreateStateSet();
1451     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1452     skyGroup->addChild(_sky->getPreRoot());
1453     sunLight->addChild(skyGroup);
1454     mRoot->addChild(sceneGroup);
1455     if ( _classicalRenderer )
1456         mRoot->addChild(sunLight);
1457     
1458     // Clouds are added to the scene graph later
1459     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1460     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1461     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1462     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1463
1464     // enable disable specular highlights.
1465     // is the place where we might plug in an other fragment shader ...
1466     osg::LightModel* lightModel = new osg::LightModel;
1467     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1468     stateSet->setAttribute(lightModel);
1469
1470     // switch to enable wireframe
1471     osg::PolygonMode* polygonMode = new osg::PolygonMode;
1472     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1473     stateSet->setAttributeAndModes(polygonMode);
1474
1475     // scene fog handling
1476     osg::Fog* fog = new osg::Fog;
1477     fog->setUpdateCallback(new FGFogUpdateCallback);
1478     stateSet->setAttributeAndModes(fog);
1479     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1480
1481     // plug in the GUI
1482     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1483     if (guiCamera) {
1484         
1485         osg::Geode* geode = new osg::Geode;
1486         geode->addDrawable(new SGPuDrawable);
1487         geode->addDrawable(new SGHUDDrawable);
1488         guiCamera->addChild(geode);
1489       
1490         
1491       guiCamera->addChild(FGPanelNode::create2DPanelNode());
1492     }
1493     
1494     osg::Switch* sw = new osg::Switch;
1495     sw->setUpdateCallback(new FGScenerySwitchCallback);
1496     sw->addChild(mRoot.get());
1497     mRealRoot->addChild(sw);
1498     // The clouds are attached directly to the scene graph root
1499     // because, in theory, they don't want the same default state set
1500     // as the rest of the scene. This may not be true in practice.
1501         if ( _classicalRenderer ) {
1502                 mRealRoot->addChild(_sky->getCloudRoot());
1503                 mRealRoot->addChild(FGCreateRedoutNode());
1504         }
1505     // Attach empty program to the scene root so that shader programs
1506     // don't leak into state sets (effects) that shouldn't have one.
1507     stateSet = mRealRoot->getOrCreateStateSet();
1508     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1509
1510     mDeferredRealRoot->addChild( mRealRoot.get() );
1511
1512     DeletionManager::install(mRealRoot.get());
1513 }
1514                                     
1515 // Update all Visuals (redraws anything graphics related)
1516 void
1517 FGRenderer::update( ) {
1518     if (!(_scenery_loaded->getBoolValue() || 
1519            _scenery_override->getBoolValue()))
1520     {
1521         _splash_alpha->setDoubleValue(1.0);
1522         return;
1523     }
1524     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1525
1526     if (_splash_alpha->getDoubleValue()>0.0)
1527     {
1528         // Fade out the splash screen
1529         const double fade_time = 0.5;
1530         const double fade_steps_per_sec = 10;
1531         double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1532                                          (SGTimeStamp::now() - _splash_time).toSecs());
1533         _splash_time = SGTimeStamp::now();
1534         double sAlpha = _splash_alpha->getDoubleValue();
1535         sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1536         FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1537         _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1538     }
1539
1540     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1541         if (!_classicalRenderer ) {
1542                 _ambientFactor->set( toOsg(l->scene_ambient()) );
1543                 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1544                 _sunSpecular->set( toOsg(l->scene_specular()) );
1545                 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1546         }
1547
1548     // update fog params
1549     double actual_visibility;
1550     if (_cloud_status->getBoolValue()) {
1551         actual_visibility = _sky->get_visibility();
1552     } else {
1553         actual_visibility = _visibility_m->getDoubleValue();
1554     }
1555
1556     // idle_state is now 1000 meaning we've finished all our
1557     // initializations and are running the main loop, so this will
1558     // now work without seg faulting the system.
1559
1560     FGViewer *current__view = globals->get_current_view();
1561     // Force update of center dependent values ...
1562     current__view->set_dirty();
1563   
1564     osg::Camera *camera = viewer->getCamera();
1565
1566     bool skyblend = _skyblend->getBoolValue();
1567     if ( skyblend ) {
1568         
1569         if ( _textures->getBoolValue() ) {
1570             SGVec4f clearColor(l->adj_fog_color());
1571             camera->setClearColor(toOsg(clearColor));
1572         }
1573     } else {
1574         SGVec4f clearColor(l->sky_color());
1575         camera->setClearColor(toOsg(clearColor));
1576     }
1577
1578     // update fog params if visibility has changed
1579     double visibility_meters = _visibility_m->getDoubleValue();
1580     _sky->set_visibility(visibility_meters);
1581
1582     double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1583     _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1584
1585     // update the sky dome
1586     if ( skyblend ) {
1587
1588         // The sun and moon distances are scaled down versions
1589         // of the actual distance to get both the moon and the sun
1590         // within the range of the far clip plane.
1591         // Moon distance:    384,467 kilometers
1592         // Sun distance: 150,000,000 kilometers
1593
1594         double sun_horiz_eff, moon_horiz_eff;
1595         if (_horizon_effect->getBoolValue()) {
1596             sun_horiz_eff
1597                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1598                                              0.0),
1599                              0.33) / 3.0;
1600             moon_horiz_eff
1601                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1602                                              0.0),
1603                              0.33)/3.0;
1604         } else {
1605            sun_horiz_eff = moon_horiz_eff = 1.0;
1606         }
1607
1608         SGSkyState sstate;
1609         sstate.pos       = current__view->getViewPosition();
1610         sstate.pos_geod  = current__view->getPosition();
1611         sstate.ori       = current__view->getViewOrientation();
1612         sstate.spin      = l->get_sun_rotation();
1613         sstate.gst       = globals->get_time_params()->getGst();
1614         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
1615         sstate.moon_dist = 40000.0 * moon_horiz_eff;
1616         sstate.sun_angle = l->get_sun_angle();
1617
1618         SGSkyColor scolor;
1619         scolor.sky_color   = SGVec3f(l->sky_color().data());
1620         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1621         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
1622         scolor.cloud_color = SGVec3f(l->cloud_color().data());
1623         scolor.sun_angle   = l->get_sun_angle();
1624         scolor.moon_angle  = l->get_moon_angle();
1625   
1626         double delta_time_sec = _sim_delta_sec->getDoubleValue();
1627         _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1628         _sky->repaint( scolor, *globals->get_ephem() );
1629
1630             //OSGFIXME
1631 //         shadows->setupShadows(
1632 //           current__view->getLongitude_deg(),
1633 //           current__view->getLatitude_deg(),
1634 //           globals->get_time_params()->getGst(),
1635 //           globals->get_ephem()->getSunRightAscension(),
1636 //           globals->get_ephem()->getSunDeclination(),
1637 //           l->get_sun_angle());
1638
1639     }
1640
1641 //     sgEnviro.setLight(l->adj_fog_color());
1642 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
1643 //         current__view->get_world_up(),
1644 //         current__view->getLongitude_deg(),
1645 //         current__view->getLatitude_deg(),
1646 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1647 //         delta_time_sec);
1648
1649     // OSGFIXME
1650 //     sgEnviro.drawLightning();
1651
1652 //        double current_view_origin_airspeed_horiz_kt =
1653 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
1654 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1655 //                                * SGD_DEGREES_TO_RADIANS);
1656
1657     // OSGFIXME
1658 //     if( is_internal )
1659 //         shadows->endOfFrame();
1660
1661     // need to call the update visitor once
1662     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1663     mUpdateVisitor->setViewData(current__view->getViewPosition(),
1664                                 current__view->getViewOrientation());
1665     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1666     mUpdateVisitor->setLight(direction, l->scene_ambient(),
1667                              l->scene_diffuse(), l->scene_specular(),
1668                              l->adj_fog_color(),
1669                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1670     mUpdateVisitor->setVisibility(actual_visibility);
1671     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1672     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1673     cullMask |= simgear::GroundLightManager::instance()
1674         ->getLightNodeMask(mUpdateVisitor.get());
1675     if (_panel_hotspots->getBoolValue())
1676         cullMask |= simgear::PICK_BIT;
1677     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1678         if ( !_classicalRenderer ) {
1679                 _fogColor->set( toOsg( l->adj_fog_color() ) );
1680                 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1681         }
1682 }
1683
1684 void
1685 FGRenderer::resize( int width, int height )
1686 {
1687     int curWidth = _xsize->getIntValue(),
1688         curHeight = _ysize->getIntValue();
1689     SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1690     if ((curHeight != height) || (curWidth != width)) {
1691     // must guard setting these, or PLIB-PUI fails with too many live interfaces
1692         _xsize->setIntValue(width);
1693         _ysize->setIntValue(height);
1694     }
1695 }
1696
1697 bool
1698 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1699                  const osgGA::GUIEventAdapter* ea)
1700 {
1701     // wipe out the return ...
1702     pickList.clear();
1703     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1704     Intersections intersections;
1705
1706     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1707         return false;
1708     for (Intersections::iterator hit = intersections.begin(),
1709              e = intersections.end();
1710          hit != e;
1711          ++hit) {
1712         const osg::NodePath& np = hit->nodePath;
1713         osg::NodePath::const_reverse_iterator npi;
1714         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1715             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1716             if (!ud)
1717                 continue;
1718             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1719                 SGPickCallback* pickCallback = ud->getPickCallback(i);
1720                 if (!pickCallback)
1721                     continue;
1722                 SGSceneryPick sceneryPick;
1723                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1724                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1725                 sceneryPick.callback = pickCallback;
1726                 pickList.push_back(sceneryPick);
1727             }
1728         }
1729     }
1730     return !pickList.empty();
1731 }
1732
1733 void
1734 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1735 {
1736     viewer = viewer_;
1737 }
1738
1739 void
1740 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1741 {
1742     eventHandler = eventHandler_;
1743 }
1744
1745 void
1746 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1747 {
1748     mRealRoot->addChild(camera);
1749 }
1750
1751 void
1752 FGRenderer::removeCamera(osg::Camera* camera)
1753 {
1754     mRealRoot->removeChild(camera);
1755 }
1756                                     
1757 void
1758 FGRenderer::setPlanes( double zNear, double zFar )
1759 {
1760         _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1761 }
1762
1763 bool
1764 fgDumpSceneGraphToFile(const char* filename)
1765 {
1766     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1767 }
1768
1769 bool
1770 fgDumpTerrainBranchToFile(const char* filename)
1771 {
1772     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1773                                  filename );
1774 }
1775
1776 // For debugging
1777 bool
1778 fgDumpNodeToFile(osg::Node* node, const char* filename)
1779 {
1780     return osgDB::writeNodeFile(*node, filename);
1781 }
1782
1783 namespace flightgear
1784 {
1785 using namespace osg;
1786
1787 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1788 {
1789 public:
1790     VisibleSceneInfoVistor()
1791         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1792     {
1793         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1794                        | CullSettings::VIEW_FRUSTUM_CULLING);
1795         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1796     }
1797
1798     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1799     {
1800     }
1801
1802     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1803
1804     typedef std::map<const std::string,int> InfoMap;
1805
1806     void getNodeInfo(Node* node)
1807     {
1808         const char* typeName = typeid(*node).name();
1809         classInfo[typeName]++;
1810         const std::string& nodeName = node->getName();
1811         if (!nodeName.empty())
1812             nodeInfo[nodeName]++;
1813     }
1814
1815     void dumpInfo()
1816     {
1817         using namespace std;
1818         typedef vector<InfoMap::iterator> FreqVector;
1819         cout << "class info:\n";
1820         FreqVector classes;
1821         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1822              itr != end;
1823              ++itr)
1824             classes.push_back(itr);
1825         sort(classes.begin(), classes.end(), freqComp);
1826         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1827              itr != end;
1828              ++itr) {
1829             cout << (*itr)->first << " " << (*itr)->second << "\n";
1830         }
1831         cout << "\nnode info:\n";
1832         FreqVector nodes;
1833         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1834              itr != end;
1835              ++itr)
1836             nodes.push_back(itr);
1837
1838         sort (nodes.begin(), nodes.end(), freqComp);
1839         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1840              itr != end;
1841              ++itr) {
1842             cout << (*itr)->first << " " << (*itr)->second << "\n";
1843         }
1844         cout << endl;
1845     }
1846     
1847     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1848     {
1849         ref_ptr<RefMatrix> projection
1850             = createOrReuseMatrix(camera->getProjectionMatrix());
1851         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1852         if (!viewport)
1853             viewport = camera->getViewport();
1854         if (viewport)
1855             pushViewport(viewport);
1856         pushProjectionMatrix(projection.get());
1857         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1858         root->accept(*this);
1859         popModelViewMatrix();
1860         popProjectionMatrix();
1861         if (viewport)
1862             popViewport();
1863         dumpInfo();
1864     }
1865
1866     void apply(Node& node)
1867     {
1868         if (isCulled(node))
1869             return;
1870         pushCurrentMask();
1871         getNodeInfo(&node);
1872         traverse(node);
1873         popCurrentMask();
1874     }
1875     void apply(Group& node)
1876     {
1877         if (isCulled(node))
1878             return;
1879         pushCurrentMask();
1880         getNodeInfo(&node);
1881         traverse(node);
1882         popCurrentMask();
1883     }
1884
1885     void apply(Transform& node)
1886     {
1887         if (isCulled(node))
1888             return;
1889         pushCurrentMask();
1890         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1891         node.computeLocalToWorldMatrix(*matrix,this);
1892         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1893         getNodeInfo(&node);
1894         traverse(node);
1895         popModelViewMatrix();
1896         popCurrentMask();
1897     }
1898
1899     void apply(Camera& camera)
1900     {
1901         // Save current cull settings
1902         CullSettings saved_cull_settings(*this);
1903
1904         // set cull settings from this Camera
1905         setCullSettings(camera);
1906         // inherit the settings from above
1907         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1908
1909         // set the cull mask.
1910         unsigned int savedTraversalMask = getTraversalMask();
1911         bool mustSetCullMask = (camera.getInheritanceMask()
1912                                 & osg::CullSettings::CULL_MASK) == 0;
1913         if (mustSetCullMask)
1914             setTraversalMask(camera.getCullMask());
1915
1916         osg::RefMatrix* projection = 0;
1917         osg::RefMatrix* modelview = 0;
1918
1919         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1920             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1921                 projection = createOrReuseMatrix(*getProjectionMatrix()
1922                                                  *camera.getProjectionMatrix());
1923                 modelview = createOrReuseMatrix(*getModelViewMatrix()
1924                                                 * camera.getViewMatrix());
1925             }
1926             else {              // pre multiply 
1927                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1928                                                  * (*getProjectionMatrix()));
1929                 modelview = createOrReuseMatrix(camera.getViewMatrix()
1930                                                 * (*getModelViewMatrix()));
1931             }
1932         } else {
1933             // an absolute reference frame
1934             projection = createOrReuseMatrix(camera.getProjectionMatrix());
1935             modelview = createOrReuseMatrix(camera.getViewMatrix());
1936         }
1937         if (camera.getViewport())
1938             pushViewport(camera.getViewport());
1939
1940         pushProjectionMatrix(projection);
1941         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
1942
1943         traverse(camera);
1944     
1945         // restore the previous model view matrix.
1946         popModelViewMatrix();
1947
1948         // restore the previous model view matrix.
1949         popProjectionMatrix();
1950
1951         if (camera.getViewport()) popViewport();
1952
1953         // restore the previous traversal mask settings
1954         if (mustSetCullMask)
1955             setTraversalMask(savedTraversalMask);
1956
1957         // restore the previous cull settings
1958         setCullSettings(saved_cull_settings);
1959     }
1960
1961 protected:
1962     // sort in reverse
1963     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1964     {
1965         return lhs->second > rhs->second;
1966     }
1967     InfoMap classInfo;
1968     InfoMap nodeInfo;
1969 };
1970
1971 bool printVisibleSceneInfo(FGRenderer* renderer)
1972 {
1973     osgViewer::Viewer* viewer = renderer->getViewer();
1974     VisibleSceneInfoVistor vsv;
1975     Viewport* vp = 0;
1976     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1977         const View::Slave& slave = viewer->getSlave(0);
1978         vp = slave._camera->getViewport();
1979     }
1980     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1981     return true;
1982 }
1983
1984 }
1985 // end of renderer.cxx
1986