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