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