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