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