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