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