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