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