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 #ifdef FG_JPEG_SERVER
387 static void updateRenderer()
389 globals->get_renderer()->update();
393 FGRenderer::FGRenderer() :
395 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
396 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
397 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
398 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
399 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
400 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
401 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
402 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
403 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
404 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
406 #ifdef FG_JPEG_SERVER
407 jpgRenderFrame = updateRenderer;
409 eventHandler = new FGEventHandler;
412 _cascadeFar[0] = 5.f;
413 _cascadeFar[1] = 50.f;
414 _cascadeFar[2] = 500.f;
415 _cascadeFar[3] = 5000.f;
418 FGRenderer::~FGRenderer()
420 #ifdef FG_JPEG_SERVER
421 jpgRenderFrame = NULL;
426 // Initialize various GL/view parameters
427 // XXX This should be called "preinit" or something, as it initializes
428 // critical parts of the scene graph in addition to the splash screen.
430 FGRenderer::splashinit( void ) {
431 osgViewer::Viewer* viewer = getViewer();
432 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
433 ref_ptr<Node> splashNode = fgCreateSplashNode();
434 if (_classicalRenderer) {
435 mRealRoot->addChild(splashNode.get());
437 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
438 ii != CameraGroup::getDefault()->camerasEnd();
441 CameraInfo* info = ii->get();
442 Camera* camera = info->getCamera(DISPLAY_CAMERA);
443 if (camera == 0) continue;
445 camera->addChild(splashNode.get());
448 mFrameStamp = viewer->getFrameStamp();
449 // Scene doesn't seem to pass the frame stamp to the update
450 // visitor automatically.
451 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
452 viewer->setUpdateVisitor(mUpdateVisitor.get());
453 fgSetDouble("/sim/startup/splash-alpha", 1.0);
456 class ShadowMapSizeListener : public SGPropertyChangeListener {
458 virtual void valueChanged(SGPropertyNode* node) {
459 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
463 class ShadowEnabledListener : public SGPropertyChangeListener {
465 virtual void valueChanged(SGPropertyNode* node) {
466 globals->get_renderer()->enableShadows(node->getBoolValue());
470 class ShadowNumListener : public SGPropertyChangeListener {
472 virtual void valueChanged(SGPropertyNode* node) {
473 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
477 class ShadowRangeListener : public SGPropertyChangeListener {
479 virtual void valueChanged(SGPropertyNode* node) {
480 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
485 FGRenderer::init( void )
487 sgUserDataInit( globals->get_props() );
489 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
490 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
491 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
492 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
493 ShadowRangeListener* srl = new ShadowRangeListener;
494 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
495 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
496 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
497 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
498 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
499 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
500 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
501 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
502 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
503 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
504 updateCascadeNumber(_numCascades);
505 updateCascadeFar(0, _cascadeFar[0]);
506 updateCascadeFar(1, _cascadeFar[1]);
507 updateCascadeFar(2, _cascadeFar[2]);
508 updateCascadeFar(3, _cascadeFar[3]);
509 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
510 _depthInColor->set( _useColorForDepth );
512 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
513 if (!_classicalRenderer)
514 _pipeline = makeRenderingPipeline(_renderer, 0);
515 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
516 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
517 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
518 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
520 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
522 _xsize = fgGetNode("/sim/startup/xsize", true);
523 _ysize = fgGetNode("/sim/startup/ysize", true);
524 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
526 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
527 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
528 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
529 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
530 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
531 _textures = fgGetNode("/sim/rendering/textures", true);
533 _altitude_ft = fgGetNode("/position/altitude-ft", true);
535 _cloud_status = fgGetNode("/environment/clouds/status", true);
536 _visibility_m = fgGetNode("/environment/visibility-m", true);
538 bool use_point_sprites = _point_sprites->getBoolValue();
539 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
540 bool distance_attenuation = _distance_attenuation->getBoolValue();
542 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
543 distance_attenuation );
545 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
546 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
547 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
548 strcmp(tc, "none") == 0) {
549 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
550 } else if (strcmp(tc, "arb") == 0) {
551 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
552 } else if (strcmp(tc, "dxt1") == 0) {
553 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
554 } else if (strcmp(tc, "dxt3") == 0) {
555 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
556 } else if (strcmp(tc, "dxt5") == 0) {
557 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
559 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
563 // create sky, but can't build until setupView, since we depend
564 // on other subsystems to be inited, eg Ephemeris
567 SGPath texture_path(globals->get_fg_root());
568 texture_path.append("Textures");
569 texture_path.append("Sky");
570 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
571 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
572 _sky->add_cloud_layer(layer);
575 _sky->texture_path( texture_path.str() );
577 if (!_classicalRenderer) {
578 eventHandler->setChangeStatsCameraRenderOrder( true );
582 void installCullVisitor(Camera* camera)
584 osgViewer::Renderer* renderer
585 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
586 for (int i = 0; i < 2; ++i) {
587 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
588 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
589 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
591 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
592 identifier = sceneView->getCullVisitor()->getIdentifier();
593 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
594 sceneView->getCullVisitor()->setIdentifier(identifier.get());
596 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
597 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
598 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
600 identifier = sceneView->getCullVisitorRight()->getIdentifier();
601 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
602 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
608 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
610 const Matrix& projection,
611 osg::GraphicsContext* gc,
612 bool useMasterSceneData)
614 CameraInfo* info = 0;
615 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
616 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
621 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
622 _classicalRenderer = true;
623 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
628 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
629 const osg::Matrix& view,
630 const osg::Matrix& projection,
631 bool useMasterSceneData)
633 CameraInfo* info = new CameraInfo(flags);
634 // The camera group will always update the camera
635 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
637 Camera* farCamera = 0;
638 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
639 farCamera = new Camera;
640 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
641 farCamera->setGraphicsContext(camera->getGraphicsContext());
642 farCamera->setCullingMode(camera->getCullingMode());
643 farCamera->setInheritanceMask(camera->getInheritanceMask());
644 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
645 // Each camera's viewport is written when the window is
646 // resized; if the the viewport isn't copied here, it gets updated
647 // twice and ends up with the wrong value.
648 farCamera->setViewport(simgear::clone(camera->getViewport()));
649 farCamera->setDrawBuffer(camera->getDrawBuffer());
650 farCamera->setReadBuffer(camera->getReadBuffer());
651 farCamera->setRenderTargetImplementation(
652 camera->getRenderTargetImplementation());
653 const Camera::BufferAttachmentMap& bufferMap
654 = camera->getBufferAttachmentMap();
655 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
657 Camera::COLOR_BUFFER,
658 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
660 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
661 installCullVisitor(farCamera);
662 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
663 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
664 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
665 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
666 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
668 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
669 installCullVisitor(camera);
670 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
671 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
672 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
673 cgroup->addCamera(info);
677 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
679 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
680 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
681 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
682 osg::Camera* camera = static_cast<osg::Camera*>(n);
684 cv->clearBufferList();
685 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
686 cv->addBuffer(ii->first, ii->second.texture);
689 if ( !info->getRenderStageInfo(kind).fullscreen )
690 info->setMatrices( camera );
693 osg::Matrix projInverse;
694 info->projInverse->get( projInverse );
696 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
697 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
698 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
701 cv->traverse( *camera );
703 if ( kind == GEOMETRY_CAMERA ) {
704 // Save transparent bins to render later
705 osgUtil::RenderStage* renderStage = cv->getRenderStage();
706 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
707 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
708 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
709 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
715 } else if ( kind == LIGHTING_CAMERA ) {
716 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
717 if (mainShadowCamera.valid()) {
718 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
719 for (int i = 0; i < 4; ++i ) {
720 if (!grp->getValue(i))
722 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
723 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
725 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
726 // compute the matrix which takes a vertex from view coords into tex coords
727 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
728 osg::Matrix::translate(1.0,1.0,1.0) *
729 osg::Matrix::scale(0.5f,0.5f,0.5f) );
731 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
733 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
736 // Render saved transparent render bins
737 osgUtil::RenderStage* renderStage = cv->getRenderStage();
738 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
739 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
740 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
742 info->savedTransparentBins.clear();
752 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
754 osg::Texture2D* tex = new osg::Texture2D;
755 tex->setResizeNonPowerOfTwoHint( false );
756 tex->setInternalFormat( internalFormat );
757 tex->setShadowComparison(shadowComparison);
758 if (shadowComparison) {
759 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
760 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
762 tex->setSourceFormat(sourceFormat);
763 tex->setSourceType(sourceType);
764 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
765 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
766 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
767 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
771 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
773 camera->attach( c, info->getBuffer(bk) );
774 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
777 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
778 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
779 if (attachment->valid())
780 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
784 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
786 osg::Camera* camera = new osg::Camera;
787 info->addCamera(name, camera );
789 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
790 camera->setName( "GeometryC" );
791 camera->setGraphicsContext( gc );
792 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
793 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
794 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
795 camera->setClearDepth( 1.0 );
796 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
797 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
798 camera->setViewport( new osg::Viewport );
799 buildAttachments(info, camera, name, attachments);
800 camera->setDrawBuffer(GL_FRONT);
801 camera->setReadBuffer(GL_FRONT);
803 osg::StateSet* ss = camera->getOrCreateStateSet();
804 ss->addUniform( _depthInColor );
806 camera->addChild( mDeferredRealRoot.get() );
811 static void setShadowCascadeStateSet( osg::Camera* cam ) {
812 osg::StateSet* ss = cam->getOrCreateStateSet();
813 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
814 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
815 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
816 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
817 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
818 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
819 osg::Program* program = new osg::Program;
820 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
821 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
822 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
823 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
824 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
825 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
826 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
827 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
828 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
831 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
832 osg::Camera* cascadeCam = new osg::Camera;
833 setShadowCascadeStateSet( cascadeCam );
835 std::ostringstream oss;
836 oss << "CascadeCamera" << (no + 1);
837 cascadeCam->setName( oss.str() );
838 cascadeCam->setClearMask(0);
839 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
840 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
841 cascadeCam->setAllowEventFocus(false);
842 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
843 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
844 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
845 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
849 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
851 osg::Camera* mainShadowCamera = new osg::Camera;
852 info->addCamera(name, mainShadowCamera, 0.0f );
854 mainShadowCamera->setName( "ShadowC" );
855 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
856 mainShadowCamera->setClearDepth( 1.0 );
857 mainShadowCamera->setAllowEventFocus(false);
858 mainShadowCamera->setGraphicsContext(gc);
859 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
860 buildAttachments(info, mainShadowCamera, name, attachments);
861 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
862 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
863 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
864 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
865 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
866 mainShadowCamera->setDrawBuffer(GL_FRONT);
867 mainShadowCamera->setReadBuffer(GL_FRONT);
868 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
870 osg::Switch* shadowSwitch = new osg::Switch;
871 mainShadowCamera->addChild( shadowSwitch );
873 for (int i = 0; i < 4; ++i ) {
874 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
875 cascadeCam->addChild( mDeferredRealRoot.get() );
876 shadowSwitch->addChild( cascadeCam );
877 info->shadowTexGen[i] = new osg::TexGen;
879 if (fgGetBool("/sim/rendering/shadows/enabled", true))
880 shadowSwitch->setAllChildrenOn();
882 shadowSwitch->setAllChildrenOff();
884 return mainShadowCamera;
887 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)
889 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
890 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
891 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
893 osg::BoundingSphere bs;
894 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
895 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
896 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
897 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
899 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
901 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
902 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
903 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
906 osg::Vec3 FGRenderer::getSunDirection() const
909 _sunDirection->get( val );
913 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
915 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
916 if (mainShadowCamera.valid()) {
917 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
918 osg::Vec3d up = position,
919 dir = getSunDirection();
922 // cos(100 deg) == -0.17
923 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
924 shadowSwitch->setAllChildrenOff();
926 double left,right,bottom,top,zNear,zFar;
927 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
928 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
930 shadowSwitch->setAllChildrenOn();
931 if (_numCascades == 1) {
932 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
933 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
935 for (int no = 0; no < 4; ++no) {
936 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
937 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
940 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
941 if (_numCascades > 1) {
942 shadowSwitch->setValue(1, true);
943 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
945 shadowSwitch->setValue(1, false);
947 if (_numCascades > 2) {
948 shadowSwitch->setValue(2, true);
949 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
951 shadowSwitch->setValue(2, false);
953 if (_numCascades > 3) {
954 shadowSwitch->setValue(3, true);
955 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
957 shadowSwitch->setValue(3, false);
960 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
962 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
964 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
965 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
971 void FGRenderer::updateShadowMapSize(int mapSize)
973 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
974 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
977 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
978 ii != CameraGroup::getDefault()->camerasEnd();
981 CameraInfo* info = ii->get();
982 Camera* camera = info->getCamera(SHADOW_CAMERA);
983 if (camera == 0) continue;
985 Texture2D* tex = info->getBuffer("shadow");
986 if (tex == 0) continue;
988 tex->setTextureSize( mapSize, mapSize );
989 tex->dirtyTextureObject();
991 Viewport* vp = camera->getViewport();
992 vp->width() = mapSize;
993 vp->height() = mapSize;
995 osgViewer::Renderer* renderer
996 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
997 for (int i = 0; i < 2; ++i) {
998 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
999 sceneView->getRenderStage()->setFrameBufferObject(0);
1000 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1001 if (sceneView->getRenderStageLeft()) {
1002 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1003 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1005 if (sceneView->getRenderStageRight()) {
1006 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1007 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1011 int cascadeSize = mapSize / 2;
1012 Group* grp = camera->getChild(0)->asGroup();
1013 for (int i = 0; i < 4; ++i ) {
1014 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1015 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1018 _shadowMapSize = mapSize;
1022 void FGRenderer::enableShadows(bool enabled)
1024 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1025 ii != CameraGroup::getDefault()->camerasEnd();
1028 CameraInfo* info = ii->get();
1029 Camera* camera = info->getCamera(SHADOW_CAMERA);
1030 if (camera == 0) continue;
1032 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1034 shadowSwitch->setAllChildrenOn();
1036 shadowSwitch->setAllChildrenOff();
1040 void FGRenderer::updateCascadeFar(int index, float far_m)
1042 if (index < 0 || index > 3)
1044 _cascadeFar[index] = far_m;
1045 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1048 void FGRenderer::updateCascadeNumber(size_t num)
1050 if (num < 1 || num > 4)
1053 _shadowNumber->set( (int)_numCascades );
1056 osg::Camera* FGRenderer::buildDeferredLightingCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
1058 osg::Camera* camera = new osg::Camera;
1059 info->addCamera(name, camera );
1061 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
1062 camera->setAllowEventFocus(false);
1063 camera->setGraphicsContext(gc);
1064 camera->setViewport(new Viewport);
1065 camera->setName("LightingC");
1066 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1067 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 50);
1068 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1069 camera->setViewport( new osg::Viewport );
1070 buildAttachments(info, camera, name, attachments);
1071 camera->setDrawBuffer(GL_FRONT);
1072 camera->setReadBuffer(GL_FRONT);
1073 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1074 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1075 osg::StateSet* ss = camera->getOrCreateStateSet();
1076 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1077 ss->addUniform( _depthInColor );
1079 osg::Group* lightingGroup = new osg::Group;
1081 osg::Camera* quadCam1 = new osg::Camera;
1082 quadCam1->setName( "QuadCamera1" );
1083 quadCam1->setClearMask(0);
1084 quadCam1->setAllowEventFocus(false);
1085 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1086 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1087 quadCam1->setViewMatrix(osg::Matrix::identity());
1088 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1089 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1090 ss = quadCam1->getOrCreateStateSet();
1091 ss->addUniform( _ambientFactor );
1092 ss->addUniform( info->projInverse );
1093 ss->addUniform( info->viewInverse );
1094 ss->addUniform( info->view );
1095 ss->addUniform( _sunDiffuse );
1096 ss->addUniform( _sunSpecular );
1097 ss->addUniform( _sunDirection );
1098 ss->addUniform( _planes );
1099 ss->addUniform( _shadowNumber );
1100 ss->addUniform( _shadowDistances );
1102 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1103 g->setUseDisplayList(false);
1104 simgear::EffectGeode* eg = new simgear::EffectGeode;
1105 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1107 SG_LOG(SG_VIEW, SG_ALERT, "Effects/ambient not found");
1110 eg->setEffect( effect );
1111 g->setName( "AmbientQuad" );
1112 eg->setName("AmbientQuad");
1113 eg->setCullingActive(false);
1115 quadCam1->addChild( eg );
1117 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1118 g->setUseDisplayList(false);
1119 g->setName( "SunlightQuad" );
1120 eg = new simgear::EffectGeode;
1121 effect = simgear::makeEffect("Effects/sunlight", true);
1123 SG_LOG(SG_VIEW, SG_ALERT, "Effects/sunlight not found");
1126 eg->setEffect( effect );
1127 eg->setName("SunlightQuad");
1128 eg->setCullingActive(false);
1130 quadCam1->addChild( eg );
1132 osg::Camera* lightCam = new osg::Camera;
1133 ss = lightCam->getOrCreateStateSet();
1134 ss->addUniform( _planes );
1135 ss->addUniform( info->bufferSize );
1136 lightCam->setName( "LightCamera" );
1137 lightCam->setClearMask(0);
1138 lightCam->setAllowEventFocus(false);
1139 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1140 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1141 lightCam->setViewMatrix(osg::Matrix::identity());
1142 lightCam->setProjectionMatrix(osg::Matrix::identity());
1143 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1144 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1145 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1146 lightCam->addChild( mDeferredRealRoot.get() );
1149 osg::Camera* quadCam2 = new osg::Camera;
1150 quadCam2->setName( "QuadCamera1" );
1151 quadCam2->setClearMask(0);
1152 quadCam2->setAllowEventFocus(false);
1153 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1154 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1155 quadCam2->setViewMatrix(osg::Matrix::identity());
1156 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1157 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1158 ss = quadCam2->getOrCreateStateSet();
1159 ss->addUniform( _ambientFactor );
1160 ss->addUniform( info->projInverse );
1161 ss->addUniform( info->viewInverse );
1162 ss->addUniform( info->view );
1163 ss->addUniform( _sunDiffuse );
1164 ss->addUniform( _sunSpecular );
1165 ss->addUniform( _sunDirection );
1166 ss->addUniform( _fogColor );
1167 ss->addUniform( _fogDensity );
1168 ss->addUniform( _planes );
1170 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1171 g->setUseDisplayList(false);
1172 g->setName( "FogQuad" );
1173 eg = new simgear::EffectGeode;
1174 effect = simgear::makeEffect("Effects/fog", true);
1176 SG_LOG(SG_VIEW, SG_ALERT, "Effects/fog not found");
1179 eg->setEffect( effect );
1180 eg->setName("FogQuad");
1181 eg->setCullingActive(false);
1183 quadCam2->addChild( eg );
1185 lightingGroup->addChild( _sky->getPreRoot() );
1186 lightingGroup->addChild( _sky->getCloudRoot() );
1187 lightingGroup->addChild( quadCam1 );
1188 lightingGroup->addChild( lightCam );
1189 lightingGroup->addChild( quadCam2 );
1191 camera->addChild( lightingGroup );
1197 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1199 osg::Camera* camera = new osg::Camera;
1200 info->addCamera(stage->name, camera );
1202 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1203 camera->setAllowEventFocus(false);
1204 camera->setGraphicsContext(gc);
1205 camera->setViewport(new Viewport);
1206 camera->setName(stage->name+"C");
1207 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1208 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1209 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1210 camera->setViewport( new osg::Viewport );
1211 buildAttachments(info, camera, stage->name, stage->attachments);
1212 camera->setDrawBuffer(GL_FRONT);
1213 camera->setReadBuffer(GL_FRONT);
1214 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1215 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1216 osg::StateSet* ss = camera->getOrCreateStateSet();
1217 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1218 ss->addUniform( _depthInColor );
1220 osg::Group* lightingGroup = new osg::Group;
1222 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1223 ref_ptr<Node> node = buildPass(info, pass);
1225 lightingGroup->addChild(node);
1228 camera->addChild( lightingGroup );
1234 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1235 const osg::Matrix& view,
1236 const osg::Matrix& projection,
1237 osg::GraphicsContext* gc)
1239 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1243 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1245 osg::Camera* camera = new osg::Camera;
1247 camera->setClearMask( 0 );
1248 camera->setAllowEventFocus(false);
1249 camera->setName(pass->name+"C");
1250 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1251 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1252 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1253 camera->setViewMatrix(osg::Matrix::identity());
1254 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1256 osg::StateSet* ss = camera->getOrCreateStateSet();
1257 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1258 ss->addUniform( info->projInverse );
1259 ss->addUniform( info->viewInverse );
1260 ss->addUniform( info->view );
1261 ss->addUniform( info->bufferSize );
1262 ss->addUniform( _ambientFactor );
1263 ss->addUniform( _sunDiffuse );
1264 ss->addUniform( _sunSpecular );
1265 ss->addUniform( _sunDirection );
1266 ss->addUniform( _planes );
1267 ss->addUniform( _shadowNumber );
1268 ss->addUniform( _shadowDistances );
1269 ss->addUniform( _fogColor );
1270 ss->addUniform( _fogDensity );
1271 ss->addUniform( _planes );
1273 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1274 g->setUseDisplayList(false);
1275 simgear::EffectGeode* eg = new simgear::EffectGeode;
1276 simgear::Effect* effect = simgear::makeEffect(pass->effect, true);
1278 eg->setEffect( effect );
1281 eg->setName(pass->name+"Quad");
1282 eg->setCullingActive(false);
1284 camera->addChild(eg);
1290 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1292 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1293 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1295 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1296 camera->setGraphicsContext(gc);
1297 camera->setViewport(new Viewport);
1298 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1299 buildAttachments(info, camera, stage->name, stage->attachments);
1300 camera->setDrawBuffer(GL_FRONT);
1301 camera->setReadBuffer(GL_FRONT);
1302 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1303 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1304 camera->setViewMatrix(osg::Matrix::identity());
1305 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1307 osg::StateSet* ss = camera->getOrCreateStateSet();
1308 if (stage->needsDuDv) {
1309 ss->addUniform( info->du );
1310 ss->addUniform( info->dv );
1317 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const std::string& name, osg::GraphicsContext* gc )
1319 camera->setName( "DisplayC" );
1320 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
1321 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1322 camera->setAllowEventFocus(false);
1323 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1324 g->setUseDisplayList(false); //DEBUG
1325 simgear::EffectGeode* eg = new simgear::EffectGeode;
1326 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1328 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1331 eg->setEffect(effect);
1332 eg->setCullingActive(false);
1334 camera->setViewMatrix(osg::Matrix::identity());
1335 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1336 camera->addChild(eg);
1338 osg::StateSet* ss = camera->getOrCreateStateSet();
1339 ss->addUniform( _depthInColor );
1343 FGRenderer::buildStage(CameraInfo* info,
1344 FGRenderingPipeline::Stage* stage,
1345 CameraGroup* cgroup,
1346 osg::Camera* mainCamera,
1347 osg::GraphicsContext* gc)
1349 if (!stage->valid())
1352 ref_ptr<Camera> camera;
1353 if (stage->type == "geometry")
1354 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1355 else if (stage->type == "lighting-builtin")
1356 camera = buildDeferredLightingCamera(info, gc, stage->name, stage->attachments);
1357 else if (stage->type == "lighting")
1358 camera = buildDeferredLightingCamera(info, gc, stage);
1359 else if (stage->type == "shadow")
1360 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1361 else if (stage->type == "fullscreen")
1362 camera = buildDeferredFullscreenCamera(info, gc, stage);
1363 else if (stage->type == "display") {
1364 camera = mainCamera;
1365 buildDeferredDisplayCamera(camera, info, stage->name, gc);
1367 throw sg_exception("Stage type is not supported");
1369 cgroup->getViewer()->addSlave(camera, false);
1370 installCullVisitor(camera);
1371 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1372 if (stage->type == "display")
1373 info->addCamera( stage->type, camera, slaveIndex, true );
1374 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1378 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1380 Group* group = new Group;
1381 group->addChild( _sky->getPreRoot() );
1382 group->addChild( _sky->getCloudRoot() );
1387 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1389 osg::Camera* lightCam = new osg::Camera;
1390 StateSet* ss = lightCam->getOrCreateStateSet();
1391 ss->addUniform( _planes );
1392 ss->addUniform( info->bufferSize );
1393 lightCam->setName( "LightCamera" );
1394 lightCam->setClearMask(0);
1395 lightCam->setAllowEventFocus(false);
1396 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1397 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1398 lightCam->setViewMatrix(osg::Matrix::identity());
1399 lightCam->setProjectionMatrix(osg::Matrix::identity());
1400 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1401 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1402 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1403 lightCam->addChild( mDeferredRealRoot.get() );
1409 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1415 if (pass->type == "sky-clouds")
1416 node = buildLightingSkyCloudsPass(pass);
1417 else if (pass->type == "fullscreen")
1418 node = buildDeferredFullscreenCamera(info, pass);
1419 else if (pass->type == "lights")
1420 node = buildLightingLightsPass(info, pass);
1422 throw sg_exception("Pass type is not supported");
1424 return node.release();
1428 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1430 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1431 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1432 if (buffer->valid()) {
1433 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1434 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1435 buffer->sourceFormat,
1438 buffer->shadowComparison),
1439 fullscreen ? buffer->scaleFactor : 0.0f);
1441 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1447 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1448 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1450 CameraInfo* info = new CameraInfo(flags);
1451 buildBuffers(rpipe, info);
1453 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1454 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1455 buildStage(info, stage, cgroup, camera, gc);
1458 cgroup->addCamera(info);
1464 FGRenderer::setupView( void )
1466 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1467 osg::initNotifyLevel();
1469 // The number of polygon-offset "units" to place between layers. In
1470 // principle, one is supposed to be enough. In practice, I find that
1471 // my hardware/driver requires many more.
1472 osg::PolygonOffset::setUnitsMultiplier(1);
1473 osg::PolygonOffset::setFactorMultiplier(1);
1475 // Go full screen if requested ...
1476 if ( fgGetBool("/sim/startup/fullscreen") )
1480 // The sun and moon diameters are scaled down numbers of the
1481 // actual diameters. This was needed to fit both the sun and the
1482 // moon within the distance to the far clip plane.
1483 // Moon diameter: 3,476 kilometers
1484 // Sun diameter: 1,390,000 kilometers
1485 _sky->build( 80000.0, 80000.0,
1487 *globals->get_ephem(),
1488 fgGetNode("/environment", true));
1491 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1493 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1495 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1497 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1498 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1500 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1501 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1502 stateSet->setAttribute(new osg::BlendFunc);
1503 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1505 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1507 // this will be set below
1508 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1510 osg::Material* material = new osg::Material;
1511 stateSet->setAttribute(material);
1513 stateSet->setTextureAttribute(0, new osg::TexEnv);
1514 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1516 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1517 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1518 stateSet->setAttribute(hint);
1519 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1520 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1521 stateSet->setAttribute(hint);
1522 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1523 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1524 stateSet->setAttribute(hint);
1525 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1526 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1527 stateSet->setAttribute(hint);
1528 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1529 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1530 stateSet->setAttribute(hint);
1532 osg::Group* sceneGroup = new osg::Group;
1533 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1534 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1536 //sceneGroup->addChild(thesky->getCloudRoot());
1538 stateSet = sceneGroup->getOrCreateStateSet();
1539 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1541 // need to update the light on every frame
1542 // OSG LightSource objects are rather confusing. OSG only supports
1543 // the 10 lights specified by OpenGL itself; if more than one
1544 // LightSource in the scene graph have the same light number, it's
1545 // indeterminate which values will be used to render geometry that
1546 // has that light number enabled. Also, adding children to a
1547 // LightSource is just a shortcut for setting up a state set that
1548 // has the corresponding OpenGL light enabled: a LightSource will
1549 // affect geometry anywhere in the scene graph that has its light
1550 // number enabled in a state set.
1551 LightSource* lightSource = new LightSource;
1552 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1553 // relative because of CameraView being just a clever transform node
1554 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1555 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1556 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1557 mRealRoot->addChild(lightSource);
1558 // we need a white diffuse light for the phase of the moon
1559 osg::LightSource* sunLight = new osg::LightSource;
1560 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1561 sunLight->getLight()->setLightNum(1);
1562 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1563 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1564 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1566 // Hang a StateSet above the sky subgraph in order to turn off
1568 Group* skyGroup = new Group;
1569 StateSet* skySS = skyGroup->getOrCreateStateSet();
1570 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1571 skyGroup->addChild(_sky->getPreRoot());
1572 sunLight->addChild(skyGroup);
1573 mRoot->addChild(sceneGroup);
1574 if ( _classicalRenderer )
1575 mRoot->addChild(sunLight);
1577 // Clouds are added to the scene graph later
1578 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1579 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1580 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1581 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1583 // enable disable specular highlights.
1584 // is the place where we might plug in an other fragment shader ...
1585 osg::LightModel* lightModel = new osg::LightModel;
1586 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1587 stateSet->setAttribute(lightModel);
1589 // switch to enable wireframe
1590 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1591 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1592 stateSet->setAttributeAndModes(polygonMode);
1594 // scene fog handling
1595 osg::Fog* fog = new osg::Fog;
1596 fog->setUpdateCallback(new FGFogUpdateCallback);
1597 stateSet->setAttributeAndModes(fog);
1598 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1601 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1604 osg::Geode* geode = new osg::Geode;
1605 geode->addDrawable(new SGPuDrawable);
1606 geode->addDrawable(new SGHUDDrawable);
1607 guiCamera->addChild(geode);
1610 guiCamera->addChild(FGPanelNode::create2DPanelNode());
1613 osg::Switch* sw = new osg::Switch;
1614 sw->setUpdateCallback(new FGScenerySwitchCallback);
1615 sw->addChild(mRoot.get());
1616 mRealRoot->addChild(sw);
1617 // The clouds are attached directly to the scene graph root
1618 // because, in theory, they don't want the same default state set
1619 // as the rest of the scene. This may not be true in practice.
1620 if ( _classicalRenderer ) {
1621 mRealRoot->addChild(_sky->getCloudRoot());
1622 mRealRoot->addChild(FGCreateRedoutNode());
1624 // Attach empty program to the scene root so that shader programs
1625 // don't leak into state sets (effects) that shouldn't have one.
1626 stateSet = mRealRoot->getOrCreateStateSet();
1627 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1629 mDeferredRealRoot->addChild( mRealRoot.get() );
1632 // Update all Visuals (redraws anything graphics related)
1634 FGRenderer::update( ) {
1635 if (!(_scenery_loaded->getBoolValue() ||
1636 _scenery_override->getBoolValue()))
1638 _splash_alpha->setDoubleValue(1.0);
1641 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1643 if (_splash_alpha->getDoubleValue()>0.0)
1645 // Fade out the splash screen
1646 const double fade_time = 0.5;
1647 const double fade_steps_per_sec = 10;
1648 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1649 (SGTimeStamp::now() - _splash_time).toSecs());
1650 _splash_time = SGTimeStamp::now();
1651 double sAlpha = _splash_alpha->getDoubleValue();
1652 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1653 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1654 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1657 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1658 if (!_classicalRenderer ) {
1659 _ambientFactor->set( toOsg(l->scene_ambient()) );
1660 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1661 _sunSpecular->set( toOsg(l->scene_specular()) );
1662 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1665 // update fog params
1666 double actual_visibility;
1667 if (_cloud_status->getBoolValue()) {
1668 actual_visibility = _sky->get_visibility();
1670 actual_visibility = _visibility_m->getDoubleValue();
1673 // idle_state is now 1000 meaning we've finished all our
1674 // initializations and are running the main loop, so this will
1675 // now work without seg faulting the system.
1677 FGViewer *current__view = globals->get_current_view();
1678 // Force update of center dependent values ...
1679 current__view->set_dirty();
1681 osg::Camera *camera = viewer->getCamera();
1683 bool skyblend = _skyblend->getBoolValue();
1686 if ( _textures->getBoolValue() ) {
1687 SGVec4f clearColor(l->adj_fog_color());
1688 camera->setClearColor(toOsg(clearColor));
1691 SGVec4f clearColor(l->sky_color());
1692 camera->setClearColor(toOsg(clearColor));
1695 // update fog params if visibility has changed
1696 double visibility_meters = _visibility_m->getDoubleValue();
1697 _sky->set_visibility(visibility_meters);
1699 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1700 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1702 // update the sky dome
1705 // The sun and moon distances are scaled down versions
1706 // of the actual distance to get both the moon and the sun
1707 // within the range of the far clip plane.
1708 // Moon distance: 384,467 kilometers
1709 // Sun distance: 150,000,000 kilometers
1711 double sun_horiz_eff, moon_horiz_eff;
1712 if (_horizon_effect->getBoolValue()) {
1714 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1718 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1722 sun_horiz_eff = moon_horiz_eff = 1.0;
1726 sstate.pos = current__view->getViewPosition();
1727 sstate.pos_geod = current__view->getPosition();
1728 sstate.ori = current__view->getViewOrientation();
1729 sstate.spin = l->get_sun_rotation();
1730 sstate.gst = globals->get_time_params()->getGst();
1731 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1732 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1733 sstate.sun_angle = l->get_sun_angle();
1736 scolor.sky_color = SGVec3f(l->sky_color().data());
1737 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1738 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1739 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1740 scolor.sun_angle = l->get_sun_angle();
1741 scolor.moon_angle = l->get_moon_angle();
1743 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1744 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1745 _sky->repaint( scolor, *globals->get_ephem() );
1748 // shadows->setupShadows(
1749 // current__view->getLongitude_deg(),
1750 // current__view->getLatitude_deg(),
1751 // globals->get_time_params()->getGst(),
1752 // globals->get_ephem()->getSunRightAscension(),
1753 // globals->get_ephem()->getSunDeclination(),
1754 // l->get_sun_angle());
1758 // sgEnviro.setLight(l->adj_fog_color());
1759 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1760 // current__view->get_world_up(),
1761 // current__view->getLongitude_deg(),
1762 // current__view->getLatitude_deg(),
1763 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1767 // sgEnviro.drawLightning();
1769 // double current_view_origin_airspeed_horiz_kt =
1770 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1771 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1772 // * SGD_DEGREES_TO_RADIANS);
1775 // if( is_internal )
1776 // shadows->endOfFrame();
1778 // need to call the update visitor once
1779 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1780 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1781 current__view->getViewOrientation());
1782 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1783 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1784 l->scene_diffuse(), l->scene_specular(),
1786 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1787 mUpdateVisitor->setVisibility(actual_visibility);
1788 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1789 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1790 cullMask |= simgear::GroundLightManager::instance()
1791 ->getLightNodeMask(mUpdateVisitor.get());
1792 if (_panel_hotspots->getBoolValue())
1793 cullMask |= simgear::PICK_BIT;
1794 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1795 if ( !_classicalRenderer ) {
1796 _fogColor->set( toOsg( l->adj_fog_color() ) );
1797 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1802 FGRenderer::resize( int width, int height )
1804 int curWidth = _xsize->getIntValue(),
1805 curHeight = _ysize->getIntValue();
1806 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1807 if ((curHeight != height) || (curWidth != width)) {
1808 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1809 _xsize->setIntValue(width);
1810 _ysize->setIntValue(height);
1815 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1816 const osgGA::GUIEventAdapter* ea)
1818 // wipe out the return ...
1820 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1821 Intersections intersections;
1823 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1825 for (Intersections::iterator hit = intersections.begin(),
1826 e = intersections.end();
1829 const osg::NodePath& np = hit->nodePath;
1830 osg::NodePath::const_reverse_iterator npi;
1831 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1832 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1835 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1836 SGPickCallback* pickCallback = ud->getPickCallback(i);
1839 SGSceneryPick sceneryPick;
1840 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1841 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1842 sceneryPick.callback = pickCallback;
1843 pickList.push_back(sceneryPick);
1847 return !pickList.empty();
1851 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1857 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1859 eventHandler = eventHandler_;
1863 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1865 mRealRoot->addChild(camera);
1869 FGRenderer::removeCamera(osg::Camera* camera)
1871 mRealRoot->removeChild(camera);
1875 FGRenderer::setPlanes( double zNear, double zFar )
1877 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1881 fgDumpSceneGraphToFile(const char* filename)
1883 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1887 fgDumpTerrainBranchToFile(const char* filename)
1889 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1895 fgDumpNodeToFile(osg::Node* node, const char* filename)
1897 return osgDB::writeNodeFile(*node, filename);
1900 namespace flightgear
1902 using namespace osg;
1904 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1907 VisibleSceneInfoVistor()
1908 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1910 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1911 | CullSettings::VIEW_FRUSTUM_CULLING);
1912 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1915 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1919 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1921 typedef std::map<const std::string,int> InfoMap;
1923 void getNodeInfo(Node* node)
1925 const char* typeName = typeid(*node).name();
1926 classInfo[typeName]++;
1927 const std::string& nodeName = node->getName();
1928 if (!nodeName.empty())
1929 nodeInfo[nodeName]++;
1934 using namespace std;
1935 typedef vector<InfoMap::iterator> FreqVector;
1936 cout << "class info:\n";
1938 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1941 classes.push_back(itr);
1942 sort(classes.begin(), classes.end(), freqComp);
1943 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1946 cout << (*itr)->first << " " << (*itr)->second << "\n";
1948 cout << "\nnode info:\n";
1950 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1953 nodes.push_back(itr);
1955 sort (nodes.begin(), nodes.end(), freqComp);
1956 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1959 cout << (*itr)->first << " " << (*itr)->second << "\n";
1964 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1966 ref_ptr<RefMatrix> projection
1967 = createOrReuseMatrix(camera->getProjectionMatrix());
1968 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1970 viewport = camera->getViewport();
1972 pushViewport(viewport);
1973 pushProjectionMatrix(projection.get());
1974 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1975 root->accept(*this);
1976 popModelViewMatrix();
1977 popProjectionMatrix();
1983 void apply(Node& node)
1992 void apply(Group& node)
2002 void apply(Transform& node)
2007 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
2008 node.computeLocalToWorldMatrix(*matrix,this);
2009 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
2012 popModelViewMatrix();
2016 void apply(Camera& camera)
2018 // Save current cull settings
2019 CullSettings saved_cull_settings(*this);
2021 // set cull settings from this Camera
2022 setCullSettings(camera);
2023 // inherit the settings from above
2024 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2026 // set the cull mask.
2027 unsigned int savedTraversalMask = getTraversalMask();
2028 bool mustSetCullMask = (camera.getInheritanceMask()
2029 & osg::CullSettings::CULL_MASK) == 0;
2030 if (mustSetCullMask)
2031 setTraversalMask(camera.getCullMask());
2033 osg::RefMatrix* projection = 0;
2034 osg::RefMatrix* modelview = 0;
2036 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2037 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2038 projection = createOrReuseMatrix(*getProjectionMatrix()
2039 *camera.getProjectionMatrix());
2040 modelview = createOrReuseMatrix(*getModelViewMatrix()
2041 * camera.getViewMatrix());
2043 else { // pre multiply
2044 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2045 * (*getProjectionMatrix()));
2046 modelview = createOrReuseMatrix(camera.getViewMatrix()
2047 * (*getModelViewMatrix()));
2050 // an absolute reference frame
2051 projection = createOrReuseMatrix(camera.getProjectionMatrix());
2052 modelview = createOrReuseMatrix(camera.getViewMatrix());
2054 if (camera.getViewport())
2055 pushViewport(camera.getViewport());
2057 pushProjectionMatrix(projection);
2058 pushModelViewMatrix(modelview, camera.getReferenceFrame());
2062 // restore the previous model view matrix.
2063 popModelViewMatrix();
2065 // restore the previous model view matrix.
2066 popProjectionMatrix();
2068 if (camera.getViewport()) popViewport();
2070 // restore the previous traversal mask settings
2071 if (mustSetCullMask)
2072 setTraversalMask(savedTraversalMask);
2074 // restore the previous cull settings
2075 setCullSettings(saved_cull_settings);
2080 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2082 return lhs->second > rhs->second;
2088 bool printVisibleSceneInfo(FGRenderer* renderer)
2090 osgViewer::Viewer* viewer = renderer->getViewer();
2091 VisibleSceneInfoVistor vsv;
2093 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2094 const View::Slave& slave = viewer->getSlave(0);
2095 vp = slave._camera->getViewport();
2097 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2102 // end of renderer.cxx