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/DeletionManager.hxx>
78 #include <simgear/scene/util/SGUpdateVisitor.hxx>
79 #include <simgear/scene/util/RenderConstants.hxx>
80 #include <simgear/scene/util/SGSceneUserData.hxx>
81 #include <simgear/scene/tgdb/GroundLightManager.hxx>
82 #include <simgear/scene/tgdb/pt_lights.hxx>
83 #include <simgear/scene/tgdb/userdata.hxx>
84 #include <simgear/structure/OSGUtils.hxx>
85 #include <simgear/props/props.hxx>
86 #include <simgear/timing/sg_time.hxx>
87 #include <simgear/ephemeris/ephemeris.hxx>
88 #include <simgear/math/sg_random.h>
90 #include <Time/light.hxx>
91 #include <Time/light.hxx>
92 #include <Cockpit/panel.hxx>
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>
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"
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);
222 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
231 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
232 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
237 class FGLightSourceUpdateCallback : public osg::NodeCallback {
241 * @param isSun true if the light is the actual sun i.e., for
242 * illuminating the moon.
244 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
245 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
247 : NodeCallback(nc, op), _isSun(nc._isSun)
249 META_Object(flightgear,FGLightSourceUpdateCallback);
251 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
253 assert(dynamic_cast<osg::LightSource*>(node));
254 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
255 osg::Light* light = lightSource->getLight();
257 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
259 // lighting is down during re-init
264 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
265 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
266 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
268 light->setAmbient(toOsg(l->scene_ambient()));
269 light->setDiffuse(toOsg(l->scene_diffuse()));
270 light->setSpecular(toOsg(l->scene_specular()));
272 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
273 light->setPosition(position);
281 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
283 FGWireFrameModeUpdateCallback() :
284 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
286 virtual void operator()(osg::StateAttribute* stateAttribute,
289 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
290 osg::PolygonMode* polygonMode;
291 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
293 if (mWireframe->getBoolValue())
294 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
295 osg::PolygonMode::LINE);
297 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
298 osg::PolygonMode::FILL);
301 SGPropertyNode_ptr mWireframe;
304 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
306 FGLightModelUpdateCallback() :
307 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
309 virtual void operator()(osg::StateAttribute* stateAttribute,
312 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
313 osg::LightModel* lightModel;
314 lightModel = static_cast<osg::LightModel*>(stateAttribute);
317 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
318 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
320 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
322 lightModel->setTwoSided(true);
323 lightModel->setLocalViewer(false);
325 if (mHighlights->getBoolValue()) {
326 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
328 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
332 SGPropertyNode_ptr mHighlights;
335 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
337 FGFogEnableUpdateCallback() :
338 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
340 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
342 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
343 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
345 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
349 SGPropertyNode_ptr mFogEnabled;
352 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
354 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
356 assert(dynamic_cast<SGUpdateVisitor*>(nv));
357 assert(dynamic_cast<osg::Fog*>(sa));
358 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
359 osg::Fog* fog = static_cast<osg::Fog*>(sa);
360 fog->setMode(osg::Fog::EXP2);
361 fog->setColor(toOsg(updateVisitor->getFogColor()));
362 fog->setDensity(updateVisitor->getFogExp2Density());
366 // update callback for the switch node guarding that splash
367 class FGScenerySwitchCallback : public osg::NodeCallback {
369 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
371 assert(dynamic_cast<osg::Switch*>(node));
372 osg::Switch* sw = static_cast<osg::Switch*>(node);
374 bool enabled = scenery_enabled;
375 sw->setValue(0, enabled);
381 static bool scenery_enabled;
384 bool FGScenerySwitchCallback::scenery_enabled = false;
386 FGRenderer::FGRenderer() :
388 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
389 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
390 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
391 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
392 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
393 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
394 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
395 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
396 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
397 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
399 // it's not the real root, whatever that means
400 _root = new osg::Group;
401 _root->setName("fakeRoot");
403 _updateVisitor = new SGUpdateVisitor;
404 _root = new osg::Group;
405 _deferredRealRoot = new osg::Group;
408 _cascadeFar[0] = 5.f;
409 _cascadeFar[1] = 50.f;
410 _cascadeFar[2] = 500.f;
411 _cascadeFar[3] = 5000.f;
414 FGRenderer::~FGRenderer()
416 SGPropertyChangeListenerVec::iterator i = _listeners.begin();
417 for (; i != _listeners.end(); ++i) {
421 // replace the viewer's scene completely
423 getViewer()->setSceneData(new osg::Group);
429 // Initialize various GL/view parameters
430 // XXX This should be called "preinit" or something, as it initializes
431 // critical parts of the scene graph in addition to the splash screen.
433 FGRenderer::splashinit( void )
435 // important that we reset the viewer sceneData here, to ensure the reference
436 // time for everything is in sync; otherwise on reset the Viewer and
437 // GraphicsWindow clocks are out of sync.
438 osgViewer::Viewer* viewer = getViewer();
439 viewer->setName("osgViewer");
440 _viewerSceneRoot = new osg::Group;
441 _viewerSceneRoot->setName("viewerSceneRoot");
442 viewer->setSceneData(_viewerSceneRoot);
444 ref_ptr<Node> splashNode = fgCreateSplashNode();
445 if (_classicalRenderer) {
446 _viewerSceneRoot->addChild(splashNode.get());
448 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
449 ii != CameraGroup::getDefault()->camerasEnd();
452 CameraInfo* info = ii->get();
453 Camera* camera = info->getCamera(DISPLAY_CAMERA);
454 if (camera == 0) continue;
456 camera->addChild(splashNode.get());
460 _frameStamp = new osg::FrameStamp;
461 viewer->setFrameStamp(_frameStamp.get());
462 // Scene doesn't seem to pass the frame stamp to the update
463 // visitor automatically.
464 _updateVisitor->setFrameStamp(_frameStamp.get());
465 viewer->setUpdateVisitor(_updateVisitor.get());
466 fgSetDouble("/sim/startup/splash-alpha", 1.0);
469 class ShadowMapSizeListener : public SGPropertyChangeListener {
471 virtual void valueChanged(SGPropertyNode* node) {
472 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
476 class ShadowEnabledListener : public SGPropertyChangeListener {
478 virtual void valueChanged(SGPropertyNode* node) {
479 globals->get_renderer()->enableShadows(node->getBoolValue());
483 class ShadowNumListener : public SGPropertyChangeListener {
485 virtual void valueChanged(SGPropertyNode* node) {
486 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
490 class ShadowRangeListener : public SGPropertyChangeListener {
492 virtual void valueChanged(SGPropertyNode* node) {
493 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
498 FGRenderer::addChangeListener(SGPropertyChangeListener* l, const char* path)
500 _listeners.push_back(l);
501 fgAddChangeListener(l, path);
505 FGRenderer::init( void )
508 eventHandler = new FGEventHandler();
510 sgUserDataInit( globals->get_props() );
512 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
513 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
514 addChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
515 addChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
516 ShadowRangeListener* srl = new ShadowRangeListener;
517 addChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
518 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
519 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
520 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
521 addChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
522 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
523 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
524 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
525 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
526 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
527 updateCascadeNumber(_numCascades);
528 updateCascadeFar(0, _cascadeFar[0]);
529 updateCascadeFar(1, _cascadeFar[1]);
530 updateCascadeFar(2, _cascadeFar[2]);
531 updateCascadeFar(3, _cascadeFar[3]);
532 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
533 _depthInColor->set( _useColorForDepth );
535 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
536 if (!_classicalRenderer)
537 _pipeline = makeRenderingPipeline(_renderer, 0);
538 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
539 _position_finalized = fgGetNode("/sim/position-finalized", true);
541 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
542 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
544 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
546 _xsize = fgGetNode("/sim/startup/xsize", true);
547 _ysize = fgGetNode("/sim/startup/ysize", true);
548 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
550 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
551 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
552 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
553 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
554 _textures = fgGetNode("/sim/rendering/textures", true);
556 _altitude_ft = fgGetNode("/position/altitude-ft", true);
558 _cloud_status = fgGetNode("/environment/clouds/status", true);
559 _visibility_m = fgGetNode("/environment/visibility-m", true);
561 bool use_point_sprites = _point_sprites->getBoolValue();
562 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
563 bool distance_attenuation = _distance_attenuation->getBoolValue();
565 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
566 distance_attenuation );
568 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
569 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
570 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
571 strcmp(tc, "none") == 0) {
572 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
573 } else if (strcmp(tc, "arb") == 0) {
574 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
575 } else if (strcmp(tc, "dxt1") == 0) {
576 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
577 } else if (strcmp(tc, "dxt3") == 0) {
578 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
579 } else if (strcmp(tc, "dxt5") == 0) {
580 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
582 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
586 // create sky, but can't build until setupView, since we depend
587 // on other subsystems to be inited, eg Ephemeris
590 SGPath texture_path(globals->get_fg_root());
591 texture_path.append("Textures");
592 texture_path.append("Sky");
593 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
594 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
595 _sky->add_cloud_layer(layer);
598 _sky->texture_path( texture_path.str() );
600 if (!_classicalRenderer) {
601 eventHandler->setChangeStatsCameraRenderOrder( true );
605 void installCullVisitor(Camera* camera)
607 osgViewer::Renderer* renderer
608 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
609 for (int i = 0; i < 2; ++i) {
610 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
612 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
613 identifier = sceneView->getCullVisitor()->getIdentifier();
614 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
615 sceneView->getCullVisitor()->setIdentifier(identifier.get());
617 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
618 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
619 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
621 identifier = sceneView->getCullVisitorRight()->getIdentifier();
622 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
623 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
629 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
631 const Matrix& projection,
632 osg::GraphicsContext* gc,
633 bool useMasterSceneData)
635 CameraInfo* info = 0;
636 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
637 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
642 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
643 _classicalRenderer = true;
644 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
649 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
650 const osg::Matrix& view,
651 const osg::Matrix& projection,
652 bool useMasterSceneData)
654 CameraInfo* info = new CameraInfo(flags);
655 // The camera group will always update the camera
656 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
657 info->name = "classic";
659 Camera* farCamera = 0;
660 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
661 farCamera = new Camera;
662 farCamera->setName("farCamera");
663 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
664 farCamera->setGraphicsContext(camera->getGraphicsContext());
665 farCamera->setCullingMode(camera->getCullingMode());
666 farCamera->setInheritanceMask(camera->getInheritanceMask());
667 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
668 // Each camera's viewport is written when the window is
669 // resized; if the the viewport isn't copied here, it gets updated
670 // twice and ends up with the wrong value.
671 farCamera->setViewport(simgear::clone(camera->getViewport()));
672 farCamera->setDrawBuffer(camera->getDrawBuffer());
673 farCamera->setReadBuffer(camera->getReadBuffer());
674 farCamera->setRenderTargetImplementation(
675 camera->getRenderTargetImplementation());
676 const Camera::BufferAttachmentMap& bufferMap
677 = camera->getBufferAttachmentMap();
678 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
680 Camera::COLOR_BUFFER,
681 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
683 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
684 installCullVisitor(farCamera);
685 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
686 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
687 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
688 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
689 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
691 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
692 installCullVisitor(camera);
693 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
694 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
695 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
696 cgroup->addCamera(info);
700 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
702 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
703 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
704 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
705 osg::Camera* camera = static_cast<osg::Camera*>(n);
707 cv->clearBufferList();
708 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
709 cv->addBuffer(ii->first, ii->second.texture);
712 if ( !info->getRenderStageInfo(kind).fullscreen )
713 info->setMatrices( camera );
716 osg::Matrix projInverse;
717 info->projInverse->get( projInverse );
719 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
720 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
721 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
724 cv->traverse( *camera );
726 if ( kind == GEOMETRY_CAMERA ) {
727 // Remove transparent bins. They will be renderer in the additional light stage (side effect)
728 osgUtil::RenderStage* renderStage = cv->getRenderStage();
729 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
730 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
731 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
737 } else if ( kind == LIGHTING_CAMERA ) {
738 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
739 if (mainShadowCamera.valid()) {
740 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
741 for (int i = 0; i < 4; ++i ) {
742 if (!grp->getValue(i))
745 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
746 osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
747 cascadeCam->getViewMatrix() *
748 cascadeCam->getProjectionMatrix() *
749 osg::Matrix::translate(1.0, 1.0, 1.0) *
750 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
752 info->shadowMatrix[i]->set( shadowMatrix );
764 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
766 osg::Texture2D* tex = new osg::Texture2D;
767 tex->setResizeNonPowerOfTwoHint( false );
768 tex->setInternalFormat( internalFormat );
769 tex->setShadowComparison(shadowComparison);
770 if (shadowComparison) {
771 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
772 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
774 tex->setSourceFormat(sourceFormat);
775 tex->setSourceType(sourceType);
776 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
777 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
778 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
779 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
783 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
785 camera->attach( c, info->getBuffer(bk) );
786 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
789 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
790 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
791 if (attachment->valid())
792 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
796 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
798 osg::Camera* camera = new osg::Camera;
799 info->addCamera(name, camera );
801 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
802 camera->setName( "GeometryC" );
803 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
804 camera->setGraphicsContext( gc );
805 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
806 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
807 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
808 camera->setClearDepth( 1.0 );
809 camera->setColorMask(true, true, true, true);
810 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
811 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
812 camera->setViewport( new osg::Viewport );
813 buildAttachments(info, camera, name, attachments);
814 camera->setDrawBuffer(GL_FRONT);
815 camera->setReadBuffer(GL_FRONT);
817 osg::StateSet* ss = camera->getOrCreateStateSet();
818 ss->addUniform( _depthInColor );
820 camera->addChild( _deferredRealRoot.get() );
825 static void setShadowCascadeStateSet( osg::Camera* cam ) {
826 osg::StateSet* ss = cam->getOrCreateStateSet();
827 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
828 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
829 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
830 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
831 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
832 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
833 osg::Program* program = new osg::Program;
834 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
835 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
836 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
837 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
838 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
839 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
840 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
841 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
842 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
845 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
846 osg::Camera* cascadeCam = new osg::Camera;
847 setShadowCascadeStateSet( cascadeCam );
849 std::ostringstream oss;
850 oss << "CascadeCamera" << (no + 1);
851 cascadeCam->setName( oss.str() );
852 cascadeCam->setClearMask(0);
853 cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
854 cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
855 cascadeCam->setAllowEventFocus(false);
856 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
857 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
858 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
859 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
863 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
865 osg::Camera* mainShadowCamera = new osg::Camera;
866 info->addCamera(name, mainShadowCamera, 0.0f );
868 mainShadowCamera->setName( "ShadowC" );
869 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
870 mainShadowCamera->setClearDepth( 1.0 );
871 mainShadowCamera->setAllowEventFocus(false);
872 mainShadowCamera->setGraphicsContext(gc);
873 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
874 buildAttachments(info, mainShadowCamera, name, attachments);
875 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
876 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
877 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
878 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
879 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
880 mainShadowCamera->setDrawBuffer(GL_FRONT);
881 mainShadowCamera->setReadBuffer(GL_FRONT);
882 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
884 osg::Switch* shadowSwitch = new osg::Switch;
885 mainShadowCamera->addChild( shadowSwitch );
887 for (int i = 0; i < 4; ++i ) {
888 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
889 cascadeCam->addChild( _deferredRealRoot.get() );
890 shadowSwitch->addChild( cascadeCam );
892 if (fgGetBool("/sim/rendering/shadows/enabled", true))
893 shadowSwitch->setAllChildrenOn();
895 shadowSwitch->setAllChildrenOff();
897 return mainShadowCamera;
900 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)
902 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
903 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
904 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
906 osg::BoundingSphere bs;
907 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
908 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
909 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
910 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
912 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
914 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
915 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
916 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
919 osg::Vec3 FGRenderer::getSunDirection() const
922 _sunDirection->get( val );
926 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
928 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
929 if (mainShadowCamera.valid()) {
930 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
931 osg::Vec3d up = position,
932 dir = getSunDirection();
935 // cos(100 deg) == -0.17
936 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
937 shadowSwitch->setAllChildrenOff();
939 double left,right,bottom,top,zNear,zFar;
940 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
941 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
943 shadowSwitch->setAllChildrenOn();
944 if (_numCascades == 1) {
945 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
946 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
948 for (int no = 0; no < 4; ++no) {
949 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
950 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
953 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
954 if (_numCascades > 1) {
955 shadowSwitch->setValue(1, true);
956 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
958 shadowSwitch->setValue(1, false);
960 if (_numCascades > 2) {
961 shadowSwitch->setValue(2, true);
962 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
964 shadowSwitch->setValue(2, false);
966 if (_numCascades > 3) {
967 shadowSwitch->setValue(3, true);
968 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
970 shadowSwitch->setValue(3, false);
973 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
975 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
977 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
978 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
984 void FGRenderer::updateShadowMapSize(int mapSize)
986 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
987 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
990 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
991 ii != CameraGroup::getDefault()->camerasEnd();
994 CameraInfo* info = ii->get();
995 Camera* camera = info->getCamera(SHADOW_CAMERA);
996 if (camera == 0) continue;
998 Texture2D* tex = info->getBuffer("shadow");
999 if (tex == 0) continue;
1001 tex->setTextureSize( mapSize, mapSize );
1002 tex->dirtyTextureObject();
1004 Viewport* vp = camera->getViewport();
1005 vp->width() = mapSize;
1006 vp->height() = mapSize;
1008 osgViewer::Renderer* renderer
1009 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1010 for (int i = 0; i < 2; ++i) {
1011 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1012 sceneView->getRenderStage()->setFrameBufferObject(0);
1013 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1014 if (sceneView->getRenderStageLeft()) {
1015 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1016 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1018 if (sceneView->getRenderStageRight()) {
1019 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1020 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1024 int cascadeSize = mapSize / 2;
1025 Group* grp = camera->getChild(0)->asGroup();
1026 for (int i = 0; i < 4; ++i ) {
1027 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1028 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1031 _shadowMapSize = mapSize;
1035 void FGRenderer::enableShadows(bool enabled)
1037 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1038 ii != CameraGroup::getDefault()->camerasEnd();
1041 CameraInfo* info = ii->get();
1042 Camera* camera = info->getCamera(SHADOW_CAMERA);
1043 if (camera == 0) continue;
1045 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1047 shadowSwitch->setAllChildrenOn();
1049 shadowSwitch->setAllChildrenOff();
1053 void FGRenderer::updateCascadeFar(int index, float far_m)
1055 if (index < 0 || index > 3)
1057 _cascadeFar[index] = far_m;
1058 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1061 void FGRenderer::updateCascadeNumber(size_t num)
1063 if (num < 1 || num > 4)
1066 _shadowNumber->set( (int)_numCascades );
1069 class DebugPassListener : public SGPropertyChangeListener {
1071 DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1072 virtual void valueChanged(SGPropertyNode* node) {
1073 _switch->setValue(_index, node->getBoolValue());
1077 osg::ref_ptr<osg::Switch> _switch;
1082 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1084 osg::Camera* camera = new osg::Camera;
1085 info->addCamera(stage->name, camera );
1087 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1088 camera->setAllowEventFocus(false);
1089 camera->setGraphicsContext(gc);
1090 camera->setViewport(new Viewport);
1091 camera->setName(stage->name+"C");
1092 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1093 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1094 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1095 camera->setViewport( new osg::Viewport );
1096 buildAttachments(info, camera, stage->name, stage->attachments);
1097 camera->setDrawBuffer(GL_FRONT);
1098 camera->setReadBuffer(GL_FRONT);
1099 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1100 osg::StateSet* ss = camera->getOrCreateStateSet();
1101 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1102 ss->addUniform( _depthInColor );
1104 osg::Switch* lightingGroup = new osg::Switch;
1106 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1107 ref_ptr<Node> node = buildPass(info, pass);
1109 lightingGroup->addChild(node);
1110 if (!pass->debugProperty.empty()) {
1111 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1112 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1117 camera->addChild( lightingGroup );
1123 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1124 const osg::Matrix& view,
1125 const osg::Matrix& projection,
1126 osg::GraphicsContext* gc)
1128 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1132 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1134 osg::Camera* camera = new osg::Camera;
1136 camera->setClearMask( 0 );
1137 camera->setAllowEventFocus(false);
1138 camera->setName(pass->name+"C");
1139 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1140 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1141 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1142 camera->setViewMatrix(osg::Matrix::identity());
1143 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1145 osg::StateSet* ss = camera->getOrCreateStateSet();
1146 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1147 ss->addUniform( info->projInverse );
1148 ss->addUniform( info->viewInverse );
1149 ss->addUniform( info->view );
1150 ss->addUniform( info->bufferSize );
1151 ss->addUniform( info->worldPosCart );
1152 ss->addUniform( info->worldPosGeod );
1153 ss->addUniform( info->shadowMatrix[0] );
1154 ss->addUniform( info->shadowMatrix[1] );
1155 ss->addUniform( info->shadowMatrix[2] );
1156 ss->addUniform( info->shadowMatrix[3] );
1157 ss->addUniform( _ambientFactor );
1158 ss->addUniform( _sunDiffuse );
1159 ss->addUniform( _sunSpecular );
1160 ss->addUniform( _sunDirection );
1161 ss->addUniform( _planes );
1162 ss->addUniform( _shadowNumber );
1163 ss->addUniform( _shadowDistances );
1164 ss->addUniform( _fogColor );
1165 ss->addUniform( _fogDensity );
1167 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1168 g->setUseDisplayList(false);
1169 simgear::EffectGeode* eg = new simgear::EffectGeode;
1170 osg::ref_ptr<SGReaderWriterOptions> opt;
1171 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1172 opt->setPropertyNode(globals->get_props());
1173 simgear::Effect* effect = simgear::makeEffect(pass->effect, true, opt.get());
1175 eg->setEffect( effect );
1178 eg->setName(pass->name+"Quad");
1179 eg->setCullingActive(false);
1181 camera->addChild(eg);
1187 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1189 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1190 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1192 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1193 camera->setGraphicsContext(gc);
1194 camera->setViewport(new Viewport);
1195 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1196 buildAttachments(info, camera, stage->name, stage->attachments);
1197 camera->setDrawBuffer(GL_FRONT);
1198 camera->setReadBuffer(GL_FRONT);
1199 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1200 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1201 camera->setViewMatrix(osg::Matrix::identity());
1202 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1204 osg::StateSet* ss = camera->getOrCreateStateSet();
1205 if (stage->needsDuDv) {
1206 ss->addUniform( info->du );
1207 ss->addUniform( info->dv );
1214 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1216 camera->setName( "DisplayC" );
1217 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1218 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1219 camera->setAllowEventFocus(false);
1220 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1221 g->setUseDisplayList(false); //DEBUG
1222 simgear::EffectGeode* eg = new simgear::EffectGeode;
1223 osg::ref_ptr<SGReaderWriterOptions> opt;
1224 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1225 opt->setPropertyNode(globals->get_props());
1226 simgear::Effect* effect = simgear::makeEffect(stage->effect, true, opt.get());
1228 SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1231 eg->setEffect(effect);
1232 eg->setCullingActive(false);
1234 camera->setViewMatrix(osg::Matrix::identity());
1235 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1236 camera->addChild(eg);
1238 osg::StateSet* ss = camera->getOrCreateStateSet();
1239 ss->addUniform( _depthInColor );
1240 ss->addUniform( info->projInverse );
1241 ss->addUniform( info->viewInverse );
1242 ss->addUniform( info->view );
1243 ss->addUniform( info->bufferSize );
1244 ss->addUniform( info->worldPosCart );
1245 ss->addUniform( info->worldPosGeod );
1246 ss->addUniform( info->shadowMatrix[0] );
1247 ss->addUniform( info->shadowMatrix[1] );
1248 ss->addUniform( info->shadowMatrix[2] );
1249 ss->addUniform( info->shadowMatrix[3] );
1250 ss->addUniform( _ambientFactor );
1251 ss->addUniform( _sunDiffuse );
1252 ss->addUniform( _sunSpecular );
1253 ss->addUniform( _sunDirection );
1254 ss->addUniform( _planes );
1255 ss->addUniform( _shadowNumber );
1256 ss->addUniform( _shadowDistances );
1257 ss->addUniform( _fogColor );
1258 ss->addUniform( _fogDensity );
1262 FGRenderer::buildStage(CameraInfo* info,
1263 FGRenderingPipeline::Stage* stage,
1264 CameraGroup* cgroup,
1265 osg::Camera* mainCamera,
1266 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1268 if (!stage->valid())
1271 ref_ptr<Camera> camera;
1272 bool needOffsets = false;
1273 if (stage->type == "geometry") {
1274 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1276 } else if (stage->type == "lighting") {
1277 camera = buildDeferredLightingCamera(info, gc, stage);
1279 } else if (stage->type == "shadow")
1280 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1281 else if (stage->type == "fullscreen")
1282 camera = buildDeferredFullscreenCamera(info, gc, stage);
1283 else if (stage->type == "display") {
1284 camera = mainCamera;
1285 buildDeferredDisplayCamera(camera, info, stage, gc);
1287 throw sg_exception("Stage type is not supported");
1290 cgroup->getViewer()->addSlave(camera, projection, view, false);
1292 cgroup->getViewer()->addSlave(camera, false);
1293 installCullVisitor(camera);
1294 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1295 if (stage->type == "display")
1296 info->addCamera( stage->type, camera, slaveIndex, true );
1297 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1301 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1303 Group* group = new Group;
1304 group->setName("skyCloudsGroup");
1305 group->setNodeMask(simgear::BACKGROUND_BIT);
1307 StateSet* ss = group->getOrCreateStateSet();
1308 ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1309 group->addChild( _sky->getPreRoot() );
1310 group->addChild( _sky->getCloudRoot() );
1315 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1317 osg::Camera* lightCam = new osg::Camera;
1318 StateSet* ss = lightCam->getOrCreateStateSet();
1319 ss->addUniform( _planes );
1320 ss->addUniform( info->bufferSize );
1321 ss->addUniform( _fogColor );
1322 ss->addUniform( _fogDensity );
1323 lightCam->setName( "LightCamera" );
1324 lightCam->setClearMask(0);
1325 lightCam->setAllowEventFocus(false);
1326 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1327 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1328 lightCam->setViewMatrix(osg::Matrix::identity());
1329 lightCam->setProjectionMatrix(osg::Matrix::identity());
1330 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1331 lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1332 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1333 lightCam->addChild( _deferredRealRoot.get() );
1339 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1345 if (pass->type == "sky-clouds")
1346 node = buildLightingSkyCloudsPass(pass);
1347 else if (pass->type == "fullscreen")
1348 node = buildDeferredFullscreenCamera(info, pass);
1349 else if (pass->type == "lights")
1350 node = buildLightingLightsPass(info, pass);
1352 throw sg_exception("Pass type is not supported");
1354 return node.release();
1358 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1360 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1361 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1362 if (buffer->valid()) {
1363 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1364 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1365 buffer->sourceFormat,
1368 buffer->shadowComparison),
1369 fullscreen ? buffer->scaleFactor : 0.0f);
1371 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1377 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1378 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1380 CameraInfo* info = new CameraInfo(flags);
1381 buildBuffers(rpipe, info);
1383 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1384 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1385 buildStage(info, stage, cgroup, camera, view, projection, gc);
1388 cgroup->addCamera(info);
1394 FGRenderer::setupView( void )
1396 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1397 osg::initNotifyLevel();
1399 // The number of polygon-offset "units" to place between layers. In
1400 // principle, one is supposed to be enough. In practice, I find that
1401 // my hardware/driver requires many more.
1402 osg::PolygonOffset::setUnitsMultiplier(1);
1403 osg::PolygonOffset::setFactorMultiplier(1);
1406 // The sun and moon diameters are scaled down numbers of the
1407 // actual diameters. This was needed to fit both the sun and the
1408 // moon within the distance to the far clip plane.
1409 // Moon diameter: 3,476 kilometers
1410 // Sun diameter: 1,390,000 kilometers
1411 osg::ref_ptr<SGReaderWriterOptions> opt;
1412 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1413 opt->setPropertyNode(globals->get_props());
1414 _sky->build( 80000.0, 80000.0,
1416 *globals->get_ephem(),
1417 fgGetNode("/environment", true),
1421 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1423 osg::StateSet* stateSet = _root->getOrCreateStateSet();
1425 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1427 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1428 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1430 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1431 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1432 stateSet->setAttribute(new osg::BlendFunc);
1433 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1435 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1437 // this will be set below
1438 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1440 osg::Material* material = new osg::Material;
1441 stateSet->setAttribute(material);
1443 stateSet->setTextureAttribute(0, new osg::TexEnv);
1444 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1446 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1447 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1448 stateSet->setAttribute(hint);
1449 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1450 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1451 stateSet->setAttribute(hint);
1452 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1453 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1454 stateSet->setAttribute(hint);
1455 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1456 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1457 stateSet->setAttribute(hint);
1458 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1459 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1460 stateSet->setAttribute(hint);
1462 osg::Group* sceneGroup = new osg::Group;
1463 sceneGroup->setName("rendererScene");
1464 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1465 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1467 //sceneGroup->addChild(thesky->getCloudRoot());
1469 stateSet = sceneGroup->getOrCreateStateSet();
1470 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1472 // need to update the light on every frame
1473 // OSG LightSource objects are rather confusing. OSG only supports
1474 // the 10 lights specified by OpenGL itself; if more than one
1475 // LightSource in the scene graph have the same light number, it's
1476 // indeterminate which values will be used to render geometry that
1477 // has that light number enabled. Also, adding children to a
1478 // LightSource is just a shortcut for setting up a state set that
1479 // has the corresponding OpenGL light enabled: a LightSource will
1480 // affect geometry anywhere in the scene graph that has its light
1481 // number enabled in a state set.
1482 LightSource* lightSource = new LightSource;
1483 lightSource->setName("FGLightSource");
1484 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1485 // relative because of CameraView being just a clever transform node
1486 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1487 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1488 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1489 _viewerSceneRoot->addChild(lightSource);
1491 // we need a white diffuse light for the phase of the moon
1492 osg::LightSource* sunLight = new osg::LightSource;
1493 sunLight->setName("sunLightSource");
1494 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1495 sunLight->getLight()->setLightNum(1);
1496 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1497 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1498 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1500 // Hang a StateSet above the sky subgraph in order to turn off
1502 Group* skyGroup = new Group;
1503 skyGroup->setName("rendererSkyParent");
1504 StateSet* skySS = skyGroup->getOrCreateStateSet();
1505 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1506 skyGroup->addChild(_sky->getPreRoot());
1507 sunLight->addChild(skyGroup);
1509 _root->addChild(sceneGroup);
1510 if ( _classicalRenderer )
1511 _root->addChild(sunLight);
1513 // Clouds are added to the scene graph later
1514 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1515 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1516 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1517 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1519 // enable disable specular highlights.
1520 // is the place where we might plug in an other fragment shader ...
1521 osg::LightModel* lightModel = new osg::LightModel;
1522 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1523 stateSet->setAttribute(lightModel);
1525 // switch to enable wireframe
1526 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1527 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1528 stateSet->setAttributeAndModes(polygonMode);
1530 // scene fog handling
1531 osg::Fog* fog = new osg::Fog;
1532 fog->setUpdateCallback(new FGFogUpdateCallback);
1533 stateSet->setAttributeAndModes(fog);
1534 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1537 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1540 osg::Geode* geode = new osg::Geode;
1541 geode->addDrawable(new SGPuDrawable);
1542 geode->addDrawable(new SGHUDDrawable);
1543 guiCamera->addChild(geode);
1546 guiCamera->addChild(FGPanelNode::create2DPanelNode());
1549 osg::Switch* sw = new osg::Switch;
1550 sw->setName("scenerySwitch");
1551 sw->setUpdateCallback(new FGScenerySwitchCallback);
1552 sw->addChild(_root.get());
1553 _viewerSceneRoot->addChild(sw);
1554 // The clouds are attached directly to the scene graph root
1555 // because, in theory, they don't want the same default state set
1556 // as the rest of the scene. This may not be true in practice.
1557 if ( _classicalRenderer ) {
1558 _viewerSceneRoot->addChild(_sky->getCloudRoot());
1559 _viewerSceneRoot->addChild(FGCreateRedoutNode());
1561 // Attach empty program to the scene root so that shader programs
1562 // don't leak into state sets (effects) that shouldn't have one.
1563 stateSet = _viewerSceneRoot->getOrCreateStateSet();
1564 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1566 if ( !_classicalRenderer ) {
1567 _deferredRealRoot->addChild( _viewerSceneRoot.get() );
1571 // Update all Visuals (redraws anything graphics related)
1573 FGRenderer::update( ) {
1574 if (!_position_finalized || !_scenery_loaded->getBoolValue())
1576 _splash_alpha->setDoubleValue(1.0);
1579 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1581 if (_splash_alpha->getDoubleValue()>0.0)
1583 // Fade out the splash screen
1584 const double fade_time = 0.5;
1585 const double fade_steps_per_sec = 10;
1586 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1587 (SGTimeStamp::now() - _splash_time).toSecs());
1588 _splash_time = SGTimeStamp::now();
1589 double sAlpha = _splash_alpha->getDoubleValue();
1590 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1591 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1592 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1595 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1596 if (!_classicalRenderer ) {
1597 _ambientFactor->set( toOsg(l->scene_ambient()) );
1598 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1599 _sunSpecular->set( toOsg(l->scene_specular()) );
1600 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1603 // update fog params
1604 double actual_visibility;
1605 if (_cloud_status->getBoolValue()) {
1606 actual_visibility = _sky->get_visibility();
1608 actual_visibility = _visibility_m->getDoubleValue();
1611 // idle_state is now 1000 meaning we've finished all our
1612 // initializations and are running the main loop, so this will
1613 // now work without seg faulting the system.
1615 FGViewer *current__view = globals->get_current_view();
1616 // Force update of center dependent values ...
1617 current__view->set_dirty();
1619 osg::Camera *camera = viewer->getCamera();
1621 if ( _textures->getBoolValue() ) {
1622 SGVec4f clearColor(l->adj_fog_color());
1623 camera->setClearColor(toOsg(clearColor));
1628 // need to call the update visitor once
1629 _frameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1630 _updateVisitor->setViewData(current__view->getViewPosition(),
1631 current__view->getViewOrientation());
1632 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1633 _updateVisitor->setLight(direction, l->scene_ambient(),
1634 l->scene_diffuse(), l->scene_specular(),
1636 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1637 _updateVisitor->setVisibility(actual_visibility);
1638 simgear::GroundLightManager::instance()->update(_updateVisitor.get());
1639 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1640 cullMask |= simgear::GroundLightManager::instance()
1641 ->getLightNodeMask(_updateVisitor.get());
1642 if (_panel_hotspots->getBoolValue())
1643 cullMask |= simgear::PICK_BIT;
1644 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1645 if ( !_classicalRenderer ) {
1646 _fogColor->set( toOsg( l->adj_fog_color() ) );
1647 _fogDensity->set( float( _updateVisitor->getFogExp2Density() ) );
1652 FGRenderer::updateSky()
1654 // update fog params if visibility has changed
1655 double visibility_meters = _visibility_m->getDoubleValue();
1656 _sky->set_visibility(visibility_meters);
1658 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1659 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1661 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1663 // The sun and moon distances are scaled down versions
1664 // of the actual distance to get both the moon and the sun
1665 // within the range of the far clip plane.
1666 // Moon distance: 384,467 kilometers
1667 // Sun distance: 150,000,000 kilometers
1669 double sun_horiz_eff, moon_horiz_eff;
1670 if (_horizon_effect->getBoolValue()) {
1672 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1676 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1680 sun_horiz_eff = moon_horiz_eff = 1.0;
1684 sstate.pos = globals->get_current_view()->getViewPosition();
1685 sstate.pos_geod = globals->get_current_view()->getPosition();
1686 sstate.ori = globals->get_current_view()->getViewOrientation();
1687 sstate.spin = l->get_sun_rotation();
1688 sstate.gst = globals->get_time_params()->getGst();
1689 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1690 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1691 sstate.sun_angle = l->get_sun_angle();
1694 scolor.sky_color = SGVec3f(l->sky_color().data());
1695 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1696 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1697 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1698 scolor.sun_angle = l->get_sun_angle();
1699 scolor.moon_angle = l->get_moon_angle();
1701 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1702 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1703 _sky->repaint( scolor, *globals->get_ephem() );
1707 FGRenderer::resize( int width, int height )
1709 int curWidth = _xsize->getIntValue(),
1710 curHeight = _ysize->getIntValue();
1711 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1712 if ((curHeight != height) || (curWidth != width)) {
1713 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1714 _xsize->setIntValue(width);
1715 _ysize->setIntValue(height);
1719 typedef osgUtil::LineSegmentIntersector::Intersection Intersection;
1720 SGVec2d uvFromIntersection(const Intersection& hit)
1722 // Taken from http://trac.openscenegraph.org/projects/osg/browser/OpenSceneGraph/trunk/examples/osgmovie/osgmovie.cpp
1724 osg::Drawable* drawable = hit.drawable.get();
1725 osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
1726 osg::Vec3Array* vertices =
1727 geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
1731 SG_LOG(SG_INPUT, SG_WARN, "Unable to get vertices for intersection.");
1732 return SGVec2d(-9999,-9999);
1735 // get the vertex indices.
1736 const Intersection::IndexList& indices = hit.indexList;
1737 const Intersection::RatioList& ratios = hit.ratioList;
1739 if( indices.size() != 3 || ratios.size() != 3 )
1743 "Intersection has insufficient indices to work with." );
1744 return SGVec2d(-9999,-9999);
1747 unsigned int i1 = indices[0];
1748 unsigned int i2 = indices[1];
1749 unsigned int i3 = indices[2];
1751 float r1 = ratios[0];
1752 float r2 = ratios[1];
1753 float r3 = ratios[2];
1755 osg::Array* texcoords =
1756 (geometry->getNumTexCoordArrays() > 0) ? geometry->getTexCoordArray(0) : 0;
1757 osg::Vec2Array* texcoords_Vec2Array =
1758 dynamic_cast<osg::Vec2Array*>(texcoords);
1760 if( !texcoords_Vec2Array )
1762 SG_LOG(SG_INPUT, SG_WARN, "Unable to get texcoords for intersection.");
1763 return SGVec2d(-9999,-9999);
1766 // we have tex coord array so now we can compute the final tex coord at the
1767 // point of intersection.
1768 osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
1769 osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
1770 osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
1772 return toSG( osg::Vec2d(tc1 * r1 + tc2 * r2 + tc3 * r3) );
1776 FGRenderer::pick(std::vector<SGSceneryPick>& pickList, const osg::Vec2& windowPos)
1778 // wipe out the return ...
1780 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1781 Intersections intersections;
1783 if (!computeIntersections(CameraGroup::getDefault(), windowPos, intersections))
1785 for (Intersections::iterator hit = intersections.begin(),
1786 e = intersections.end();
1789 const osg::NodePath& np = hit->nodePath;
1790 osg::NodePath::const_reverse_iterator npi;
1792 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1793 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1794 if (!ud || (ud->getNumPickCallbacks() == 0))
1797 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1798 SGPickCallback* pickCallback = ud->getPickCallback(i);
1801 SGSceneryPick sceneryPick;
1802 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1803 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1805 if( pickCallback->needsUV() )
1806 sceneryPick.info.uv = uvFromIntersection(*hit);
1808 sceneryPick.callback = pickCallback;
1809 pickList.push_back(sceneryPick);
1810 } // of installed pick callbacks iteration
1811 } // of reverse node path walk
1814 return !pickList.empty();
1818 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1824 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1826 eventHandler = eventHandler_;
1830 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1832 _viewerSceneRoot->addChild(camera);
1836 FGRenderer::removeCamera(osg::Camera* camera)
1838 _viewerSceneRoot->removeChild(camera);
1842 FGRenderer::setPlanes( double zNear, double zFar )
1844 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1848 fgDumpSceneGraphToFile(const char* filename)
1850 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1851 return osgDB::writeNodeFile(*viewer->getSceneData(), filename);
1855 fgDumpTerrainBranchToFile(const char* filename)
1857 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1863 fgDumpNodeToFile(osg::Node* node, const char* filename)
1865 return osgDB::writeNodeFile(*node, filename);
1868 namespace flightgear
1870 using namespace osg;
1872 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1875 VisibleSceneInfoVistor()
1876 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1878 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1879 | CullSettings::VIEW_FRUSTUM_CULLING);
1880 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1883 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1887 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1889 typedef std::map<const std::string,int> InfoMap;
1891 void getNodeInfo(Node* node)
1893 const char* typeName = typeid(*node).name();
1894 classInfo[typeName]++;
1895 const std::string& nodeName = node->getName();
1896 if (!nodeName.empty())
1897 nodeInfo[nodeName]++;
1902 using namespace std;
1903 typedef vector<InfoMap::iterator> FreqVector;
1904 cout << "class info:\n";
1906 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1909 classes.push_back(itr);
1910 sort(classes.begin(), classes.end(), freqComp);
1911 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1914 cout << (*itr)->first << " " << (*itr)->second << "\n";
1916 cout << "\nnode info:\n";
1918 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1921 nodes.push_back(itr);
1923 sort (nodes.begin(), nodes.end(), freqComp);
1924 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1927 cout << (*itr)->first << " " << (*itr)->second << "\n";
1932 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1934 ref_ptr<RefMatrix> projection
1935 = createOrReuseMatrix(camera->getProjectionMatrix());
1936 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1938 viewport = camera->getViewport();
1940 pushViewport(viewport);
1941 pushProjectionMatrix(projection.get());
1942 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1943 root->accept(*this);
1944 popModelViewMatrix();
1945 popProjectionMatrix();
1951 void apply(Node& node)
1960 void apply(Group& node)
1970 void apply(Transform& node)
1975 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1976 node.computeLocalToWorldMatrix(*matrix,this);
1977 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1980 popModelViewMatrix();
1984 void apply(Camera& camera)
1986 // Save current cull settings
1987 CullSettings saved_cull_settings(*this);
1989 // set cull settings from this Camera
1990 setCullSettings(camera);
1991 // inherit the settings from above
1992 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1994 // set the cull mask.
1995 unsigned int savedTraversalMask = getTraversalMask();
1996 bool mustSetCullMask = (camera.getInheritanceMask()
1997 & osg::CullSettings::CULL_MASK) == 0;
1998 if (mustSetCullMask)
1999 setTraversalMask(camera.getCullMask());
2001 osg::RefMatrix* projection = 0;
2002 osg::RefMatrix* modelview = 0;
2004 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2005 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2006 projection = createOrReuseMatrix(*getProjectionMatrix()
2007 *camera.getProjectionMatrix());
2008 modelview = createOrReuseMatrix(*getModelViewMatrix()
2009 * camera.getViewMatrix());
2011 else { // pre multiply
2012 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2013 * (*getProjectionMatrix()));
2014 modelview = createOrReuseMatrix(camera.getViewMatrix()
2015 * (*getModelViewMatrix()));
2018 // an absolute reference frame
2019 projection = createOrReuseMatrix(camera.getProjectionMatrix());
2020 modelview = createOrReuseMatrix(camera.getViewMatrix());
2022 if (camera.getViewport())
2023 pushViewport(camera.getViewport());
2025 pushProjectionMatrix(projection);
2026 pushModelViewMatrix(modelview, camera.getReferenceFrame());
2030 // restore the previous model view matrix.
2031 popModelViewMatrix();
2033 // restore the previous model view matrix.
2034 popProjectionMatrix();
2036 if (camera.getViewport()) popViewport();
2038 // restore the previous traversal mask settings
2039 if (mustSetCullMask)
2040 setTraversalMask(savedTraversalMask);
2042 // restore the previous cull settings
2043 setCullSettings(saved_cull_settings);
2048 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2050 return lhs->second > rhs->second;
2056 bool printVisibleSceneInfo(FGRenderer* renderer)
2058 osgViewer::Viewer* viewer = renderer->getViewer();
2059 VisibleSceneInfoVistor vsv;
2061 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2062 const View::Slave& slave = viewer->getSlave(0);
2063 vp = slave._camera->getViewport();
2065 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2070 // end of renderer.cxx