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