1 // renderer.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
6 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
30 #include <simgear/compiler.h>
38 #include <boost/foreach.hpp>
40 #include <osg/ref_ptr>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
44 #include <osg/CullFace>
45 #include <osg/CullStack>
51 #include <osg/LightModel>
52 #include <osg/LightSource>
53 #include <osg/Material>
55 #include <osg/NodeCallback>
57 #include <osg/PolygonMode>
58 #include <osg/PolygonOffset>
59 #include <osg/Program>
60 #include <osg/Version>
63 #include <osgUtil/LineSegmentIntersector>
65 #include <osg/io_utils>
66 #include <osgDB/WriteFile>
67 #include <osgViewer/Renderer>
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/SGUpdateVisitor.hxx>
78 #include <simgear/scene/util/RenderConstants.hxx>
79 #include <simgear/scene/util/SGSceneUserData.hxx>
80 #include <simgear/scene/tgdb/GroundLightManager.hxx>
81 #include <simgear/scene/tgdb/pt_lights.hxx>
82 #include <simgear/scene/tgdb/userdata.hxx>
83 #include <simgear/structure/OSGUtils.hxx>
84 #include <simgear/props/props.hxx>
85 #include <simgear/timing/sg_time.hxx>
86 #include <simgear/ephemeris/ephemeris.hxx>
87 #include <simgear/math/sg_random.h>
89 #include <simgear/screen/jpgfactory.hxx>
92 #include <Time/light.hxx>
93 #include <Time/light.hxx>
94 #include <Cockpit/panel.hxx>
96 #include <Model/panelnode.hxx>
97 #include <Model/modelmgr.hxx>
98 #include <Model/acmodel.hxx>
99 #include <Scenery/scenery.hxx>
100 #include <Scenery/redout.hxx>
101 #include <GUI/new_gui.hxx>
102 #include <Instrumentation/HUD/HUD.hxx>
103 #include <Environment/precipitation_mgr.hxx>
104 #include <Environment/environment_mgr.hxx>
106 //#include <Main/main.hxx>
107 #include "viewer.hxx"
108 #include "viewmgr.hxx"
109 #include "splash.hxx"
110 #include "renderer.hxx"
111 #include "CameraGroup.hxx"
112 #include "FGEventHandler.hxx"
115 using namespace simgear;
116 using namespace flightgear;
118 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
120 FGHintUpdateCallback(const char* configNode) :
121 mConfigNode(fgGetNode(configNode, true))
123 virtual void operator()(osg::StateAttribute* stateAttribute,
126 assert(dynamic_cast<osg::Hint*>(stateAttribute));
127 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
129 const char* value = mConfigNode->getStringValue();
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);
137 hint->setMode(GL_DONT_CARE);
140 SGPropertyNode_ptr mConfigNode;
144 class SGPuDrawable : public osg::Drawable {
148 // Dynamic stuff, do not store geometry
149 setUseDisplayList(false);
150 setDataVariance(Object::DYNAMIC);
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);
161 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
163 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
164 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
166 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
167 { drawImplementation(*renderInfo.getState()); }
168 void drawImplementation(osg::State& state) const
170 state.setActiveTextureUnit(0);
171 state.setClientActiveTextureUnit(0);
173 state.disableAllVertexArrays();
175 glPushAttrib(GL_ALL_ATTRIB_BITS);
176 glPushClientAttrib(~0u);
184 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
185 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
190 class SGHUDDrawable : public osg::Drawable {
194 // Dynamic stuff, do not store geometry
195 setUseDisplayList(false);
196 setDataVariance(Object::DYNAMIC);
198 osg::StateSet* stateSet = getOrCreateStateSet();
199 stateSet->setRenderBinDetails(1000, "RenderBin");
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);
208 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
210 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
211 { drawImplementation(*renderInfo.getState()); }
212 void drawImplementation(osg::State& state) const
214 state.setActiveTextureUnit(0);
215 state.setClientActiveTextureUnit(0);
216 state.disableAllVertexArrays();
218 glPushAttrib(GL_ALL_ATTRIB_BITS);
219 glPushClientAttrib(~0u);
221 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
228 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
229 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
238 * @param isSun true if the light is the actual sun i.e., for
239 * illuminating the moon.
241 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
242 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
244 : NodeCallback(nc, op), _isSun(nc._isSun)
246 META_Object(flightgear,FGLightSourceUpdateCallback);
248 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
250 assert(dynamic_cast<osg::LightSource*>(node));
251 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
252 osg::Light* light = lightSource->getLight();
254 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
256 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
258 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
260 light->setAmbient(toOsg(l->scene_ambient()));
261 light->setDiffuse(toOsg(l->scene_diffuse()));
262 light->setSpecular(toOsg(l->scene_specular()));
264 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
265 light->setPosition(position);
273 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
275 FGWireFrameModeUpdateCallback() :
276 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
278 virtual void operator()(osg::StateAttribute* stateAttribute,
281 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
282 osg::PolygonMode* polygonMode;
283 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
285 if (mWireframe->getBoolValue())
286 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287 osg::PolygonMode::LINE);
289 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290 osg::PolygonMode::FILL);
293 SGPropertyNode_ptr mWireframe;
296 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
298 FGLightModelUpdateCallback() :
299 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
301 virtual void operator()(osg::StateAttribute* stateAttribute,
304 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
305 osg::LightModel* lightModel;
306 lightModel = static_cast<osg::LightModel*>(stateAttribute);
309 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
310 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
312 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
314 lightModel->setTwoSided(true);
315 lightModel->setLocalViewer(false);
317 if (mHighlights->getBoolValue()) {
318 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
320 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
324 SGPropertyNode_ptr mHighlights;
327 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
329 FGFogEnableUpdateCallback() :
330 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
332 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
334 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
335 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
337 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
341 SGPropertyNode_ptr mFogEnabled;
344 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
346 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
348 assert(dynamic_cast<SGUpdateVisitor*>(nv));
349 assert(dynamic_cast<osg::Fog*>(sa));
350 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
351 osg::Fog* fog = static_cast<osg::Fog*>(sa);
352 fog->setMode(osg::Fog::EXP2);
353 fog->setColor(toOsg(updateVisitor->getFogColor()));
354 fog->setDensity(updateVisitor->getFogExp2Density());
358 // update callback for the switch node guarding that splash
359 class FGScenerySwitchCallback : public osg::NodeCallback {
361 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
363 assert(dynamic_cast<osg::Switch*>(node));
364 osg::Switch* sw = static_cast<osg::Switch*>(node);
366 bool enabled = scenery_enabled;
367 sw->setValue(0, enabled);
373 static bool scenery_enabled;
376 bool FGScenerySwitchCallback::scenery_enabled = false;
378 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
379 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
381 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
382 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
384 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
386 static osg::ref_ptr<osg::Switch> panelSwitch;
389 // update callback for the switch node controlling the 2D panel
390 class FGPanelSwitchCallback : public osg::NodeCallback {
392 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
394 assert(dynamic_cast<osg::Switch*>(node));
395 osg::Switch* sw = static_cast<osg::Switch*>(node);
397 bool enabled = fgPanelVisible();
398 sw->setValue(0, enabled);
405 #ifdef FG_JPEG_SERVER
406 static void updateRenderer()
408 globals->get_renderer()->update();
412 FGRenderer::FGRenderer() :
414 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
415 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
416 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
417 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
418 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
419 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
420 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
421 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
422 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
423 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
425 #ifdef FG_JPEG_SERVER
426 jpgRenderFrame = updateRenderer;
428 eventHandler = new FGEventHandler;
431 _cascadeFar[0] = 5.f;
432 _cascadeFar[1] = 50.f;
433 _cascadeFar[2] = 500.f;
434 _cascadeFar[3] = 5000.f;
437 FGRenderer::~FGRenderer()
439 #ifdef FG_JPEG_SERVER
440 jpgRenderFrame = NULL;
445 // Initialize various GL/view parameters
446 // XXX This should be called "preinit" or something, as it initializes
447 // critical parts of the scene graph in addition to the splash screen.
449 FGRenderer::splashinit( void ) {
450 osgViewer::Viewer* viewer = getViewer();
451 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
452 ref_ptr<Node> splashNode = fgCreateSplashNode();
453 if (_classicalRenderer) {
454 mRealRoot->addChild(splashNode.get());
456 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
457 ii != CameraGroup::getDefault()->camerasEnd();
460 CameraInfo* info = ii->get();
461 Camera* camera = info->getCamera(DISPLAY_CAMERA);
462 if (camera == 0) continue;
464 camera->addChild(splashNode.get());
467 mFrameStamp = viewer->getFrameStamp();
468 // Scene doesn't seem to pass the frame stamp to the update
469 // visitor automatically.
470 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
471 viewer->setUpdateVisitor(mUpdateVisitor.get());
472 fgSetDouble("/sim/startup/splash-alpha", 1.0);
475 class ShadowMapSizeListener : public SGPropertyChangeListener {
477 virtual void valueChanged(SGPropertyNode* node) {
478 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
482 class ShadowEnabledListener : public SGPropertyChangeListener {
484 virtual void valueChanged(SGPropertyNode* node) {
485 globals->get_renderer()->enableShadows(node->getBoolValue());
489 class ShadowNumListener : public SGPropertyChangeListener {
491 virtual void valueChanged(SGPropertyNode* node) {
492 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
496 class ShadowRangeListener : public SGPropertyChangeListener {
498 virtual void valueChanged(SGPropertyNode* node) {
499 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
504 FGRenderer::init( void )
506 sgUserDataInit( globals->get_props() );
508 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
509 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
510 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
511 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
512 ShadowRangeListener* srl = new ShadowRangeListener;
513 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
514 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
515 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
516 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
517 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
518 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
519 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
520 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
521 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
522 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
523 updateCascadeNumber(_numCascades);
524 updateCascadeFar(0, _cascadeFar[0]);
525 updateCascadeFar(1, _cascadeFar[1]);
526 updateCascadeFar(2, _cascadeFar[2]);
527 updateCascadeFar(3, _cascadeFar[3]);
528 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
529 _depthInColor->set( _useColorForDepth );
531 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
532 if (!_classicalRenderer)
533 _pipeline = makeRenderingPipeline(_renderer, 0);
534 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
535 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
536 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
537 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
539 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
541 _xsize = fgGetNode("/sim/startup/xsize", true);
542 _ysize = fgGetNode("/sim/startup/ysize", true);
543 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
545 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
546 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
547 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
548 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
549 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
550 _textures = fgGetNode("/sim/rendering/textures", true);
552 _altitude_ft = fgGetNode("/position/altitude-ft", true);
554 _cloud_status = fgGetNode("/environment/clouds/status", true);
555 _visibility_m = fgGetNode("/environment/visibility-m", true);
557 bool use_point_sprites = _point_sprites->getBoolValue();
558 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
559 bool distance_attenuation = _distance_attenuation->getBoolValue();
561 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
562 distance_attenuation );
564 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
565 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
566 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
567 strcmp(tc, "none") == 0) {
568 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
569 } else if (strcmp(tc, "arb") == 0) {
570 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
571 } else if (strcmp(tc, "dxt1") == 0) {
572 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
573 } else if (strcmp(tc, "dxt3") == 0) {
574 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
575 } else if (strcmp(tc, "dxt5") == 0) {
576 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
578 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
582 // create sky, but can't build until setupView, since we depend
583 // on other subsystems to be inited, eg Ephemeris
586 SGPath texture_path(globals->get_fg_root());
587 texture_path.append("Textures");
588 texture_path.append("Sky");
589 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
590 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
591 _sky->add_cloud_layer(layer);
594 _sky->texture_path( texture_path.str() );
596 if (!_classicalRenderer) {
597 eventHandler->setChangeStatsCameraRenderOrder( true );
601 void installCullVisitor(Camera* camera)
603 osgViewer::Renderer* renderer
604 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
605 for (int i = 0; i < 2; ++i) {
606 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
607 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
608 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
610 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
611 identifier = sceneView->getCullVisitor()->getIdentifier();
612 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
613 sceneView->getCullVisitor()->setIdentifier(identifier.get());
615 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
616 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
617 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
619 identifier = sceneView->getCullVisitorRight()->getIdentifier();
620 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
621 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
627 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
629 const Matrix& projection,
630 osg::GraphicsContext* gc,
631 bool useMasterSceneData)
633 CameraInfo* info = 0;
634 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
635 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
640 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
641 _classicalRenderer = true;
642 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
647 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
648 const osg::Matrix& view,
649 const osg::Matrix& projection,
650 bool useMasterSceneData)
652 CameraInfo* info = new CameraInfo(flags);
653 // The camera group will always update the camera
654 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
656 Camera* farCamera = 0;
657 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
658 farCamera = new Camera;
659 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
660 farCamera->setGraphicsContext(camera->getGraphicsContext());
661 farCamera->setCullingMode(camera->getCullingMode());
662 farCamera->setInheritanceMask(camera->getInheritanceMask());
663 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
664 // Each camera's viewport is written when the window is
665 // resized; if the the viewport isn't copied here, it gets updated
666 // twice and ends up with the wrong value.
667 farCamera->setViewport(simgear::clone(camera->getViewport()));
668 farCamera->setDrawBuffer(camera->getDrawBuffer());
669 farCamera->setReadBuffer(camera->getReadBuffer());
670 farCamera->setRenderTargetImplementation(
671 camera->getRenderTargetImplementation());
672 const Camera::BufferAttachmentMap& bufferMap
673 = camera->getBufferAttachmentMap();
674 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
676 Camera::COLOR_BUFFER,
677 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
679 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
680 installCullVisitor(farCamera);
681 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
682 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
683 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
684 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
685 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
687 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
688 installCullVisitor(camera);
689 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
690 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
691 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
692 cgroup->addCamera(info);
696 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
698 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
699 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
700 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
701 osg::Camera* camera = static_cast<osg::Camera*>(n);
703 cv->clearBufferList();
704 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
705 cv->addBuffer(ii->first, ii->second.texture);
708 if ( !info->getRenderStageInfo(kind).fullscreen )
709 info->setMatrices( camera );
712 osg::Matrix projInverse;
713 info->projInverse->get( projInverse );
715 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
716 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
717 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
720 cv->traverse( *camera );
722 if ( kind == GEOMETRY_CAMERA ) {
723 // Save transparent bins to render later
724 osgUtil::RenderStage* renderStage = cv->getRenderStage();
725 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
726 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
727 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
728 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
734 } else if ( kind == LIGHTING_CAMERA ) {
735 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
736 if (mainShadowCamera.valid()) {
737 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
738 for (int i = 0; i < 4; ++i ) {
739 if (!grp->getValue(i))
741 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
742 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
744 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
745 // compute the matrix which takes a vertex from view coords into tex coords
746 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
747 osg::Matrix::translate(1.0,1.0,1.0) *
748 osg::Matrix::scale(0.5f,0.5f,0.5f) );
750 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
752 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
755 // Render saved transparent render bins
756 osgUtil::RenderStage* renderStage = cv->getRenderStage();
757 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
758 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
759 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
761 info->savedTransparentBins.clear();
771 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
773 osg::Texture2D* tex = new osg::Texture2D;
774 tex->setResizeNonPowerOfTwoHint( false );
775 tex->setInternalFormat( internalFormat );
776 tex->setShadowComparison(shadowComparison);
777 if (shadowComparison) {
778 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
779 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
781 tex->setSourceFormat(sourceFormat);
782 tex->setSourceType(sourceType);
783 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
784 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
785 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
786 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
790 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
792 camera->attach( c, info->getBuffer(bk) );
793 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
796 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
797 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
798 if (attachment->valid())
799 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
803 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
805 osg::Camera* camera = new osg::Camera;
806 info->addCamera(name, camera );
808 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
809 camera->setName( "GeometryC" );
810 camera->setGraphicsContext( gc );
811 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
812 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
813 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
814 camera->setClearDepth( 1.0 );
815 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
816 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
817 camera->setViewport( new osg::Viewport );
818 buildAttachments(info, camera, name, attachments);
819 camera->setDrawBuffer(GL_FRONT);
820 camera->setReadBuffer(GL_FRONT);
822 osg::StateSet* ss = camera->getOrCreateStateSet();
823 ss->addUniform( _depthInColor );
825 camera->addChild( mDeferredRealRoot.get() );
830 static void setShadowCascadeStateSet( osg::Camera* cam ) {
831 osg::StateSet* ss = cam->getOrCreateStateSet();
832 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
833 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
834 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
835 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
836 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
837 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
838 osg::Program* program = new osg::Program;
839 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
840 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
841 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
842 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
843 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
844 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
845 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
846 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
847 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
850 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
851 osg::Camera* cascadeCam = new osg::Camera;
852 setShadowCascadeStateSet( cascadeCam );
854 std::ostringstream oss;
855 oss << "CascadeCamera" << (no + 1);
856 cascadeCam->setName( oss.str() );
857 cascadeCam->setClearMask(0);
858 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
859 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
860 cascadeCam->setAllowEventFocus(false);
861 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
862 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
863 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
864 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
868 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
870 osg::Camera* mainShadowCamera = new osg::Camera;
871 info->addCamera(name, mainShadowCamera, 0.0f );
873 mainShadowCamera->setName( "ShadowC" );
874 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
875 mainShadowCamera->setClearDepth( 1.0 );
876 mainShadowCamera->setAllowEventFocus(false);
877 mainShadowCamera->setGraphicsContext(gc);
878 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
879 buildAttachments(info, mainShadowCamera, name, attachments);
880 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
881 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
882 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
883 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
884 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
885 mainShadowCamera->setDrawBuffer(GL_FRONT);
886 mainShadowCamera->setReadBuffer(GL_FRONT);
887 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
889 osg::Switch* shadowSwitch = new osg::Switch;
890 mainShadowCamera->addChild( shadowSwitch );
892 for (int i = 0; i < 4; ++i ) {
893 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
894 cascadeCam->addChild( mDeferredRealRoot.get() );
895 shadowSwitch->addChild( cascadeCam );
896 info->shadowTexGen[i] = new osg::TexGen;
898 if (fgGetBool("/sim/rendering/shadows/enabled", true))
899 shadowSwitch->setAllChildrenOn();
901 shadowSwitch->setAllChildrenOff();
903 return mainShadowCamera;
906 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)
908 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
909 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
910 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
912 osg::BoundingSphere bs;
913 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
914 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
915 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
916 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
918 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
920 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
921 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
922 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
925 osg::Vec3 FGRenderer::getSunDirection() const
928 _sunDirection->get( val );
932 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
934 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
935 if (mainShadowCamera.valid()) {
936 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
937 osg::Vec3d up = position,
938 dir = getSunDirection();
941 // cos(100 deg) == -0.17
942 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
943 shadowSwitch->setAllChildrenOff();
945 double left,right,bottom,top,zNear,zFar;
946 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
947 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
949 shadowSwitch->setAllChildrenOn();
950 if (_numCascades == 1) {
951 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
952 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
954 for (int no = 0; no < 4; ++no) {
955 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
956 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
959 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
960 if (_numCascades > 1) {
961 shadowSwitch->setValue(1, true);
962 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
964 shadowSwitch->setValue(1, false);
966 if (_numCascades > 2) {
967 shadowSwitch->setValue(2, true);
968 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
970 shadowSwitch->setValue(2, false);
972 if (_numCascades > 3) {
973 shadowSwitch->setValue(3, true);
974 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
976 shadowSwitch->setValue(3, false);
979 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
981 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
983 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
984 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
990 void FGRenderer::updateShadowMapSize(int mapSize)
992 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
993 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
996 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
997 ii != CameraGroup::getDefault()->camerasEnd();
1000 CameraInfo* info = ii->get();
1001 Camera* camera = info->getCamera(SHADOW_CAMERA);
1002 if (camera == 0) continue;
1004 Texture2D* tex = info->getBuffer("shadow");
1005 if (tex == 0) continue;
1007 tex->setTextureSize( mapSize, mapSize );
1008 tex->dirtyTextureObject();
1010 Viewport* vp = camera->getViewport();
1011 vp->width() = mapSize;
1012 vp->height() = mapSize;
1014 osgViewer::Renderer* renderer
1015 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1016 for (int i = 0; i < 2; ++i) {
1017 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1018 sceneView->getRenderStage()->setFrameBufferObject(0);
1019 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1020 if (sceneView->getRenderStageLeft()) {
1021 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1022 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1024 if (sceneView->getRenderStageRight()) {
1025 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1026 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1030 int cascadeSize = mapSize / 2;
1031 Group* grp = camera->getChild(0)->asGroup();
1032 for (int i = 0; i < 4; ++i ) {
1033 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1034 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1037 _shadowMapSize = mapSize;
1041 void FGRenderer::enableShadows(bool enabled)
1043 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1044 ii != CameraGroup::getDefault()->camerasEnd();
1047 CameraInfo* info = ii->get();
1048 Camera* camera = info->getCamera(SHADOW_CAMERA);
1049 if (camera == 0) continue;
1051 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1053 shadowSwitch->setAllChildrenOn();
1055 shadowSwitch->setAllChildrenOff();
1059 void FGRenderer::updateCascadeFar(int index, float far_m)
1061 if (index < 0 || index > 3)
1063 _cascadeFar[index] = far_m;
1064 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1067 void FGRenderer::updateCascadeNumber(size_t num)
1069 if (num < 1 || num > 4)
1072 _shadowNumber->set( (int)_numCascades );
1075 osg::Camera* FGRenderer::buildDeferredLightingCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
1077 osg::Camera* camera = new osg::Camera;
1078 info->addCamera(name, camera );
1080 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
1081 camera->setAllowEventFocus(false);
1082 camera->setGraphicsContext(gc);
1083 camera->setViewport(new Viewport);
1084 camera->setName("LightingC");
1085 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1086 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 50);
1087 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1088 camera->setViewport( new osg::Viewport );
1089 buildAttachments(info, camera, name, attachments);
1090 camera->setDrawBuffer(GL_FRONT);
1091 camera->setReadBuffer(GL_FRONT);
1092 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1093 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1094 osg::StateSet* ss = camera->getOrCreateStateSet();
1095 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1096 ss->addUniform( _depthInColor );
1098 osg::Group* lightingGroup = new osg::Group;
1100 osg::Camera* quadCam1 = new osg::Camera;
1101 quadCam1->setName( "QuadCamera1" );
1102 quadCam1->setClearMask(0);
1103 quadCam1->setAllowEventFocus(false);
1104 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1105 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1106 quadCam1->setViewMatrix(osg::Matrix::identity());
1107 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1108 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1109 ss = quadCam1->getOrCreateStateSet();
1110 ss->addUniform( _ambientFactor );
1111 ss->addUniform( info->projInverse );
1112 ss->addUniform( info->viewInverse );
1113 ss->addUniform( info->view );
1114 ss->addUniform( _sunDiffuse );
1115 ss->addUniform( _sunSpecular );
1116 ss->addUniform( _sunDirection );
1117 ss->addUniform( _planes );
1118 ss->addUniform( _shadowNumber );
1119 ss->addUniform( _shadowDistances );
1121 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1122 g->setUseDisplayList(false);
1123 simgear::EffectGeode* eg = new simgear::EffectGeode;
1124 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1126 SG_LOG(SG_VIEW, SG_ALERT, "Effects/ambient not found");
1129 eg->setEffect( effect );
1130 g->setName( "AmbientQuad" );
1131 eg->setName("AmbientQuad");
1132 eg->setCullingActive(false);
1134 quadCam1->addChild( eg );
1136 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1137 g->setUseDisplayList(false);
1138 g->setName( "SunlightQuad" );
1139 eg = new simgear::EffectGeode;
1140 effect = simgear::makeEffect("Effects/sunlight", true);
1142 SG_LOG(SG_VIEW, SG_ALERT, "Effects/sunlight not found");
1145 eg->setEffect( effect );
1146 eg->setName("SunlightQuad");
1147 eg->setCullingActive(false);
1149 quadCam1->addChild( eg );
1151 osg::Camera* lightCam = new osg::Camera;
1152 ss = lightCam->getOrCreateStateSet();
1153 ss->addUniform( _planes );
1154 ss->addUniform( info->bufferSize );
1155 lightCam->setName( "LightCamera" );
1156 lightCam->setClearMask(0);
1157 lightCam->setAllowEventFocus(false);
1158 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1159 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1160 lightCam->setViewMatrix(osg::Matrix::identity());
1161 lightCam->setProjectionMatrix(osg::Matrix::identity());
1162 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1163 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1164 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1165 lightCam->addChild( mDeferredRealRoot.get() );
1168 osg::Camera* quadCam2 = new osg::Camera;
1169 quadCam2->setName( "QuadCamera1" );
1170 quadCam2->setClearMask(0);
1171 quadCam2->setAllowEventFocus(false);
1172 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1173 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1174 quadCam2->setViewMatrix(osg::Matrix::identity());
1175 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1176 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1177 ss = quadCam2->getOrCreateStateSet();
1178 ss->addUniform( _ambientFactor );
1179 ss->addUniform( info->projInverse );
1180 ss->addUniform( info->viewInverse );
1181 ss->addUniform( info->view );
1182 ss->addUniform( _sunDiffuse );
1183 ss->addUniform( _sunSpecular );
1184 ss->addUniform( _sunDirection );
1185 ss->addUniform( _fogColor );
1186 ss->addUniform( _fogDensity );
1187 ss->addUniform( _planes );
1189 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1190 g->setUseDisplayList(false);
1191 g->setName( "FogQuad" );
1192 eg = new simgear::EffectGeode;
1193 effect = simgear::makeEffect("Effects/fog", true);
1195 SG_LOG(SG_VIEW, SG_ALERT, "Effects/fog not found");
1198 eg->setEffect( effect );
1199 eg->setName("FogQuad");
1200 eg->setCullingActive(false);
1202 quadCam2->addChild( eg );
1204 lightingGroup->addChild( _sky->getPreRoot() );
1205 lightingGroup->addChild( _sky->getCloudRoot() );
1206 lightingGroup->addChild( quadCam1 );
1207 lightingGroup->addChild( lightCam );
1208 lightingGroup->addChild( quadCam2 );
1210 camera->addChild( lightingGroup );
1216 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1218 osg::Camera* camera = new osg::Camera;
1219 info->addCamera(stage->name, camera );
1221 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1222 camera->setAllowEventFocus(false);
1223 camera->setGraphicsContext(gc);
1224 camera->setViewport(new Viewport);
1225 camera->setName(stage->name+"C");
1226 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1227 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1228 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1229 camera->setViewport( new osg::Viewport );
1230 buildAttachments(info, camera, stage->name, stage->attachments);
1231 camera->setDrawBuffer(GL_FRONT);
1232 camera->setReadBuffer(GL_FRONT);
1233 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1234 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1235 osg::StateSet* ss = camera->getOrCreateStateSet();
1236 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1237 ss->addUniform( _depthInColor );
1239 osg::Group* lightingGroup = new osg::Group;
1241 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1242 ref_ptr<Node> node = buildPass(info, pass);
1244 lightingGroup->addChild(node);
1247 camera->addChild( lightingGroup );
1253 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1254 const osg::Matrix& view,
1255 const osg::Matrix& projection,
1256 osg::GraphicsContext* gc)
1258 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1262 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1264 osg::Camera* camera = new osg::Camera;
1266 camera->setClearMask( 0 );
1267 camera->setAllowEventFocus(false);
1268 camera->setName(pass->name+"C");
1269 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1270 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1271 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1272 camera->setViewMatrix(osg::Matrix::identity());
1273 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1275 osg::StateSet* ss = camera->getOrCreateStateSet();
1276 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1277 ss->addUniform( info->projInverse );
1278 ss->addUniform( info->viewInverse );
1279 ss->addUniform( info->view );
1280 ss->addUniform( info->bufferSize );
1281 ss->addUniform( _ambientFactor );
1282 ss->addUniform( _sunDiffuse );
1283 ss->addUniform( _sunSpecular );
1284 ss->addUniform( _sunDirection );
1285 ss->addUniform( _planes );
1286 ss->addUniform( _shadowNumber );
1287 ss->addUniform( _shadowDistances );
1288 ss->addUniform( _fogColor );
1289 ss->addUniform( _fogDensity );
1290 ss->addUniform( _planes );
1292 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1293 g->setUseDisplayList(false);
1294 simgear::EffectGeode* eg = new simgear::EffectGeode;
1295 simgear::Effect* effect = simgear::makeEffect(pass->effect, true);
1297 eg->setEffect( effect );
1300 eg->setName(pass->name+"Quad");
1301 eg->setCullingActive(false);
1303 camera->addChild(eg);
1309 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1311 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1312 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1314 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1315 camera->setGraphicsContext(gc);
1316 camera->setViewport(new Viewport);
1317 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1318 buildAttachments(info, camera, stage->name, stage->attachments);
1319 camera->setDrawBuffer(GL_FRONT);
1320 camera->setReadBuffer(GL_FRONT);
1321 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1322 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1323 camera->setViewMatrix(osg::Matrix::identity());
1324 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1326 osg::StateSet* ss = camera->getOrCreateStateSet();
1327 if (stage->needsDuDv) {
1328 ss->addUniform( info->du );
1329 ss->addUniform( info->dv );
1336 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const std::string& name, osg::GraphicsContext* gc )
1338 camera->setName( "DisplayC" );
1339 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
1340 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1341 camera->setAllowEventFocus(false);
1342 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1343 g->setUseDisplayList(false); //DEBUG
1344 simgear::EffectGeode* eg = new simgear::EffectGeode;
1345 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1347 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1350 eg->setEffect(effect);
1351 eg->setCullingActive(false);
1353 camera->setViewMatrix(osg::Matrix::identity());
1354 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1355 camera->addChild(eg);
1357 osg::StateSet* ss = camera->getOrCreateStateSet();
1358 ss->addUniform( _depthInColor );
1362 FGRenderer::buildStage(CameraInfo* info,
1363 FGRenderingPipeline::Stage* stage,
1364 CameraGroup* cgroup,
1365 osg::Camera* mainCamera,
1366 osg::GraphicsContext* gc)
1368 if (!stage->valid())
1371 ref_ptr<Camera> camera;
1372 if (stage->type == "geometry")
1373 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1374 else if (stage->type == "lighting-builtin")
1375 camera = buildDeferredLightingCamera(info, gc, stage->name, stage->attachments);
1376 else if (stage->type == "lighting")
1377 camera = buildDeferredLightingCamera(info, gc, stage);
1378 else if (stage->type == "shadow")
1379 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1380 else if (stage->type == "fullscreen")
1381 camera = buildDeferredFullscreenCamera(info, gc, stage);
1382 else if (stage->type == "display") {
1383 camera = mainCamera;
1384 buildDeferredDisplayCamera(camera, info, stage->name, gc);
1386 throw sg_exception("Stage type is not supported");
1388 cgroup->getViewer()->addSlave(camera, false);
1389 installCullVisitor(camera);
1390 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1391 if (stage->type == "display")
1392 info->addCamera( stage->type, camera, slaveIndex, true );
1393 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1397 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1399 Group* group = new Group;
1400 group->addChild( _sky->getPreRoot() );
1401 group->addChild( _sky->getCloudRoot() );
1406 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1408 osg::Camera* lightCam = new osg::Camera;
1409 StateSet* ss = lightCam->getOrCreateStateSet();
1410 ss->addUniform( _planes );
1411 ss->addUniform( info->bufferSize );
1412 lightCam->setName( "LightCamera" );
1413 lightCam->setClearMask(0);
1414 lightCam->setAllowEventFocus(false);
1415 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1416 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1417 lightCam->setViewMatrix(osg::Matrix::identity());
1418 lightCam->setProjectionMatrix(osg::Matrix::identity());
1419 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1420 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1421 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1422 lightCam->addChild( mDeferredRealRoot.get() );
1428 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1434 if (pass->type == "sky-clouds")
1435 node = buildLightingSkyCloudsPass(pass);
1436 else if (pass->type == "fullscreen")
1437 node = buildDeferredFullscreenCamera(info, pass);
1438 else if (pass->type == "lights")
1439 node = buildLightingLightsPass(info, pass);
1441 throw sg_exception("Pass type is not supported");
1443 return node.release();
1447 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1449 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1450 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1451 if (buffer->valid()) {
1452 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1453 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1454 buffer->sourceFormat,
1457 buffer->shadowComparison),
1458 fullscreen ? buffer->scaleFactor : 0.0f);
1460 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1466 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1467 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1469 CameraInfo* info = new CameraInfo(flags);
1470 buildBuffers(rpipe, info);
1472 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1473 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1474 buildStage(info, stage, cgroup, camera, gc);
1477 cgroup->addCamera(info);
1483 FGRenderer::setupView( void )
1485 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1486 osg::initNotifyLevel();
1488 // The number of polygon-offset "units" to place between layers. In
1489 // principle, one is supposed to be enough. In practice, I find that
1490 // my hardware/driver requires many more.
1491 osg::PolygonOffset::setUnitsMultiplier(1);
1492 osg::PolygonOffset::setFactorMultiplier(1);
1494 // Go full screen if requested ...
1495 if ( fgGetBool("/sim/startup/fullscreen") )
1499 // The sun and moon diameters are scaled down numbers of the
1500 // actual diameters. This was needed to fit both the sun and the
1501 // moon within the distance to the far clip plane.
1502 // Moon diameter: 3,476 kilometers
1503 // Sun diameter: 1,390,000 kilometers
1504 _sky->build( 80000.0, 80000.0,
1506 *globals->get_ephem(),
1507 fgGetNode("/environment", true));
1510 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1512 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1514 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1516 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1517 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1519 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1520 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1521 stateSet->setAttribute(new osg::BlendFunc);
1522 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1524 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1526 // this will be set below
1527 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1529 osg::Material* material = new osg::Material;
1530 stateSet->setAttribute(material);
1532 stateSet->setTextureAttribute(0, new osg::TexEnv);
1533 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1535 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1536 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1537 stateSet->setAttribute(hint);
1538 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1539 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1540 stateSet->setAttribute(hint);
1541 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1542 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1543 stateSet->setAttribute(hint);
1544 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1545 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1546 stateSet->setAttribute(hint);
1547 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1548 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1549 stateSet->setAttribute(hint);
1551 osg::Group* sceneGroup = new osg::Group;
1552 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1553 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1555 //sceneGroup->addChild(thesky->getCloudRoot());
1557 stateSet = sceneGroup->getOrCreateStateSet();
1558 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1560 // need to update the light on every frame
1561 // OSG LightSource objects are rather confusing. OSG only supports
1562 // the 10 lights specified by OpenGL itself; if more than one
1563 // LightSource in the scene graph have the same light number, it's
1564 // indeterminate which values will be used to render geometry that
1565 // has that light number enabled. Also, adding children to a
1566 // LightSource is just a shortcut for setting up a state set that
1567 // has the corresponding OpenGL light enabled: a LightSource will
1568 // affect geometry anywhere in the scene graph that has its light
1569 // number enabled in a state set.
1570 LightSource* lightSource = new LightSource;
1571 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1572 // relative because of CameraView being just a clever transform node
1573 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1574 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1575 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1576 mRealRoot->addChild(lightSource);
1577 // we need a white diffuse light for the phase of the moon
1578 osg::LightSource* sunLight = new osg::LightSource;
1579 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1580 sunLight->getLight()->setLightNum(1);
1581 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1582 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1583 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1585 // Hang a StateSet above the sky subgraph in order to turn off
1587 Group* skyGroup = new Group;
1588 StateSet* skySS = skyGroup->getOrCreateStateSet();
1589 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1590 skyGroup->addChild(_sky->getPreRoot());
1591 sunLight->addChild(skyGroup);
1592 mRoot->addChild(sceneGroup);
1593 if ( _classicalRenderer )
1594 mRoot->addChild(sunLight);
1596 // Clouds are added to the scene graph later
1597 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1598 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1599 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1600 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1602 // enable disable specular highlights.
1603 // is the place where we might plug in an other fragment shader ...
1604 osg::LightModel* lightModel = new osg::LightModel;
1605 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1606 stateSet->setAttribute(lightModel);
1608 // switch to enable wireframe
1609 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1610 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1611 stateSet->setAttributeAndModes(polygonMode);
1613 // scene fog handling
1614 osg::Fog* fog = new osg::Fog;
1615 fog->setUpdateCallback(new FGFogUpdateCallback);
1616 stateSet->setAttributeAndModes(fog);
1617 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1620 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1623 osg::Geode* geode = new osg::Geode;
1624 geode->addDrawable(new SGPuDrawable);
1625 geode->addDrawable(new SGHUDDrawable);
1626 guiCamera->addChild(geode);
1628 panelSwitch = new osg::Switch;
1629 osg::StateSet* stateSet = panelSwitch->getOrCreateStateSet();
1630 stateSet->setRenderBinDetails(1000, "RenderBin");
1632 // speed optimization?
1633 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
1634 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
1635 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
1636 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1637 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1640 panelSwitch->setUpdateCallback(new FGPanelSwitchCallback);
1643 guiCamera->addChild(panelSwitch.get());
1646 osg::Switch* sw = new osg::Switch;
1647 sw->setUpdateCallback(new FGScenerySwitchCallback);
1648 sw->addChild(mRoot.get());
1649 mRealRoot->addChild(sw);
1650 // The clouds are attached directly to the scene graph root
1651 // because, in theory, they don't want the same default state set
1652 // as the rest of the scene. This may not be true in practice.
1653 if ( _classicalRenderer ) {
1654 mRealRoot->addChild(_sky->getCloudRoot());
1655 mRealRoot->addChild(FGCreateRedoutNode());
1657 // Attach empty program to the scene root so that shader programs
1658 // don't leak into state sets (effects) that shouldn't have one.
1659 stateSet = mRealRoot->getOrCreateStateSet();
1660 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1662 mDeferredRealRoot->addChild( mRealRoot.get() );
1665 void FGRenderer::panelChanged()
1671 osg::Node* n = FGPanelNode::createNode(globals->get_current_panel());
1672 if (panelSwitch->getNumChildren()) {
1673 panelSwitch->setChild(0, n);
1675 panelSwitch->addChild(n);
1679 // Update all Visuals (redraws anything graphics related)
1681 FGRenderer::update( ) {
1682 if (!(_scenery_loaded->getBoolValue() ||
1683 _scenery_override->getBoolValue()))
1685 _splash_alpha->setDoubleValue(1.0);
1688 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1690 if (_splash_alpha->getDoubleValue()>0.0)
1692 // Fade out the splash screen
1693 const double fade_time = 0.5;
1694 const double fade_steps_per_sec = 10;
1695 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1696 (SGTimeStamp::now() - _splash_time).toSecs());
1697 _splash_time = SGTimeStamp::now();
1698 double sAlpha = _splash_alpha->getDoubleValue();
1699 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1700 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1701 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1704 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1705 if (!_classicalRenderer ) {
1706 _ambientFactor->set( toOsg(l->scene_ambient()) );
1707 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1708 _sunSpecular->set( toOsg(l->scene_specular()) );
1709 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1712 // update fog params
1713 double actual_visibility;
1714 if (_cloud_status->getBoolValue()) {
1715 actual_visibility = _sky->get_visibility();
1717 actual_visibility = _visibility_m->getDoubleValue();
1720 // idle_state is now 1000 meaning we've finished all our
1721 // initializations and are running the main loop, so this will
1722 // now work without seg faulting the system.
1724 FGViewer *current__view = globals->get_current_view();
1725 // Force update of center dependent values ...
1726 current__view->set_dirty();
1728 osg::Camera *camera = viewer->getCamera();
1730 bool skyblend = _skyblend->getBoolValue();
1733 if ( _textures->getBoolValue() ) {
1734 SGVec4f clearColor(l->adj_fog_color());
1735 camera->setClearColor(toOsg(clearColor));
1738 SGVec4f clearColor(l->sky_color());
1739 camera->setClearColor(toOsg(clearColor));
1742 // update fog params if visibility has changed
1743 double visibility_meters = _visibility_m->getDoubleValue();
1744 _sky->set_visibility(visibility_meters);
1746 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1747 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1749 // update the sky dome
1752 // The sun and moon distances are scaled down versions
1753 // of the actual distance to get both the moon and the sun
1754 // within the range of the far clip plane.
1755 // Moon distance: 384,467 kilometers
1756 // Sun distance: 150,000,000 kilometers
1758 double sun_horiz_eff, moon_horiz_eff;
1759 if (_horizon_effect->getBoolValue()) {
1761 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1765 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1769 sun_horiz_eff = moon_horiz_eff = 1.0;
1773 sstate.pos = current__view->getViewPosition();
1774 sstate.pos_geod = current__view->getPosition();
1775 sstate.ori = current__view->getViewOrientation();
1776 sstate.spin = l->get_sun_rotation();
1777 sstate.gst = globals->get_time_params()->getGst();
1778 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1779 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1780 sstate.sun_angle = l->get_sun_angle();
1783 scolor.sky_color = SGVec3f(l->sky_color().data());
1784 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1785 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1786 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1787 scolor.sun_angle = l->get_sun_angle();
1788 scolor.moon_angle = l->get_moon_angle();
1790 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1791 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1792 _sky->repaint( scolor, *globals->get_ephem() );
1795 // shadows->setupShadows(
1796 // current__view->getLongitude_deg(),
1797 // current__view->getLatitude_deg(),
1798 // globals->get_time_params()->getGst(),
1799 // globals->get_ephem()->getSunRightAscension(),
1800 // globals->get_ephem()->getSunDeclination(),
1801 // l->get_sun_angle());
1805 // sgEnviro.setLight(l->adj_fog_color());
1806 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1807 // current__view->get_world_up(),
1808 // current__view->getLongitude_deg(),
1809 // current__view->getLatitude_deg(),
1810 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1814 // sgEnviro.drawLightning();
1816 // double current_view_origin_airspeed_horiz_kt =
1817 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1818 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1819 // * SGD_DEGREES_TO_RADIANS);
1822 // if( is_internal )
1823 // shadows->endOfFrame();
1825 // need to call the update visitor once
1826 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1827 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1828 current__view->getViewOrientation());
1829 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1830 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1831 l->scene_diffuse(), l->scene_specular(),
1833 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1834 mUpdateVisitor->setVisibility(actual_visibility);
1835 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1836 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1837 cullMask |= simgear::GroundLightManager::instance()
1838 ->getLightNodeMask(mUpdateVisitor.get());
1839 if (_panel_hotspots->getBoolValue())
1840 cullMask |= simgear::PICK_BIT;
1841 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1842 if ( !_classicalRenderer ) {
1843 _fogColor->set( toOsg( l->adj_fog_color() ) );
1844 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1849 FGRenderer::resize( int width, int height )
1851 int curWidth = _xsize->getIntValue(),
1852 curHeight = _ysize->getIntValue();
1853 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1854 if ((curHeight != height) || (curWidth != width)) {
1855 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1856 _xsize->setIntValue(width);
1857 _ysize->setIntValue(height);
1862 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1863 const osgGA::GUIEventAdapter* ea)
1865 // wipe out the return ...
1867 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1868 Intersections intersections;
1870 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1872 for (Intersections::iterator hit = intersections.begin(),
1873 e = intersections.end();
1876 const osg::NodePath& np = hit->nodePath;
1877 osg::NodePath::const_reverse_iterator npi;
1878 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1879 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1882 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1883 SGPickCallback* pickCallback = ud->getPickCallback(i);
1886 SGSceneryPick sceneryPick;
1887 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1888 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1889 sceneryPick.callback = pickCallback;
1890 pickList.push_back(sceneryPick);
1894 return !pickList.empty();
1898 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1904 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1906 eventHandler = eventHandler_;
1910 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1912 mRealRoot->addChild(camera);
1916 FGRenderer::removeCamera(osg::Camera* camera)
1918 mRealRoot->removeChild(camera);
1922 FGRenderer::setPlanes( double zNear, double zFar )
1924 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1928 fgDumpSceneGraphToFile(const char* filename)
1930 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1934 fgDumpTerrainBranchToFile(const char* filename)
1936 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1942 fgDumpNodeToFile(osg::Node* node, const char* filename)
1944 return osgDB::writeNodeFile(*node, filename);
1947 namespace flightgear
1949 using namespace osg;
1951 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1954 VisibleSceneInfoVistor()
1955 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1957 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1958 | CullSettings::VIEW_FRUSTUM_CULLING);
1959 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1962 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1966 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1968 typedef std::map<const std::string,int> InfoMap;
1970 void getNodeInfo(Node* node)
1972 const char* typeName = typeid(*node).name();
1973 classInfo[typeName]++;
1974 const std::string& nodeName = node->getName();
1975 if (!nodeName.empty())
1976 nodeInfo[nodeName]++;
1981 using namespace std;
1982 typedef vector<InfoMap::iterator> FreqVector;
1983 cout << "class info:\n";
1985 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1988 classes.push_back(itr);
1989 sort(classes.begin(), classes.end(), freqComp);
1990 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1993 cout << (*itr)->first << " " << (*itr)->second << "\n";
1995 cout << "\nnode info:\n";
1997 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
2000 nodes.push_back(itr);
2002 sort (nodes.begin(), nodes.end(), freqComp);
2003 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
2006 cout << (*itr)->first << " " << (*itr)->second << "\n";
2011 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
2013 ref_ptr<RefMatrix> projection
2014 = createOrReuseMatrix(camera->getProjectionMatrix());
2015 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
2017 viewport = camera->getViewport();
2019 pushViewport(viewport);
2020 pushProjectionMatrix(projection.get());
2021 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
2022 root->accept(*this);
2023 popModelViewMatrix();
2024 popProjectionMatrix();
2030 void apply(Node& node)
2039 void apply(Group& node)
2049 void apply(Transform& node)
2054 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
2055 node.computeLocalToWorldMatrix(*matrix,this);
2056 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
2059 popModelViewMatrix();
2063 void apply(Camera& camera)
2065 // Save current cull settings
2066 CullSettings saved_cull_settings(*this);
2068 // set cull settings from this Camera
2069 setCullSettings(camera);
2070 // inherit the settings from above
2071 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2073 // set the cull mask.
2074 unsigned int savedTraversalMask = getTraversalMask();
2075 bool mustSetCullMask = (camera.getInheritanceMask()
2076 & osg::CullSettings::CULL_MASK) == 0;
2077 if (mustSetCullMask)
2078 setTraversalMask(camera.getCullMask());
2080 osg::RefMatrix* projection = 0;
2081 osg::RefMatrix* modelview = 0;
2083 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2084 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2085 projection = createOrReuseMatrix(*getProjectionMatrix()
2086 *camera.getProjectionMatrix());
2087 modelview = createOrReuseMatrix(*getModelViewMatrix()
2088 * camera.getViewMatrix());
2090 else { // pre multiply
2091 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2092 * (*getProjectionMatrix()));
2093 modelview = createOrReuseMatrix(camera.getViewMatrix()
2094 * (*getModelViewMatrix()));
2097 // an absolute reference frame
2098 projection = createOrReuseMatrix(camera.getProjectionMatrix());
2099 modelview = createOrReuseMatrix(camera.getViewMatrix());
2101 if (camera.getViewport())
2102 pushViewport(camera.getViewport());
2104 pushProjectionMatrix(projection);
2105 pushModelViewMatrix(modelview, camera.getReferenceFrame());
2109 // restore the previous model view matrix.
2110 popModelViewMatrix();
2112 // restore the previous model view matrix.
2113 popProjectionMatrix();
2115 if (camera.getViewport()) popViewport();
2117 // restore the previous traversal mask settings
2118 if (mustSetCullMask)
2119 setTraversalMask(savedTraversalMask);
2121 // restore the previous cull settings
2122 setCullSettings(saved_cull_settings);
2127 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2129 return lhs->second > rhs->second;
2135 bool printVisibleSceneInfo(FGRenderer* renderer)
2137 osgViewer::Viewer* viewer = renderer->getViewer();
2138 VisibleSceneInfoVistor vsv;
2140 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2141 const View::Slave& slave = viewer->getSlave(0);
2142 vp = slave._camera->getViewport();
2144 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2149 // end of renderer.cxx