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