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