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