]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/renderer.cxx
Assume OSG version 3.0 as a minimum
[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
601         osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
602         identifier = sceneView->getCullVisitor()->getIdentifier();
603         sceneView->setCullVisitor(new simgear::EffectCullVisitor);
604         sceneView->getCullVisitor()->setIdentifier(identifier.get());
605
606         identifier = sceneView->getCullVisitorLeft()->getIdentifier();
607         sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
608         sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
609
610         identifier = sceneView->getCullVisitorRight()->getIdentifier();
611         sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
612         sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
613
614     }
615 }
616
617 CameraInfo*
618 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
619                                    const Matrix& view,
620                                    const Matrix& projection,
621                                                                    osg::GraphicsContext* gc,
622                                    bool useMasterSceneData)
623 {
624         CameraInfo* info = 0;
625         if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
626                 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
627
628         if (info) {
629                 return info;
630         } else {
631                 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
632                         _classicalRenderer = true;
633                 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
634         }
635 }
636
637 CameraInfo*
638 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
639                                 const osg::Matrix& view,
640                                 const osg::Matrix& projection,
641                                 bool useMasterSceneData)
642 {
643     CameraInfo* info = new CameraInfo(flags);
644     // The camera group will always update the camera
645     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
646     info->name = "classic";
647     
648     Camera* farCamera = 0;
649     if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
650         farCamera = new Camera;
651         farCamera->setName("farCamera");
652         farCamera->setAllowEventFocus(camera->getAllowEventFocus());
653         farCamera->setGraphicsContext(camera->getGraphicsContext());
654         farCamera->setCullingMode(camera->getCullingMode());
655         farCamera->setInheritanceMask(camera->getInheritanceMask());
656         farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
657         // Each camera's viewport is written when the window is
658         // resized; if the the viewport isn't copied here, it gets updated
659         // twice and ends up with the wrong value.
660         farCamera->setViewport(simgear::clone(camera->getViewport()));
661         farCamera->setDrawBuffer(camera->getDrawBuffer());
662         farCamera->setReadBuffer(camera->getReadBuffer());
663         farCamera->setRenderTargetImplementation(
664             camera->getRenderTargetImplementation());
665         const Camera::BufferAttachmentMap& bufferMap
666             = camera->getBufferAttachmentMap();
667         if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
668             farCamera->attach(
669                 Camera::COLOR_BUFFER,
670                 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
671         }
672         cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
673         installCullVisitor(farCamera);
674                 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
675                 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
676         farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
677         camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
678         camera->setClearMask(GL_DEPTH_BUFFER_BIT);
679     }
680     cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
681     installCullVisitor(camera);
682     int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
683     info->addCamera( MAIN_CAMERA, camera, slaveIndex );
684     camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
685     cgroup->addCamera(info);
686     return info;
687 }
688
689 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
690 public:
691     FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
692     virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
693         simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
694         osg::Camera* camera = static_cast<osg::Camera*>(n);
695
696         cv->clearBufferList();
697         for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
698             cv->addBuffer(ii->first, ii->second.texture);
699         }
700
701         if ( !info->getRenderStageInfo(kind).fullscreen )
702             info->setMatrices( camera );
703
704         if (needsDuDv) {
705             osg::Matrix projInverse;
706             info->projInverse->get( projInverse );
707
708             osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
709             info->du->set( osg::Vec4(  1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
710             info->dv->set( osg::Vec4( -1.0,  1.0, 0.0, 1.0 ) * projInverse - p0 );
711         }
712
713         cv->traverse( *camera );
714
715         if ( kind == GEOMETRY_CAMERA ) {
716             // Remove transparent bins. They will be renderer in the additional light stage (side effect)
717             osgUtil::RenderStage* renderStage = cv->getRenderStage();
718             osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
719             for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
720                 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
721                     rbl.erase( rbi++ );
722                 } else {
723                     ++rbi;
724                 }
725             }
726         } else if ( kind == LIGHTING_CAMERA ) {
727             osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
728             if (mainShadowCamera.valid()) {
729                 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
730                 for (int i = 0; i < 4; ++i ) {
731                     if (!grp->getValue(i))
732                         continue;
733
734                     osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
735                     osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
736                                                 cascadeCam->getViewMatrix() *
737                                                 cascadeCam->getProjectionMatrix() *
738                                                 osg::Matrix::translate(1.0, 1.0, 1.0) *
739                                                 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
740
741                     info->shadowMatrix[i]->set( shadowMatrix );
742                 }
743             }
744         }
745     }
746
747 private:
748     std::string kind;
749     CameraInfo* info;
750     bool needsDuDv;
751 };
752
753 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
754 {
755     osg::Texture2D* tex = new osg::Texture2D;
756     tex->setResizeNonPowerOfTwoHint( false );
757     tex->setInternalFormat( internalFormat );
758     tex->setShadowComparison(shadowComparison);
759     if (shadowComparison) {
760         tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
761         tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
762     }
763     tex->setSourceFormat(sourceFormat);
764     tex->setSourceType(sourceType);
765     tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
766     tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
767     tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
768     tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
769         return tex;
770 }
771
772 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
773 {
774     camera->attach( c, info->getBuffer(bk) );
775     info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
776 }
777
778 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
779     BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
780         if (attachment->valid())
781             attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
782     }
783 }
784
785 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
786 {
787     osg::Camera* camera = new osg::Camera;
788     info->addCamera(name, camera );
789
790     camera->setCullMask( ~simgear::MODELLIGHT_BIT );
791     camera->setName( "GeometryC" );
792     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
793     camera->setGraphicsContext( gc );
794     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
795     camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
796     camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
797     camera->setClearDepth( 1.0 );
798     camera->setColorMask(true, true, true, true);
799     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
800     camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
801     camera->setViewport( new osg::Viewport );
802     buildAttachments(info, camera, name, attachments);
803     camera->setDrawBuffer(GL_FRONT);
804     camera->setReadBuffer(GL_FRONT);
805
806     osg::StateSet* ss = camera->getOrCreateStateSet();
807     ss->addUniform( _depthInColor );
808
809     camera->addChild( mDeferredRealRoot.get() );
810
811     return camera;
812 }
813
814 static void setShadowCascadeStateSet( osg::Camera* cam ) {
815     osg::StateSet* ss = cam->getOrCreateStateSet();
816     ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
817     ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
818     ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
819     ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
820     ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
821     ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
822     osg::Program* program = new osg::Program;
823     ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
824     ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
825     ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
826     //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
827     ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
828     ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
829     ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
830     ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
831     ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
832 }
833
834 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
835     osg::Camera* cascadeCam = new osg::Camera;
836     setShadowCascadeStateSet( cascadeCam );
837
838     std::ostringstream oss;
839     oss << "CascadeCamera" << (no + 1);
840     cascadeCam->setName( oss.str() );
841     cascadeCam->setClearMask(0);
842     cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
843     cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
844     cascadeCam->setAllowEventFocus(false);
845     cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
846     cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
847     cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
848     cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
849     return cascadeCam;
850 }
851
852 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
853 {
854     osg::Camera* mainShadowCamera = new osg::Camera;
855     info->addCamera(name, mainShadowCamera, 0.0f );
856
857     mainShadowCamera->setName( "ShadowC" );
858     mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
859     mainShadowCamera->setClearDepth( 1.0 );
860     mainShadowCamera->setAllowEventFocus(false);
861     mainShadowCamera->setGraphicsContext(gc);
862     mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
863     buildAttachments(info, mainShadowCamera, name, attachments);
864     mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
865     mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
866     mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
867     mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
868     mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
869     mainShadowCamera->setDrawBuffer(GL_FRONT);
870     mainShadowCamera->setReadBuffer(GL_FRONT);
871     mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
872
873     osg::Switch* shadowSwitch = new osg::Switch;
874     mainShadowCamera->addChild( shadowSwitch );
875
876     for (int i = 0; i < 4; ++i ) {
877         osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
878         cascadeCam->addChild( mDeferredRealRoot.get() );
879         shadowSwitch->addChild( cascadeCam );
880     }
881     if (fgGetBool("/sim/rendering/shadows/enabled", true))
882         shadowSwitch->setAllChildrenOn();
883     else
884         shadowSwitch->setAllChildrenOff();
885
886     return mainShadowCamera;
887 }
888
889 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)
890 {
891     osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
892     osg::Matrixd &viewMatrix = cascade->getViewMatrix();
893     osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
894
895     osg::BoundingSphere bs;
896     bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
897     bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
898     bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
899     bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
900
901     osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
902
903     projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
904     osg::Vec3 position( aim.x(), aim.y(), aim.z() );
905     viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
906 }
907
908 osg::Vec3 FGRenderer::getSunDirection() const
909 {
910     osg::Vec3 val;
911     _sunDirection->get( val );
912     return val;
913 }
914
915 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
916 {
917     ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
918     if (mainShadowCamera.valid()) {
919         ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
920         osg::Vec3d up = position,
921             dir = getSunDirection();
922         up.normalize();
923         dir.normalize();
924         // cos(100 deg) == -0.17
925         if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
926             shadowSwitch->setAllChildrenOff();
927         } else {
928             double left,right,bottom,top,zNear,zFar;
929             ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
930             camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
931
932             shadowSwitch->setAllChildrenOn();
933             if (_numCascades == 1) {
934                 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
935                 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
936             } else {
937                 for (int no = 0; no < 4; ++no) {
938                     osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
939                     cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
940                 }
941             }
942             updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
943             if (_numCascades > 1) {
944                 shadowSwitch->setValue(1, true);
945                 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
946             } else {
947                 shadowSwitch->setValue(1, false);
948             }
949             if (_numCascades > 2) {
950                 shadowSwitch->setValue(2, true);
951                 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
952             } else {
953                 shadowSwitch->setValue(2, false);
954             }
955             if (_numCascades > 3) {
956                 shadowSwitch->setValue(3, true);
957                 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
958             } else {
959                 shadowSwitch->setValue(3, false);
960             }
961             {
962             osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
963
964             osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
965
966             osg::Vec3 position( aim.x(), aim.y(), aim.z() );
967             viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
968             }
969         }
970     }
971 }
972
973 void FGRenderer::updateShadowMapSize(int mapSize)
974 {
975     if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
976         SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
977         return;
978     }
979     for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
980             ii != CameraGroup::getDefault()->camerasEnd();
981             ++ii )
982     {
983         CameraInfo* info = ii->get();
984         Camera* camera = info->getCamera(SHADOW_CAMERA);
985         if (camera == 0) continue;
986
987         Texture2D* tex = info->getBuffer("shadow");
988         if (tex == 0) continue;
989
990         tex->setTextureSize( mapSize, mapSize );
991         tex->dirtyTextureObject();
992
993         Viewport* vp = camera->getViewport();
994         vp->width() = mapSize;
995         vp->height() = mapSize;
996
997         osgViewer::Renderer* renderer
998             = static_cast<osgViewer::Renderer*>(camera->getRenderer());
999         for (int i = 0; i < 2; ++i) {
1000             osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1001             sceneView->getRenderStage()->setFrameBufferObject(0);
1002             sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1003             if (sceneView->getRenderStageLeft()) {
1004                 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1005                 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1006             }
1007             if (sceneView->getRenderStageRight()) {
1008                 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1009                 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1010             }
1011         }
1012
1013         int cascadeSize = mapSize / 2;
1014         Group* grp = camera->getChild(0)->asGroup();
1015         for (int i = 0; i < 4; ++i ) {
1016             Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1017             cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1018         }
1019
1020         _shadowMapSize = mapSize;
1021     }
1022 }
1023
1024 void FGRenderer::enableShadows(bool enabled)
1025 {
1026     for (   CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1027             ii != CameraGroup::getDefault()->camerasEnd();
1028             ++ii )
1029     {
1030         CameraInfo* info = ii->get();
1031         Camera* camera = info->getCamera(SHADOW_CAMERA);
1032         if (camera == 0) continue;
1033
1034         osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1035         if (enabled)
1036             shadowSwitch->setAllChildrenOn();
1037         else
1038             shadowSwitch->setAllChildrenOff();
1039     }
1040 }
1041
1042 void FGRenderer::updateCascadeFar(int index, float far_m)
1043 {
1044     if (index < 0 || index > 3)
1045         return;
1046     _cascadeFar[index] = far_m;
1047     _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1048 }
1049
1050 void FGRenderer::updateCascadeNumber(size_t num)
1051 {
1052     if (num < 1 || num > 4)
1053         return;
1054     _numCascades = num;
1055     _shadowNumber->set( (int)_numCascades );
1056 }
1057
1058 class DebugPassListener : public SGPropertyChangeListener {
1059 public:
1060     DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1061     virtual void valueChanged(SGPropertyNode* node) {
1062         _switch->setValue(_index, node->getBoolValue());
1063     }
1064
1065 private:
1066     osg::ref_ptr<osg::Switch> _switch;
1067     int _index;
1068 };
1069
1070 osg::Camera*
1071 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1072 {
1073     osg::Camera* camera = new osg::Camera;
1074     info->addCamera(stage->name, camera );
1075
1076     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1077     camera->setAllowEventFocus(false);
1078     camera->setGraphicsContext(gc);
1079     camera->setViewport(new Viewport);
1080     camera->setName(stage->name+"C");
1081     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1082     camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1083     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1084     camera->setViewport( new osg::Viewport );
1085     buildAttachments(info, camera, stage->name, stage->attachments);
1086     camera->setDrawBuffer(GL_FRONT);
1087     camera->setReadBuffer(GL_FRONT);
1088     camera->setClearColor( osg::Vec4( 0.5, 0.5, 0.5, 1. ) );
1089     camera->setClearMask( GL_COLOR_BUFFER_BIT );
1090     osg::StateSet* ss = camera->getOrCreateStateSet();
1091     ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1092     ss->addUniform( _depthInColor );
1093
1094     osg::Switch* lightingGroup = new osg::Switch;
1095
1096     BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1097         ref_ptr<Node> node = buildPass(info, pass);
1098         if (node.valid()) {
1099             lightingGroup->addChild(node);
1100             if (!pass->debugProperty.empty()) {
1101                 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1102                 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1103             }
1104         }
1105     }
1106
1107     camera->addChild( lightingGroup );
1108
1109     return camera;
1110 }
1111
1112 CameraInfo*
1113 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1114                                     const osg::Matrix& view,
1115                                     const osg::Matrix& projection,
1116                                     osg::GraphicsContext* gc)
1117 {
1118     return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1119 }
1120
1121 osg::Camera* 
1122 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1123 {
1124     osg::Camera* camera = new osg::Camera;
1125
1126     camera->setClearMask( 0 );
1127     camera->setAllowEventFocus(false);
1128     camera->setName(pass->name+"C");
1129     camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1130     camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1131     camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1132     camera->setViewMatrix(osg::Matrix::identity());
1133     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1134
1135     osg::StateSet* ss = camera->getOrCreateStateSet();
1136     ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1137     ss->addUniform( info->projInverse );
1138     ss->addUniform( info->viewInverse );
1139     ss->addUniform( info->view );
1140     ss->addUniform( info->bufferSize );
1141     ss->addUniform( info->worldPosCart );
1142     ss->addUniform( info->worldPosGeod );
1143     ss->addUniform( info->shadowMatrix[0] );
1144     ss->addUniform( info->shadowMatrix[1] );
1145     ss->addUniform( info->shadowMatrix[2] );
1146     ss->addUniform( info->shadowMatrix[3] );
1147     ss->addUniform( _ambientFactor );
1148     ss->addUniform( _sunDiffuse );
1149     ss->addUniform( _sunSpecular );
1150     ss->addUniform( _sunDirection );
1151     ss->addUniform( _planes );
1152     ss->addUniform( _shadowNumber );
1153     ss->addUniform( _shadowDistances );
1154     ss->addUniform( _fogColor );
1155     ss->addUniform( _fogDensity );
1156
1157     osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1158     g->setUseDisplayList(false);
1159     simgear::EffectGeode* eg = new simgear::EffectGeode;
1160     osg::ref_ptr<SGReaderWriterOptions> opt;
1161     opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1162     opt->setPropertyNode(globals->get_props());
1163     simgear::Effect* effect = simgear::makeEffect(pass->effect, true, opt.get());
1164     if (effect) {
1165         eg->setEffect( effect );
1166     }
1167
1168     eg->setName(pass->name+"Quad");
1169     eg->setCullingActive(false);
1170     eg->addDrawable(g);
1171     camera->addChild(eg);
1172
1173     return camera;
1174 }
1175
1176 osg::Camera* 
1177 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1178 {
1179     osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1180     info->addCamera(stage->name, camera, stage->scaleFactor, true);
1181
1182     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1183     camera->setGraphicsContext(gc);
1184     camera->setViewport(new Viewport);
1185     camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1186     buildAttachments(info, camera, stage->name, stage->attachments);
1187     camera->setDrawBuffer(GL_FRONT);
1188     camera->setReadBuffer(GL_FRONT);
1189     camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1190     camera->setClearMask( GL_COLOR_BUFFER_BIT );
1191     camera->setViewMatrix(osg::Matrix::identity());
1192     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1193
1194     osg::StateSet* ss = camera->getOrCreateStateSet();
1195     if (stage->needsDuDv) {
1196         ss->addUniform( info->du );
1197         ss->addUniform( info->dv );
1198     }
1199
1200     return camera;
1201 }
1202
1203 void
1204 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1205 {
1206     camera->setName( "DisplayC" );
1207     camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1208     camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1209     camera->setAllowEventFocus(false);
1210     osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1211     g->setUseDisplayList(false); //DEBUG
1212     simgear::EffectGeode* eg = new simgear::EffectGeode;
1213     osg::ref_ptr<SGReaderWriterOptions> opt;
1214     opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1215     opt->setPropertyNode(globals->get_props());
1216     simgear::Effect* effect = simgear::makeEffect(stage->effect, true, opt.get());
1217     if (!effect) {
1218         SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1219         return;
1220     }
1221     eg->setEffect(effect);
1222     eg->setCullingActive(false);
1223     eg->addDrawable(g);
1224     camera->setViewMatrix(osg::Matrix::identity());
1225     camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1226     camera->addChild(eg);
1227
1228     osg::StateSet* ss = camera->getOrCreateStateSet();
1229     ss->addUniform( _depthInColor );
1230     ss->addUniform( info->projInverse );
1231     ss->addUniform( info->viewInverse );
1232     ss->addUniform( info->view );
1233     ss->addUniform( info->bufferSize );
1234     ss->addUniform( info->worldPosCart );
1235     ss->addUniform( info->worldPosGeod );
1236     ss->addUniform( info->shadowMatrix[0] );
1237     ss->addUniform( info->shadowMatrix[1] );
1238     ss->addUniform( info->shadowMatrix[2] );
1239     ss->addUniform( info->shadowMatrix[3] );
1240     ss->addUniform( _ambientFactor );
1241     ss->addUniform( _sunDiffuse );
1242     ss->addUniform( _sunSpecular );
1243     ss->addUniform( _sunDirection );
1244     ss->addUniform( _planes );
1245     ss->addUniform( _shadowNumber );
1246     ss->addUniform( _shadowDistances );
1247     ss->addUniform( _fogColor );
1248     ss->addUniform( _fogDensity );
1249 }
1250
1251 void
1252 FGRenderer::buildStage(CameraInfo* info,
1253                         FGRenderingPipeline::Stage* stage,
1254                         CameraGroup* cgroup,
1255                         osg::Camera* mainCamera,
1256                         const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1257 {
1258     if (!stage->valid())
1259         return;
1260
1261     ref_ptr<Camera> camera;
1262     bool needOffsets = false;
1263     if (stage->type == "geometry") {
1264         camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1265         needOffsets = true;
1266     } else if (stage->type == "lighting") {
1267         camera = buildDeferredLightingCamera(info, gc, stage);
1268         needOffsets = true;
1269     } else if (stage->type == "shadow")
1270         camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1271     else if (stage->type == "fullscreen")
1272         camera = buildDeferredFullscreenCamera(info, gc, stage);
1273     else if (stage->type == "display") {
1274         camera = mainCamera;
1275         buildDeferredDisplayCamera(camera, info, stage, gc);
1276     } else
1277         throw sg_exception("Stage type is not supported");
1278
1279     if (needOffsets)
1280         cgroup->getViewer()->addSlave(camera, projection, view, false);
1281     else
1282         cgroup->getViewer()->addSlave(camera, false);
1283     installCullVisitor(camera);
1284     int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1285     if (stage->type == "display")
1286         info->addCamera( stage->type, camera, slaveIndex, true );
1287     info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1288 }
1289
1290 osg::Node*
1291 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1292 {
1293     Group* group = new Group;
1294     group->setName("skyCloudsGroup");
1295     group->setNodeMask(simgear::BACKGROUND_BIT);
1296     
1297     StateSet* ss = group->getOrCreateStateSet();
1298     ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1299     group->addChild( _sky->getPreRoot() );
1300     group->addChild( _sky->getCloudRoot() );
1301     return group;
1302 }
1303
1304 osg::Node*
1305 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1306 {
1307     osg::Camera* lightCam = new osg::Camera;
1308     StateSet* ss = lightCam->getOrCreateStateSet();
1309     ss->addUniform( _planes );
1310     ss->addUniform( info->bufferSize );
1311     ss->addUniform( _fogColor );
1312     ss->addUniform( _fogDensity );
1313     lightCam->setName( "LightCamera" );
1314     lightCam->setClearMask(0);
1315     lightCam->setAllowEventFocus(false);
1316     lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1317     lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1318     lightCam->setViewMatrix(osg::Matrix::identity());
1319     lightCam->setProjectionMatrix(osg::Matrix::identity());
1320     lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1321     lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1322     lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1323     lightCam->addChild( mDeferredRealRoot.get() );
1324
1325     return lightCam;
1326 }
1327
1328 osg::Node*
1329 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1330 {
1331     if (!pass->valid())
1332         return 0;
1333
1334     ref_ptr<Node> node;
1335     if (pass->type == "sky-clouds")
1336         node = buildLightingSkyCloudsPass(pass);
1337     else if (pass->type == "fullscreen")
1338         node = buildDeferredFullscreenCamera(info, pass);
1339     else if (pass->type == "lights")
1340         node = buildLightingLightsPass(info, pass);
1341     else
1342         throw sg_exception("Pass type is not supported");
1343
1344     return node.release();
1345 }
1346
1347 void
1348 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1349 {
1350     for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1351         osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1352         if (buffer->valid()) {
1353             bool fullscreen = buffer->width == -1 && buffer->height == -1;
1354             info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1355                                                                 buffer->sourceFormat,
1356                                                                 buffer->sourceType,
1357                                                                 buffer->wrapMode,
1358                                                                 buffer->shadowComparison),
1359                             fullscreen ? buffer->scaleFactor : 0.0f);
1360             if (!fullscreen) {
1361                 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1362             }
1363         }
1364     }
1365 }
1366
1367 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1368                                     const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1369 {
1370     CameraInfo* info = new CameraInfo(flags);
1371     buildBuffers(rpipe, info);
1372     
1373     for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1374         osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1375         buildStage(info, stage, cgroup, camera, view, projection, gc);
1376     }
1377
1378     cgroup->addCamera(info);
1379
1380     return info;
1381 }
1382
1383 void
1384 FGRenderer::setupView( void )
1385 {
1386     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1387     osg::initNotifyLevel();
1388
1389     // The number of polygon-offset "units" to place between layers.  In
1390     // principle, one is supposed to be enough.  In practice, I find that
1391     // my hardware/driver requires many more.
1392     osg::PolygonOffset::setUnitsMultiplier(1);
1393     osg::PolygonOffset::setFactorMultiplier(1);
1394
1395 // build the sky    
1396     // The sun and moon diameters are scaled down numbers of the
1397     // actual diameters. This was needed to fit both the sun and the
1398     // moon within the distance to the far clip plane.
1399     // Moon diameter:    3,476 kilometers
1400     // Sun diameter: 1,390,000 kilometers
1401     osg::ref_ptr<SGReaderWriterOptions> opt;
1402     opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1403     opt->setPropertyNode(globals->get_props());
1404     _sky->build( 80000.0, 80000.0,
1405                   463.3, 361.8,
1406                   *globals->get_ephem(),
1407                   fgGetNode("/environment", true),
1408                   opt.get());
1409     
1410     viewer->getCamera()
1411         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1412     
1413     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1414
1415     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1416     
1417     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1418     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1419
1420     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1421     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1422     stateSet->setAttribute(new osg::BlendFunc);
1423     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1424
1425     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1426     
1427     // this will be set below
1428     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1429
1430     osg::Material* material = new osg::Material;
1431     stateSet->setAttribute(material);
1432     
1433     stateSet->setTextureAttribute(0, new osg::TexEnv);
1434     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1435
1436     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1437     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1438     stateSet->setAttribute(hint);
1439     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1440     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1441     stateSet->setAttribute(hint);
1442     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1443     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1444     stateSet->setAttribute(hint);
1445     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1446     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1447     stateSet->setAttribute(hint);
1448     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1449     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1450     stateSet->setAttribute(hint);
1451
1452     osg::Group* sceneGroup = new osg::Group;
1453     sceneGroup->setName("rendererScene");
1454     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1455     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1456
1457     //sceneGroup->addChild(thesky->getCloudRoot());
1458
1459     stateSet = sceneGroup->getOrCreateStateSet();
1460     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1461
1462     // need to update the light on every frame
1463     // OSG LightSource objects are rather confusing. OSG only supports
1464     // the 10 lights specified by OpenGL itself; if more than one
1465     // LightSource in the scene graph have the same light number, it's
1466     // indeterminate which values will be used to render geometry that
1467     // has that light number enabled. Also, adding children to a
1468     // LightSource is just a shortcut for setting up a state set that
1469     // has the corresponding OpenGL light enabled: a LightSource will
1470     // affect geometry anywhere in the scene graph that has its light
1471     // number enabled in a state set. 
1472     LightSource* lightSource = new LightSource;
1473     lightSource->setName("FGLightSource");
1474     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1475     // relative because of CameraView being just a clever transform node
1476     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1477     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1478     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1479     mRealRoot->addChild(lightSource);
1480     // we need a white diffuse light for the phase of the moon
1481     osg::LightSource* sunLight = new osg::LightSource;
1482     sunLight->setName("sunLightSource");
1483     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1484     sunLight->getLight()->setLightNum(1);
1485     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1486     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1487     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1488     
1489     // Hang a StateSet above the sky subgraph in order to turn off
1490     // light 0
1491     Group* skyGroup = new Group;
1492     skyGroup->setName("rendererSkyParent");
1493     StateSet* skySS = skyGroup->getOrCreateStateSet();
1494     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1495     skyGroup->addChild(_sky->getPreRoot());
1496     sunLight->addChild(skyGroup);
1497     mRoot->addChild(sceneGroup);
1498     if ( _classicalRenderer )
1499         mRoot->addChild(sunLight);
1500     
1501     // Clouds are added to the scene graph later
1502     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1503     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1504     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1505     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1506
1507     // enable disable specular highlights.
1508     // is the place where we might plug in an other fragment shader ...
1509     osg::LightModel* lightModel = new osg::LightModel;
1510     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1511     stateSet->setAttribute(lightModel);
1512
1513     // switch to enable wireframe
1514     osg::PolygonMode* polygonMode = new osg::PolygonMode;
1515     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1516     stateSet->setAttributeAndModes(polygonMode);
1517
1518     // scene fog handling
1519     osg::Fog* fog = new osg::Fog;
1520     fog->setUpdateCallback(new FGFogUpdateCallback);
1521     stateSet->setAttributeAndModes(fog);
1522     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1523
1524     // plug in the GUI
1525     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1526     if (guiCamera) {
1527         
1528         osg::Geode* geode = new osg::Geode;
1529         geode->addDrawable(new SGPuDrawable);
1530         geode->addDrawable(new SGHUDDrawable);
1531         guiCamera->addChild(geode);
1532       
1533         
1534       guiCamera->addChild(FGPanelNode::create2DPanelNode());
1535     }
1536     
1537     osg::Switch* sw = new osg::Switch;
1538     sw->setName("scenerySwitch");
1539     sw->setUpdateCallback(new FGScenerySwitchCallback);
1540     sw->addChild(mRoot.get());
1541     mRealRoot->addChild(sw);
1542     // The clouds are attached directly to the scene graph root
1543     // because, in theory, they don't want the same default state set
1544     // as the rest of the scene. This may not be true in practice.
1545         if ( _classicalRenderer ) {
1546                 mRealRoot->addChild(_sky->getCloudRoot());
1547                 mRealRoot->addChild(FGCreateRedoutNode());
1548         }
1549     // Attach empty program to the scene root so that shader programs
1550     // don't leak into state sets (effects) that shouldn't have one.
1551     stateSet = mRealRoot->getOrCreateStateSet();
1552     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1553
1554     mDeferredRealRoot->addChild( mRealRoot.get() );
1555
1556     DeletionManager::install(mRealRoot.get());
1557 }
1558
1559 // Update all Visuals (redraws anything graphics related)
1560 void
1561 FGRenderer::update( ) {
1562     if (!_position_finalized || !_scenery_loaded->getBoolValue())
1563     {
1564         _splash_alpha->setDoubleValue(1.0);
1565         return;
1566     }
1567     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1568
1569     if (_splash_alpha->getDoubleValue()>0.0)
1570     {
1571         // Fade out the splash screen
1572         const double fade_time = 0.5;
1573         const double fade_steps_per_sec = 10;
1574         double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1575                                          (SGTimeStamp::now() - _splash_time).toSecs());
1576         _splash_time = SGTimeStamp::now();
1577         double sAlpha = _splash_alpha->getDoubleValue();
1578         sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1579         FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1580         _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1581     }
1582
1583     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1584         if (!_classicalRenderer ) {
1585                 _ambientFactor->set( toOsg(l->scene_ambient()) );
1586                 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1587                 _sunSpecular->set( toOsg(l->scene_specular()) );
1588                 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1589         }
1590
1591     // update fog params
1592     double actual_visibility;
1593     if (_cloud_status->getBoolValue()) {
1594         actual_visibility = _sky->get_visibility();
1595     } else {
1596         actual_visibility = _visibility_m->getDoubleValue();
1597     }
1598
1599     // idle_state is now 1000 meaning we've finished all our
1600     // initializations and are running the main loop, so this will
1601     // now work without seg faulting the system.
1602
1603     FGViewer *current__view = globals->get_current_view();
1604     // Force update of center dependent values ...
1605     current__view->set_dirty();
1606   
1607     osg::Camera *camera = viewer->getCamera();
1608
1609     bool skyblend = _skyblend->getBoolValue();
1610     if ( skyblend ) {
1611         
1612         if ( _textures->getBoolValue() ) {
1613             SGVec4f clearColor(l->adj_fog_color());
1614             camera->setClearColor(toOsg(clearColor));
1615         }
1616     } else {
1617         SGVec4f clearColor(l->sky_color());
1618         camera->setClearColor(toOsg(clearColor));
1619     }
1620
1621     // update fog params if visibility has changed
1622     double visibility_meters = _visibility_m->getDoubleValue();
1623     _sky->set_visibility(visibility_meters);
1624
1625     double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1626     _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1627
1628     // update the sky dome
1629     if ( skyblend ) {
1630
1631         // The sun and moon distances are scaled down versions
1632         // of the actual distance to get both the moon and the sun
1633         // within the range of the far clip plane.
1634         // Moon distance:    384,467 kilometers
1635         // Sun distance: 150,000,000 kilometers
1636
1637         double sun_horiz_eff, moon_horiz_eff;
1638         if (_horizon_effect->getBoolValue()) {
1639             sun_horiz_eff
1640                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1641                                              0.0),
1642                              0.33) / 3.0;
1643             moon_horiz_eff
1644                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1645                                              0.0),
1646                              0.33)/3.0;
1647         } else {
1648            sun_horiz_eff = moon_horiz_eff = 1.0;
1649         }
1650
1651         SGSkyState sstate;
1652         sstate.pos       = current__view->getViewPosition();
1653         sstate.pos_geod  = current__view->getPosition();
1654         sstate.ori       = current__view->getViewOrientation();
1655         sstate.spin      = l->get_sun_rotation();
1656         sstate.gst       = globals->get_time_params()->getGst();
1657         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
1658         sstate.moon_dist = 40000.0 * moon_horiz_eff;
1659         sstate.sun_angle = l->get_sun_angle();
1660
1661         SGSkyColor scolor;
1662         scolor.sky_color   = SGVec3f(l->sky_color().data());
1663         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1664         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
1665         scolor.cloud_color = SGVec3f(l->cloud_color().data());
1666         scolor.sun_angle   = l->get_sun_angle();
1667         scolor.moon_angle  = l->get_moon_angle();
1668   
1669         double delta_time_sec = _sim_delta_sec->getDoubleValue();
1670         _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1671         _sky->repaint( scolor, *globals->get_ephem() );
1672
1673             //OSGFIXME
1674 //         shadows->setupShadows(
1675 //           current__view->getLongitude_deg(),
1676 //           current__view->getLatitude_deg(),
1677 //           globals->get_time_params()->getGst(),
1678 //           globals->get_ephem()->getSunRightAscension(),
1679 //           globals->get_ephem()->getSunDeclination(),
1680 //           l->get_sun_angle());
1681
1682     }
1683
1684 //     sgEnviro.setLight(l->adj_fog_color());
1685 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
1686 //         current__view->get_world_up(),
1687 //         current__view->getLongitude_deg(),
1688 //         current__view->getLatitude_deg(),
1689 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1690 //         delta_time_sec);
1691
1692     // OSGFIXME
1693 //     sgEnviro.drawLightning();
1694
1695 //        double current_view_origin_airspeed_horiz_kt =
1696 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
1697 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1698 //                                * SGD_DEGREES_TO_RADIANS);
1699
1700     // OSGFIXME
1701 //     if( is_internal )
1702 //         shadows->endOfFrame();
1703
1704     // need to call the update visitor once
1705     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1706     mUpdateVisitor->setViewData(current__view->getViewPosition(),
1707                                 current__view->getViewOrientation());
1708     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1709     mUpdateVisitor->setLight(direction, l->scene_ambient(),
1710                              l->scene_diffuse(), l->scene_specular(),
1711                              l->adj_fog_color(),
1712                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1713     mUpdateVisitor->setVisibility(actual_visibility);
1714     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1715     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1716     cullMask |= simgear::GroundLightManager::instance()
1717         ->getLightNodeMask(mUpdateVisitor.get());
1718     if (_panel_hotspots->getBoolValue())
1719         cullMask |= simgear::PICK_BIT;
1720     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1721         if ( !_classicalRenderer ) {
1722                 _fogColor->set( toOsg( l->adj_fog_color() ) );
1723                 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1724         }
1725 }
1726
1727 void
1728 FGRenderer::resize( int width, int height )
1729 {
1730     int curWidth = _xsize->getIntValue(),
1731         curHeight = _ysize->getIntValue();
1732     SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1733     if ((curHeight != height) || (curWidth != width)) {
1734     // must guard setting these, or PLIB-PUI fails with too many live interfaces
1735         _xsize->setIntValue(width);
1736         _ysize->setIntValue(height);
1737     }
1738 }
1739
1740 typedef osgUtil::LineSegmentIntersector::Intersection Intersection;
1741 SGVec2d uvFromIntersection(const Intersection& hit)
1742 {
1743   // Taken from http://trac.openscenegraph.org/projects/osg/browser/OpenSceneGraph/trunk/examples/osgmovie/osgmovie.cpp
1744
1745   osg::Drawable* drawable = hit.drawable.get();
1746   osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
1747   osg::Vec3Array* vertices =
1748     geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
1749
1750   if( !vertices )
1751   {
1752     SG_LOG(SG_INPUT, SG_WARN, "Unable to get vertices for intersection.");
1753     return SGVec2d(-9999,-9999);
1754   }
1755
1756   // get the vertex indices.
1757   const Intersection::IndexList& indices = hit.indexList;
1758   const Intersection::RatioList& ratios = hit.ratioList;
1759
1760   if( indices.size() != 3 || ratios.size() != 3 )
1761   {
1762     SG_LOG( SG_INPUT,
1763             SG_WARN,
1764             "Intersection has insufficient indices to work with." );
1765     return SGVec2d(-9999,-9999);
1766   }
1767
1768   unsigned int i1 = indices[0];
1769   unsigned int i2 = indices[1];
1770   unsigned int i3 = indices[2];
1771
1772   float r1 = ratios[0];
1773   float r2 = ratios[1];
1774   float r3 = ratios[2];
1775
1776   osg::Array* texcoords =
1777     (geometry->getNumTexCoordArrays() > 0) ? geometry->getTexCoordArray(0) : 0;
1778   osg::Vec2Array* texcoords_Vec2Array =
1779     dynamic_cast<osg::Vec2Array*>(texcoords);
1780
1781   if( !texcoords_Vec2Array )
1782   {
1783     SG_LOG(SG_INPUT, SG_WARN, "Unable to get texcoords for intersection.");
1784     return SGVec2d(-9999,-9999);
1785   }
1786
1787   // we have tex coord array so now we can compute the final tex coord at the
1788   // point of intersection.
1789   osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
1790   osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
1791   osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
1792
1793   return toSG( osg::Vec2d(tc1 * r1 + tc2 * r2 + tc3 * r3) );
1794 }
1795
1796 bool
1797 FGRenderer::pick(std::vector<SGSceneryPick>& pickList, const osg::Vec2& windowPos)
1798 {
1799     // wipe out the return ...
1800     pickList.clear();
1801     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1802     Intersections intersections;
1803
1804     if (!computeIntersections(CameraGroup::getDefault(), windowPos, intersections))
1805         return false;
1806     for (Intersections::iterator hit = intersections.begin(),
1807              e = intersections.end();
1808          hit != e;
1809          ++hit) {
1810         const osg::NodePath& np = hit->nodePath;
1811         osg::NodePath::const_reverse_iterator npi;
1812         
1813         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1814             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1815             if (!ud || (ud->getNumPickCallbacks() == 0))
1816                 continue;
1817             
1818             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1819                 SGPickCallback* pickCallback = ud->getPickCallback(i);
1820                 if (!pickCallback)
1821                     continue;
1822                 SGSceneryPick sceneryPick;
1823                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1824                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1825
1826                 if( pickCallback->needsUV() )
1827                   sceneryPick.info.uv = uvFromIntersection(*hit);
1828
1829                 sceneryPick.callback = pickCallback;
1830                 pickList.push_back(sceneryPick);
1831             } // of installed pick callbacks iteration
1832         } // of reverse node path walk
1833     }
1834     
1835     return !pickList.empty();
1836 }
1837
1838 void
1839 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1840 {
1841     viewer = viewer_;
1842 }
1843
1844 void
1845 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1846 {
1847     eventHandler = eventHandler_;
1848 }
1849
1850 void
1851 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1852 {
1853     mRealRoot->addChild(camera);
1854 }
1855
1856 void
1857 FGRenderer::removeCamera(osg::Camera* camera)
1858 {
1859     mRealRoot->removeChild(camera);
1860 }
1861                                     
1862 void
1863 FGRenderer::setPlanes( double zNear, double zFar )
1864 {
1865         _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1866 }
1867
1868 bool
1869 fgDumpSceneGraphToFile(const char* filename)
1870 {
1871     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1872 }
1873
1874 bool
1875 fgDumpTerrainBranchToFile(const char* filename)
1876 {
1877     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1878                                  filename );
1879 }
1880
1881 // For debugging
1882 bool
1883 fgDumpNodeToFile(osg::Node* node, const char* filename)
1884 {
1885     return osgDB::writeNodeFile(*node, filename);
1886 }
1887
1888 namespace flightgear
1889 {
1890 using namespace osg;
1891
1892 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1893 {
1894 public:
1895     VisibleSceneInfoVistor()
1896         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1897     {
1898         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1899                        | CullSettings::VIEW_FRUSTUM_CULLING);
1900         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1901     }
1902
1903     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1904     {
1905     }
1906
1907     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1908
1909     typedef std::map<const std::string,int> InfoMap;
1910
1911     void getNodeInfo(Node* node)
1912     {
1913         const char* typeName = typeid(*node).name();
1914         classInfo[typeName]++;
1915         const std::string& nodeName = node->getName();
1916         if (!nodeName.empty())
1917             nodeInfo[nodeName]++;
1918     }
1919
1920     void dumpInfo()
1921     {
1922         using namespace std;
1923         typedef vector<InfoMap::iterator> FreqVector;
1924         cout << "class info:\n";
1925         FreqVector classes;
1926         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1927              itr != end;
1928              ++itr)
1929             classes.push_back(itr);
1930         sort(classes.begin(), classes.end(), freqComp);
1931         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1932              itr != end;
1933              ++itr) {
1934             cout << (*itr)->first << " " << (*itr)->second << "\n";
1935         }
1936         cout << "\nnode info:\n";
1937         FreqVector nodes;
1938         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1939              itr != end;
1940              ++itr)
1941             nodes.push_back(itr);
1942
1943         sort (nodes.begin(), nodes.end(), freqComp);
1944         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1945              itr != end;
1946              ++itr) {
1947             cout << (*itr)->first << " " << (*itr)->second << "\n";
1948         }
1949         cout << endl;
1950     }
1951     
1952     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1953     {
1954         ref_ptr<RefMatrix> projection
1955             = createOrReuseMatrix(camera->getProjectionMatrix());
1956         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1957         if (!viewport)
1958             viewport = camera->getViewport();
1959         if (viewport)
1960             pushViewport(viewport);
1961         pushProjectionMatrix(projection.get());
1962         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1963         root->accept(*this);
1964         popModelViewMatrix();
1965         popProjectionMatrix();
1966         if (viewport)
1967             popViewport();
1968         dumpInfo();
1969     }
1970
1971     void apply(Node& node)
1972     {
1973         if (isCulled(node))
1974             return;
1975         pushCurrentMask();
1976         getNodeInfo(&node);
1977         traverse(node);
1978         popCurrentMask();
1979     }
1980     void apply(Group& node)
1981     {
1982         if (isCulled(node))
1983             return;
1984         pushCurrentMask();
1985         getNodeInfo(&node);
1986         traverse(node);
1987         popCurrentMask();
1988     }
1989
1990     void apply(Transform& node)
1991     {
1992         if (isCulled(node))
1993             return;
1994         pushCurrentMask();
1995         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1996         node.computeLocalToWorldMatrix(*matrix,this);
1997         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1998         getNodeInfo(&node);
1999         traverse(node);
2000         popModelViewMatrix();
2001         popCurrentMask();
2002     }
2003
2004     void apply(Camera& camera)
2005     {
2006         // Save current cull settings
2007         CullSettings saved_cull_settings(*this);
2008
2009         // set cull settings from this Camera
2010         setCullSettings(camera);
2011         // inherit the settings from above
2012         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2013
2014         // set the cull mask.
2015         unsigned int savedTraversalMask = getTraversalMask();
2016         bool mustSetCullMask = (camera.getInheritanceMask()
2017                                 & osg::CullSettings::CULL_MASK) == 0;
2018         if (mustSetCullMask)
2019             setTraversalMask(camera.getCullMask());
2020
2021         osg::RefMatrix* projection = 0;
2022         osg::RefMatrix* modelview = 0;
2023
2024         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2025             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2026                 projection = createOrReuseMatrix(*getProjectionMatrix()
2027                                                  *camera.getProjectionMatrix());
2028                 modelview = createOrReuseMatrix(*getModelViewMatrix()
2029                                                 * camera.getViewMatrix());
2030             }
2031             else {              // pre multiply 
2032                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2033                                                  * (*getProjectionMatrix()));
2034                 modelview = createOrReuseMatrix(camera.getViewMatrix()
2035                                                 * (*getModelViewMatrix()));
2036             }
2037         } else {
2038             // an absolute reference frame
2039             projection = createOrReuseMatrix(camera.getProjectionMatrix());
2040             modelview = createOrReuseMatrix(camera.getViewMatrix());
2041         }
2042         if (camera.getViewport())
2043             pushViewport(camera.getViewport());
2044
2045         pushProjectionMatrix(projection);
2046         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
2047
2048         traverse(camera);
2049     
2050         // restore the previous model view matrix.
2051         popModelViewMatrix();
2052
2053         // restore the previous model view matrix.
2054         popProjectionMatrix();
2055
2056         if (camera.getViewport()) popViewport();
2057
2058         // restore the previous traversal mask settings
2059         if (mustSetCullMask)
2060             setTraversalMask(savedTraversalMask);
2061
2062         // restore the previous cull settings
2063         setCullSettings(saved_cull_settings);
2064     }
2065
2066 protected:
2067     // sort in reverse
2068     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2069     {
2070         return lhs->second > rhs->second;
2071     }
2072     InfoMap classInfo;
2073     InfoMap nodeInfo;
2074 };
2075
2076 bool printVisibleSceneInfo(FGRenderer* renderer)
2077 {
2078     osgViewer::Viewer* viewer = renderer->getViewer();
2079     VisibleSceneInfoVistor vsv;
2080     Viewport* vp = 0;
2081     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2082         const View::Slave& slave = viewer->getSlave(0);
2083         vp = slave._camera->getViewport();
2084     }
2085     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2086     return true;
2087 }
2088
2089 }
2090 // end of renderer.cxx
2091