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