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