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